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

102 lines
4.5 KiB
Python

"""Agent-owned native session histories, independent of task and inbox identities."""
import asyncio
from collections import deque
from hashlib import sha256
import json
from ....schema.proactive_runtime import AgentSession, validate_agent_name
from ....utils.async_utils import complete_in_thread, finish_cleanup
class AgentSessions:
"""Persist every created session; only primary sessions determine current execution."""
def __init__(self, agents):
self.agents = agents
self.files = agents.files
self.locks = {}
def path(self, agent_name):
"""Keep registry files separate from native transcripts and standard dialog notes."""
return self.files.checked(self.agents.path(agent_name) / "sessions.jsonl")
def lock(self, agent_name):
"""Coordinate selection with new-session publication and native delivery."""
validate_agent_name(agent_name)
return self.locks.setdefault(agent_name, asyncio.Lock())
def _records(self, agent_name):
for value in self.files.iter_jsonl(self.path(agent_name), incomplete_ok=True):
yield AgentSession.model_validate(value)
def _latest(self, agent_name):
current = None
for record in self._records(agent_name):
if not record.temporary:
current = record
return current
async def current(self, agent_name):
"""Read the last primary reference without creating or restoring a native thread."""
return await asyncio.to_thread(self._latest, agent_name)
async def list(self, agent_name, offset=0, limit=10):
"""Return newest-first history; pagination never prunes or activates sessions."""
if type(offset) is not int or offset < 0 or type(limit) is not int or limit < 1:
raise ValueError("offset must be a nonnegative integer and limit a positive integer")
def read():
records = deque(maxlen=offset + limit)
total = 0
for record in self._records(agent_name):
records.append(record)
total += 1
items = list(reversed(records))[offset : offset + limit]
return {
"items": [record.model_dump(mode="json", exclude={"signature"}) for record in items],
"total": total,
"offset": offset,
"limit": limit,
}
return await asyncio.to_thread(read)
def _record(self, agent_name, record):
if not any(previous.session_id == record.session_id for previous in self._records(agent_name)):
self.files.append_jsonl(self.path(agent_name), record.model_dump(mode="json"))
async def record(self, agent_name, session_id, now, *, temporary=False):
"""Retain temporary forks for audit without making them the next execution source."""
async with self.lock(agent_name):
record = AgentSession(session_id=session_id, created_at=now, temporary=temporary)
await complete_in_thread(self._record, agent_name, record)
async def ensure(self, agent_name, wrapper, options, now, *, new=False):
"""Select or create a session with the supplied instructions and bindings."""
signature = sha256(json.dumps(options, sort_keys=True).encode()).hexdigest()
async with self.lock(agent_name):
previous = await self.current(agent_name)
exists = not new and previous is not None and await wrapper.session_exists(previous.session_id)
if exists and previous.signature == signature:
return previous.session_id
async def create():
arguments = dict(options)
if not new and exists:
arguments.update(resume=previous.session_id, fork_session=True)
session_id = await wrapper.create_session(**arguments)
try:
record = AgentSession(session_id=session_id, created_at=now, signature=signature)
await complete_in_thread(self._record, agent_name, record)
except BaseException:
await finish_cleanup(wrapper.release_session(session_id))
raise
if previous is not None:
try:
await wrapper.release_session(previous.session_id)
except Exception as exc:
wrapper.logger.warning(f"Could not release previous session: {exc}")
return session_id
return await finish_cleanup(create())