ReMe/reme/components/proactive_runtime/base_proactive_runtime.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

141 lines
4.7 KiB
Python

"""Coordinate proactive tasks and reminder delivery through an Agent wrapper."""
from __future__ import annotations
from abc import abstractmethod
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from datetime import datetime
from typing import TYPE_CHECKING
from ..base import BaseComponent
from ...enumeration import ComponentEnum
if TYPE_CHECKING:
import asyncio
from ...utils.files.workspace_files import WorkspaceFiles
from ...utils.proactive_record import RoundRecord
from ._internal.notifications import ChatNotifications
from ._internal.outbox import ReminderOutbox
from ._internal.registry import AgentRegistry
from ._internal.sessions import AgentSessions
from ._internal.live_turn import LiveTurns
from ..agent_wrapper import BaseAgentWrapper
from ..agent_inbox import BaseAgentInbox
from ...schema.proactive_agent import ProactiveAgent
from ...schema.agent_activity import AgentActivity
from ...schema.event import Event
class BaseProactiveRuntime(BaseComponent):
"""Expose owned Agent resources and operations independently of the local backend."""
component_type = ComponentEnum.PROACTIVE_RUNTIME
agent_wrapper: BaseAgentWrapper
files: WorkspaceFiles
agents: AgentRegistry
sessions: AgentSessions
live_turns: LiveTurns
inbox: BaseAgentInbox
notifications: ChatNotifications
outbox: ReminderOutbox
chat_lock: asyncio.Lock
chat_tasks: set[asyncio.Task]
workers: dict[str, asyncio.Task]
agent_tasks: dict[asyncio.Task, str]
activities: dict[str, AgentActivity]
changed: asyncio.Event
closed: bool
retry_seconds: float
@abstractmethod
def now(self) -> datetime:
"""Read time in the application timezone."""
@abstractmethod
async def definition(self, agent_name: str) -> ProactiveAgent:
"""Read the latest task definition."""
@abstractmethod
async def create(self, config: dict) -> dict:
"""Create or restore a durable task identity."""
@abstractmethod
async def update(self, agent_name: str, config: dict) -> dict:
"""Update execution settings independently of the task description."""
@abstractmethod
async def delete(self, agent_name: str) -> dict:
"""Stop owned execution while preserving task history."""
@abstractmethod
async def append_events(self, agent_name: str, events: list[Event]) -> dict:
"""Persist external observations for a background task."""
@abstractmethod
async def status(self, agent_name: str) -> dict:
"""Return execution settings, status, and the task document path."""
@abstractmethod
async def list_agents(self) -> dict:
"""List task settings, current status, and document paths."""
@asynccontextmanager
@abstractmethod
async def chat_turn(self) -> AsyncIterator[None]:
"""Own one serial Chat turn and its cancellation."""
yield
@asynccontextmanager
@abstractmethod
async def query_session(self, agent_name: str, options: dict) -> AsyncIterator[str]:
"""Own a fork of the latest task session through query completion and cleanup."""
yield
@abstractmethod
async def list_views(self) -> dict:
"""Read all foreground and task identities with current session state."""
@abstractmethod
async def view_agent(self, agent_name: str) -> dict:
"""Read one Agent's public settings and state without loading its transcript."""
@abstractmethod
async def read_agent(self, agent_name: str) -> dict:
"""Read one current session without creating it."""
@abstractmethod
async def watch_agent(self, agent_name: str) -> AsyncIterator[dict]:
"""Observe one current conversation and global Agent state."""
yield {}
@abstractmethod
async def list_inputs(self, agent_name: str, **kwargs) -> dict:
"""Page retained inputs without acquiring a consumption lease."""
@abstractmethod
async def list_chat_sessions(self, offset=0, limit=10) -> dict:
"""Inspect the Chat Agent's retained session references."""
@abstractmethod
async def run(
self,
agent_name: str,
execute: Callable,
*,
record: RoundRecord | None = None,
) -> dict:
"""Execute one serial input batch and commit its optional round record."""
@abstractmethod
async def tick(self, run_job: Callable) -> None:
"""Schedule task and Chat work."""
@abstractmethod
async def stop_workers(self) -> None:
"""Stop the owned scheduler workers and notification task."""
@abstractmethod
async def wait(self, stop: asyncio.Event, seconds=1) -> None:
"""Wait for input, configuration changes or shutdown."""