ReMe/reme/components/agent_wrapper/cc_session_history.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

145 lines
6.1 KiB
Python

"""Display projection of Claude's full transcript, including pre-compaction history."""
from typing import Callable
from ...enumeration import ChunkEnum
from ...schema import SessionMessage, StreamChunk
from .cc_sessions import AppendRecord, SessionData, SessionRuntime, native_id
def text_content(content) -> str:
"""Keep text independent from thinking, tool results and native metadata."""
if isinstance(content, str):
return content
return "".join(block.get("text", "") for block in content or [] if block.get("type") == "text")
def accepted_message(entry: dict, record: AppendRecord) -> SessionMessage:
"""Native history must agree with the stored intent before it can be published."""
content = text_content((entry.get("message") or {}).get("content"))
expected = record.message.content
prefixed = f"[MESSAGE FROM NON-USER SOURCE - NOT USER INPUT]\n{expected}"
if entry.get("type") != record.message.role or content not in (expected, prefixed):
raise ValueError("Claude native message differs from its append record")
return record.message.model_copy(deep=True)
def last_turn_id(entries: list[dict], data: SessionData | None = None) -> str | None:
"""Recover an ordinary prompt anchor from existing native-only sessions."""
injected = {record.native_id for record in data.appends} if data else set()
return next(
(
entry.get("uuid")
for entry in reversed(entries)
if entry.get("type") == "user"
and entry.get("uuid") not in injected
and not (entry.get("isMeta") or entry.get("isSidechain") or entry.get("isCompactSummary"))
and text_content((entry.get("message") or {}).get("content"))
),
None,
)
def messages(session_id: str, entries: list[dict], data: SessionData, convert: Callable) -> list[SessionMessage]:
"""Group model blocks by API message ID, associating tool results with their calls."""
from claude_agent_sdk._internal.message_parser import parse_message
records = {record.native_id: record for record in data.appends}
hidden = {
*data.hidden_ids,
native_id(session_id, "seed"),
*(native_id(session_id, f"flush:{key}") for key in records),
}
result: list[SessionMessage] = []
grouped: dict[str, SessionMessage] = {}
tools: dict[str, SessionMessage] = {}
offsets: dict[str, int] = {}
seen = set()
turn_id = None
for entry in entries:
role, identifier = entry.get("type"), entry.get("uuid")
if role not in {"user", "assistant"} or entry.get("isSidechain"):
continue
if not identifier or identifier in hidden or identifier in seen:
continue
seen.add(identifier)
if identifier in records:
result.append(accepted_message(entry, records[identifier]))
continue
raw = entry.get("message") or {}
if raw.get("model") == "<synthetic>" or entry.get("isCompactSummary") or entry.get("isMeta"):
continue
model_message = parse_message({**entry, "session_id": session_id})
message_id = raw.get("id") or identifier
chunks = convert(
model_message,
session_id=session_id,
include_text=role == "assistant",
message_id=message_id,
block_offset=offsets.get(message_id, 0),
)
if chunks:
chunks[0].metadata["native"] = entry
elif role == "assistant" and raw.get("content"):
chunks = [StreamChunk(chunk_type=ChunkEnum.DATA, event="end", chunk=raw, metadata={"native": entry})]
content = text_content(raw.get("content"))
if role == "user":
for chunk in chunks:
owner = tools.get(chunk.tool_call_id)
if owner is not None:
chunk.turn_id = owner.turn_id
owner.chunks.append(chunk)
if not content:
continue
turn_id = identifier
result.append(
SessionMessage(
id=identifier,
role="user",
content=content,
created_at=entry.get("timestamp"),
turn_id=turn_id,
),
)
continue
message = grouped.get(message_id)
if message is None:
message = SessionMessage(
id=message_id,
role="assistant",
content="",
created_at=entry.get("timestamp"),
turn_id=turn_id,
)
grouped[message_id] = message
result.append(message)
message.content += content
message.chunks.extend(chunks)
offsets[message_id] = offsets.get(message_id, 0) + len(raw.get("content", []))
for chunk in chunks:
chunk.turn_id = turn_id
if chunk.tool_call_id:
tools[chunk.tool_call_id] = message
return result
def overlay_live(history: list[SessionMessage], runtime: SessionRuntime) -> None:
"""Expose detached partial output while the native writer is still generating."""
if runtime.input is not None and not any(message.id == runtime.input.id for message in history):
history.append(runtime.input.model_copy(deep=True))
if not runtime.chunks:
return
identifier = runtime.chunks[0].message_id
message = next((item for item in history if item.id == identifier and item.role == "assistant"), None)
if message is None:
message = SessionMessage(id=identifier, role="assistant", content="", completed=False)
history.append(message)
message.turn_id = runtime.input.turn_id if runtime.input is not None else None
message.completed = False
message.chunks = [chunk.model_copy(deep=True) for chunk in runtime.chunks]
blocks: dict[str | None, str] = {}
for chunk in message.chunks:
if chunk.chunk_type == ChunkEnum.CONTENT and isinstance(chunk.chunk, str):
key = chunk.block_id
blocks[key] = blocks.get(key, "") + chunk.chunk if chunk.event == "delta" else chunk.chunk
message.content = "".join(blocks.values())