ReMe/reme/components/agent_wrapper/session_append.py
jinliyl 3db84c735f
feat(agent)!: add file-native proactive runtimes and ReMe Desktop (#743)
* feat(agent): unify persistent sessions and native fork settings

* fix(agent): preserve continuation and rejected session settings

* feat(event_stream): add bounded durable event streams

* fix(agent): preserve session guards and execution policies

* Revert "fix(agent): preserve session guards and execution policies"

This reverts commit 02188565dc.

* refactor(agent)!: unify file-native proactive runtimes

Coordinate named cron and event agents through an application-owned runtime,
with per-agent memory, native session registries and Markdown reminders.
Initialize Chat and task memories once under reme_agents and remove the old
PA delivery APIs and duplicated session state.

Serialize temporary query ownership with collection, recover incomplete
session-registry appends, and migrate benchmark plugins to public file helpers.
Split model providers into registered modules without changing their behavior.

* feat(proactive): add speech and scheduled observation collectors

Add DashScope ASR/TTS components, restart-safe finance collectors and
five-minute screenshot/Codex dialogue observations with bilingual docs.

Use response receipt time for stock freshness and recover interrupted
work-observation cleanup without replaying committed dialogue.

* refactor(core)!: unify execution cleanup and remove legacy contracts

Track queued Agent operations through shutdown and deletion, keep retry
backoff bounded, and reuse the local process runner for Shell steps.
Reject BASE registrations and remove duplicate config/path helpers.

BREAKING CHANGE: plugin discovery requires package-only entry points
and plugin.yaml; FileLink.predicate and the dream.ProactiveResult alias
are removed. Rebuild old derived graph indexes from workspace notes.

* feat(agent)!: add desktop workspace and isolated inbox delivery

* chore(desktop): remove one-click restart launcher

* fix(agent): guard session content and persist incremental display history

* test(home): verify host network isolation across platforms

* refactor(agent)!: unify durable inbox components

* docs: illustrate personal and proactive agent runtimes

* Refactor agent streaming and durable reminder delivery

Project formal turns through one ordered transcript, with live snapshots until native history catches up. Render localized activity groups, stable Markdown blocks and paged conversation history.

Bound proactive batches and preserve retries, persist reminder links before delivery, and synchronize explicit user-read receipts across sessions. Remove the obsolete desktop receipt format.

* Align desktop streaming activity with Codex

Keep assistant progress in the conversation and fold reasoning into activity details. Normalize native command actions into file, directory, search and command summaries with localized disclosure and explicit completion.

Match user bubbles and activity styling while preserving streaming anchors, links and expansion state.

* docs: explain proactive agents and personal runtime

* Align proactive runtime settings and documentation

* Unify agent runtime APIs and resource collection

* Deduplicate proactive observations and respect market sessions

* Refine proactive sessions and screenshot filtering

* Add desktop background transparency and tab transitions

* Tighten observation validation and task prompts

* Align streaming tool display with canonical item snapshots

* Unify Agent identity, task memory, and session workflows

Use agent_name and agent_type across the runtime, APIs, collectors and Desktop.
Initialize task_memory into MEMORY.md and return memory paths for native edits.
Keep task questions in read-only forks and automatic runs in validated file stages.
Document current behavior and cover default conversation rendering and SDK forks.

* Unify active sessions and task files; remove prompt wording tests

* Refine proactive jobs and fix coverage reporting

* Remove unused desktop artifacts and protocol probe

* Simplify proactive runs and commit validated artifacts after model failures

* Allow daily summaries for new records without reminders

* refactor(proactive): improve proactive and cron agent prompts and workflow steps

- Update cron agent description to emphasize recording what happened and reporting results
- Change sleep reminder rule to be specifically tagged for proactive agent
- Rename query fields to proactive_query for clarity
- Streamline and clarify proactive agent workflow steps in English and Chinese versions
- Enhance task analysis and reminder decision logic with clearer instructions
- Revise today's summary update format and examples with time stamps and consistent headings
- Provide separate detailed steps for cron agent execution and reporting
- Ensure reminder generation logic is more precise and avoid assumptions about user knowledge

* Add notebook and task management with resilient agent cleanup

* Improve search accounting and desktop conversation controls

* Guard conversation reset against endpoint changes

* refactor(proactive): simplify session options and improve markdown link warnings

- Remove unused failure status detection and associated UI styling in activity component
- Simplify session_options method by removing unnecessary parameters and excessive prompt formatting
- Enhance _query method to handle task content and event inputs conditionally based on agent type
- Add static method to extract and decode markdown links ignoring code blocks
- Introduce _warn_local_links to log warnings on broken local links without failing artifact validation
- Integrate local link warnings into artifact reading flow for proactive and cron agents
- Modify tests to reflect session_options signature changes and verify local link warning behavior
- Ensure TASK.md is non-empty before task execution, enforcing content validation
- Refactor CSS to remove deprecated broken activity state styles
- Improve test coverage with parameterized tests for broken local link warnings under various scenarios

* fix(agent): preserve user edits and recover durable commits

* fix(agent): guard outbox writes and defer full inbox delivery

* fix(agent): preserve reminder eligibility and serialize lifecycle transitions

* Simplify proactive task storage and desktop protocol

* Make proactive timeline limits configurable

* test(proactive): remove prompt checks and redundant cases

* Unify proactive task APIs and documentation

* fix(proactive): preserve incomplete triggers and skip oversized reminders

* fix(proactive): preserve queued trigger types across task updates

* docs(proactive): improve instructions for recording scheduled task results

- Clarify steps to follow after completing the scheduled task work
- Specify writing `action: write` in frontmatter when overwriting the record file
- Simplify description of what to include in the record body
- Emphasize using only necessary tools for the task and writing the record
- Align English and Chinese instructions for consistency

* fix(proactive): keep scheduled time and bypass event cooldown for cron
2026-11-19 21:37:25 +08:00

93 lines
3.9 KiB
Python

"""Shared append validation and application-owned pending receipts.
Submission is distinct from persistence. A caller timing out never cancels a
queued append; the session owner settles it or fails it during its own cleanup.
Backend queues are consumed by their existing execution lifecycle, not by an
untracked background worker.
"""
import asyncio
import math
import re
from dataclasses import dataclass
from typing import Any
from ...schema import SessionMessage, SessionSnapshot
def validate_append(content, message_id, role, timeout, delivery):
"""Keep the public append contract identical across all three backends."""
if role not in ("user", "assistant"):
raise ValueError("role must be 'user' or 'assistant'")
if not isinstance(message_id, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", message_id):
raise ValueError("message_id must contain 1-128 letters, digits, underscores or hyphens")
if not isinstance(content, str) or not content.strip() or len(content) > 100_000:
raise ValueError("content must contain 1-100000 characters")
if delivery not in ("idle", "immediate"):
raise ValueError("Invalid chat delivery policy")
if type(timeout) not in (int, float) or not math.isfinite(timeout) or timeout <= 0:
raise ValueError("timeout must be positive and finite")
def check_identity(message, content, role):
"""A retry must refer to exactly the same observation."""
if (message.content, message.role) != (content, role):
raise ValueError("message_id already belongs to different content or role")
def check_guard(snapshot: SessionSnapshot, expected_turn_id, expected_revision):
"""Apply guards only to new appends, after recovering accepted retry IDs."""
if expected_turn_id is not None and (snapshot.last_turn_id or "") != expected_turn_id:
raise RuntimeError("Session changed before appending")
if expected_revision is not None and snapshot.revision != expected_revision:
raise RuntimeError("Session changed before appending")
@dataclass
class PendingAppend:
"""One shared retry identity plus backend-owned native input data."""
message: SessionMessage
receipt: asyncio.Future
payload: Any = None
submitted: bool = False
async def wait(self):
"""Cancellation of an observer must not cancel the session's receipt."""
return (await asyncio.shield(self.receipt)).model_copy(deep=True)
class SessionAppends:
"""Serialize append admission and publication independently from generation."""
def __init__(self):
self.lock = asyncio.Lock()
self.pending: dict[str, PendingAppend] = {}
def get(self, identifier, content, role):
"""Recover an in-flight retry before reading partially committed native state."""
pending = self.pending.get(identifier)
if pending is not None:
check_identity(pending.message, content, role)
return pending
def add(self, message, payload=None):
"""Register before dispatch so uncertain writes cannot be duplicated."""
receipt = asyncio.get_running_loop().create_future()
receipt.add_done_callback(lambda future: None if future.cancelled() else future.exception())
pending = PendingAppend(message, receipt, payload)
self.pending[message.id] = pending
return pending
def resolve(self, message):
"""Publish only after the backend's durable state agrees with the input."""
pending = self.pending.pop(message.id)
if not pending.receipt.done():
pending.receipt.set_result(message.model_copy(deep=True))
def fail(self, error):
"""Release waiters on execution failure; persisted IDs remain recoverable."""
for pending in self.pending.values():
if not pending.receipt.done():
pending.receipt.set_exception(error)
self.pending.clear()