ReMe/reme/schema/proactive_agent.py
jinliyl 524b1b6908
feat(studio): unify the workbench and proactive runtime (#764)
* fix(proactive): simplify round files and restore failed summaries

* fix(proactive): validate document-relative Markdown links

* feat(proactive_agent): implement v2 daily record workflow with single-file decision

- Add ProactiveAgentStepV2 class to support single daily note decision and reminder
- Introduce RoundOutputs for v2 round file tracking, and keep RoundArtifacts for v1 summary backup
- Refactor AgentOutbox to support both v1 standalone reminder files and v2 daily reminder records
- Add proactive_record utilities to parse and validate v2 daily record frontmatter and metadata
- Enhance proactive_agent to prepare, read, and manage artifacts for both v1 and v2 flows
- Add configuration profile proactive_v2 to enable new workflow with backward compatibility
- Update proactive.yaml and reactive proactive_agent_step configuration comment for easy switching
- Provide extensive schema validation for v2 reminders ensuring priority and message consistency
- Document v2 workflow and usage in English and Chinese runtime docs
- Add unit tests for v2 step verifying single file output and proper decision handling

* refactor(agent/runtime): replace ReminderRef with string keys and simplify reminder handling

- Remove ReminderRef model and switch to using workspace-relative string keys for reminders
- Simplify AgentOutbox to read, write, and manage reminders keyed by strings
- Change file locking and version checking to protect concurrent edits on daily record files
- Replace legacy and v2 reminder file handling with unified ReminderFiles storage
- Adjust ChatNotifications to operate with the new key scheme and update pending/read sets
- Refactor RoundOutputs to RoundRecord for safer round record tracking and rollback
- Remove unused ProactiveRunResult and related references from imports and exports
- Update InboxWakeRequest, AgentReminder, and related models for consistent ID and path validation
- Adjust proactive agent runtime and local runtime to check reminder versions before commit
- Correct language and docs to describe reminders as daily records instead of separate files
- Clean up roles of inbox and outbox for reminder ownership, delivery, and acknowledgments

* fix(proactive): serialize round commits and align desktop reminders

* refactor(proactive): unify task triggers in Proactive Runtime

* fix(proactive): bound reminder payloads and simplify receipts

* refactor(studio): share workbench and simplify proactive delivery

* fix(studio): update and centralize build dependencies

* fix(proactive): guard draft repair and verify Studio deployments

* chore(docs): update source-map-js

* feat(release): support publishing selected artifacts from a tag

* chore(studio): remove the public playground

* refactor: simplify reminders and release workflows

* fix: preserve proactive records and align release provenance

* test(proactive): remove brittle prompt and preset assertions

* fix(proactive): register reminders after input acknowledgement

* feat(notebook): list projects across todos and ideas

* feat(studio): connect mobile apps to configurable ReMe services

* fix(proactive): reserve registered reminder paths

* fix(studio): request Android local network access

* fix(proactive): reserve reminder paths referenced by receipts
2026-11-23 17:19:21 +08:00

183 lines
6.6 KiB
Python

"""Proactive task definitions and structured model results."""
from datetime import datetime
from typing import Literal
from pydantic import (
AwareDatetime,
BaseModel,
ConfigDict,
Field,
StrictBool,
field_validator,
model_validator,
)
from ..constants import CHAT_AGENT_NAME
from .agent_message import ClientModel
from .event import Event
from .proactive_runtime import AgentName, AgentReminder, InboxPriority
CRON_EVENT_SOURCE = "cron"
class AppendTaskEventsRequest(BaseModel):
"""Append a nonempty batch of observations to one existing background task."""
model_config = ConfigDict(extra="forbid")
agent_name: AgentName
events: list[Event] = Field(min_length=1)
class NotificationWindow(BaseModel):
"""An application-local notification window; equal endpoints mean all day."""
model_config = ConfigDict(extra="forbid")
start: str = Field(pattern=r"^(?:[01][0-9]|2[0-3]):[0-5][0-9]$")
end: str = Field(pattern=r"^(?:[01][0-9]|2[0-3]):[0-5][0-9]$")
def allows(self, now: datetime) -> bool:
"""Include the opening minute and exclude the closing minute."""
current = now.strftime("%H:%M")
if self.start == self.end:
return True
if self.start < self.end:
return self.start <= current < self.end
return current >= self.start or current < self.end
class TaskSettings(ClientModel):
"""One set of editable settings shared by task definitions and client views."""
model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
enabled: StrictBool = True
cron: str | None = None
min_trigger_interval_seconds: float = Field(default=0, ge=0)
notify_window: NotificationWindow | None = None
@field_validator("min_trigger_interval_seconds", mode="before")
@classmethod
def numeric_interval(cls, value):
"""Do not interpret booleans or numeric strings as delays."""
if type(value) not in (int, float):
raise ValueError("min_trigger_interval_seconds must be a number")
return value
@field_validator("cron")
@classmethod
def validate_cron(cls, expression):
"""Validate the optional schedule independently of observation processing."""
if expression is not None:
from croniter import croniter
if not expression or not croniter.is_valid(expression):
raise ValueError("cron must be a valid expression")
return expression
class ProactiveAgentConfig(TaskSettings):
"""A named task with internal batching limits; requirements live in TASK.md."""
agent_name: AgentName
max_batch_events: int = Field(default=20, ge=1, strict=True)
@field_validator("agent_name")
@classmethod
def safe_name(cls, value: str) -> str:
"""Task names identify workspace files; Remy owns the main conversation."""
if value.casefold() == CHAT_AGENT_NAME.casefold():
raise ValueError(f"{CHAT_AGENT_NAME} is a reserved agent name")
return value
class CreateProactiveAgentConfig(ProactiveAgentConfig):
"""Accept initial task text only when creating an Agent."""
task_description: str = Field(min_length=1, max_length=100000)
@field_validator("task_description")
@classmethod
def nonblank_task_description(cls, value: str) -> str:
"""Reject blank task descriptions and preserve the original Markdown."""
if not value.strip():
raise ValueError("task_description must not be blank")
return value
class ProactiveAgent(ProactiveAgentConfig):
"""The creation name is the immutable application identity, including after restoration."""
model_config = ConfigDict(extra="forbid")
created_at: AwareDatetime
deleted_at: AwareDatetime | None = None
class ProactiveRecordDecision(BaseModel):
"""The inbox delivery decision in a daily record's frontmatter."""
model_config = ConfigDict(extra="forbid")
reminder_priority: Literal[InboxPriority, "skip"]
reminder_message: str = Field(max_length=100000)
@field_validator("reminder_message")
@classmethod
def nonblank_reminder_message(cls, value):
"""Require the inbox message or the reason for skipping delivery."""
if not value.strip():
raise ValueError("reminder_message must not be blank")
return value
def reminder(self, path: str) -> AgentReminder | None:
"""Build the reminder identified by its source daily record."""
if self.reminder_priority == "skip":
return None
return AgentReminder(priority=self.reminder_priority, message=self.reminder_message, id=path)
class ManageProactiveAgentRequest(TaskSettings):
"""Named task operations expose only the fields relevant to each action."""
model_config = ConfigDict(extra="forbid")
action: Literal["list", "create", "status", "update", "delete", "query"]
agent_name: AgentName | None = None
task_description: str | None = Field(default=None, min_length=1, max_length=100000)
question: str | None = Field(default=None, min_length=1, max_length=100000)
@field_validator("task_description", "question")
@classmethod
def nonblank_text(cls, value):
"""Keep task text verbatim while rejecting whitespace-only requests."""
if value is not None and not value.strip():
raise ValueError("must not be blank")
return value
@model_validator(mode="after")
def action_arguments(self):
"""Reject unused fields instead of silently ignoring misspecified calls."""
settings = {"enabled", "cron", "min_trigger_interval_seconds", "notify_window"}
required, allowed = {
"list": (set(), set()),
"create": (
{"agent_name", "task_description"},
settings | {"agent_name", "task_description"},
),
"status": ({"agent_name"}, {"agent_name"}),
"update": ({"agent_name"}, settings | {"agent_name"}),
"delete": ({"agent_name"}, {"agent_name"}),
"query": ({"agent_name", "question"}, {"agent_name", "question"}),
}[self.action]
supplied = self.model_fields_set - {"action"}
if supplied - allowed:
raise ValueError(f"{self.action} does not accept: {', '.join(sorted(supplied - allowed))}")
missing = {key for key in required if getattr(self, key) is None}
if missing:
raise ValueError(f"{self.action} requires: {', '.join(sorted(missing))}")
if self.action == "update" and not supplied & settings:
raise ValueError("update requires at least one setting")
return self