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

213 lines
9.7 KiB
Python

"""Reconstructible UI views over runtime ownership and native session history."""
import asyncio
from pathlib import PurePosixPath
from time import monotonic
from ....constants import CHAT_AGENT_NAME
from ....schema.agent_view import (
AgentSessionView,
AgentView,
AgentSnapshot,
AgentUpdate,
AgentHeartbeat,
ClientActivity,
)
from ....utils.agent_transcript import project_messages
from ....schema.agent_session import SessionSnapshot, SessionStatus
class AgentViews:
"""Subscriptions own no generation tasks and never create or select sessions."""
def __init__(self, runtime):
self.runtime = runtime
async def view(self, agent_name):
"""Read identity, native activity and original file references."""
runtime = self.runtime
if agent_name == CHAT_AGENT_NAME:
inbox = runtime.notifications
config, facts, agent_type = (
{},
{
"error": inbox.error,
"last_started_at": inbox.last_started_at.isoformat() if inbox.last_started_at else None,
"last_completed_at": inbox.last_completed_at.isoformat() if inbox.last_completed_at else None,
"next_trigger_at": inbox.retry_at.isoformat() if inbox.retry_at else None,
},
"chat",
)
directory = runtime.agents.path(CHAT_AGENT_NAME).relative_to(runtime.workspace_path).as_posix()
document = {"memory_path": runtime.agents.chat_memory_path().relative_to(runtime.workspace_path).as_posix()}
running = runtime.chat_lock.locked() or inbox.worker is not None
else:
facts = await runtime.status(agent_name)
config = facts["config"]
agent_type = "cron" if config.get("cron") is not None else "proactive"
directory = PurePosixPath(facts["task_path"]).parent.as_posix()
document = {"task_path": facts["task_path"]}
running = facts["running"]
session = await runtime.sessions.current(agent_name)
status, error = "idle", facts.get("error")
problems = [
f"{path}: {message}"
for path, message in runtime.outbox.issues.items()
if agent_name == CHAT_AGENT_NAME or runtime.outbox.storage.owns(path, agent_name)
]
if problems:
error = "; ".join(filter(None, [error, *problems]))[:2000]
if session:
try:
if await runtime.agent_wrapper.session_exists(session.session_id):
status = (await runtime.agent_wrapper.get_session_status(session.session_id)).status
else:
status = "not_loaded"
except Exception as exc: # A missing native thread must not hide the Agent's files.
status, error = "error", str(exc)
if running:
status = "active"
elif error:
status = "error"
return AgentView(
agent_name=agent_name,
agent_type=agent_type,
enabled=config.get("enabled", True),
cron=config.get("cron"),
min_trigger_interval_seconds=config.get("min_trigger_interval_seconds", 0),
notify_window=config.get("notify_window"),
status=status,
session_id=session.session_id if session else None,
directory=directory,
pending_events=facts.get("pending_events", 0),
in_flight_events=facts.get("in_flight_events", 0),
last_started_at=facts.get("last_started_at"),
last_completed_at=facts.get("last_completed_at"),
next_trigger_at=facts.get("next_trigger_at"),
error=error,
**document,
)
async def list(self):
"""Include the fixed chat identity before named tasks."""
agents = await asyncio.to_thread(self.runtime.agents.load)
items = [await self.view(agent_name) for agent_name in [CHAT_AGENT_NAME, *agents]]
return {
"items": [item.model_dump(mode="json") for item in items],
"total": len(items),
}
async def native(self, agent_name):
"""Keep Chat history; task workspaces expose only their latest native turn."""
agent = await self.view(agent_name)
snapshot = None
if agent.session_id is not None:
if await self.runtime.agent_wrapper.session_exists(agent.session_id):
snapshot = await self.runtime.agent_wrapper.read_session(agent.session_id)
if agent.agent_type != "chat":
snapshot = snapshot.model_copy(
update={
"messages": [
message
for message in snapshot.messages
if snapshot.last_turn_id and message.turn_id == snapshot.last_turn_id
],
},
)
else:
# Native empty threads may have no rollout until the first turn. Keep the
# application reference visible; the next send will ensure a usable thread.
snapshot = SessionSnapshot(
session_id=agent.session_id,
state=SessionStatus(session_id=agent.session_id, status="not_loaded"),
)
return {
"agent": agent.model_dump(mode="json"),
"session_id": agent.session_id,
"snapshot": snapshot.model_dump(mode="json") if snapshot else None,
}
def project(self, agent_name, value):
"""Keep native reconciliation internal; publish only canonical display messages."""
current = self.runtime.live_turns.overlay(agent_name, value)
activities = {}
for name, activity in self.runtime.activities.items():
if name != agent_name and (agent_name != CHAT_AGENT_NAME or name not in self.runtime.workers):
continue
if name == agent_name and activity.session_id != current["session_id"]:
continue
activities[name] = ClientActivity(
session_id=activity.session_id,
turn_id=activity.turn_id,
phase=activity.phase,
tool=activity.tool,
started_at=activity.started_at.isoformat() if activity.started_at else None,
)
return AgentSessionView(
agent=current["agent"],
messages=project_messages(
current["session_id"] or "",
(current["snapshot"] or {}).get("messages", []),
notifications=agent_name == CHAT_AGENT_NAME,
),
activities=activities,
).model_dump(mode="json")
async def read(self, agent_name):
"""Read exactly the state used by the subscription's authoritative snapshot."""
return self.project(agent_name, await self.native(agent_name))
async def events(self, agent_name, interval=1, heartbeat=15):
"""Replace on reconnect/session change; otherwise batch complete-message upserts.
Polling observes external edits. Live output wakes observers without rereading native files.
Only the main subscription carries the global Agent roster and background activities.
"""
wake = asyncio.Event()
self.runtime.live_turns.listeners.add(wake)
try:
previous: dict = {}
last_emit, next_poll, polled_epoch = monotonic(), 0, -1
value: dict = {}
agents = None
while not self.runtime.closed:
wake.clear()
live = self.runtime.live_turns.turns.get(agent_name)
epoch = self.runtime.live_turns.epoch
if (
not value
or monotonic() >= next_poll
or epoch != polled_epoch
or (live and live.session_id != value["session_id"])
):
value = await self.native(agent_name)
agents = (await self.list())["items"] if agent_name == CHAT_AGENT_NAME else None
if epoch != self.runtime.live_turns.epoch:
continue
polled_epoch, next_poll = epoch, monotonic() + interval
current = {**self.project(agent_name, value), "agents": agents}
if current != previous:
old = {message["id"]: message for message in previous["messages"]} if previous else {}
messages = current["messages"]
ids = [message["id"] for message in messages]
replace = (
not previous
or previous["agent"]["session_id"] != current["agent"]["session_id"]
or list(old) != ids[: len(old)]
)
if replace:
yield AgentSnapshot.model_validate(current).model_dump(mode="json")
else:
changed = [message for message in messages if message != old.get(message["id"])]
yield AgentUpdate.model_validate({**current, "messages": changed}).model_dump(mode="json")
previous, last_emit = current, monotonic()
elif monotonic() - last_emit >= heartbeat:
yield AgentHeartbeat().model_dump(mode="json")
last_emit = monotonic()
try:
await asyncio.wait_for(wake.wait(), timeout=max(0, next_poll - monotonic()))
await asyncio.sleep(0.025)
except TimeoutError:
pass
finally:
self.runtime.live_turns.listeners.discard(wake)