Skip to content

feat(agents): 已记录会话可恢复、导出、看子代理,文件夹分类与搜索片段由 Core 给出 - #262

Merged
xiaoyumuxi merged 1 commit into
mainfrom
feat/agent-session-resume
Dec 3, 2026
Merged

xiaoyumuxi merged 1 commit into
mainfrom
feat/agent-session-resume

Conversation

@xiaoyumuxi

Copy link
Copy Markdown
Contributor

关联

改动

本 PR 的改动都是 API-45 agents 能力 0 内的补充,不升版本,对 Agent 的会话文件都只读。没有新增插件可调用的宿主方法或通知;scan、read 仍是普通 JSON 函数,四个 SDK 没有类型或版本变化。

一、恢复命令

  • 清单 agents[].terminal 新增可选 resumeArguments:1–64 个参数,至少含一次 ${sessionID},不得有别的 ${。安装审查列出的终端程序会带上这个模板。
  • 新宿主命令 agentSessions.resume {agent, sessionID, toolPath, shell?},回答 {pluginID, agentID, sessionID, executable, arguments, shell, cwd?, commandLine?}。
    • commandLine 按 posix 或 powershell 转义,可直接复制;不指定时随宿主平台。转义实现在 lithe-platform 新增的 shell.rs。
    • 会话 ID 只接受字母、数字、.、_、:、-,不以 - 开头,最长 256 字节。
    • 需要 agents.run。宿主用已有的终端形式运行,不新增执行通道。
  • agentSessions.list 的会话新增 resumable。
  • 新错误码 agentSessions.unknownSession、runNotGranted、toolNotFound、noResume、unsafeResume。

二、导出为 Markdown

  • 新宿主命令 agentSessions.export {agent, sessionID, labels, maxBytes?, keep?, utcOffsetSeconds?},回答 {changed, markdown, messages, truncated}。
  • 内容:导出用户消息、回复、每次工具调用一行和时间,不含思考和工具输出。
  • 大小:maxBytes 4 KiB–4 MiB,默认 1 MiB;keep 取 start 或 end;源文件最多读 64 MiB。
  • 文字:导出里的文字全部来自必填的 labels(13 个:untitled、agent、session、directory、started、lastActive、timeZone、user、assistant、tool、failed、earlierOmitted、laterOmitted),由宿主按界面语言传入,Core 不带任何默认文字。
    • 每个标签 1–256 字节,不能为空白,不能含控制字符。
    • 缺少、多出或不合法的标签都以新错误码 agentSessions.invalidExport 拒绝。
  • 结构:Core 只写 Markdown 结构、会话原文、时间、ID 和路径;UTC±hh:mm 是技术写法,保留不变。

三、子代理

  • scan 请求新增可选 threads: true。只有收到它时,后端才可以在回答里带 threads,每项为 {sessionID, threadID, parentThreadID?, kind?, startedAtMs?, updatedAtMs?, titleRange?}。
  • 新宿主命令 agentSessions.subagents {agent, sessionID}:合并线程描述和带 threadID 的调用,回答每个子代理的调用行与用量汇总。插件不报告时回答空列表。

四、其他文件夹

  • agentSessions.list 的 groups 新增 category(root、temporary、hidden),按路径形式套用 macOS、Linux、Windows 的规则(agent-sessions/src/folders.rs)。
  • 三个平台共用一份用例:rust/fixtures/agents/folder-categories-v1.json。

五、搜索片段

  • agentSessions.search 新增可选 snippets: true,命中会带两个字段:
    • snippet:从第一个命中词前 36 个字符到其后 120 个字符,截断处加 …。
    • snippetMatches:片段内的 UTF-8 字节区间;多个词都标出,不分大小写,重叠或相接的区间合并。
  • 匹配规则与搜索索引相同。
  • 单个命中超过 256 KiB、或一次搜索累计超过 4 MiB 时不给片段,也不报错。

六、一个错误码只对应一个数字码

  • agentSessions.unknownAgent 只在一处生成,固定配 entry_not_found。
  • read、page、resume、export、subagents 都走这一处。此前 agent 键拆不开时,read 回答 invalid_request,page 回答 agentSessions.invalidPage。

七、日志

agent-runtime 里原来用 let _ = 丢掉的四处错误改为正常记录,没有新增豁免:

  • log_fields 写日志被拒时,改为和 core、git、debug、lsp-engine 一样调用 note_dropped(),下次取日志时会报告丢了一条。
  • 新事件 agent.session.cleanup_failed(warn):Core 停不掉 Agent CLI、它可能还在运行时记录。启动失败和会话结束两条路径都会记(后者原来只把 agent.session.finished 的 reason 记成 failed)。字段为 plugin、agent、session 和脱敏后的错误(带 Core 错误码),不带参数或 CLI 输出。
  • agents/didExit 通知发不出去时记 agent.interaction.failed,因为后端收不到通知会一直把会话当成在运行。
  • 新事件 agent.records.rate_limits_save_failed(warn):额度快照写入或换名失败时记录,只带步骤(write、rename)和文件系统错误类别,不带路径。

八、文档

对宿主的影响

  • 宿主每次调用 agentSessions.export 都必须带 labels,词条放在 shared/i18n。
  • 会话页接入恢复、导出、子代理、文件夹分类和搜索片段,在 1lck/Lithe-IDEA 另开 PR,并把 PINNED_CORE_REVISION 升到本 PR 的合入提交。
  • 插件要补的内容在 Lithe-IDEA/lithe-ai-plugins 另做,不由本 PR 发布:Codex、Claude Code 声明 resumeArguments,并在 scan 里报告 threads。

验证

本机 macOS arm64,基于 main e8ffcf7:

  • cargo test --locked -p lithe-plugin-agents -p lithe-platform -p lithe-agent-sessions -p lithe-agent-runtime -p lithe-diagnostics -p lithe-core:全部通过(agent-runtime 119、agent-sessions 64、core 975 等)。
  • cargo fmt --all -- --check,cargo clippy --locked --workspace --all-targets -- -D warnings:通过。
  • Windows 目标:LIBSQLITE3_SYS_USE_PKG_CONFIG=1 cargo clippy --all-targets --target x86_64-pc-windows-msvc 对 platform、agent-sessions、agent-runtime、plugin-agents、diagnostics 通过。lithe-core 经插件市场依赖 zstd-sys,本机没有 Windows C 头文件,交叉编译不了,留给 CI。
  • node shared/plugins/scripts/verify-docs.mjs、node shared/plugins/scripts/sdk-e2e.mjs(4 passed)、node scripts/logging/generate-log-events.mjs --check、scripts/rust-core/verify-rust-core-comments.sh、node scripts/rust-core/verify-platform-tests.mjs:通过。
  • 新测试:
    • 恢复命令的模板校验、两种转义、拒绝不安全的会话 ID;
    • 导出用中文标签逐字节比对完整输出,并覆盖每种标签拒绝;
    • 子代理的合并与空列表;
    • 三个平台的文件夹分类共享用例;
    • 片段的截取、多词区间与上限;
    • 五个命令对未知 Agent 都回答同一个数字码;
    • 启动失败和会话结束时停不掉的 CLI 会记日志,正常停掉的不记;
    • 退出通知发不出去时记日志;
    • 额度快照存不下来时记日志,内存里的额度照常返回。

@xiaoyumuxi
xiaoyumuxi force-pushed the feat/agent-session-resume branch from ea3d965 to 31def84 Compare December 3, 2026 12:07
@xiaoyumuxi
xiaoyumuxi marked this pull request as ready for review December 3, 2026 12:07
@xiaoyumuxi
xiaoyumuxi merged commit 3351f74 into main Dec 3, 2026
7 of 11 checks passed

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 6 potential issues.

Devin Review

Comment on lines +183 to +189
let read_batch = |bytes: &[u8]| -> Result<Vec<ReadMessage>, CoreError> {
let item = json!({ "path": session.path, "lines": text_lines(bytes) });
let answer = call_read(&*runtime.link, &agent, source, "messages", vec![item], true)?;
decode_messages(answer.into_iter().next().unwrap_or_else(|| json!({})), true)
};
let Some((messages, unread)) =
self.read_messages(&session, request.keep, max_bytes, read_batch)?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Exports mix sessions sharing a file

When several sessions share a file, read_batch asks the backend for messages without identifying the selected session. The Markdown can contain another conversation under the selected session’s title.

Learn more

The cache associates each session ID with a source file, and a rebuild fixture stores multiple session IDs in one file. find_session selects the cache row, not a session-specific reading range. Export walks that row’s file and the read request contains only its path and lines. The backend has no selected session ID to filter by.

Example: One log contains a prompt for session A followed by a prompt for session B. Exporting A with enough space prints both prompts under A’s title.

Recommended fix: Add a session-scoped backend read contract or use complete, verified session-specific ranges. Refuse ambiguous shared-file exports when the backend cannot scope the response. Test two sessions in the same source file.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +454 to +455
} else if message.tool_name.is_none() {
parts.push(cut(&message.text, MAX_TOOL_SUMMARY_BYTES));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tool output included in exports

When a tool result has no name, title, or command, tool_summary prints the first line of its output. Result records can carry just the call ID and output.

Suggested change
} else if message.tool_name.is_none() {
parts.push(cut(&message.text, MAX_TOOL_SUMMARY_BYTES));
}

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +242 to +243
if estimate >= max_bytes || read >= MAX_EXPORT_SOURCE_BYTES {
return Ok(Some((windows.into_iter().flatten().collect(), true)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Mirrored records truncate exports early

read_messages counts mirrors and tool status updates against the byte budget before folding them. It can omit messages that fit after duplicates are removed.

Learn more

Export reads a window and counts the estimated size of every decoded record. estimated_size counts each mirrored reply in full and charges each tool record separately. fold removes the duplicates only after reading stops. The unused space cannot bring back any unread messages.

Example: A 4 KiB export finds two copies of a 2 KiB reply near the start, followed by enough tool output to put the next short prompt outside the first read window. It stops after the first window and omits the next prompt, even though the Markdown would fit both messages once the mirrored reply is folded.

Recommended fix: Account for the rendered size of unique, exportable blocks before stopping on the Markdown budget. Keep the independent source-byte cap and test mirror and tool-call records across window boundaries.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

let directory = quote_word(directory, platform)?;
Some(match platform {
Platform::Unix => format!("cd {directory} && {run}"),
Platform::Windows => format!("Set-Location -LiteralPath {directory}; {run}"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 PowerShell resume uses the wrong directory

When the recorded folder has moved, command_line still launches the CLI after Set-Location fails. The CLI runs in the terminal’s current directory instead.

Learn more

resume uses the recorded working directory to generate the copyable command. PowerShell normally reports a missing location as a non-terminating error. A semicolon does not make the next command depend on that location change.

Example: A session recorded in C:\Projects\OldName is resumed after the project is renamed. Pasting the command from a terminal open in C:\Scratch still runs the agent there.

Recommended fix: Gate the call operator explicitly on a successful Set-Location, with compatibility for Windows PowerShell 5.1. Add a platform test that checks both an existing location and a missing one.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +419 to +421
let text = message.text.trim();
if text.is_empty() {
return None;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Export strips leading code indentation

When a message starts with indented code, block removes its first line’s indentation. Markdown can render that line as prose instead of code.

Suggested change
let text = message.text.trim();
if text.is_empty() {
return None;
let text = &message.text;
if text.trim().is_empty() {
return None;

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +129 to +135
let ranges = match_ranges(&characters, &terms);
if let Some(&[at, end]) = ranges.first() {
let start = at.saturating_sub(SNIPPET_BEFORE_CHARS);
let end = end
.saturating_add(SNIPPET_AFTER_CHARS)
.min(characters.len());
return Some(cut_snippet(&characters, start, end, &ranges));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Adjacent matches defeat snippet bounds

When matches touch across a long run of text, snippet measures its cutoff from the end of the merged range. The result includes the entire run instead of stopping 120 characters after the first match.

Learn more

Search snippets use the first match to choose the excerpt, then merge touching and overlapping highlights for display. match_ranges currently merges before the excerpt is chosen, so a chain of matches loses its first match boundary.

Example: Searching for 哈 in a message containing a long uninterrupted run of 哈 highlights the entire run. The snippet includes every character in the run instead of at most 120 characters after the first one.

Recommended fix: Retain the first individual match separately or defer merging until after selecting and clipping the excerpt. Test a continuous run that exceeds the excerpt length.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant