ReMe/reme/components/proactive_manager/_internal/notifications.py
jinliyl ae55e2e570
Some checks are pending
CI / Python packages / Build and verify distributions (push) Waiting to run
CI / Python quality / GitHub Actions (push) Waiting to run
CI / Python quality / Pre-commit (push) Waiting to run
CI / Python tests / Hermes embedded - ubuntu-latest (push) Waiting to run
CI / Python tests / Hermes embedded - windows-latest (push) Waiting to run
CI / Python tests / Unit Tests - py3.11 (push) Waiting to run
CI / Python tests / Unit Tests - py3.12 (push) Waiting to run
CI / Python tests / Unit Tests - py3.13 (push) Waiting to run
CI / Python tests / Unit Tests - py3.14 (push) Waiting to run
CI / ReMe Studio / Studio checks (push) Waiting to run
CI / Windows / CLI smoke - py3.11 (push) Waiting to run
Deploy / Documentation / Build documentation (push) Waiting to run
Deploy / Documentation / deploy (push) Blocked by required conditions
Security / CodeQL / Analyze javascript-typescript (push) Waiting to run
Security / CodeQL / Analyze python (push) Waiting to run
feat!: split proactive runtimes and add Studio backend management (#776)
* refactor(proactive)!: separate runtime ownership and unify delivery

* refactor(proactive): finish runtime and Studio migration

* test(proactive): make scheduled skip coverage deterministic

* refactor(studio): unify navigation and notebook resource loading

* feat(studio): edit workspace documents and update proactive task names

* refactor(studio): simplify task settings and navigation

* feat(studio): secure and supervise backend settings

* feat(studio): unify workbench timelines and refine desktop updates

Use shared timeline panes for notebook, memory, and resources. Add Todo creation ordering, persist companion visibility, and align desktop update handling and release artifacts.

Recheck editor file versions at read and publication boundaries. Retry reminder detail requests from the resource view.

* fix(studio): support unsigned GitHub preview releases

* fix: verify container state and isolate proactive view errors

Mount private supervisor state in Docker smoke tests and verify token and settings persistence. Exercise Studio startup with a loopback-only model fixture, and exclude packaged desktop output from Docker contexts.

Keep Remy subscriptions and healthy tasks available when an individual task has an invalid workspace path or session history.

* fix(home): align candidate Docker context exclusions

* chore(deps): update openai-codex dependency to v0.172.0

- Bump openai-codex from version 0.169.0 to 0.172.0 in pyproject.toml
- Keep other dependencies unchanged
- Ensure compatibility with latest openai-codex features and fixes

* fix(daemon): discover parent dotenv and isolate listeners

Restore parent-directory environment discovery in workers while retaining system precedence. Partition the default supervisor profile and lock by the configured bind address and port.
2026-11-25 21:33:16 +08:00

350 lines
16 KiB
Python

"""Chat reminder scheduling and disposable-fork decisions over daily records."""
import asyncio
from collections import defaultdict
from contextlib import asynccontextmanager, nullcontext
from dataclasses import dataclass, field
from datetime import timedelta, timezone
from hashlib import sha256
from uuid import uuid4
from ....schema.response import JOB_ERROR_METADATA_KEY
from ....constants import CHAT_AGENT_NAME, PROACTIVE_MESSAGE_ID_PREFIX
from ....schema.proactive_runtime import NotificationConfig
from ....schema.agent_session import SessionMessage
from ....utils.async_utils import finish_cleanup
_INBOX_SEPARATOR = "\n\n"
@dataclass
class InboxTurn:
"""One disposable fork's tools and explicit delivery decision."""
session_id: str
priority: str
msg_ids: tuple[str, ...]
chat_revision: int = 0
session_revision: str | None = None
session_turn_id: str | None = None
active_delivery: bool = False
id: str = field(default_factory=lambda: uuid4().hex)
items: list[dict] | None = None
content: str | None = None
message: SessionMessage | None = None
done: bool = False
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
@property
def message_id(self):
"""Keep retries of the same batch idempotent."""
value = "\0".join((self.session_id, *sorted(self.msg_ids)))
return "reminder-" + sha256(value.encode()).hexdigest()
class ChatNotifications:
"""Coordinate Chat wakeups while daily records hold reminders and acknowledgements."""
def __init__(self, manager, config: NotificationConfig):
self.manager = manager
self.config = config
self.lock = asyncio.Lock()
self.last_activity_at = self.manager.now()
self.worker = None
self.retry_at = None
self.active_turn: InboxTurn | None = None
self.chat_revision = 0
self.error = None
self.failures = 0
self.blocked = False
self.last_started_at = None
self.last_completed_at = None
self._reported_oversized: set[str] = set()
def reset(self):
"""Restart idle and retry timers after owned work has stopped."""
self.last_activity_at = self.manager.now()
self.retry_at = self.error = None
self.failures = 0
self.blocked = False
@property
def pending(self):
"""Project unread reminders without duplicating queue state."""
return {ref for ref, entry in self.manager.outbox.entries.items() if entry.reminder.read_at is None}
@property
def read_refs(self):
"""Keep the same bounded reference horizon as the inbox component."""
return set(self.manager.outbox.processed_refs())
def activity(self):
"""Restart idle timing after every foreground or internally requested Chat turn."""
self.last_activity_at = self.manager.now()
def foreground(self):
"""Invalidate an older reminder decision as soon as a user turn is queued."""
self.chat_revision += 1
async def consume(self, msg_ids):
"""Acknowledge the messages covered by a committed decision."""
async with self.lock:
await self._consume(msg_ids, self.manager.outbox.update)
async def _consume(self, msg_ids, update):
identifiers = dict.fromkeys(msg_ids)
if identifiers.keys() - (self.read_refs | self.pending):
raise ValueError("unknown inbox message ID")
async def save():
for identifier in identifiers:
await update(identifier, read_at=self.manager.now())
await finish_cleanup(save())
@staticmethod
def _inbox_item(item):
return f"### {item['from_agent_name']} · {item['delivered_at']}\n\n{item['message']}\n\n`{item['id']}`"
def _bounded(self, refs):
"""Bound one inference batch using the configured inbox count and byte budgets."""
inbox = self.manager.inbox
limit = min(20, inbox.claim_max_items, inbox.max_read_items, inbox.max_pending_items)
byte_limit = min(inbox.claim_max_bytes, inbox.max_pending_bytes)
separator_size = len(_INBOX_SEPARATOR.encode("utf-8"))
remaining = byte_limit + separator_size # The first item has no separator before it.
selected = []
for ref in refs:
if len(selected) >= limit:
break
size = len(self._inbox_item(self.manager.outbox.message(ref)).encode("utf-8"))
if size > byte_limit:
if ref not in self._reported_oversized:
self._reported_oversized.add(ref)
self.manager.logger.warning(
f"Chat reminder {ref} remains pending: content is {size} bytes "
f"and does not fit the {byte_limit}-byte batch limit",
)
continue
if size + separator_size > remaining:
break
selected.append(ref)
remaining -= size + separator_size
return tuple(selected)
@asynccontextmanager
async def turn(self, session_id, priority, msg_ids):
"""Own one in-memory batch; canonical acknowledgements survive cancellation and restart."""
async with self.lock:
if self.active_turn is not None:
raise RuntimeError("an inbox fork is already running")
pending = self.pending
refs = [
identifier
for identifier in dict.fromkeys(msg_ids)
if identifier in pending and self.manager.outbox.entries[identifier].reminder.priority == priority
]
selected = self._bounded(refs)
if not selected:
raise ValueError("no pending messages at the selected priority")
turn = InboxTurn(session_id, priority, selected, chat_revision=self.chat_revision)
self.active_turn = turn
try:
snapshot = await self.manager.agent_wrapper.read_session(session_id)
turn.session_revision = snapshot.revision
turn.session_turn_id = snapshot.last_turn_id
turn.active_delivery = priority == "P0" and snapshot.state.status == "active"
messages = {message.id: message for message in snapshot.messages if message.role == "assistant"}
recovered = {}
for identifier in selected:
entry = self.manager.outbox.entries.get(identifier)
if entry is None:
continue
for message_id in entry.reminder.chat_message_ids:
if message_id in messages:
recovered[identifier] = messages[message_id]
break
if recovered:
# Native acceptance is the durable decision; finish only its source acknowledgements.
await finish_cleanup(self.consume(list(recovered)))
remaining = tuple(identifier for identifier in selected if identifier not in recovered)
if remaining:
turn.msg_ids = remaining
else:
turn.message = recovered[selected[0]]
turn.content, turn.done = turn.message.content, True
yield turn
finally:
self.active_turn = None
def current_turn(self, identifier):
"""Reject foreground calls and capabilities left over from a finished fork."""
if self.active_turn is None or identifier != self.active_turn.id:
raise ValueError("inbox tools require an active reminder fork")
return self.active_turn
async def read_turn(self, turn):
"""Snapshot this wakeup's batch and render it for the reminder prompt."""
async with turn.lock:
self.current_turn(turn.id)
if turn.items is None:
outbox = self.manager.outbox
await outbox.refresh()
async with self.lock:
refs = sorted(self.pending.intersection(turn.msg_ids), key=outbox.order)
turn.msg_ids = self._bounded(
ref for ref in refs if outbox.entries[ref].reminder.priority == turn.priority
)
turn.items = [outbox.message(ref) for ref in turn.msg_ids]
return _INBOX_SEPARATOR.join(self._inbox_item(item) for item in turn.items)
async def send(self, turn, content):
"""Commit the explicit text or silence, then consume only what the fork read."""
content = content.strip()
async with turn.lock:
self.current_turn(turn.id)
if turn.items is None:
raise ValueError("inbox batch must be prepared before submitting a reminder decision")
if content and not turn.items:
raise ValueError("no reminders were read")
if turn.content is not None and content != turn.content:
raise ValueError("the reminder decision has already been submitted")
turn.content = content
if not turn.done:
async with nullcontext() if turn.active_delivery else self.manager.chat_lock:
current = await self.manager.sessions.current(CHAT_AGENT_NAME)
if self.manager.closed or current is None or current.session_id != turn.session_id:
raise RuntimeError("Chat session changed; retry the reminders in the current conversation")
if self.chat_revision != turn.chat_revision:
raise RuntimeError("Chat conversation changed; reassess reminders after the latest user turn")
await self.manager.outbox.refresh()
async def commit(update):
if content and turn.message is None:
message_id = turn.message_id
for item in turn.items:
await update(
item["id"],
chat_message_ids=[f"{PROACTIVE_MESSAGE_ID_PREFIX}{message_id}"],
)
turn.message = await self.manager.agent_wrapper.append_session(
turn.session_id,
content,
message_id=message_id,
role="assistant",
expected_turn_id=(turn.session_turn_id if turn.active_delivery else None),
expected_revision=(None if turn.active_delivery else turn.session_revision),
delivery=("immediate" if turn.priority == "P0" else "idle"),
)
current = await self.manager.sessions.current(CHAT_AGENT_NAME)
if (
current is None
or current.session_id != turn.session_id
or self.chat_revision != turn.chat_revision
):
raise RuntimeError("Chat conversation changed during delivery; reassess reminders")
await self._consume([item["id"] for item in turn.items], update)
turn.done = True
guard = (
self.manager.agent_wrapper.session_guard(
turn.session_id,
expected_revision=turn.session_revision,
)
if not content
else nullcontext()
)
async with (
guard,
self.lock,
self.manager.outbox.decision(turn.items) as update,
):
agents = await asyncio.to_thread(self.manager.registry.load)
pending = self.pending
if not all(
item["id"] in pending and self.manager.outbox.allows(item["id"], agents, self.manager.now())
for item in turn.items
):
raise RuntimeError("reminders are no longer eligible for delivery")
await finish_cleanup(commit(update))
return {
"sent": bool(content),
"message_id": turn.message.id if turn.message else None,
}
async def tick(self, run_job):
"""Coalesce eligible messages into one lifecycle-owned Chat wakeup."""
if self.worker is not None or self.manager.closed:
return
if self.blocked:
return
now = self.manager.now()
if self.retry_at is not None and now.timestamp() < self.retry_at.timestamp():
return
agents = await asyncio.to_thread(self.manager.registry.load)
async with self.lock:
if self.worker is not None or self.manager.closed:
return
idle = max(0, now.timestamp() - self.last_activity_at.timestamp())
busy = bool(self.manager.chat_tasks) or self.manager.chat_lock.locked()
pending = self.pending
self._reported_oversized.intersection_update(pending)
candidates = defaultdict(list)
for ref in pending:
item = self.manager.outbox.entries[ref].reminder
if not self.manager.outbox.allows(ref, agents, now):
continue
if item.priority == "P0":
if now.timestamp() - item.delivered_at.timestamp() < self.config.p0_delay_seconds:
continue
elif busy or idle < getattr(self.config, f"{item.priority.lower()}_idle_seconds"):
continue
candidates[item.priority].append(ref)
for priority, refs in sorted(candidates.items()):
refs.sort(key=self.manager.outbox.order)
identifiers = self._bounded(refs)
if not identifiers:
continue
self.worker = asyncio.create_task(
self._wake(run_job, priority, identifiers),
name="inbox:chat",
)
break
async def _wake(self, run_job, priority, identifiers):
permanent = False
self.last_started_at = self.manager.now()
try:
response = await run_job("process_chat_reminders", priority=priority, msg_ids=identifiers)
if not response.success:
failure = response.metadata.get(JOB_ERROR_METADATA_KEY, {})
permanent = failure.get("type") in {"TypeError", "ImportError", "ModuleNotFoundError"}
raise RuntimeError(str(response.answer))
if isinstance(response.answer, dict) and response.answer.get("skipped"):
if response.answer["skipped"] == "busy":
now = self.manager.now().astimezone(timezone.utc)
self.retry_at = now + timedelta(seconds=self.manager.retry_seconds)
return
self.retry_at = self.error = None
self.failures = 0
self.last_completed_at = self.manager.now()
except Exception as exc:
self.error = (str(exc).strip() or type(exc).__name__)[:2000]
self.failures += 1
self.blocked = permanent or isinstance(exc, (TypeError, ImportError))
delay = min(300, max(1, self.manager.retry_seconds) * 2 ** min(self.failures - 1, 8))
self.retry_at = (
None if self.blocked else self.manager.now().astimezone(timezone.utc) + timedelta(seconds=delay)
)
recovery = "repair the environment and restart" if self.blocked else f"retry in {delay:g}s"
self.manager.logger.error(f"Inbox wakeup failed ({recovery}): {self.error}")
finally:
self.worker = None
async def close(self):
"""Cancel the owned wakeup before closing shared agent infrastructure."""
if self.worker is not None:
task = self.worker
task.cancel()
await finish_cleanup(asyncio.gather(task, return_exceptions=True))
self.worker = None