Skip to content

armgit / Wake

Public Imported from GitHub
0

All your AI agent sessions in one place — browse, search, resume. Rust + GPUI.

Rust

feat(kilo): index Kilo Code sessions from kilo.db and legacy extension tasks (#59)

Corey Chiu0981a99691f5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 876592d..a940630 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,10 @@
# Changelog
+## [Unreleased]
+
+- New: Kilo Code sessions are indexed — from the database the VS Code extension, the `kilo` CLI and the JetBrains plugin share (`~/.local/share/kilo/kilo.db`, read-only), and from the legacy extension's task folders in VS Code and other VS Code-based editors. Titles, models, thinking, tool calls and token counts included; legacy sub-tasks are listed under the task that started them, and a legacy task the new extension has imported is listed once. Open In continues a session with `kilo --session` in its project directory (legacy tasks have no Open In). On remote hosts only the legacy tasks are mirrored, since `kilo.db` also holds Kilo's credentials (#59, thanks @ICEY4040727)
+- Fix: OpenCode sessions show the slash command that started a sub-agent instead of an empty message, and on Windows they are grouped under the same project as other agents' sessions
+
## [0.8.6] — 2026-10-01
- Fix: Remote sync on Windows now accepts local cache paths with drive letters, avoiding the "source and destination cannot both be remote" error before any files transfer (#56, thanks @zhyg).
diff --git a/Cargo.lock b/Cargo.lock
index 3d3f875..7e822c1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -7776,6 +7776,7 @@ dependencies = [
"rusqlite",
"serde",
"serde_json",
+ "sha1_smol",
"sha2 0.10.9",
"tempfile",
"trash",
diff --git a/PRODUCT.md b/PRODUCT.md
index 1fbe282..965f461 100644
--- a/PRODUCT.md
+++ b/PRODUCT.md
@@ -28,9 +28,9 @@ Corey 本人(独立开发者,主力工具 Claude Code 与 Codex,中文为主)。
## Capabilities and Constraints
-已实现:二十一家 adapter、FTS5 trigram 搜索(<3 码点 LIKE 降级)、**搜索跳转定位**(2026-08-18:⌘K 命中直达详情页对应消息并高亮,seq 契约保证)、详情页逐消息渲染(气泡/工具折叠簇/thinking/tree-sitter 高亮;2026-08-17 由整篇 markdown 方案升级)、恢复/收藏/置顶/导出/删除(废纸篓+墓碑)、文件监听增量、Insights 统计页(0.3.0:活跃热力图与 streak、时段/星期/月份分布、Agents·Projects·Models 三榜单按 sessions/tokens/prompts 切换;2026-09-03 加 Last 7 days 周对比行与 Over time 近 53 周按 agent 堆叠的每周 prompts 趋势图;口径=主线用户消息,规格见 DESIGN.md)、Updates 页与 macOS Wake 菜单手动检查 GitHub 最新正式版并打开 Release 页更新(不后台联网、不自动替换应用包)、测试套件(adapter 契约、DB 往返、scanner 回归 + CI 三平台 + pre-commit,合成 fixture)、三端桌面(macOS 主平台;Linux/Windows experimental,终端恢复/废纸篓·回收站/剪贴板按平台原生实现,发版 CI 自动出六产物)、窗口记忆(0.3.6:记住所在屏幕/屏内位置/最大化/全屏,重启与 Dock 重开都回到原处,Settings 开在主窗所在屏)、完整 macOS 菜单栏(0.3.6:标准 Edit/Window 菜单、⌘W、Window → Main Window,主窗关闭后 About/Settings/Updates 仍可用)、导出 Markdown 与保存图片走系统「另存为」并记住上次目录(0.3.6,issue #25)、远程 host(0.4.0,issue #21:Settings → Remote hosts 配 SSH 目标,rsync 白名单镜像会话数据到本地缓存后与本地会话同列同搜,`@host` 徽章标识;阶段 1 只读——不动远端文件、远程会话禁删,resume 以 Copy SSH command 形态提供;分期计划见 CLAUDE.md「远程 host」节)、**MCP 接入**(0.5.0:随应用打包的只读 `wake-mcp` stdio server,四个工具 wake_search / wake_list_sessions / wake_get_session / wake_list_projects,Claude Code / Codex / Cursor 等任何 MCP 客户端可搜历史、按项目列会话、分页读转录;Settings → Connect 展示路径与可复制配置片段,只展示不代写别家配置;零 LLM、零网络、不写库;完整参考 docs/mcp.md)、**命令行与 Skill**(0.6.0:并排打包的只读 `wake-cli`,四个子命令 search / sessions / show / projects 加 setup,给"能跑 shell 但不说 MCP"的 agent 和真人用——它不新写查询逻辑,argv 翻成 JSON 喂同一批工具,输出与 MCP 客户端看到的**逐字节相同**(仅 CLI 末尾补一个换行)并由测试卡住,所以文档只需描述一份格式;`skills/wake/SKILL.md` 是可一行安装的 skill(`npx skills add iAmCorey/Wake`),用触发条件而非名词解释写 description,让 agent 自己想得起来去翻会话历史;完整参考 docs/cli.md;0.6.3 加 `wake-cli index`——装了 Wake 却从没启动过时,agent 自己跑一条就能把索引建起来继续干活,而不是停下来问人。它**只建不存在的索引**,已有的库原样交给 GUI:扫描落在旁边的临时库、扫完才原子占位,所以被中途杀掉可重试、撞上 GUI 首扫就退让;2026-09-22 加 `wake-cli refresh`,issue #43:app 不开时增量刷新已有索引,给靠 MCP / CLI 用 Wake、只在浏览时开 app 的人用 launch agent / systemd timer 定时跑,Wake 开着窗或还有扫描在写就退让——GUI 与两个写命令共用一把索引写锁,锁跟 Workbench 与写线程走、关窗即放,GUI 启动会等正在跑的 refresh 收尾)、Connect 页四区块(0.6.1:MCP server / MCP clients / Command line / Skill,每个面的第一块挂自己的文档链接)、**记忆可见层**(2026-09-17 起,只读:把各家 agent 自己写下的记忆——Claude Code 的按项目 auto-memory、Codex 的 memories 与逐会话摘要、ZCode 的按项目记忆——按项目聚合;GUI 的 Memory 页是侧栏底部的整页目的地,侧栏在这一页换成按记忆计数的 All Memory / Agents / Projects 导航;MCP 加第五个工具 `wake_list_memories`,`wake_get_session` 认 `wake://memory/…` 引用现场读文件,`wake_search` 末尾附记忆命中;CLI 加 `memories`;记忆的项目归属按它挂的会话在读时解析,永远跟着索引走。二期(2026-09-21)把用户写给 agent 的指令文件也收进来:各家 home 里的 CLAUDE.md / AGENTS.md(与 `rules/*.rules`)/ GEMINI.md,以及已索引项目根下的 CLAUDE.md / AGENTS.md / GEMINI.md / `.cursor/rules` / `.cursorrules` / `.kiro/steering` / `.github/copilot-instructions.md`,与记忆同列同搜、不另作区分;Settings 加 Memory locations 页,与 Session locations 同形制:逐来源开关、添加自定义目录或文件、Restore defaults。不编辑、不同步、不删除——写别家数据破铁律,要改一个 Reveal 就到;也不做"把会话自动写成记忆")。后续边界(2026-09-07 定):摘要层(需 LLM、opt-in、明示会把会话正文发给用户配置的端点)只在 MCP 接入有真实使用之后再做;Timeline / Profile 一类视图建立在摘要之上;不做 ChatGPT / Claude.ai 导出导入主线、不做实体本体与知识图谱、不做 Chrome 扩展注入。
+已实现:二十二家 adapter、FTS5 trigram 搜索(<3 码点 LIKE 降级)、**搜索跳转定位**(2026-08-18:⌘K 命中直达详情页对应消息并高亮,seq 契约保证)、详情页逐消息渲染(气泡/工具折叠簇/thinking/tree-sitter 高亮;2026-08-17 由整篇 markdown 方案升级)、恢复/收藏/置顶/导出/删除(废纸篓+墓碑)、文件监听增量、Insights 统计页(0.3.0:活跃热力图与 streak、时段/星期/月份分布、Agents·Projects·Models 三榜单按 sessions/tokens/prompts 切换;2026-09-03 加 Last 7 days 周对比行与 Over time 近 53 周按 agent 堆叠的每周 prompts 趋势图;口径=主线用户消息,规格见 DESIGN.md)、Updates 页与 macOS Wake 菜单手动检查 GitHub 最新正式版并打开 Release 页更新(不后台联网、不自动替换应用包)、测试套件(adapter 契约、DB 往返、scanner 回归 + CI 三平台 + pre-commit,合成 fixture)、三端桌面(macOS 主平台;Linux/Windows experimental,终端恢复/废纸篓·回收站/剪贴板按平台原生实现,发版 CI 自动出六产物)、窗口记忆(0.3.6:记住所在屏幕/屏内位置/最大化/全屏,重启与 Dock 重开都回到原处,Settings 开在主窗所在屏)、完整 macOS 菜单栏(0.3.6:标准 Edit/Window 菜单、⌘W、Window → Main Window,主窗关闭后 About/Settings/Updates 仍可用)、导出 Markdown 与保存图片走系统「另存为」并记住上次目录(0.3.6,issue #25)、远程 host(0.4.0,issue #21:Settings → Remote hosts 配 SSH 目标,rsync 白名单镜像会话数据到本地缓存后与本地会话同列同搜,`@host` 徽章标识;阶段 1 只读——不动远端文件、远程会话禁删,resume 以 Copy SSH command 形态提供;分期计划见 CLAUDE.md「远程 host」节)、**MCP 接入**(0.5.0:随应用打包的只读 `wake-mcp` stdio server,四个工具 wake_search / wake_list_sessions / wake_get_session / wake_list_projects,Claude Code / Codex / Cursor 等任何 MCP 客户端可搜历史、按项目列会话、分页读转录;Settings → Connect 展示路径与可复制配置片段,只展示不代写别家配置;零 LLM、零网络、不写库;完整参考 docs/mcp.md)、**命令行与 Skill**(0.6.0:并排打包的只读 `wake-cli`,四个子命令 search / sessions / show / projects 加 setup,给"能跑 shell 但不说 MCP"的 agent 和真人用——它不新写查询逻辑,argv 翻成 JSON 喂同一批工具,输出与 MCP 客户端看到的**逐字节相同**(仅 CLI 末尾补一个换行)并由测试卡住,所以文档只需描述一份格式;`skills/wake/SKILL.md` 是可一行安装的 skill(`npx skills add iAmCorey/Wake`),用触发条件而非名词解释写 description,让 agent 自己想得起来去翻会话历史;完整参考 docs/cli.md;0.6.3 加 `wake-cli index`——装了 Wake 却从没启动过时,agent 自己跑一条就能把索引建起来继续干活,而不是停下来问人。它**只建不存在的索引**,已有的库原样交给 GUI:扫描落在旁边的临时库、扫完才原子占位,所以被中途杀掉可重试、撞上 GUI 首扫就退让;2026-09-22 加 `wake-cli refresh`,issue #43:app 不开时增量刷新已有索引,给靠 MCP / CLI 用 Wake、只在浏览时开 app 的人用 launch agent / systemd timer 定时跑,Wake 开着窗或还有扫描在写就退让——GUI 与两个写命令共用一把索引写锁,锁跟 Workbench 与写线程走、关窗即放,GUI 启动会等正在跑的 refresh 收尾)、Connect 页四区块(0.6.1:MCP server / MCP clients / Command line / Skill,每个面的第一块挂自己的文档链接)、**记忆可见层**(2026-09-17 起,只读:把各家 agent 自己写下的记忆——Claude Code 的按项目 auto-memory、Codex 的 memories 与逐会话摘要、ZCode 的按项目记忆——按项目聚合;GUI 的 Memory 页是侧栏底部的整页目的地,侧栏在这一页换成按记忆计数的 All Memory / Agents / Projects 导航;MCP 加第五个工具 `wake_list_memories`,`wake_get_session` 认 `wake://memory/…` 引用现场读文件,`wake_search` 末尾附记忆命中;CLI 加 `memories`;记忆的项目归属按它挂的会话在读时解析,永远跟着索引走。二期(2026-09-21)把用户写给 agent 的指令文件也收进来:各家 home 里的 CLAUDE.md / AGENTS.md(与 `rules/*.rules`)/ GEMINI.md,以及已索引项目根下的 CLAUDE.md / AGENTS.md / GEMINI.md / `.cursor/rules` / `.cursorrules` / `.kiro/steering` / `.github/copilot-instructions.md`,与记忆同列同搜、不另作区分;Settings 加 Memory locations 页,与 Session locations 同形制:逐来源开关、添加自定义目录或文件、Restore defaults。不编辑、不同步、不删除——写别家数据破铁律,要改一个 Reveal 就到;也不做"把会话自动写成记忆")。后续边界(2026-09-07 定):摘要层(需 LLM、opt-in、明示会把会话正文发给用户配置的端点)只在 MCP 接入有真实使用之后再做;Timeline / Profile 一类视图建立在摘要之上;不做 ChatGPT / Claude.ai 导出导入主线、不做实体本体与知识图谱、不做 Chrome 扩展注入。
约束:对 agent 数据目录只读;绝不写 Codex 的 SQLite;不读凭证;GPUI 无 SF Symbols(图标用 lucide SVG 自备)。
-已支持二十一家 agent:Claude Code、Codex(0.6.6 起排除可识别的内部线程:guardian auto-review、`/review`、compaction、memory consolidation 与用户会话同树,adapter 文件边界按首行 session_meta 的 source / thread_source 认出即不枚举;老格式或读不出的首行保守放行,`codex exec --thread-source` 打了标签的自动化线程照常收录,issue #30。`spawn_agent` 子代理是其中唯一的例外,issue #42:那是用户自己派出去的活,收录后挂在派它的会话下面、以任务名为标题,fork 进来的父线程历史折成一条不入库的占位,父会话的对话不会被索引两遍)、Qoder CLI(`~/.qoder/projects` JSONL,active-leaf 分支恢复、tool result 回挂、`QODER_CONFIG_DIR`)、Copilot CLI、Cursor(CLI 转录 + 0.6.7 起 IDE Chat/Composer 历史,PR #32:`globalStorage/state.vscdb` 明文 KV 库,composerData 给顺序、bubbleId 行给正文;转录带正文的会话归转录源,库只补转录缺失或只剩 turn_ended 空壳的会话;库里多数老会话没存工作区路径,落 Unknown project)、OpenCode(含 OpenCode 2 next,stable 的 `opencode.db` 与 next 的 `opencode-next.db` 同时扫描;逐会话兼容 `message+part`、真实 `session+session_message` 及早期 `session_v2` schema;preview 会话标 opencode2 徽章)、Kiro、Gemini CLI(2026-08-17 P1 五家落地)+ Pi、Oh My Pi、Grok Build、Kimi Code、Antigravity CLI(2026-08-19 对齐 kooky 内置 roster;Antigravity 正文加密仅元数据卡片)+ DeepSeek Harness(dsh,2026-08-20,zstd 事件日志透明解压;格式由源码推断,当天用户跑出真实会话完成首验)+ Hermes Agent(2026-09-03,多档案 state.db,无 cwd 故 project 留空)、OpenClaw(2026-09-03,两代存储同扫;本机零会话,格式由源码推断未经真机验证)、CodeBuddy(2026-09-14,issue #27:`~/.codebuddy/projects` 的 Responses 形 JSONL,custom / ai / topic 三级标题,`CODEBUDDY_CONFIG_DIR`;本机零会话,格式由官方 CLI 文档与三家第三方实现交叉推断、未经真机验证)、WorkBuddy(同日,CodeBuddy 的孪生实例:同一解析核心,`~/.workbuddy/projects`、`WORKBUDDY_CONFIG_DIR`;桌面 app 无 CLI,不提供 resume;同构只有 cc-switch 一家佐证)、ZCode(2026-09-21:Z.ai 的 GLM-5.3 官方 harness,桌面 app;运行时是 OpenCode 衍生物——`~/.zcode/cli/db/db.sqlite` 的 session/message/part 与 OpenCode v1 同形、part 解码复用,但 session 表没有 model/tokens 列故另起一家;`v2/tasks-index.sqlite` 只借 deleted / migration_source 两个过滤位;按 `task_type` 白名单只列 interactive / fork / selection_side_chat(subagent_child 等运行时会话不列);`semantics.transcriptVisibility == hidden` 与用户消息 `origin != real_user` 归 Meta、compact_summary 折成一条、字段缺席放行;`ZCODE_STORAGE_DIR`;桌面 app 无 CLI、`zcode://` 没有按会话打开的深链,不提供 resume;本机 3.14.0 真会话首验通过,同日开源(Apache-2.0)后语义全部按源码核对)、Craft Agents(2026-09-24,issue #44:Craft Docs 的开源桌面 app,自己不带引擎——Anthropic 连接跑 Claude Agent SDK、其余连接(ChatGPT / Codex 订阅、Copilot、Google)跑 Pi SDK,另记一份给用户看的 `~/.craft-agent/workspaces/<工作区>/sessions/<id>/session.jsonl`,Wake 读这一份;子任务与分支挂回原会话,分支从父会话复制来的那段折成一条;Claude 连接在 `~/.claude/projects` 留下的引擎副本由通用的"认领"机制藏掉,原件还在才藏;工作区可建在任意位置,但登记表带 server token 不读,别处的工作区走 Session locations;桌面 app 无 CLI,不提供 resume;本机 0.13.5 真会话首验通过,ChatGPT 与 Claude 连接各一条)、Devin(2026-09-24,issue #46:`~/.local/share/devin/cli/sessions.db` 单库两表,message_nodes 森林按 `main_chain_id` 叶子沿 `parent_node_id` 取主链,hidden 会话与零正文不列,逐消息 `generation_model` 与 `metrics` 按主链累计;`XDG_DATA_HOME`;`devin --resume <id>` 按 cwd 分桶 resume;格式按本机真库验证)。做不了的:Windsurf/Trae 加密,Amp/Factory(Droid)/Warp 云端无本地数据,Reasonix 本机零会话格式未实测。
+已支持二十二家 agent:Claude Code、Codex(0.6.6 起排除可识别的内部线程:guardian auto-review、`/review`、compaction、memory consolidation 与用户会话同树,adapter 文件边界按首行 session_meta 的 source / thread_source 认出即不枚举;老格式或读不出的首行保守放行,`codex exec --thread-source` 打了标签的自动化线程照常收录,issue #30。`spawn_agent` 子代理是其中唯一的例外,issue #42:那是用户自己派出去的活,收录后挂在派它的会话下面、以任务名为标题,fork 进来的父线程历史折成一条不入库的占位,父会话的对话不会被索引两遍)、Qoder CLI(`~/.qoder/projects` JSONL,active-leaf 分支恢复、tool result 回挂、`QODER_CONFIG_DIR`)、Copilot CLI、Cursor(CLI 转录 + 0.6.7 起 IDE Chat/Composer 历史,PR #32:`globalStorage/state.vscdb` 明文 KV 库,composerData 给顺序、bubbleId 行给正文;转录带正文的会话归转录源,库只补转录缺失或只剩 turn_ended 空壳的会话;库里多数老会话没存工作区路径,落 Unknown project)、OpenCode(含 OpenCode 2 next,stable 的 `opencode.db` 与 next 的 `opencode-next.db` 同时扫描;逐会话兼容 `message+part`、真实 `session+session_message` 及早期 `session_v2` schema;preview 会话标 opencode2 徽章)、Kiro、Gemini CLI(2026-08-17 P1 五家落地)+ Pi、Oh My Pi、Grok Build、Kimi Code、Antigravity CLI(2026-08-19 对齐 kooky 内置 roster;Antigravity 正文加密仅元数据卡片)+ DeepSeek Harness(dsh,2026-08-20,zstd 事件日志透明解压;格式由源码推断,当天用户跑出真实会话完成首验)+ Hermes Agent(2026-09-03,多档案 state.db,无 cwd 故 project 留空)、OpenClaw(2026-09-03,两代存储同扫;本机零会话,格式由源码推断未经真机验证)、CodeBuddy(2026-09-14,issue #27:`~/.codebuddy/projects` 的 Responses 形 JSONL,custom / ai / topic 三级标题,`CODEBUDDY_CONFIG_DIR`;本机零会话,格式由官方 CLI 文档与三家第三方实现交叉推断、未经真机验证)、WorkBuddy(同日,CodeBuddy 的孪生实例:同一解析核心,`~/.workbuddy/projects`、`WORKBUDDY_CONFIG_DIR`;桌面 app 无 CLI,不提供 resume;同构只有 cc-switch 一家佐证)、ZCode(2026-09-21:Z.ai 的 GLM-5.3 官方 harness,桌面 app;运行时是 OpenCode 衍生物——`~/.zcode/cli/db/db.sqlite` 的 session/message/part 与 OpenCode v1 同形、part 解码复用,但 session 表没有 model/tokens 列故另起一家;`v2/tasks-index.sqlite` 只借 deleted / migration_source 两个过滤位;按 `task_type` 白名单只列 interactive / fork / selection_side_chat(subagent_child 等运行时会话不列);`semantics.transcriptVisibility == hidden` 与用户消息 `origin != real_user` 归 Meta、compact_summary 折成一条、字段缺席放行;`ZCODE_STORAGE_DIR`;桌面 app 无 CLI、`zcode://` 没有按会话打开的深链,不提供 resume;本机 3.14.0 真会话首验通过,同日开源(Apache-2.0)后语义全部按源码核对)、Craft Agents(2026-09-24,issue #44:Craft Docs 的开源桌面 app,自己不带引擎——Anthropic 连接跑 Claude Agent SDK、其余连接(ChatGPT / Codex 订阅、Copilot、Google)跑 Pi SDK,另记一份给用户看的 `~/.craft-agent/workspaces/<工作区>/sessions/<id>/session.jsonl`,Wake 读这一份;子任务与分支挂回原会话,分支从父会话复制来的那段折成一条;Claude 连接在 `~/.claude/projects` 留下的引擎副本由通用的"认领"机制藏掉,原件还在才藏;工作区可建在任意位置,但登记表带 server token 不读,别处的工作区走 Session locations;桌面 app 无 CLI,不提供 resume;本机 0.13.5 真会话首验通过,ChatGPT 与 Claude 连接各一条)、Devin(2026-09-24,issue #46:`~/.local/share/devin/cli/sessions.db` 单库两表,message_nodes 森林按 `main_chain_id` 叶子沿 `parent_node_id` 取主链,hidden 会话与零正文不列,逐消息 `generation_model` 与 `metrics` 按主链累计;`XDG_DATA_HOME`;`devin --resume <id>` 按 cwd 分桶 resume;格式按本机真库验证)、Kilo Code(2026-10-07,issue #59:一家两源——2026-04 起的新版 VS Code 扩展、`kilo` CLI 与 JetBrains 插件是 OpenCode 分支,三端共用 `~/.local/share/kilo/kilo.db`,表与 OpenCode 同形、按 OpenCode 的孪生实例读;session_message 里只有实验开关零星双写的 shell 一类记录时读 message + part(OpenCode 同一条规则);旧版扩展(Roo / Cline 系)每个任务一个目录,在各个 VS Code 系编辑器的 `globalStorage/kilocode.kilo-code/tasks` 里,正文是 Anthropic 消息数组,`<task>` / `<feedback>` / `<answer>` 才是人打的字、编辑器快照丢掉,旧任务用新版导入时给的 `ses_migrated_` id,导入过的那份 kilo.db 胜出;新版 `kilo --session` 在原项目目录续,旧任务没有 Open In、也不实时监听(任务目录里有整份 checkpoints 影子仓库);kilo.db 里同库存着凭证,远程只同步 vscode-server 下的旧任务;本机零会话,新版的表结构按源码的建库语句核过,数据形状由源码推断、未经真机验证)。做不了的:Windsurf/Trae 加密,Amp/Factory(Droid)/Warp 云端无本地数据,Reasonix 本机零会话格式未实测。
## Brand Commitments
diff --git a/README.md b/README.md
index 5b426aa..6d79256 100644
--- a/README.md
+++ b/README.md
@@ -53,8 +53,9 @@ Your agent history is scattered across `~/.claude`, `~/.codex`, and a dozen othe
| ZCode | `~/.zcode/cli/db/db.sqlite` + `v2/tasks-index.sqlite` (read-only; `ZCODE_STORAGE_DIR` is respected; desktop app, so no resume) | ✅ | — |
| Craft Agents | `~/.craft-agent/workspaces/*/sessions/*/session.jsonl` (workspaces kept elsewhere can be added under Session locations; desktop app, so no resume) | ✅ | ✅ |
| Devin | `~/.local/share/devin/cli/sessions.db` (read-only; `XDG_DATA_HOME` is respected) | ✅ | — |
+| Kilo Code | `~/.local/share/kilo/kilo.db` (VS Code extension, CLI and JetBrains plugin share it; read-only; `XDG_DATA_HOME` and `KILO_DB` are respected) + the legacy extension's `globalStorage/kilocode.kilo-code/tasks` in VS Code and other VS Code-based editors | ✅ | ✅ |
-**Model** = whether Wake shows which LLM a session used (the model the session last used). **Via** = whether Wake shows where the session was started from (CLI, IDE extension, desktop app) — Codex records this in its local data; Hermes and OpenClaw record the channel a session came in through (Telegram, Discord, …); Craft Agents marks sessions its automations started. A "—" means the agent's local data simply doesn't record that field, not a missing feature.
+**Model** = whether Wake shows which LLM a session used (the model the session last used). **Via** = whether Wake shows where the session was started from (CLI, IDE extension, desktop app) — Codex records this in its local data; Hermes and OpenClaw record the channel a session came in through (Telegram, Discord, …); Craft Agents marks sessions its automations started; Kilo Code's legacy tasks show which editor they ran in. A "—" means the agent's local data simply doesn't record that field, not a missing feature.
Craft Agents runs other agents' engines rather than its own: a Claude connection drives the Claude Agent SDK, which also saves every conversation into Claude Code's history. Wake lists the Craft session and hides that engine copy for as long as the Craft session exists — delete the session in Craft and the copy shows up again as a Claude Code session. Craft's short title-generation calls on a Claude connection are saved by the SDK too, and appear as one-message Claude Code sessions under *Unknown project*.
@@ -62,6 +63,8 @@ Codex writes its background threads — the guardian auto-review, `/review`, com
Cursor keeps two stores. A chat that has a full transcript under `~/.cursor/projects` is read from there; local workspace metadata and filesystem matching restore its project path, including spaces. Project metadata is refreshed on each scan even if the transcript is unchanged. Chats that only live in Cursor's own database — older ones, or Cursor versions that leave nothing but a `turn_ended` marker in the transcript — are read from `state.vscdb`. Older IDE chats that Cursor stored without a workspace show up under *Unknown project*.
+Kilo Code rebuilt its extension on the OpenCode engine in April 2026; the VS Code extension, the `kilo` CLI and the JetBrains plugin now share one database, and Open In continues a session with `kilo --session`. Tasks from the earlier extension (4.x/5.x) stay in each editor's `globalStorage`; Wake lists them too, without Open In since the new CLI can't continue them. A legacy task the new extension has imported is listed once, from the database. On remote hosts Wake mirrors only the legacy tasks (from `~/.vscode-server`): the new `kilo.db` also stores Kilo's API keys and login tokens, so it isn't copied.
+
Token statistics depend on the usage recorded by each agent. Qoder CLI transcripts that contain only zero token counts leave token usage unknown in Wake, even when they include Credits or a context usage ratio. Those values measure different things and are not converted into tokens; the sessions remain visible in the Sessions and Prompts views of Insights.
Windsurf and Trae encrypt their local data; Amp, Factory (Droid), and Warp keep sessions in the cloud — none of those are supported. Reasonix stores sessions locally but hasn't been mapped yet.
diff --git a/crates/wake-core/Cargo.toml b/crates/wake-core/Cargo.toml
index 00df417..9c85b44 100644
--- a/crates/wake-core/Cargo.toml
+++ b/crates/wake-core/Cargo.toml
@@ -16,6 +16,9 @@ chrono.workspace = true
zstd.workspace = true
base64.workspace = true
sha2 = "0.10"
+# Kilo Code 旧任务导入新版时的会话 id 是 sha1(任务 id)(adapters/kilo.rs);
+# uuid 已经把它带进了工作区,不是新下载
+sha1_smol = "1"
# Linux 废纸篓:freedesktop Trash spec 的纯库实现
# (macOS 走 Finder/osascript,行为已验证不动)
diff --git a/crates/wake-core/src/adapters/cursor_ide.rs b/crates/wake-core/src/adapters/cursor_ide.rs
index 618d4e6..d44d798 100644
--- a/crates/wake-core/src/adapters/cursor_ide.rs
+++ b/crates/wake-core/src/adapters/cursor_ide.rs
@@ -47,22 +47,11 @@ pub struct CursorIdeAdapter {
links_cache: MtimeCache<Vec<(String, String)>>,
}
-/// `globalStorage/state.vscdb` 的默认路径。VS Code 系三平台的用户数据根不同:
-/// macOS 在 `~/Library/Application Support`,Windows 在 `%APPDATA%`,
-/// Linux 在 `$XDG_CONFIG_HOME`(缺省 `~/.config`)。这里只做路径推导、
-/// 不探测存在性——缺根由 list_session_files 降级为空(roster 契约)。
-/// 三平台都从 `home_dir()` 派生而非 `dirs::config_dir()`:后者在 Windows 上
-/// 走 SHGetKnownFolderPath,`WAKE_HOME` 改道对它无效(见 mod.rs 的 home_dir)
+/// `globalStorage/state.vscdb` 的默认路径(用户数据目录三平台各异,见
+/// `vscode_user_data`)。只做路径推导、不探测存在性——缺根由 list_session_files
+/// 降级为空(roster 契约)
pub(super) fn default_db_path() -> PathBuf {
- let home = super::home_dir().unwrap_or_default();
- let base = if cfg!(target_os = "macos") {
- home.join("Library").join("Application Support")
- } else if cfg!(target_os = "windows") {
- home.join("AppData").join("Roaming")
- } else {
- super::env_dir("XDG_CONFIG_HOME").unwrap_or_else(|| home.join(".config"))
- };
- base.join("Cursor")
+ super::vscode_user_data("Cursor")
.join("User")
.join("globalStorage")
.join(DB_NAME)
diff --git a/crates/wake-core/src/adapters/kilo.rs b/crates/wake-core/src/adapters/kilo.rs
new file mode 100644
index 0000000..e3bacc4
--- /dev/null
+++ b/crates/wake-core/src/adapters/kilo.rs
@@ -0,0 +1,1160 @@
+//! Kilo Code 一家两个数据源:
+//!
+//! - **新版**(2026-04 起 VS Code 扩展、CLI 与 JetBrains 插件共用的 OpenCode 分支):
+//! `~/.local/share/kilo/kilo.db`,由 `opencode::OpencodeAdapter::kilo()` 读——表与
+//! OpenCode 同形。
+//! - **旧版扩展**(v4.x / v5.x,Roo Code / Cline 一系):每个任务一个目录
+//! `<编辑器用户数据>/User/globalStorage/kilocode.kilo-code/tasks/<taskId>/`,正文是
+//! `api_conversation_history.json`(Anthropic 消息数组),本文件的 `KiloLegacyAdapter`。
+//! 扩展可以装在任何 VS Code 系编辑器里,所以默认根按编辑器各一条。
+//!
+//! 同一段对话在两边的身份:新版扩展把旧任务导进 kilo.db 时,会话 id 定成
+//! `ses_migrated_` + sha1(任务 id) 的前 26 位(kilo-vscode 的
+//! legacy-migration/sessions/lib/ids.ts)。旧任务在 Wake 里直接用这个 id——导过的那份
+//! 与 kilo.db 里的同 key,交 scanner 的副本裁决(本源 `dedup_rank` 1,kilo.db 胜出,
+//! 本源留作解析失败的回退);没导过的照常列出,日后导了 key 也不变,收藏与置顶跟着走。
+//!
+//! 正文的读法照 Kilo 自己的导入器(legacy-migration/sessions/lib/parts):`<task>` 里才是
+//! 用户的任务、`<environment_details>` 是每轮附带的编辑器快照(丢掉)、`attempt_completion`
+//! 的 result 是最终答复;此外把 tool_result 回挂到发起它的工具调用上(导入器挂在用户消息
+//! 里),工具结果里夹带的用户回复(`<feedback>` / `<answer>`)单独成一条用户消息——工具
+//! 输出不进全文索引,不拆出来这些话就搜不到。
+
+use super::parse_utils::*;
+use super::sqlite_ro::open_sqlite_ro;
+use super::AgentAdapter;
+use crate::models::*;
+use anyhow::{anyhow, Context as _, Result};
+use rusqlite::OptionalExtension;
+use serde_json::Value;
+use std::borrow::Cow;
+use std::collections::HashMap;
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+/// 扩展 id:globalStorage 下的目录名,也是 state.vscdb 里 globalState 的 key
+const EXTENSION_ID: &str = "kilocode.kilo-code";
+const API_FILE: &str = "api_conversation_history.json";
+/// 较新的旧版逐任务写的元数据(标题 / 工作区 / token / 父任务)
+const ITEM_FILE: &str = "history_item.json";
+/// Roo 后来把 taskHistory 从 globalState 挪到了这里(Kilo 的 Roo 导入器同样两处都认)
+const INDEX_FILE: &str = "_index.json";
+
+/// 可能装过旧版扩展的 VS Code 系编辑器:(用户数据目录名, 显示名)。用户数据根三平台
+/// 各异(`vscode_user_data`),目录名相同。显示名作 via 徽章
+const EDITORS: &[(&str, &str)] = &[
+ ("Code", "VS Code"),
+ ("Code - Insiders", "VS Code Insiders"),
+ ("VSCodium", "VSCodium"),
+ ("Cursor", "Cursor"),
+ ("Windsurf", "Windsurf"),
+ ("Trae", "Trae"),
+ ("Trae CN", "Trae CN"),
+ ("Kiro", "Kiro"),
+ ("Antigravity", "Antigravity"),
+ ("Void", "Void"),
+ ("Positron", "Positron"),
+ ("CodeBuddy", "CodeBuddy"),
+ ("Qoder", "Qoder"),
+];
+
+/// Remote-SSH 一类的服务端:用户数据在 `<home>/<目录>/data`(扩展装在远端时写在这里;
+/// Wake 跑在那台机器上时它就是本地数据)。远程同步只镜像得到 VS Code 那个(见
+/// remote::REMOTE_LAYOUTS,每家一个挂载点)
+const SERVERS: &[(&str, &str)] = &[
+ (".vscode-server", "VS Code"),
+ (".cursor-server", "Cursor"),
+ (".windsurf-server", "Windsurf"),
+];
+
+/// 新版扩展导入旧任务时给的会话 id(见文件头)。Wake 里旧任务的 native id 就是它
+pub fn migrated_session_id(task_id: &str) -> String {
+ let digest = sha1_smol::Sha1::from(task_id.as_bytes())
+ .digest()
+ .to_string();
+ format!("ses_migrated_{}", &digest[..26])
+}
+
+/// 旧任务在 Wake 里的会话 key
+pub fn legacy_task_key(task_id: &str) -> String {
+ session_key(AgentId::Kilo, "", &migrated_session_id(task_id))
+}
+
+/// 会话的胜出副本是不是旧版任务文件:旧任务没有能接着聊的 CLI(新版 `kilo --session`
+/// 只认 kilo.db 里的会话),Open In 据此不画
+pub fn is_legacy_task(file_path: &str) -> bool {
+ Path::new(file_path)
+ .file_name()
+ .is_some_and(|name| name == API_FILE)
+}
+
+/// 旧版扩展的任务目录:选中的就是它(`tasks`)、扩展目录、globalStorage、编辑器的 User
+/// 目录或用户数据根都认。目录名就是 tasks / 扩展 id 时只看名字——远程挂载点在同步落盘
+/// 之前就要定形;再往上几层看存在性
+fn legacy_tasks_dir(dir: &Path) -> Option<PathBuf> {
+ let name = dir.file_name()?.to_string_lossy();
+ if name.eq_ignore_ascii_case(EXTENSION_ID) {
+ return Some(dir.join("tasks"));
+ }
+ if name == "tasks" {
+ return Some(dir.to_path_buf());
+ }
+ [
+ PathBuf::from(EXTENSION_ID),
+ Path::new("globalStorage").join(EXTENSION_ID),
+ Path::new("User").join("globalStorage").join(EXTENSION_ID),
+ ]
+ .into_iter()
+ .map(|sub| dir.join(sub))
+ .find(|ext| ext.is_dir())
+ .map(|ext| ext.join("tasks"))
+}
+
+fn editor_tasks_dir(user_data: &Path) -> PathBuf {
+ user_data
+ .join("User")
+ .join("globalStorage")
+ .join(EXTENSION_ID)
+ .join("tasks")
+}
+
+/// 任务目录在哪个编辑器的用户数据里(`editor_tasks_dir` 的逆):默认根、自定义 location
+/// 与远程镜像都按它认出编辑器——远程 `~/.vscode-server` 下的任务照样标 VS Code。
+/// 认不出 = None
+fn editor_of(tasks: &Path) -> Option<&'static str> {
+ let user_data = tasks.ancestors().nth(4)?;
+ if tasks != editor_tasks_dir(user_data) {
+ return None;
+ }
+ let name = user_data.file_name()?.to_string_lossy();
+ if let Some((_, editor)) = EDITORS.iter().find(|(dir, _)| *dir == name) {
+ return Some(editor);
+ }
+ // 服务端的用户数据是 `<home>/.vscode-server/data`:名字在上一级
+ let server = user_data.parent()?.file_name()?.to_string_lossy();
+ SERVERS
+ .iter()
+ .find(|(dir, _)| name == "data" && *dir == server)
+ .map(|(_, editor)| *editor)
+}
+
+/// 旧版扩展的任务目录(见文件头)
+pub struct KiloLegacyAdapter {
+ roots: Vec<LegacyRoot>,
+}
+
+struct LegacyRoot {
+ /// `…/globalStorage/kilocode.kilo-code/tasks`
+ tasks: PathBuf,
+ /// 哪个编辑器的(via 徽章,`editor_of`);认不出(任意自定义目录)是 None
+ editor: Option<&'static str>,
+ /// taskHistory 索引(`_index.json` 与编辑器 state.vscdb 里的 globalState 合在一起),
+ /// 按两个文件的戳缓存。只给缺 history_item.json 的老任务补标题 / 工作区 / 父任务
+ index: MtimeCache<Arc<HashMap<String, Value>>>,
+}
+
+impl LegacyRoot {
+ fn new(tasks: PathBuf) -> Self {
+ Self {
+ editor: editor_of(&tasks),
+ tasks,
+ index: MtimeCache::new(),
+ }
+ }
+
+ /// globalState 所在的库:`tasks` 的上两级是 globalStorage。自定义 location 不是这个
+ /// 形状(或是远程缓存里没同步这个库)就没有
+ fn state_db(&self) -> Option<PathBuf> {
+ let ext = self.tasks.parent()?;
+ ext.file_name()?
+ .to_string_lossy()
+ .eq_ignore_ascii_case(EXTENSION_ID)
+ .then(|| ext.parent().map(|g| g.join("state.vscdb")))
+ .flatten()
+ }
+
+ /// 两处索引合在一起。**None 是"不知道"**:库在却从没读成功过(读失败时交上一次读好的,
+ /// 都不缓存、下轮再试)——父子关系的快照据此整份报 None,别把读失败当成关系解除
+ fn index(&self) -> Option<Arc<HashMap<String, Value>>> {
+ let index_file = self.tasks.join(INDEX_FILE);
+ let state_db = self.state_db();
+ let file_stamp = fs::metadata(&index_file).map(|m| mtime_ms(&m)).unwrap_or(0);
+ let db_stamp = state_db
+ .as_deref()
+ .map(super::sqlite_ro::db_cache_stamp)
+ .unwrap_or(0);
+ let stamp = file_stamp.wrapping_mul(1_000_003) ^ db_stamp;
+ let build = || {
+ // globalState 先进、_index.json 后进覆盖:Roo 把索引挪出 globalState 之后,
+ // 那边留下的是停在挪走那一刻的旧表
+ let mut map = match state_db.as_deref() {
+ Some(db) => read_global_state_history(db)?,
+ None => HashMap::new(),
+ };
+ map.extend(read_index_file(&index_file));
+ Some(Arc::new(map))
+ };
+ self.index.get_or_stale(stamp, build)
+ }
+
+ /// 任务的元数据:history_item.json(逐任务、最新的写端)优先,其次两处索引;索引不知道
+ /// 时展示退到只看 _index.json
+ fn history_item(&self, task_dir: &Path, task_id: &str) -> Option<Value> {
+ if let Some(item) = read_item_file(task_dir).ok().flatten() {
+ return Some(item);
+ }
+ match self.index() {
+ Some(index) => index.get(task_id).cloned(),
+ None => read_index_file(&self.tasks.join(INDEX_FILE)).remove(task_id),
+ }
+ }
+
+ /// 任务的会话引用。缺 history_item.json 的老任务,标题 / 工作区 / token 来自索引:把
+ /// 索引里那一条也算进 mtime / size,它变了(或索引从读不出变成读得出)才会重解析——
+ /// 只看两个索引文件的戳不行,任何编辑器写 state.vscdb 都会让所有老任务重来一遍
+ fn session_ref(
+ &self,
+ task_dir: &Path,
+ index: Option<&HashMap<String, Value>>,
+ ) -> Option<SessionFileRef> {
+ let (mut r, has_item) = task_ref(task_dir)?;
+ let task_id = task_dir.file_name()?.to_string_lossy();
+ if let Some(entry) = index
+ .filter(|_| !has_item)
+ .and_then(|i| i.get(task_id.as_ref()))
+ {
+ r.mtime_ms = r.mtime_ms.max(item_i64(Some(entry), "ts"));
+ r.size += entry.to_string().len() as i64;
+ }
+ Some(r)
+ }
+}
+
+/// `history_item.json`:不存在 / 写坏了都是 None;读不出(权限、I/O)才是 Err——父子关系
+/// 的快照要分清"没有"与"不知道"
+fn read_item_file(task_dir: &Path) -> std::io::Result<Option<Value>> {
+ match fs::read(task_dir.join(ITEM_FILE)) {
+ Ok(bytes) => Ok(serde_json::from_slice::<Value>(&bytes)
+ .ok()
+ .filter(Value::is_object)),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(e) => Err(e),
+ }
+}
+
+/// 索引里的条目按任务 id 收成表(整棵 JSON 交进来、条目搬出去,不逐条复制)
+fn index_entries(mut json: Value, key: &str) -> HashMap<String, Value> {
+ let Some(Value::Array(items)) = json.get_mut(key).map(Value::take) else {
+ return HashMap::new();
+ };
+ items
+ .into_iter()
+ .filter_map(|item| {
+ let id = item.get("id")?.as_str()?.to_string();
+ Some((id, item))
+ })
+ .collect()
+}
+
+fn read_index_file(path: &Path) -> HashMap<String, Value> {
+ fs::read(path)
+ .ok()
+ .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
+ .map(|json| index_entries(json, "entries"))
+ .unwrap_or_default()
+}
+
+/// 编辑器 `state.vscdb` 的 ItemTable 里,扩展的 globalState 整份 JSON 存在扩展 id 这个
+/// key 下,taskHistory 是其中一项。表或行不在 = 没有(Some 空);库打不开 / 读出错 = None
+fn read_global_state_history(db: &Path) -> Option<HashMap<String, Value>> {
+ if !db.is_file() {
+ return Some(HashMap::new());
+ }
+ let ro = open_sqlite_ro(db, "kilo-legacy-state")?;
+ let has_table: bool = ro
+ .conn
+ .query_row(
+ "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='ItemTable')",
+ [],
+ |r| r.get(0),
+ )
+ .ok()?;
+ if !has_table {
+ return Some(HashMap::new());
+ }
+ // key 是扩展声明的 id 原样(全小写);精确比较才走得上 key 的唯一索引——Cursor 的这个库
+ // 有几个 GB,按 NOCASE 比就是整表扫
+ let state: Option<Value> = ro
+ .conn
+ .query_row(
+ "SELECT value FROM ItemTable WHERE key = ?1",
+ [EXTENSION_ID],
+ |r| {
+ Ok(r.get_ref(0)?
+ .as_bytes()
+ .ok()
+ .and_then(|v| serde_json::from_slice(v).ok()))
+ },
+ )
+ .optional()
+ .ok()?
+ .flatten();
+ Some(
+ state
+ .map(|state| index_entries(state, "taskHistory"))
+ .unwrap_or_default(),
+ )
+}
+
+/// 任务目录 → (会话引用, 有没有 history_item.json)。没有正文文件、空数组(建了任务却
+/// 没发出去)的不算会话。mtime / size 把 history_item.json 也算进去:标题与 token 在那里变
+fn task_ref(task_dir: &Path) -> Option<(SessionFileRef, bool)> {
+ let task_id = task_dir.file_name()?.to_str()?;
+ if task_id.starts_with('.') {
+ return None;
+ }
+ let api = task_dir.join(API_FILE);
+ let meta = fs::metadata(&api).ok()?;
+ if !meta.is_file() || meta.len() <= 2 {
+ return None;
+ }
+ let item = fs::metadata(task_dir.join(ITEM_FILE))
+ .ok()
+ .filter(|m| m.is_file());
+ let r = SessionFileRef {
+ agent: AgentId::Kilo,
+ native_id: migrated_session_id(task_id),
+ file_path: api.to_string_lossy().to_string(),
+ mtime_ms: item.as_ref().map_or(0, mtime_ms).max(mtime_ms(&meta)),
+ size: (meta.len() + item.as_ref().map_or(0, |m| m.len())) as i64,
+ };
+ Some((r, item.is_some()))
+}
+
+impl KiloLegacyAdapter {
+ /// 默认根:VS Code 恒在(roster 契约:每个实例至少一条数据根;没装过旧版的人也只多
+ /// 这一行),其余编辑器与远程开发服务端构造时有扩展目录才收——旧版已停更,不会
+ /// 在 Wake 启动后才冒出来
+ pub fn new() -> Self {
+ let home = super::home_dir().unwrap_or_default();
+ let editors = EDITORS.iter().map(|(dir, _)| super::vscode_user_data(dir));
+ let servers = SERVERS.iter().map(|(dir, _)| home.join(dir).join("data"));
+ let roots = editors
+ .chain(servers)
+ .map(|user_data| editor_tasks_dir(&user_data))
+ .enumerate()
+ .filter(|(i, tasks)| *i == 0 || tasks.parent().is_some_and(Path::is_dir))
+ .map(|(_, tasks)| LegacyRoot::new(tasks))
+ .collect();
+ Self { roots }
+ }
+
+ /// 自定义 location 与远程挂载点(只有一条根)
+ fn at(tasks: PathBuf) -> Self {
+ Self {
+ roots: vec![LegacyRoot::new(tasks)],
+ }
+ }
+
+ fn root_for(&self, task_dir: &Path) -> Option<&LegacyRoot> {
+ let tasks = task_dir.parent()?;
+ self.roots.iter().find(|root| root.tasks == tasks)
+ }
+
+ fn parse(
+ &self,
+ r: &SessionFileRef,
+ decode_images: bool,
+ ) -> Result<(SessionMeta, Vec<TranscriptMessage>, u32)> {
+ let _image_budget = transcript_image_decode_budget(decode_images);
+ let api = Path::new(&r.file_path);
+ let task_dir = api
+ .parent()
+ .ok_or_else(|| anyhow!("kilo task file has no task directory"))?;
+ let task_id = task_dir
+ .file_name()
+ .map(|n| n.to_string_lossy().to_string())
+ .unwrap_or_default();
+ let root = self.root_for(task_dir);
+ let item = match root {
+ Some(root) => root.history_item(task_dir, &task_id),
+ None => read_item_file(task_dir).ok().flatten(),
+ };
+ let parsed = parse_api_history(api, decode_images)?;
+ let meta = build_meta(
+ r,
+ &task_id,
+ item.as_ref(),
+ &parsed,
+ root.and_then(|root| root.editor),
+ );
+ Ok((meta, parsed.messages, parsed.unknown))
+ }
+}
+
+fn item_i64(item: Option<&Value>, key: &str) -> i64 {
+ item.and_then(|v| v.get(key))
+ .and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f as i64)))
+ .unwrap_or(0)
+}
+
+/// 任务 id 里带的创建时刻:Cline 一系早年用 `Date.now()` 当 id,后来是 UUID v7
+/// (前 48 位就是毫秒时间戳)
+fn id_timestamp(task_id: &str) -> i64 {
+ if let Ok(n) = task_id.parse::<i64>() {
+ return if n > 1_000_000_000_000 { n } else { 0 };
+ }
+ let hex: String = task_id.chars().filter(|c| *c != '-').collect();
+ if hex.len() == 32 && hex.as_bytes()[12] == b'7' {
+ return i64::from_str_radix(&hex[..12], 16).unwrap_or(0);
+ }
+ 0
+}
+
+fn build_meta(
+ r: &SessionFileRef,
+ task_id: &str,
+ item: Option<&Value>,
+ parsed: &LegacyParse,
+ editor: Option<&'static str>,
+) -> SessionMeta {
+ let field = |key: &str| optional_string(item.and_then(|item| item.get(key)));
+ // VS Code 的 fsPath 在 Windows 上写小写盘符,统一成别家的写法
+ let project_path = field("workspace")
+ .or_else(|| parsed.env_cwd.clone())
+ .map(|p| canonical_project_path(&p))
+ .unwrap_or_default();
+ let title = field("task")
+ .map(|t| clean_title_candidate(&clean_task_text(&t)))
+ .filter(|t| !t.is_empty())
+ .or_else(|| title_from_messages(&parsed.messages))
+ .unwrap_or_else(|| UNTITLED.to_string());
+ let first = [id_timestamp(task_id), parsed.first_ts]
+ .into_iter()
+ .filter(|t| *t > 0)
+ .min()
+ .unwrap_or(0);
+ let last = parsed.last_ts.max(item_i64(item, "ts"));
+ // Claude 的口径:输入 + 输出 + 缓存写入(缓存读取不算新用量)
+ let tokens =
+ item_i64(item, "tokensIn") + item_i64(item, "tokensOut") + item_i64(item, "cacheWrites");
+ let message_count = parsed
+ .messages
+ .iter()
+ .filter(|m| m.kind == MessageKind::Text)
+ .count() as i64;
+ SessionMeta {
+ key: session_key(AgentId::Kilo, "", &r.native_id),
+ host: String::new(),
+ id: r.native_id.clone(),
+ agent: AgentId::Kilo,
+ title,
+ project_name: project_name_of(&project_path),
+ project_path,
+ file_path: r.file_path.clone(),
+ created_at: if first > 0 { first } else { r.mtime_ms },
+ updated_at: if last > 0 { last } else { r.mtime_ms },
+ message_count,
+ size_bytes: r.size,
+ git_branch: None,
+ model: None,
+ tokens_used: (tokens > 0).then_some(tokens),
+ archived: false,
+ source: editor.map(String::from),
+ favorite: false,
+ pinned: false,
+ }
+}
+
+// ---------------------------------------------------------------- 正文
+
+/// `<tag>…</tag>` 的内文(去首尾空白);没有或为空 = None
+fn tag_inner(text: &str, tag: &str) -> Option<String> {
+ extract_tag(text, tag)
+ .map(|s| s.trim().to_string())
+ .filter(|s| !s.is_empty())
+}
+
+/// 截掉每轮附带的 `<environment_details>` 及其后的内容(它总在消息末尾)
+fn strip_env_details(text: &str) -> &str {
+ text.find("<environment_details>")
+ .map_or(text, |i| &text[..i])
+ .trim()
+}
+
+/// 历史标题与首条任务同一种清洗:`<task>` 包着就取里面,纯编辑器快照算空
+fn clean_task_text(text: &str) -> String {
+ tag_inner(text, "task").unwrap_or_else(|| strip_env_details(text).to_string())
+}
+
+/// 编辑器快照里的工作区:Roo 写 `# Current Workspace Directory (/p) Files`,Cline 写
+/// `# Current Working Directory (/p) Files`。路径里可能有括号,按 `) Files` 收尾
+fn env_details_cwd(text: &str) -> Option<String> {
+ let env = extract_tag(text, "environment_details")?;
+ for marker in [
+ "# Current Workspace Directory (",
+ "# Current Working Directory (",
+ ] {
+ let Some(start) = env.find(marker).map(|i| i + marker.len()) else {
+ continue;
+ };
+ let rest = &env[start..];
+ let end = rest
+ .find(") Files")
+ .or_else(|| rest.find(")\n"))
+ .or_else(|| rest.find(')'))?;
+ let path = rest[..end].trim();
+ if !path.is_empty() {
+ return Some(path.to_string());
+ }
+ }
+ None
+}
+
+enum UserPiece {
+ /// 人说的话
+ Typed(String),
+ /// 给模型看的说明(报错提示、续跑提示),折叠
+ Meta(String),
+}
+
+/// 不在工具结果里的一段用户文本(已去掉编辑器快照)归哪边:包在标签里的(首条任务的
+/// `<task>`、续跑提示里的 `<user_message>` 等)取标签里的话,扩展塞的报错 / 续跑提示
+/// 折叠,其余就是人打的字。工具结果里的文本另由 `tool_result_reply` 认
+fn classify_user_text(body: &str) -> UserPiece {
+ for tag in ["task", "feedback", "answer", "user_message"] {
+ if let Some(inner) = tag_inner(body, tag) {
+ return UserPiece::Typed(inner);
+ }
+ }
+ let scaffolding = body.starts_with("[ERROR]")
+ || body.starts_with("[TASK RESUMPTION]")
+ || body.starts_with("<explicit_instructions");
+ if scaffolding {
+ UserPiece::Meta(body.to_string())
+ } else {
+ UserPiece::Typed(body.to_string())
+ }
+}
+
+/// XML 工具协议时代(原生工具调用之前)的工具结果抬头 `[read_file for 'a.ts'] Result:`:
+/// 返回工具名
+fn xml_tool_result_header(text: &str) -> Option<&str> {
+ let rest = text.strip_prefix('[')?;
+ let (head, tail) = rest.split_once(']')?;
+ if head.contains('\n') || !tail.starts_with(" Result:") {
+ return None;
+ }
+ head.split(' ').next()
+}
+
+/// 工具结果里夹带的、人说的话:反馈信封(扩展的原话都以 `The user …` 开头,话在
+/// `<feedback>` / `<user_message>` 里——批准或拒绝时附的、完成后给的反馈)与追问工具的
+/// 回答(`<answer>`)。读到的文件里恰好有这些标签不算,所以只认信封与工具
+fn tool_result_reply(text: &str, tool: Option<&str>) -> Option<String> {
+ // XML 时代抬头与正文可能在同一块
+ let body = text
+ .find("] Result:")
+ .filter(|_| xml_tool_result_header(text).is_some())
+ .map_or(text, |i| &text[i + "] Result:".len()..])
+ .trim_start();
+ if tool == Some("ask_followup_question") {
+ if let Some(answer) = tag_inner(body, "answer") {
+ return Some(answer);
+ }
+ }
+ if !body.starts_with("The user ") {
+ return None;
+ }
+ ["feedback", "user_message"]
+ .iter()
+ .find_map(|tag| tag_inner(body, tag))
+}
+
+/// 助手正文里的两种 XML 痕迹:`<thinking>` 挪进 thinking,`<attempt_completion>` 的
+/// `<result>` 换成它本身(最终答复)。其余 XML 工具调用原样留着——那就是模型当时写的
+fn split_assistant_text(text: &str, thinking: &mut Vec<String>) -> String {
+ let mut out = text.to_string();
+ while let Some(inner) = extract_tag(&out, "thinking") {
+ if !inner.trim().is_empty() {
+ thinking.push(inner.trim().to_string());
+ }
+ out = out.replacen(&format!("<thinking>{inner}</thinking>"), "", 1);
+ }
+ if let Some(block) = extract_tag(&out, "attempt_completion") {
+ if let Some(result) = tag_inner(&block, "result") {
+ out = out.replacen(
+ &format!("<attempt_completion>{block}</attempt_completion>"),
+ &result,
+ 1,
+ );
+ }
+ }
+ out.trim().to_string()
+}
+
+/// 模型的推理:Responses 式的独立 reasoning 条目(text 或 summary[])、个别 provider 放在
+/// 消息外的 reasoning_content / reasoning_details
+fn entry_reasoning(entry: &Value) -> Option<String> {
+ if entry.get("type").and_then(Value::as_str) == Some("reasoning") {
+ if let Some(text) = optional_string(entry.get("text")) {
+ return Some(text);
+ }
+ let summary = joined_texts(entry.get("summary"), &["text"]);
+ if !summary.is_empty() {
+ return Some(summary);
+ }
+ }
+ if let Some(text) = optional_string(entry.get("reasoning_content")) {
+ return Some(text);
+ }
+ let details = joined_texts(entry.get("reasoning_details"), &["text", "reasoning"]);
+ (!details.is_empty()).then_some(details)
+}
+
+fn joined_texts(items: Option<&Value>, keys: &[&str]) -> String {
+ items
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter_map(|item| keys.iter().find_map(|k| item.get(*k)?.as_str()))
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .collect::<Vec<_>>()
+ .join("\n")
+}
+
+/// 一条 API 消息的 content:字符串或块数组,统一成块(数组原地借用——内嵌图片的
+/// base64 动辄几 MB,别整块复制)
+fn content_blocks(entry: &Value) -> Cow<'_, [Value]> {
+ match entry.get("content") {
+ Some(Value::String(s)) => {
+ Cow::Owned(vec![serde_json::json!({ "type": "text", "text": s })])
+ }
+ Some(Value::Array(blocks)) => Cow::Borrowed(blocks.as_slice()),
+ _ => Cow::Owned(Vec::new()),
+ }
+}
+
+/// Responses 式的独立推理条目:只有推理、没有正文,先于它所属的回答落盘。Kilo 的类型声明
+/// 里它挂在 MessageParam 上,但 role 不保证有——不按 role 认
+fn is_reasoning_item(entry: &Value) -> bool {
+ entry.get("type").and_then(Value::as_str) == Some("reasoning") && entry.get("content").is_none()
+}
+
+/// `api_conversation_history.json` 的解析结果;逐条喂 `entry`,`finish` 收尾
+#[derive(Default)]
+struct LegacyParse {
+ messages: Vec<TranscriptMessage>,
+ unknown: u32,
+ first_ts: i64,
+ last_ts: i64,
+ /// 首条带编辑器快照的用户消息里写着的工作区(缺 history_item 时的项目路径)
+ env_cwd: Option<String>,
+ /// tool_use id → (消息下标, 工具下标);结果在下一条用户消息里
+ tool_index: HashMap<String, (usize, usize)>,
+ /// 独立的 reasoning 条目先于它所属的回答落盘,攒着并进下一条助手消息
+ pending_thinking: Vec<String>,
+}
+
+impl LegacyParse {
+ fn entry(&mut self, entry: &Value, decode_images: bool) {
+ if !entry.is_object() {
+ self.unknown += 1;
+ return;
+ }
+ let ts = entry.get("ts").and_then(Value::as_i64).unwrap_or(0);
+ if ts > 0 {
+ self.first_ts = if self.first_ts == 0 {
+ ts
+ } else {
+ self.first_ts.min(ts)
+ };
+ self.last_ts = self.last_ts.max(ts);
+ }
+ let flag = |key: &str| entry.get(key).and_then(Value::as_bool) == Some(true);
+ // 上下文压缩(condense)写下的摘要与截断标记;被摘要取代的原始消息还在
+ // (condenseParent),照常展示
+ if flag("isSummary") || flag("isTruncationMarker") {
+ let text = content_parts(entry.get("content").unwrap_or(&Value::Null), false).text;
+ if !text.is_empty() {
+ let mut m = meta_msg(&text, ts);
+ if flag("isSummary") {
+ m.kind = MessageKind::CompactSummary;
+ }
+ self.messages.push(m);
+ }
+ return;
+ }
+ if is_reasoning_item(entry) {
+ self.pending_thinking.extend(entry_reasoning(entry));
+ return;
+ }
+ match entry.get("role").and_then(Value::as_str) {
+ Some("assistant") => self.assistant(entry, ts, decode_images),
+ Some("user") => self.user(entry, ts, decode_images),
+ _ => self.unknown += 1,
+ }
+ }
+
+ fn assistant(&mut self, entry: &Value, ts: i64, decode_images: bool) {
+ let mut content = ParsedContent::default();
+ let mut thinking = std::mem::take(&mut self.pending_thinking);
+ thinking.extend(entry_reasoning(entry));
+ let mut tools = Vec::new();
+ for block in content_blocks(entry).iter() {
+ match block.get("type").and_then(Value::as_str) {
+ Some("text") => {
+ let text = block.get("text").and_then(Value::as_str).unwrap_or("");
+ content.push_text(&split_assistant_text(text, &mut thinking));
+ }
+ Some("thinking") | Some("reasoning") => {
+ thinking.extend(optional_string(
+ block.get("thinking").or_else(|| block.get("text")),
+ ));
+ }
+ Some("redacted_thinking") => {}
+ Some("tool_use") => {
+ let name = block.get("name").and_then(Value::as_str).unwrap_or("tool");
+ let input = block.get("input").cloned().unwrap_or(Value::Null);
+ // 最终答复以工具调用的形式交出来;Kilo 的导入器也把它当正文
+ let result = (name == "attempt_completion")
+ .then(|| optional_string(input.get("result")))
+ .flatten();
+ match result {
+ Some(result) => content.push_text(&result),
+ None => tools.push(tool_call_view(
+ optional_string(block.get("id")).unwrap_or_default(),
+ name,
+ &input,
+ None,
+ false,
+ )),
+ }
+ }
+ _ if is_image_part(block) => content.append(content_parts(block, decode_images)),
+ _ => self.unknown += 1,
+ }
+ }
+ self.push_assistant(content, thinking, tools, ts);
+ }
+
+ fn user(&mut self, entry: &Value, ts: i64, decode_images: bool) {
+ self.flush_thinking(ts);
+ let mut real = ParsedContent::default();
+ let mut meta: Vec<String> = Vec::new();
+ // XML 工具协议时代,一次工具结果拆成几块:先是 `[read_file for 'x'] Result:` 抬头,
+ // 内容在同一块或后面的块里——抬头之后都是结果本体(记下是哪个工具)
+ let mut tool: Option<String> = None;
+ for block in content_blocks(entry).iter() {
+ match block.get("type").and_then(Value::as_str) {
+ Some("text") => {
+ let text = block.get("text").and_then(Value::as_str).unwrap_or("");
+ if self.env_cwd.is_none() {
+ self.env_cwd = env_details_cwd(text);
+ }
+ let body = strip_env_details(text);
+ if body.is_empty() {
+ continue;
+ }
+ if let Some(name) = xml_tool_result_header(body) {
+ tool = Some(name.to_string());
+ }
+ if tool.is_some() {
+ match tool_result_reply(body, tool.as_deref()) {
+ Some(reply) => real.push_text(&reply),
+ None => meta.push(body.to_string()),
+ }
+ continue;
+ }
+ match classify_user_text(body) {
+ UserPiece::Typed(t) => real.push_text(&t),
+ UserPiece::Meta(t) => meta.push(t),
+ }
+ }
+ Some("tool_result") => self.tool_result(block, decode_images, &mut real),
+ _ if is_image_part(block) => real.append(content_parts(block, decode_images)),
+ _ => self.unknown += 1,
+ }
+ }
+ if !meta.is_empty() {
+ self.messages.push(meta_msg(&meta.join("\n\n"), ts));
+ }
+ if !real.text.is_empty() || !real.images.is_empty() {
+ let mut m = text_msg(Role::User, &real.text, ts);
+ m.images = real.images;
+ self.messages.push(m);
+ }
+ }
+
+ /// tool_result 回挂到发起它的工具调用上;结果里夹着的用户回复收进 `real`
+ fn tool_result(&mut self, block: &Value, decode_images: bool, real: &mut ParsedContent) {
+ let parsed = tool_result_parts(block.get("content").unwrap_or(&Value::Null), decode_images);
+ let target = block
+ .get("tool_use_id")
+ .and_then(Value::as_str)
+ .and_then(|id| self.tool_index.get(id))
+ .copied();
+ let tool = target.map(|(mi, ti)| self.messages[mi].tool_calls[ti].name.clone());
+ if let Some(reply) = tool_result_reply(&parsed.text, tool.as_deref()) {
+ real.push_text(&reply);
+ }
+ let Some((mi, ti)) = target else {
+ // 发起它的调用已经转成了正文(attempt_completion):用户随反馈附的图归用户消息。
+ // 按块取而不用 parsed.images——不解码时图片是 [image] 占位文字,两种解析都得
+ // 留下这条消息,seq 才对得上
+ for image in block
+ .get("content")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .filter(|v| is_image_part(v))
+ {
+ real.append(content_parts(image, decode_images));
+ }
+ return;
+ };
+ let message = &mut self.messages[mi];
+ message.tool_calls[ti].output = Some(clip(strip_env_details(&parsed.text), MAX_TOOL_IO).0);
+ if block.get("is_error").and_then(Value::as_bool) == Some(true) {
+ message.tool_calls[ti].is_error = true;
+ }
+ append_images_to_message_end(message, parsed.images);
+ }
+
+ fn push_assistant(
+ &mut self,
+ content: ParsedContent,
+ thinking: Vec<String>,
+ tools: Vec<ToolCallView>,
+ ts: i64,
+ ) {
+ if content.text.is_empty()
+ && content.images.is_empty()
+ && thinking.is_empty()
+ && tools.is_empty()
+ {
+ return;
+ }
+ let ParsedContent { text, images } = content;
+ let (text, truncated) = clip(&text, MAX_MSG_TEXT);
+ let ix = self.messages.len();
+ for (ti, tool) in tools.iter().enumerate() {
+ if !tool.id.is_empty() {
+ self.tool_index.insert(tool.id.clone(), (ix, ti));
+ }
+ }
+ self.messages.push(TranscriptMessage {
+ seq: 0,
+ role: Role::Assistant,
+ kind: MessageKind::Text,
+ text,
+ truncated,
+ tool_calls: tools,
+ thinking: (!thinking.is_empty()).then(|| clip(&thinking.join("\n\n"), MAX_TOOL_IO).0),
+ timestamp: (ts > 0).then_some(ts),
+ model: None,
+ images,
+ });
+ }
+
+ /// 攒着的推理后面没有回答了(下一条是用户消息,或到了末尾)就自成一条
+ fn flush_thinking(&mut self, ts: i64) {
+ if !self.pending_thinking.is_empty() {
+ let thinking = std::mem::take(&mut self.pending_thinking);
+ self.push_assistant(ParsedContent::default(), thinking, Vec::new(), ts);
+ }
+ }
+
+ fn finish(mut self) -> Self {
+ self.flush_thinking(self.last_ts);
+ assign_seq(&mut self.messages);
+ self
+ }
+}
+
+fn parse_api_history(path: &Path, decode_images: bool) -> Result<LegacyParse> {
+ let bytes = fs::read(path).with_context(|| format!("read {}", path.display()))?;
+ let json: Value =
+ serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display()))?;
+ let entries = json
+ .as_array()
+ .ok_or_else(|| anyhow!("kilo conversation history must be a JSON array"))?;
+ let mut parsed = LegacyParse::default();
+ for entry in entries {
+ parsed.entry(entry, decode_images);
+ }
+ Ok(parsed.finish())
+}
+
+impl AgentAdapter for KiloLegacyAdapter {
+ fn agent(&self) -> AgentId {
+ AgentId::Kilo
+ }
+
+ /// 与 kilo.db 里导入过的那份同 key(见文件头):kilo.db 先、本源后
+ fn dedup_rank(&self, _path: &str) -> u8 {
+ 1
+ }
+
+ fn list_session_files(&self) -> Result<Vec<SessionFileRef>> {
+ let mut refs = Vec::new();
+ for root in &self.roots {
+ let Ok(entries) = fs::read_dir(&root.tasks) else {
+ continue;
+ };
+ let index = root.index();
+ // `_index.json` 一类的根级文件不是目录,task_ref 自然跳过
+ refs.extend(
+ entries
+ .flatten()
+ .filter_map(|e| root.session_ref(&e.path(), index.as_deref())),
+ );
+ }
+ Ok(refs)
+ }
+
+ /// 只认正文文件(scanner 按库里的 file_path 重解析时走这里);不进文件监听,见 watch_paths
+ fn file_ref(&self, path: &Path) -> Option<SessionFileRef> {
+ if path.file_name()? != API_FILE {
+ return None;
+ }
+ let task_dir = path.parent()?;
+ match self.root_for(task_dir) {
+ Some(root) => root.session_ref(task_dir, root.index().as_deref()),
+ None => task_ref(task_dir).map(|(r, _)| r),
+ }
+ }
+
+ /// 不进文件监听。旧版扩展已停更,任务目录基本不再变,启动 / 刷新时收就够;而每个任务
+ /// 目录里都有 checkpoints/ 整份影子 git 仓库——Linux 的 inotify 递归监听逐目录挂 watch,
+ /// 几百个任务就是几万个,启动时卡在 UI 线程上,旧内核的配额还会被用光
+ fn watch_paths(&self) -> Vec<PathBuf> {
+ Vec::new()
+ }
+
+ fn parse_session(&self, r: &SessionFileRef) -> Result<ParsedSession> {
+ let (meta, messages, unknown) = self.parse(r, false)?;
+ Ok(ParsedSession::derive(meta, &messages, unknown))
+ }
+
+ fn parse_transcript(&self, r: &SessionFileRef) -> Result<ParsedTranscript> {
+ let (meta, messages, unknown) = self.parse(r, true)?;
+ Ok(ParsedTranscript {
+ meta,
+ mainline: messages,
+ sidechains: Vec::new(),
+ unknown_line_count: unknown,
+ })
+ }
+
+ fn session_paths(&self, meta: &SessionMeta) -> Vec<String> {
+ // 任务是整个目录(界面回放、元数据、检查点),整目录进废纸篓
+ Path::new(&meta.file_path)
+ .parent()
+ .map(|d| vec![d.to_string_lossy().to_string()])
+ .unwrap_or_else(|| vec![meta.file_path.clone()])
+ }
+
+ fn cleanup_paths(&self, meta: &SessionMeta) -> Option<Vec<String>> {
+ Some(self.session_paths(meta))
+ }
+
+ fn manages_parent_links(&self) -> bool {
+ true
+ }
+
+ /// 子任务(new_task 派出去的)在自己的元数据里记着 parentTaskId
+ fn parent_links_in_child(&self) -> bool {
+ true
+ }
+
+ fn parent_links(&self) -> Option<Vec<(String, String)>> {
+ let mut links = Vec::new();
+ for root in &self.roots {
+ let entries = match fs::read_dir(&root.tasks) {
+ Ok(entries) => entries,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
+ Err(_) => return None,
+ };
+ // 索引只在缺 history_item.json 时才查,一个根取一次;它不知道(读不出)整份交 None
+ let mut index: Option<Option<Arc<HashMap<String, Value>>>> = None;
+ for entry in entries.flatten() {
+ let task_dir = entry.path();
+ let Some((r, _)) = task_ref(&task_dir) else {
+ continue;
+ };
+ let task_id = entry.file_name().to_string_lossy().to_string();
+ let parent = match read_item_file(&task_dir) {
+ Ok(Some(item)) => optional_string(item.get("parentTaskId")),
+ Ok(None) => {
+ let index = index.get_or_insert_with(|| root.index()).as_ref()?;
+ optional_string(
+ index
+ .get(&task_id)
+ .and_then(|item| item.get("parentTaskId")),
+ )
+ }
+ Err(_) => return None,
+ };
+ if let Some(parent) = parent.filter(|p| *p != task_id) {
+ links.push((
+ session_key(AgentId::Kilo, "", &r.native_id),
+ legacy_task_key(&parent),
+ ));
+ }
+ }
+ }
+ Some(links)
+ }
+
+ /// 自定义 location / 远程挂载点里扩展的任务目录归本实例,其余归 kilo.db 那个实例
+ fn claims_custom_root(&self, dir: &Path) -> bool {
+ legacy_tasks_dir(dir).is_some()
+ }
+
+ fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
+ Box::new(Self::at(legacy_tasks_dir(&dir).unwrap_or(dir)))
+ }
+
+ fn data_roots(&self) -> Vec<PathBuf> {
+ self.roots.iter().map(|r| r.tasks.clone()).collect()
+ }
+
+ /// 各编辑器的任务目录彼此独立,kilo.db 那个源也是;不开这个能力位,面板上的 Remove
+ /// 会按 agent 整家压制
+ fn supports_individual_root_removal(&self) -> bool {
+ true
+ }
+
+ fn excluding_data_roots(&self, roots: &[PathBuf]) -> Option<Box<dyn AgentAdapter>> {
+ Some(Box::new(Self {
+ roots: self
+ .roots
+ .iter()
+ .filter(|r| !roots.contains(&r.tasks))
+ .map(|r| LegacyRoot::new(r.tasks.clone()))
+ .collect(),
+ }))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn migrated_ids_match_the_kilo_importer() {
+ // sha1("abc") 的前 26 位——与 Node 的 createHash("sha1").update(id).digest("hex") 同值
+ assert_eq!(
+ migrated_session_id("abc"),
+ "ses_migrated_a9993e364706816aba3e257178"
+ );
+ assert_eq!(
+ legacy_task_key("abc"),
+ "kilo:ses_migrated_a9993e364706816aba3e257178"
+ );
+ }
+
+ #[test]
+ fn task_ids_carry_their_creation_time() {
+ assert_eq!(id_timestamp("1736400000000"), 1_736_400_000_000);
+ assert_eq!(id_timestamp("42"), 0);
+ // UUID v7:前 48 位是毫秒
+ assert_eq!(
+ id_timestamp("0193f0a8-6c00-7abc-8def-0123456789ab"),
+ 0x0193_f0a8_6c00
+ );
+ // v4 没有时间
+ assert_eq!(id_timestamp("0193f0a8-6c00-4abc-8def-0123456789ab"), 0);
+ }
+
+ #[test]
+ fn user_text_keeps_only_what_a_person_typed() {
+ let first = "<task>\nFix the QR scanner\n</task>\n\n<environment_details>\n# Current Workspace Directory (/w/app) Files\n</environment_details>";
+ assert_eq!(env_details_cwd(first).as_deref(), Some("/w/app"));
+ assert!(matches!(
+ classify_user_text(strip_env_details(first)),
+ UserPiece::Typed(t) if t == "Fix the QR scanner"
+ ));
+ assert_eq!(
+ strip_env_details("<environment_details>\nstuff\n</environment_details>"),
+ ""
+ );
+ assert!(matches!(
+ classify_user_text("[ERROR] You did not use a tool in your previous response!"),
+ UserPiece::Meta(_)
+ ));
+ assert!(matches!(
+ classify_user_text("plain words"),
+ UserPiece::Typed(t) if t == "plain words"
+ ));
+ }
+
+ /// 工具结果里只有反馈信封与追问的回答是人说的;读到的文件里恰好有这些标签不算
+ #[test]
+ fn tool_results_only_yield_replies_from_envelopes() {
+ assert_eq!(
+ xml_tool_result_header("[read_file for 'a.ts'] Result:"),
+ Some("read_file")
+ );
+ assert_eq!(
+ xml_tool_result_header("[attempt_completion] Result:"),
+ Some("attempt_completion")
+ );
+ assert_eq!(xml_tool_result_header("[ERROR] nope"), None);
+ let feedback = "The user has provided feedback on the results.\n<feedback>\nadd tests too\n</feedback>";
+ assert_eq!(
+ tool_result_reply(feedback, Some("attempt_completion")).as_deref(),
+ Some("add tests too")
+ );
+ // 抬头与信封在同一块
+ let inline = format!("[attempt_completion] Result:\n\n{feedback}");
+ assert_eq!(
+ tool_result_reply(&inline, Some("attempt_completion")).as_deref(),
+ Some("add tests too")
+ );
+ assert_eq!(
+ tool_result_reply("<answer>\nvitest\n</answer>", Some("ask_followup_question"))
+ .as_deref(),
+ Some("vitest")
+ );
+ for file in [
+ "<answer>not a reply</answer>",
+ "# prompt\n<task>do X</task>\n<feedback>no</feedback>",
+ "[read_file for 'p.md'] Result:\n<task>do X</task>",
+ ] {
+ assert_eq!(tool_result_reply(file, Some("read_file")), None, "{file}");
+ }
+ }
+
+ #[test]
+ fn assistant_xml_traces_are_unwrapped() {
+ let mut thinking = Vec::new();
+ let text = split_assistant_text(
+ "<thinking>check the effect</thinking>\nDone.\n<attempt_completion>\n<result>\nFixed the leak.\n</result>\n</attempt_completion>",
+ &mut thinking,
+ );
+ assert_eq!(thinking, vec!["check the effect"]);
+ assert_eq!(text, "Done.\nFixed the leak.");
+ }
+
+ #[test]
+ fn editors_are_recognised_from_the_task_path() {
+ let support = Path::new("/h/Library/Application Support");
+ assert_eq!(
+ editor_of(&editor_tasks_dir(&support.join("Code"))),
+ Some("VS Code")
+ );
+ assert_eq!(
+ editor_of(&editor_tasks_dir(&support.join("Code - Insiders"))),
+ Some("VS Code Insiders")
+ );
+ // 远程镜像:缓存树保持远端 home 的相对布局
+ let mirror = Path::new("/w/remotes/devbox/.vscode-server/data");
+ assert_eq!(editor_of(&editor_tasks_dir(mirror)), Some("VS Code"));
+ assert_eq!(editor_of(Path::new("/backup/kilo/tasks")), None);
+ assert_eq!(editor_of(&editor_tasks_dir(Path::new("/x/SomeFork"))), None);
+ }
+}
diff --git a/crates/wake-core/src/adapters/mod.rs b/crates/wake-core/src/adapters/mod.rs
index 22e7b5d..e92203a 100644
--- a/crates/wake-core/src/adapters/mod.rs
+++ b/crates/wake-core/src/adapters/mod.rs
@@ -11,6 +11,7 @@ pub mod dsh;
pub mod gemini;
pub mod grok;
pub mod hermes;
+pub mod kilo;
pub mod kimi;
pub mod kiro;
pub mod openclaw;
@@ -169,7 +170,7 @@ pub trait AgentAdapter: Send + Sync {
/// 拥有本家 session 文件的位置",凭据/配置/索引这类不产生会话的文件不列。
/// 新增 adapter 必须实现:没有默认值,漏了编译就过不去
fn data_roots(&self) -> Vec<std::path::PathBuf>;
- /// 文件监听根目录。默认 = data_roots 中现存的目录,二十一家实测全部吻合:
+ /// 文件监听根目录。默认 = data_roots 中现存的目录,二十二家实测全部吻合:
/// 目录型给出自己的 root,SQLite 型的根是库文件、天然筛空(watcher 只认
/// .jsonl,库变更靠启动/手动刷新),codex 的 sessions + archived 一并覆盖。
/// 只有当监听范围确实不同于数据根时才覆写——否则一次根路径搬迁
@@ -188,6 +189,12 @@ pub trait AgentAdapter: Send + Sync {
/// 侧档(gemini projects.json / kimi session_index / codex state DB)必须
/// 全部相对 `dir` 派生,落回默认家目录就会拿错树。新增 adapter 必须实现。
fn with_custom_root(&self, dir: std::path::PathBuf) -> Box<dyn AgentAdapter>;
+ /// 一家多源时,自定义 location(与远程挂载点)交给哪个实例构造:认领它的实例来,
+ /// 都不认领就交同家第一个实例(`custom_root_template`)。按路径**形状**判——远程挂载点
+ /// 在同步落盘前就要定形,别依赖存在性。默认不认领;Kilo 的旧版实例认领扩展的任务目录
+ fn claims_custom_root(&self, _dir: &std::path::Path) -> bool {
+ false
+ }
/// 是否允许 Session locations 单独压制某条默认数据根。多数 adapter 的多个
/// 根共同组成一个不可拆 location;OpenCode 的 stable/next 库则彼此独立。
fn supports_individual_root_removal(&self) -> bool {
@@ -268,9 +275,42 @@ pub(crate) fn env_dir(key: &str) -> Option<std::path::PathBuf> {
.map(std::path::PathBuf::from)
}
+/// VS Code 系编辑器的用户数据目录(`<数据根>/<编辑器>`,下面是 `User/globalStorage`):
+/// macOS 在 `~/Library/Application Support`,Windows 在 `%APPDATA%`,Linux 在
+/// `$XDG_CONFIG_HOME`(缺省 `~/.config`)。只做路径推导、不探存在性。全从 `home_dir()`
+/// 派生——`dirs::config_dir()` 在 Windows 上走 SHGetKnownFolderPath,WAKE_HOME 改道对它
+/// 无效。Cursor IDE 的 state.vscdb 与 Kilo 旧版扩展的任务目录共用
+pub(crate) fn vscode_user_data(editor: &str) -> std::path::PathBuf {
+ let home = home_dir().unwrap_or_default();
+ let base = if cfg!(target_os = "macos") {
+ home.join("Library").join("Application Support")
+ } else if cfg!(target_os = "windows") {
+ home.join("AppData").join("Roaming")
+ } else {
+ env_dir("XDG_CONFIG_HOME").unwrap_or_else(|| home.join(".config"))
+ };
+ base.join(editor)
+}
+
+/// 自定义 location / 远程挂载点 `dir` 交给同家哪个实例构造(见 `claims_custom_root`)
+pub(crate) fn custom_root_template<'a>(
+ base: &'a [Box<dyn AgentAdapter>],
+ agent: AgentId,
+ dir: &Path,
+) -> Option<&'a dyn AgentAdapter> {
+ let same = || {
+ base.iter()
+ .map(|a| a.as_ref())
+ .filter(move |a| a.agent() == agent)
+ };
+ same()
+ .find(|a| a.claims_custom_root(dir))
+ .or_else(|| same().next())
+}
+
/// 各家数据根共用的 HOME。**全部 adapter 必须走这里**,不要直接
/// `dirs::home_dir()`——`WAKE_HOME` 是整组 adapter 的统一改道开关:
-/// 契约测试靠它把二十一家指向 fixture 目录,而 `dirs::home_dir()` 只在
+/// 契约测试靠它把二十二家指向 fixture 目录,而 `dirs::home_dir()` 只在
/// POSIX 上看 `$HOME`,Windows 上走 SHGetKnownFolderPath、无论如何都指向
/// 真实用户目录(于是 Windows 上的契约测试全部落空,2026-08-25 review)。
/// 对用户它顺带是便携安装/多档案切换的手动开关。
@@ -278,7 +318,7 @@ pub(crate) fn home_dir() -> Option<std::path::PathBuf> {
env_dir("WAKE_HOME").or_else(dirs::home_dir)
}
-/// 全量二十一家 roster,**不按 detect 过滤**。这是全应用唯一的构造点:
+/// 全量二十二家 roster,**不按 detect 过滤**。这是全应用唯一的构造点:
/// scanner/watcher/resume/Session locations 面板共享 Workbench 启动时的
/// 同一份实例。缺根的家由各自 list_session_files 降级为 Ok(空)(scanner
/// 对 Err 会 `?` 截断整轮,新 adapter 必须维持这条降级约定,contract 测试
@@ -289,7 +329,9 @@ pub(crate) fn home_dir() -> Option<std::path::PathBuf> {
/// **家数 ≠ 实例数**:Cursor 一家有两个数据源(CLI 的 agent-transcripts
/// 与 IDE 的 state.vscdb),各占一个实例、共用 `AgentId::Cursor`。两源对
/// 同一 composer 都有记录时(IDE 会话在 JSONL 侧是只含 turn_ended 的空壳),
-/// 由 scanner 的同家同 ID 去重按 mtime/size 裁决
+/// 由 scanner 的同家同 ID 去重按 `dedup_rank` 裁决。Kilo Code 同理:新版的
+/// kilo.db 在前,旧版扩展的任务目录在后(自定义 location 与远程挂载按
+/// `claims_custom_root` 挑实例)
pub fn create_adapters() -> Vec<Box<dyn AgentAdapter>> {
vec![
Box::new(claude::ClaudeAdapter::new()),
@@ -314,6 +356,8 @@ pub fn create_adapters() -> Vec<Box<dyn AgentAdapter>> {
Box::new(zcode::ZcodeAdapter::new()),
Box::new(craft::CraftAdapter::new()),
Box::new(devin::DevinAdapter::new()),
+ Box::new(opencode::OpencodeAdapter::kilo()),
+ Box::new(kilo::KiloLegacyAdapter::new()),
]
}
@@ -342,9 +386,7 @@ fn create_adapters_with_root_overrides(
let customs: Vec<Box<dyn AgentAdapter>> = custom_roots
.iter()
.filter_map(|(agent, root)| {
- base.iter()
- .find(|a| a.agent() == *agent)
- .map(|a| a.with_custom_root(root.clone()))
+ custom_root_template(&base, *agent, root).map(|a| a.with_custom_root(root.clone()))
})
.collect();
let mut v: Vec<Box<dyn AgentAdapter>> = Vec::new();
diff --git a/crates/wake-core/src/adapters/opencode.rs b/crates/wake-core/src/adapters/opencode.rs
index 0f72a25..a998c0e 100644
--- a/crates/wake-core/src/adapters/opencode.rs
+++ b/crates/wake-core/src/adapters/opencode.rs
@@ -15,10 +15,52 @@ use std::path::{Path, PathBuf};
/// 仍用 session 表,正文改放 session_message(type 列
/// user|synthetic|assistant,data JSON)。早期 preview 曾用 session_v2 表,这里也
/// 保持兼容。parent_id 非空 = 子代理,不进列表。
+///
+/// Kilo Code 是同一个引擎上的另一个产品(见 `Flavor`),`OpencodeAdapter::kilo()`
+/// 读它的 `~/.local/share/kilo/kilo.db`——WorkBuddy 之于 CodeBuddy 的同一种孪生
pub struct OpencodeAdapter {
+ flavor: &'static Flavor,
dbs: Vec<OcDb>,
}
+/// 跑在 OpenCode 引擎上的产品。Kilo Code 2026-04 起整个换成 OpenCode 的分支(VS Code
+/// 扩展在后台起 `kilo serve`,CLI 与 JetBrains 插件同一个引擎),三端共用一个库,表与
+/// OpenCode 同形;差别只有下面这几项
+struct Flavor {
+ agent: AgentId,
+ /// `$XDG_DATA_HOME`(缺省 `~/.local/share`)下的目录名。Windows 上同样是
+ /// `%USERPROFILE%\.local\share`(两家都用 xdg-basedir,它在 Windows 上也这么算)
+ dir: &'static str,
+ /// 常驻 roster 的固定候选库名:没装也在,装上后普通刷新就能发现
+ db_names: &'static [&'static str],
+ /// 指定库的环境变量:绝对路径,或相对数据目录的文件名(两家同一规则)
+ db_env: &'static str,
+ /// 有没有 OpenCode 2 的 preview / next 渠道:那边的会话打 opencode2 徽章,resume 据此
+ /// 换 opencode2 二进制(`OcRow::source`)。Kilo 没有这条渠道
+ marks_preview: bool,
+}
+
+/// OpenCode 2 next 渠道另起的库名(preview 会话的最强信号,见 `OcRow::source`)
+const NEXT_DB: &str = "opencode-next.db";
+
+const OPENCODE: Flavor = Flavor {
+ agent: AgentId::Opencode,
+ dir: "opencode",
+ db_names: &["opencode.db", NEXT_DB],
+ db_env: "OPENCODE_DB",
+ marks_preview: true,
+};
+
+/// 渠道库(`kilo-<channel>.db`)只有 Kilo 自己的开发构建会写,扩展还强制
+/// `KILO_DISABLE_CHANNEL_DB=true`,所以只认 `kilo.db`
+const KILO: Flavor = Flavor {
+ agent: AgentId::Kilo,
+ dir: "kilo",
+ db_names: &["kilo.db"],
+ db_env: "KILO_DB",
+ marks_preview: false,
+};
+
struct OcDb {
path: PathBuf,
/// 元数据查询带全表相关子查询,按各库 mtime 分别缓存一轮扫描内的重复调用
@@ -50,6 +92,10 @@ fn has_table(conn: &rusqlite::Connection, name: &str) -> bool {
/// 根据库内真实表组合生成一次枚举 SQL。新版 next 与 v1 共用 session 表,
/// 所以必须逐会话看 session_message 是否有正文;仅检查 session_v2 会把真实
/// next 会话误走 part 路径并以 content_len=0 全部过滤(GitHub #2)。
+///
+/// 两代表都有行时,session_message 里有用户 / 助手消息才算 v2 转录;只有 shell /
+/// compaction 这类旁路记录的(实验开关 `*_EXPERIMENTAL_EVENT_SYSTEM` 下 v1 运行时的
+/// 零星双写,Kilo 实测)读 message + part,否则整段对话会被换成那几条
fn rows_sql(conn: &rusqlite::Connection) -> Option<String> {
let has_session = has_table(conn, "session");
let has_session_v2 = has_table(conn, "session_v2");
@@ -63,7 +109,9 @@ fn rows_sql(conn: &rusqlite::Connection) -> Option<String> {
WHERE p.session_id = s.id)";
let message_len = "(SELECT COALESCE(SUM(LENGTH(m.data)), 0) FROM session_message m \
WHERE m.session_id = s.id)";
- let message_exists = "EXISTS(SELECT 1 FROM session_message m WHERE m.session_id = s.id)";
+ let v2_transcript = "(EXISTS(SELECT 1 FROM session_message m WHERE m.session_id = s.id \
+ AND m.type IN ('user', 'assistant')) \
+ OR NOT EXISTS(SELECT 1 FROM message mm WHERE mm.session_id = s.id))";
let mut selects = Vec::new();
// 早期 preview schema:session_v2 是全集,session 仅作 v1 回捞。
@@ -78,8 +126,8 @@ fn rows_sql(conn: &rusqlite::Connection) -> Option<String> {
if has_session {
let (len, v2) = match (has_parts, has_messages_v2) {
(true, true) => (
- format!("CASE WHEN {message_exists} THEN {message_len} ELSE {part_len} END"),
- format!("CASE WHEN {message_exists} THEN 1 ELSE 0 END"),
+ format!("CASE WHEN {v2_transcript} THEN {message_len} ELSE {part_len} END"),
+ v2_transcript.to_string(),
),
(true, false) => (part_len.to_string(), "0".to_string()),
(false, true) => (message_len.to_string(), "1".to_string()),
@@ -146,27 +194,28 @@ fn push_unique(paths: &mut Vec<PathBuf>, path: PathBuf) {
}
}
-fn known_db_paths(dir: &Path) -> Vec<PathBuf> {
- vec![dir.join("opencode.db"), dir.join("opencode-next.db")]
+fn known_db_paths(flavor: &Flavor, dir: &Path) -> Vec<PathBuf> {
+ flavor.db_names.iter().map(|name| dir.join(name)).collect()
}
/// OpenCode 的数据目录服从 XDG;next 渠道另命名数据库而非替换 stable 库。
/// 两个固定候选都常驻 roster,这样 Wake 启动后才安装任一 CLI,普通刷新也能发现。
/// OPENCODE_DB 若被 GUI 进程继承则作为额外候选,但绝不压掉两个标准位置。
-fn default_db_paths() -> Vec<PathBuf> {
+/// Kilo 同一套规则(`KILO_DB`,固定候选只有 `kilo.db`)
+fn default_db_paths(flavor: &Flavor) -> Vec<PathBuf> {
let default_dir = super::home_dir()
.unwrap_or_default()
.join(".local")
.join("share")
- .join("opencode");
- let xdg_dir = super::env_dir("XDG_DATA_HOME").map(|x| x.join("opencode"));
+ .join(flavor.dir);
+ let xdg_dir = super::env_dir("XDG_DATA_HOME").map(|x| x.join(flavor.dir));
let active_dir = xdg_dir
.as_ref()
- .filter(|dir| known_db_paths(dir).iter().any(|p| p.is_file()))
+ .filter(|dir| known_db_paths(flavor, dir).iter().any(|p| p.is_file()))
.unwrap_or(&default_dir);
let mut paths = Vec::new();
- if let Some(value) = std::env::var_os("OPENCODE_DB").filter(|v| !v.is_empty()) {
+ if let Some(value) = std::env::var_os(flavor.db_env).filter(|v| !v.is_empty()) {
let configured = PathBuf::from(value);
if configured != Path::new(":memory:") {
let configured = if configured.is_absolute() {
@@ -179,12 +228,12 @@ fn default_db_paths() -> Vec<PathBuf> {
}
}
}
- for path in known_db_paths(active_dir) {
+ for path in known_db_paths(flavor, active_dir) {
push_unique(&mut paths, path);
}
// XDG 位置被采信时,默认目录里已有的库仍是只读候选,避免稳定版历史消失。
if active_dir != &default_dir {
- for path in known_db_paths(&default_dir)
+ for path in known_db_paths(flavor, &default_dir)
.into_iter()
.filter(|p| p.is_file())
{
@@ -194,34 +243,45 @@ fn default_db_paths() -> Vec<PathBuf> {
paths
}
-fn custom_db_paths(dir: PathBuf) -> Vec<PathBuf> {
+fn custom_db_paths(flavor: &Flavor, dir: PathBuf) -> Vec<PathBuf> {
if dir.is_file() {
return vec![dir];
}
- let nested = dir.join("opencode");
- let db_dir = if nested.is_dir() || known_db_paths(&nested).iter().any(|p| p.is_file()) {
+ let nested = dir.join(flavor.dir);
+ let db_dir = if nested.is_dir() || known_db_paths(flavor, &nested).iter().any(|p| p.is_file()) {
nested
} else {
dir
};
- known_db_paths(&db_dir)
+ known_db_paths(flavor, &db_dir)
}
impl OpencodeAdapter {
pub fn new() -> Self {
+ Self::with_dbs(&OPENCODE, default_db_paths(&OPENCODE))
+ }
+
+ /// Kilo Code 的新版(2026-04 起)数据源:`~/.local/share/kilo/kilo.db`。旧版扩展的
+ /// 任务目录是同一家的第二个实例(adapters::kilo)
+ pub fn kilo() -> Self {
+ Self::with_dbs(&KILO, default_db_paths(&KILO))
+ }
+
+ fn with_dbs(flavor: &'static Flavor, paths: Vec<PathBuf>) -> Self {
Self {
- dbs: default_db_paths().into_iter().map(OcDb::new).collect(),
+ flavor,
+ dbs: paths.into_iter().map(OcDb::new).collect(),
}
}
- fn open(db: &Path) -> Option<SqliteRo> {
- open_sqlite_ro(db, "opencode")
+ fn open(&self, db: &Path) -> Option<SqliteRo> {
+ open_sqlite_ro(db, self.flavor.dir)
}
- fn rows(db: &OcDb) -> Option<Vec<OcRow>> {
+ fn rows(&self, db: &OcDb) -> Option<Vec<OcRow>> {
let mtime = super::sqlite_ro::db_cache_stamp(&db.path);
db.rows_cache.get_or_try_build(mtime, || {
- let ro = Self::open(&db.path)?;
+ let ro = self.open(&db.path)?;
query_rows(&ro.conn, None).ok()
})
}
@@ -242,18 +302,19 @@ impl OpencodeAdapter {
let model = serde_json::from_str::<Value>(&row.model_json)
.ok()
.and_then(|m| m.get("id").and_then(|v| v.as_str()).map(String::from));
+ let project_path = canonical_project_path(&row.directory);
SessionMeta {
- key: format!("opencode:{}", row.id),
+ key: format!("{}:{}", self.flavor.agent.as_str(), row.id),
host: String::new(),
id: row.id.clone(),
- agent: AgentId::Opencode,
+ agent: self.flavor.agent,
title: if title.is_empty() {
UNTITLED.to_string()
} else {
title
},
- project_path: row.directory.clone(),
- project_name: project_name_of(&row.directory),
+ project_name: project_name_of(&project_path),
+ project_path,
file_path: r.file_path.clone(),
created_at: if row.created_ms > 0 {
row.created_ms
@@ -275,7 +336,7 @@ impl OpencodeAdapter {
None
},
archived: row.archived,
- source: row.source(db),
+ source: self.flavor.marks_preview.then(|| row.source(db)).flatten(),
favorite: false,
pinned: false,
}
@@ -292,7 +353,9 @@ impl OpencodeAdapter {
let db = self
.db_for_ref(r)
.ok_or_else(|| anyhow!("opencode database is outside adapter roots"))?;
- let ro = Self::open(&db.path).ok_or_else(|| anyhow!("cannot open opencode db"))?;
+ let ro = self
+ .open(&db.path)
+ .ok_or_else(|| anyhow!("cannot open {} db", self.flavor.dir))?;
let row = query_rows(&ro.conn, Some(&r.native_id))?
.into_iter()
.next()
@@ -560,7 +623,22 @@ impl BlockAcc {
Some("reasoning") => self.push_reasoning(p),
Some("tool") => self.push_tool(p, decode_images),
Some("image") => self.push_image(p, decode_images),
- Some("step-start") | Some("step-finish") | Some("snapshot") | Some("patch") => {}
+ // 用户敲的命令要派子代理时,这一条用户消息里只有它(没有 text 块):照用户
+ // 敲的写回 `/命令`,命令名缺席才退到描述与派给子代理的提示词
+ Some("subtask") => {
+ let text = match optional_string(p.get("command")) {
+ Some(command) => format!("/{command}"),
+ None => ["description", "prompt"]
+ .iter()
+ .find_map(|k| optional_string(p.get(*k)))
+ .unwrap_or_default(),
+ };
+ self.content.push_text(&text);
+ }
+ // agent = 正文里 @ 了哪个代理(文字本身在 text 块里);retry = 请求重试的记录;
+ // compaction = 触发压缩的标记(摘要本身是后面那条助手消息)
+ Some("step-start") | Some("step-finish") | Some("snapshot") | Some("patch")
+ | Some("agent") | Some("retry") | Some("compaction") => {}
Some("file") if is_image_part(p) => self.push_image(p, decode_images),
Some("file") => {}
_ => return false,
@@ -707,7 +785,7 @@ impl OcRow {
/// preview 会话在 UI 标 "opencode2",resume 据此换二进制。next 库名本身
/// 是最强信号;共享库/早期 schema 则回看写入 session.version 的渠道标记。
fn source(&self, db: &Path) -> Option<String> {
- let next_db = db.file_name().and_then(|n| n.to_str()) == Some("opencode-next.db");
+ let next_db = db.file_name().and_then(|n| n.to_str()) == Some(NEXT_DB);
let v2 = next_db
|| self.version.starts_with('2')
|| self.version.contains("beta")
@@ -718,18 +796,18 @@ impl OcRow {
impl AgentAdapter for OpencodeAdapter {
fn agent(&self) -> AgentId {
- AgentId::Opencode
+ self.flavor.agent
}
fn list_session_files(&self) -> Result<Vec<SessionFileRef>> {
let mut out = Vec::new();
for db in &self.dbs {
- let Some(rows) = Self::rows(db) else { continue };
+ let Some(rows) = self.rows(db) else { continue };
out.extend(
rows.into_iter()
.filter(|row| row.content_len > 0)
.map(|row| SessionFileRef {
- agent: AgentId::Opencode,
+ agent: self.flavor.agent,
native_id: row.id.clone(),
file_path: virtual_path(&db.path, &row.id),
mtime_ms: row.updated_ms,
@@ -744,7 +822,7 @@ impl AgentAdapter for OpencodeAdapter {
let mut out = HashMap::new();
let mut opened = false;
for db in &self.dbs {
- let Some(rows) = Self::rows(db) else { continue };
+ let Some(rows) = self.rows(db) else { continue };
opened = true;
let by_id: HashMap<&str, &OcRow> =
rows.iter().map(|row| (row.id.as_str(), row)).collect();
@@ -777,10 +855,12 @@ impl AgentAdapter for OpencodeAdapter {
fn with_custom_root(&self, dir: PathBuf) -> Box<dyn AgentAdapter> {
// 目录 location 同时扫描 stable + next,直接给库文件则只认该文件。
- // 选中 XDG data 根或 opencode 目录本身都可归一化。
- Box::new(Self {
- dbs: custom_db_paths(dir).into_iter().map(OcDb::new).collect(),
- })
+ // 选中 XDG data 根或 opencode / kilo 目录本身都可归一化(Kilo 旧版扩展的任务
+ // 目录由旧版实例认领,见 adapters::kilo)
+ Box::new(Self::with_dbs(
+ self.flavor,
+ custom_db_paths(self.flavor, dir),
+ ))
}
fn data_roots(&self) -> Vec<PathBuf> {
@@ -791,14 +871,16 @@ impl AgentAdapter for OpencodeAdapter {
true
}
+ /// Kilo 一家两源(本实例的 kilo.db 与 adapters::kilo 的旧版任务目录):排除列表按
+ /// agent 收集,里面可能全是另一个源的根——那时原样交回自己,与"与我无关"等价
fn excluding_data_roots(&self, roots: &[PathBuf]) -> Option<Box<dyn AgentAdapter>> {
- Some(Box::new(Self {
- dbs: self
- .dbs
+ Some(Box::new(Self::with_dbs(
+ self.flavor,
+ self.dbs
.iter()
.filter(|db| !roots.contains(&db.path))
- .map(|db| OcDb::new(db.path.clone()))
+ .map(|db| db.path.clone())
.collect(),
- }))
+ )))
}
}
diff --git a/crates/wake-core/src/adapters/parse_utils.rs b/crates/wake-core/src/adapters/parse_utils.rs
index 9839e96..31be551 100644
--- a/crates/wake-core/src/adapters/parse_utils.rs
+++ b/crates/wake-core/src/adapters/parse_utils.rs
@@ -70,6 +70,26 @@ pub fn project_name_of(cwd: &str) -> String {
.unwrap_or_else(|| "Unknown project".to_string())
}
+/// 项目路径的规范形。Windows 形状的路径(`c:\…`、`C:/…`、`//server/…`)盘符改大写,
+/// 在 Windows 上斜杠换成反斜杠:VS Code 的 fsPath 写小写盘符,OpenCode 系把目录存成
+/// 正斜杠(它自己读出来时再换回),原样用就与别家记下的 `C:\…` 分成两个项目。
+/// POSIX 路径(含远程镜像来的)原样
+pub fn canonical_project_path(path: &str) -> String {
+ let drive = matches!(path.as_bytes(), [d, b':', b'\\' | b'/', ..] if d.is_ascii_alphabetic());
+ if !drive && !path.starts_with("//") {
+ return path.to_string();
+ }
+ let mut out = if cfg!(windows) {
+ path.replace('/', "\\")
+ } else {
+ path.to_string()
+ };
+ if drive {
+ out[..1].make_ascii_uppercase();
+ }
+ out
+}
+
/// user 消息的 kind:注入内容归 Meta 折叠
pub fn user_kind(text: &str) -> MessageKind {
if is_injected_user_content(text) {
@@ -1037,6 +1057,24 @@ pub fn make_preview(input: &Value) -> String {
mod tests {
use super::*;
+ /// Windows 形状的项目路径换成别家记的写法:盘符大写、Windows 上正斜杠换反斜杠;
+ /// POSIX 路径(含远程镜像来的)原样
+ #[test]
+ fn project_paths_are_canonical() {
+ assert_eq!(canonical_project_path("/Users/x/app"), "/Users/x/app");
+ assert_eq!(canonical_project_path(r"c:\Users\x\app"), r"C:\Users\x\app");
+ if cfg!(windows) {
+ assert_eq!(canonical_project_path("c:/Users/x/app"), r"C:\Users\x\app");
+ assert_eq!(
+ canonical_project_path("//nas/share/app"),
+ r"\\nas\share\app"
+ );
+ } else {
+ assert_eq!(canonical_project_path("c:/Users/x/app"), "C:/Users/x/app");
+ assert_eq!(canonical_project_path("//nas/share/app"), "//nas/share/app");
+ }
+ }
+
#[test]
fn clip_chars_counts_characters() {
let s = "记忆正文一共九个字";
diff --git a/crates/wake-core/src/adapters/remote.rs b/crates/wake-core/src/adapters/remote.rs
index 25c93d1..37699d8 100644
--- a/crates/wake-core/src/adapters/remote.rs
+++ b/crates/wake-core/src/adapters/remote.rs
@@ -50,7 +50,7 @@ impl RemoteAdapter {
}
}
-/// 对一个 host 构造整组远程实例:二十一家模板 × `with_custom_root`(缓存内
+/// 对一个 host 构造整组远程实例:二十二家模板 × `with_custom_root`(缓存内
/// 挂载点,见 remote::REMOTE_LAYOUTS)× 装饰器。追加进 roster 的 active 尾部
/// (不进 Session locations 面板)。`templates` 由 roster 唯一构造点传入
/// (不变量 8:本模块不得自行二次 create_adapters());产物的数据根 100%
@@ -62,10 +62,11 @@ pub fn create_remote_adapters(
) -> Vec<Box<dyn AgentAdapter>> {
let mut out: Vec<Box<dyn AgentAdapter>> = Vec::new();
for layout in crate::remote::REMOTE_LAYOUTS {
- let Some(template) = templates.iter().find(|a| a.agent() == layout.agent) else {
+ let mount = host_cache.join(layout.mount);
+ let Some(template) = super::custom_root_template(templates, layout.agent, &mount) else {
continue;
};
- let inner = template.with_custom_root(host_cache.join(layout.mount));
+ let inner = template.with_custom_root(mount);
out.push(Box::new(RemoteAdapter::new(inner, host)));
}
out
@@ -205,6 +206,10 @@ impl AgentAdapter for RemoteAdapter {
))
}
+ fn claims_custom_root(&self, dir: &Path) -> bool {
+ self.inner.claims_custom_root(dir)
+ }
+
fn supports_individual_root_removal(&self) -> bool {
self.inner.supports_individual_root_removal()
}
diff --git a/crates/wake-core/src/bin/wake_cli.rs b/crates/wake-core/src/bin/wake_cli.rs
index 69f3ba7..5c5ce99 100644
--- a/crates/wake-core/src/bin/wake_cli.rs
+++ b/crates/wake-core/src/bin/wake_cli.rs
@@ -186,7 +186,7 @@ fn setup(db: &Option<PathBuf>) -> String {
// sibling_named 取的就是 current_exe 同级目录,从 wake-cli 调恰好对
let mcp_bin = mcp::sibling_file("wake-mcp");
let path = db_path(db);
- // 只探库,不必为一行提示把二十一家 roster 建起来
+ // 只探库,不必为一行提示把二十二家 roster 建起来
let db_error = Store::open_read_only(&path).err().map(|e| format!("{e:#}"));
cli::setup_text(&cli::SetupFacts {
cli_bin: &cli_bin,
diff --git a/crates/wake-core/src/bin/wake_mcp.rs b/crates/wake-core/src/bin/wake_mcp.rs
index a5f2668..2739f53 100644
--- a/crates/wake-core/src/bin/wake_mcp.rs
+++ b/crates/wake-core/src/bin/wake_mcp.rs
@@ -102,7 +102,7 @@ fn main() -> ExitCode {
for s in mcp::setup_snippets(&bin) {
let _ = writeln!(out, "## {} — {}\n\n{}\n", s.client, s.hint, s.text);
}
- // 只探库,不必为一行提示把二十一家 roster 建起来
+ // 只探库,不必为一行提示把二十二家 roster 建起来
if let Err(e) = Store::open_read_only(&db_path(&args.db)) {
let _ = writeln!(out, "Note: {e:#}");
}
diff --git a/crates/wake-core/src/db.rs b/crates/wake-core/src/db.rs
index d015250..37d6a6f 100644
--- a/crates/wake-core/src/db.rs
+++ b/crates/wake-core/src/db.rs
@@ -207,8 +207,11 @@ CREATE TABLE IF NOT EXISTS claimed_sessions (
/// wake_lookups、记忆层一起回填——开发库可能戳着 5 或 6,换代判据是精确不等,
/// 两个都跳过;
/// "8" = Cursor 会话补上模型与 token(IDE 库的 modelInfo / modelConfig / usageData /
-/// tokenCount;转录胜出的会话向同一个 composer 借),老行靠这轮重解析回填。
-pub const FTS_FORMAT: &str = "8";
+/// tokenCount;转录胜出的会话向同一个 composer 借),老行靠这轮重解析回填;
+/// "9" = OpenCode 系(OpenCode / ZCode / 新增的 Kilo Code)认得 subtask / agent / retry /
+/// compaction 四种 part(subtask 写回用户敲的 `/命令`,其余不再计未知行),Windows 上
+/// OpenCode 存的 `C:/…` 目录换回反斜杠,老行靠这轮重解析回填。
+pub const FTS_FORMAT: &str = "9";
fn open_conn(path: &Path) -> Result<Connection> {
if let Some(dir) = path.parent() {
diff --git a/crates/wake-core/src/models.rs b/crates/wake-core/src/models.rs
index b8e9ea0..1894f06 100644
--- a/crates/wake-core/src/models.rs
+++ b/crates/wake-core/src/models.rs
@@ -26,13 +26,14 @@ pub enum AgentId {
Zcode,
CraftAgents,
Devin,
+ Kilo,
}
impl AgentId {
- /// 全部二十一家,**枚举声明序**(= Ord = 用户钉的侧栏展示序;面板成组、
+ /// 全部二十二家,**枚举声明序**(= Ord = 用户钉的侧栏展示序;面板成组、
/// 表单下拉共用同一顺序)。曾误抄 create_adapters 的构造序,下拉与侧栏
/// 排序当场对不上——契约测试现在卡它与 Ord 一致
- pub const ALL: [AgentId; 21] = [
+ pub const ALL: [AgentId; 22] = [
AgentId::ClaudeCode,
AgentId::Codex,
AgentId::Grok,
@@ -54,6 +55,7 @@ impl AgentId {
AgentId::Zcode,
AgentId::CraftAgents,
AgentId::Devin,
+ AgentId::Kilo,
];
pub fn as_str(&self) -> &'static str {
@@ -79,6 +81,7 @@ impl AgentId {
AgentId::Zcode => "zcode",
AgentId::CraftAgents => "craft-agents",
AgentId::Devin => "devin",
+ AgentId::Kilo => "kilo",
}
}
@@ -105,6 +108,7 @@ impl AgentId {
"zcode" => Some(AgentId::Zcode),
"craft-agents" => Some(AgentId::CraftAgents),
"devin" => Some(AgentId::Devin),
+ "kilo" => Some(AgentId::Kilo),
_ => None,
}
}
@@ -132,6 +136,7 @@ impl AgentId {
AgentId::Zcode => "ZCode",
AgentId::CraftAgents => "Craft Agents",
AgentId::Devin => "Devin",
+ AgentId::Kilo => "Kilo Code",
}
}
@@ -225,6 +230,15 @@ impl AgentId {
"brands/devin-light.png"
}
}
+ // lobe-icons 的 kilocode 字形(方框里的像素 "kilo",与官方标志同形),只有单色版,
+ // 同 Cursor / Devin 按模式取白版或深墨版
+ AgentId::Kilo => {
+ if dark {
+ "brands/kilo.png"
+ } else {
+ "brands/kilo-light.png"
+ }
+ }
}
}
}
@@ -970,7 +984,7 @@ pub const UNTITLED: &str = "Untitled";
/// 会话 key 的唯一构造点:本地 `{agent}:{native_id}`,远程
/// `{agent}:{host}:{native_id}`。scanner 的墓碑查询、watcher 的幸存者反查、
/// 远程装饰器的 key 改写都走这里——"远程 key 长什么样"只此一处知识。
-/// (二十一家 adapter 的本地两段构造保留各自 `format!`,它们从不涉及 host。)
+/// (二十二家 adapter 的本地两段构造保留各自 `format!`,它们从不涉及 host。)
pub fn session_key(agent: AgentId, host: &str, native_id: &str) -> String {
if host.is_empty() {
format!("{}:{native_id}", agent.as_str())
diff --git a/crates/wake-core/src/remote.rs b/crates/wake-core/src/remote.rs
index 4d0afef..9432e6b 100644
--- a/crates/wake-core/src/remote.rs
+++ b/crates/wake-core/src/remote.rs
@@ -16,7 +16,7 @@
//! ①openrsync(macOS 15+ 的 /usr/bin/rsync)做发送端时,某个源连父目录
//! 都不存在会让它中止整份文件列表,排在后面的源全部静默不传,退出码却
//! 只是 23;②rsync 家族只要发送端遇到任何 I/O 错误(缺源即算)就整体跳过
-//! 删除阶段——没有哪台机器二十一家全装,`--delete` 就永远不会生效。
+//! 删除阶段——没有哪台机器二十二家全装,`--delete` 就永远不会生效。
//!
//! 同步跑在**独立于扫描的线程**(Workbench::spawn_remote_sync):本地扫描
//! 不等网络,不可达 host 只拖慢自己;缓存落盘由 watcher 增量收编,同步
@@ -49,7 +49,7 @@ pub struct RemoteAgentLayout {
pub exclude: &'static [&'static str],
}
-/// 二十一家的远程布局。远程主机按 Linux/macOS 默认路径假设(两平台一致,
+/// 二十二家的远程布局。远程主机按 Linux/macOS 默认路径假设(两平台一致,
/// 均为 home 相对;OpenCode 的 XDG 变体、CODEX_HOME 这类 env 覆盖在远端
/// 探测不到,阶段 1 不支持非默认远程布局)。
pub const REMOTE_LAYOUTS: &[RemoteAgentLayout] = &[
@@ -255,6 +255,20 @@ pub const REMOTE_LAYOUTS: &[RemoteAgentLayout] = &[
],
exclude: &[],
},
+ RemoteAgentLayout {
+ agent: AgentId::Kilo,
+ // **只覆盖旧版扩展**:Remote-SSH 下扩展跑在远端,任务目录落在远端的
+ // vscode-server 用户数据里。新版的 `.local/share/kilo/kilo.db` 不拉——Kilo 每次
+ // 启动都把 auth.json 里的 API key / 登录 token 对账进同一个库的 credential 表,
+ // 还有存 access / refresh token 的 account 表;SQLite 是整文件,拉会话就得连凭证
+ // 一起拷到本机(OpenClaw 的库同样因此不拉)。globalStorage 的 state.vscdb
+ // 也不拉(里面有加密的 secret:// 项),缺 history_item.json 的老任务改从正文推
+ // 标题与工作区。挂载点按目录名(扩展 id)定形,不看存在性
+ mount: ".vscode-server/data/User/globalStorage/kilocode.kilo-code",
+ sync_paths: &[".vscode-server/data/User/globalStorage/kilocode.kilo-code/tasks"],
+ // 每个任务目录里的 checkpoints/ 是整份影子 git 仓库,量大且不读
+ exclude: &["kilocode.kilo-code/tasks/*/checkpoints"],
+ },
];
/// host 名合法性:进 session key 作中段(不能有 ':')、直接作为 ssh/rsync
diff --git a/crates/wake-core/src/services/terminal/macos.rs b/crates/wake-core/src/services/terminal/macos.rs
index 434fd83..7e22c45 100644
--- a/crates/wake-core/src/services/terminal/macos.rs
+++ b/crates/wake-core/src/services/terminal/macos.rs
@@ -226,6 +226,7 @@ fn kooky_cli_path() -> Option<&'static Path> {
/// 注册就退 0,Wake 这边看不出失败——所以名单外必须改走 kooky-cli 的哑管道。
/// 注意 Antigravity 不在里面:kooky 的 stores 表注释写明其 CLI 数据布局未经
/// 核实、"Absent by design"。新增 agent 时按 kooky 那张表核对,别默认落进深链
+/// (2026-10 Kilo Code 加入时核对过:kooky 不认它,走 kooky-cli)
const KOOKY_ROSTER: &[AgentId] = &[
AgentId::ClaudeCode,
AgentId::Codex,
diff --git a/crates/wake-core/src/services/terminal/mod.rs b/crates/wake-core/src/services/terminal/mod.rs
index e948f91..6fa8f82 100644
--- a/crates/wake-core/src/services/terminal/mod.rs
+++ b/crates/wake-core/src/services/terminal/mod.rs
@@ -153,6 +153,8 @@ pub fn agent_bin(agent: AgentId) -> Option<&'static str> {
// 发消息,不是能在终端里接着聊的界面
AgentId::CraftAgents => None,
AgentId::Devin => Some("devin"),
+ // npm 包 @kilocode/cli 装出 `kilo` 与 `kilocode` 两个同一份的命令
+ AgentId::Kilo => Some("kilo"),
}
}
@@ -223,6 +225,11 @@ fn resume_args(meta: &SessionMeta) -> Option<(Vec<String>, bool)> {
// Devin 会话按 cwd 分桶(`devin list` 只列当前目录),`--resume <id>`
// 在原项目目录启动
AgentId::Devin => Some((vec!["--resume".into(), id.into()], true)),
+ // Kilo 新版(OpenCode 分支)与 OpenCode 同形制;VS Code 扩展的会话与 CLI 同库,
+ // 一样续得上。会话按项目目录记,在原目录启动工具才落在原处。旧版扩展的任务
+ // 新版 CLI 不认(导入 kilo.db 之前它不在库里)——胜出副本是旧任务文件就不画
+ AgentId::Kilo if crate::adapters::kilo::is_legacy_task(&meta.file_path) => None,
+ AgentId::Kilo => Some((vec!["--session".into(), id.into()], true)),
// Kiro / Gemini CLI 没有按会话 id 续会话的形制
AgentId::Kiro | AgentId::Gemini => None,
}
@@ -700,6 +707,7 @@ mod tests {
),
(AgentId::Codebuddy, vec!["--resume", id], true),
(AgentId::Devin, vec!["--resume", id], true),
+ (AgentId::Kilo, vec!["--session", id], true),
] {
let meta = remote_meta(agent, id, "");
let (args, cwd) = super::resume_args(&meta).unwrap();
@@ -713,6 +721,25 @@ mod tests {
}
}
+ /// Kilo 旧版扩展的任务没有 CLI 续得上(新版 `kilo --session` 只认 kilo.db 里的
+ /// 会话);胜出副本是 kilo.db 那份时照常给
+ #[test]
+ fn kilo_legacy_tasks_have_no_resume() {
+ let mut meta = remote_meta(
+ AgentId::Kilo,
+ "ses_migrated_0123456789abcdef0123456789",
+ "/w",
+ );
+ meta.file_path =
+ "/h/.vscode-server/data/User/globalStorage/kilocode.kilo-code/tasks/t1/api_conversation_history.json"
+ .into();
+ assert!(super::resume_args(&meta).is_none());
+ assert!(super::resume_targets(&meta).is_empty());
+ meta.file_path =
+ "/h/.local/share/kilo/kilo.db#ses_migrated_0123456789abcdef0123456789".into();
+ assert!(super::resume_args(&meta).is_some());
+ }
+
#[test]
fn ssh_resume_command_quotes_nested_layers() {
let meta = remote_meta(AgentId::Codex, "abc-123", "/home/dev/my project");
diff --git a/crates/wake-core/tests/adapter_contracts.rs b/crates/wake-core/tests/adapter_contracts.rs
index 36762c6..f0fac56 100644
--- a/crates/wake-core/tests/adapter_contracts.rs
+++ b/crates/wake-core/tests/adapter_contracts.rs
@@ -26,6 +26,7 @@ use wake_core::adapters::dsh::DshAdapter;
use wake_core::adapters::gemini::GeminiAdapter;
use wake_core::adapters::grok::GrokAdapter;
use wake_core::adapters::hermes::HermesAdapter;
+use wake_core::adapters::kilo::{legacy_task_key, migrated_session_id, KiloLegacyAdapter};
use wake_core::adapters::kimi::KimiAdapter;
use wake_core::adapters::kiro::KiroAdapter;
use wake_core::adapters::openclaw::OpenclawAdapter;
@@ -52,6 +53,9 @@ struct TestEnv {
cursor_ide_db: PathBuf,
zcode_db: PathBuf,
devin_db: PathBuf,
+ kilo_db: PathBuf,
+ kilo_tasks: PathBuf,
+ kilo_cursor_tasks: PathBuf,
/// 假 HOME 目录本体,持有 TempDir 保证整个测试进程期间不被清理
_home: tempfile::TempDir,
}
@@ -96,6 +100,9 @@ fn setup() -> &'static TestEnv {
cursor_ide_db: sc.cursor_ide_db,
zcode_db: sc.zcode_db,
devin_db: sc.devin_db,
+ kilo_db: sc.kilo_db,
+ kilo_tasks: sc.kilo_tasks,
+ kilo_cursor_tasks: sc.kilo_cursor_tasks,
_home: home,
}
})
@@ -122,10 +129,10 @@ fn fs_ref(agent: AgentId, path: &Path, native_id: &str) -> SessionFileRef {
}
/// 默认 roster 的实例数。**不等于 `AgentId::ALL.len()`**:Cursor 一家有两个
-/// 数据源(CLI 的 agent-transcripts 与 IDE 的 state.vscdb),各占一个实例。
-/// 新增 agent 或给某家再加数据源时,这个数跟着加一——契约要卡的是"漏了实例
-/// 就爆",而不是"每家恰好一个"
-const DEFAULT_INSTANCES: usize = AgentId::ALL.len() + 1;
+/// 数据源(CLI 的 agent-transcripts 与 IDE 的 state.vscdb),Kilo Code 也是两个
+/// (新版的 kilo.db 与旧版扩展的任务目录),各占一个实例。新增 agent 或给某家
+/// 再加数据源时,这个数跟着加一——契约要卡的是"漏了实例就爆",而不是"每家恰好一个"
+const DEFAULT_INSTANCES: usize = AgentId::ALL.len() + 2;
/// SQLite 型 agent 的虚拟路径引用(`<db>#<id>`,与 sqlite_ro::virtual_path 同构)
fn db_ref(agent: AgentId, db: &Path, id: &str) -> SessionFileRef {
@@ -2029,8 +2036,13 @@ fn watch_paths_derive_from_data_roots() {
for a in wake_core::adapters::create_adapters() {
let tag = a.agent().as_str();
let watched = a.watch_paths();
- let expect: Vec<std::path::PathBuf> =
- a.data_roots().into_iter().filter(|p| p.is_dir()).collect();
+ // 唯一的例外:Kilo 旧版扩展的任务目录不进监听(每个任务里一整份 checkpoints 影子
+ // git 仓库,见 adapters::kilo);它的新版实例是库文件,本来就没有监听目录
+ let expect: Vec<std::path::PathBuf> = if a.agent() == AgentId::Kilo {
+ Vec::new()
+ } else {
+ a.data_roots().into_iter().filter(|p| p.is_dir()).collect()
+ };
assert_eq!(
watched, expect,
"[{tag}] watch_paths 必须等于 data_roots 的现存目录子集"
@@ -2106,7 +2118,7 @@ fn data_roots_contract() {
.filter(|a| a.detect())
.map(|a| a.agent().as_str())
.collect();
- for expect in ["copilot", "opencode", "antigravity", "dsh"] {
+ for expect in ["copilot", "opencode", "antigravity", "dsh", "kilo"] {
assert!(
detected.contains(&expect),
"{expect} 应被检出,实际 {detected:?}"
@@ -2441,6 +2453,30 @@ fn seq_contract_holds_for_all_agents() {
Box::new(DevinAdapter::new()),
db_ref(AgentId::Devin, &env.devin_db, "dv-0002"),
),
+ (
+ Box::new(OpencodeAdapter::kilo()),
+ db_ref(AgentId::Kilo, &env.kilo_db, "ses_kilo_0001"),
+ ),
+ (
+ Box::new(OpencodeAdapter::kilo()),
+ db_ref(AgentId::Kilo, &env.kilo_db, "ses_kilo_0002"),
+ ),
+ (
+ Box::new(OpencodeAdapter::kilo()),
+ db_ref(AgentId::Kilo, &env.kilo_db, "ses_kilo_0005"),
+ ),
+ (
+ Box::new(KiloLegacyAdapter::new()),
+ kilo_task_ref(&env.kilo_tasks, KILO_T1),
+ ),
+ (
+ Box::new(KiloLegacyAdapter::new()),
+ kilo_task_ref(&env.kilo_tasks, KILO_T2),
+ ),
+ (
+ Box::new(KiloLegacyAdapter::new()),
+ kilo_task_ref(&env.kilo_tasks, KILO_T3),
+ ),
];
for (adapter, r) in &checks {
assert_seq_contract(adapter.as_ref(), r);
@@ -3173,6 +3209,478 @@ fn devin_custom_root_normalization() {
assert_eq!(adapter.data_roots(), vec![lone]);
}
+// ---------------------------------------------------------------- Kilo Code
+
+const KILO_T1: &str = "1736400000000";
+const KILO_T2: &str = "01944f77-3500-7abc-8def-0123456789ab";
+const KILO_T3: &str = "01944f78-bba0-7abc-8def-0123456789ac";
+
+/// 旧版任务的引用:native id 是新版扩展导入它时给的 `ses_migrated_…`
+fn kilo_task_ref(tasks: &Path, task_id: &str) -> SessionFileRef {
+ fs_ref(
+ AgentId::Kilo,
+ &tasks.join(task_id).join("api_conversation_history.json"),
+ &migrated_session_id(task_id),
+ )
+}
+
+#[test]
+fn kilo_parse_contract() {
+ let env = setup();
+ let kilo = OpencodeAdapter::kilo();
+ assert_eq!(kilo.agent(), AgentId::Kilo);
+ assert_eq!(kilo.data_roots(), vec![env.kilo_db.clone()]);
+ let refs = kilo.list_session_files().unwrap();
+ let ids: Vec<&str> = refs.iter().map(|r| r.native_id.as_str()).collect();
+ let migrated = migrated_session_id("migrated-task-0004");
+ for id in [
+ "ses_kilo_0001",
+ "ses_kilo_0002",
+ "ses_kilo_0004",
+ "ses_kilo_0005",
+ migrated.as_str(),
+ ] {
+ assert!(ids.contains(&id), "{id} 应列出: {ids:?}");
+ }
+ assert!(!ids.contains(&"ses_kilo_0003"), "子代理会话不列");
+ assert!(!ids.contains(&"ses_kilo_0006"), "没有正文的会话不列");
+ assert!(refs.iter().all(|r| r.agent == AgentId::Kilo));
+
+ // 正文在 message + part;实验开关双写的那条 shell 记录不能把它换成 v2 路径
+ let r1 = db_ref(AgentId::Kilo, &env.kilo_db, "ses_kilo_0001");
+ let p = kilo.parse_session(&r1).unwrap();
+ assert_eq!(p.meta.key, "kilo:ses_kilo_0001");
+ assert_eq!(p.meta.agent, AgentId::Kilo);
+ assert_eq!(p.meta.title, "Kilo 二维码泄漏排查");
+ assert_eq!(p.meta.project_path, "/Users/tester/Github/wakefx");
+ assert_eq!(p.meta.model.as_deref(), Some("kilo-auto/free"));
+ assert_eq!(p.meta.tokens_used, Some(150));
+ assert_eq!(p.meta.source, None, "opencode2 徽章是 OpenCode 自己的");
+ assert!(!p.meta.archived);
+ assert_eq!(p.unknown_line_count, 0, "agent / retry 是已知的 part");
+ let t = kilo.parse_transcript(&r1).unwrap();
+ assert_eq!(
+ roles_kinds(&t.mainline),
+ vec![
+ (Role::User, MessageKind::Text),
+ (Role::Assistant, MessageKind::Text)
+ ]
+ );
+ assert!(t.mainline[0].text.contains("useEffect()"));
+ let reply = &t.mainline[1];
+ assert_eq!(reply.text, "找到了:卸载时没有停止扫描。");
+ assert_eq!(reply.thinking.as_deref(), Some("先看清理函数"));
+ assert_eq!(reply.tool_calls.len(), 1);
+ assert_eq!(reply.tool_calls[0].name, "grep");
+ assert!(
+ !t.mainline.iter().any(|m| m.text.contains("pnpm test")),
+ "双写的 shell 记录不该顶掉正文"
+ );
+
+ // 用户敲命令派子代理:消息里只有 subtask 块,照用户敲的写回;compaction 标记那条
+ // 用户消息没有内容
+ let t2 = kilo
+ .parse_transcript(&db_ref(AgentId::Kilo, &env.kilo_db, "ses_kilo_0002"))
+ .unwrap();
+ assert_eq!(
+ roles_kinds(&t2.mainline),
+ vec![
+ (Role::User, MessageKind::Text),
+ (Role::Assistant, MessageKind::Text),
+ (Role::Assistant, MessageKind::Text)
+ ]
+ );
+ assert_eq!(t2.mainline[0].text, "/review");
+ assert_eq!(t2.unknown_line_count, 0);
+
+ // 归档与只有 session_message 的会话
+ let archived = kilo
+ .parse_session(&db_ref(AgentId::Kilo, &env.kilo_db, "ses_kilo_0004"))
+ .unwrap();
+ assert!(archived.meta.archived);
+ let v2 = kilo
+ .parse_transcript(&db_ref(AgentId::Kilo, &env.kilo_db, "ses_kilo_0005"))
+ .unwrap();
+ assert_eq!(
+ roles_kinds(&v2.mainline),
+ vec![
+ (Role::User, MessageKind::Text),
+ (Role::Assistant, MessageKind::Text)
+ ]
+ );
+ assert_eq!(v2.mainline[1].text, "v2 回答");
+}
+
+#[test]
+fn kilo_legacy_parse_contract() {
+ let env = setup();
+ let legacy = KiloLegacyAdapter::new();
+ assert_eq!(legacy.agent(), AgentId::Kilo);
+ let roots = legacy.data_roots();
+ assert_eq!(roots[0], env.kilo_tasks, "VS Code 那条恒在、在最前");
+ assert!(
+ roots.contains(&env.kilo_cursor_tasks),
+ "装过旧版的 Cursor 也要收: {roots:?}"
+ );
+ let mut ids: Vec<String> = legacy
+ .list_session_files()
+ .unwrap()
+ .into_iter()
+ .map(|r| r.native_id)
+ .collect();
+ ids.sort();
+ let mut expect: Vec<String> = [
+ KILO_T1,
+ KILO_T2,
+ KILO_T3,
+ "migrated-task-0004",
+ "cursor-task-0007",
+ ]
+ .iter()
+ .map(|t| migrated_session_id(t))
+ .collect();
+ expect.sort();
+ assert_eq!(ids, expect, "只有界面回放的、空数组的任务不算会话");
+
+ // T1:XML 工具协议时代,没有 history_item.json
+ let r1 = kilo_task_ref(&env.kilo_tasks, KILO_T1);
+ let p1 = legacy.parse_session(&r1).unwrap();
+ assert_eq!(p1.meta.key, legacy_task_key(KILO_T1));
+ assert_eq!(
+ p1.meta.title, "修复二维码扫描的内存泄漏",
+ "_index.json 压过 globalState 里停住的旧表"
+ );
+ assert_eq!(p1.meta.project_path, "/Users/tester/Github/wakefx");
+ assert_eq!(p1.meta.tokens_used, Some(150));
+ assert_eq!(p1.meta.source.as_deref(), Some("VS Code"));
+ assert_eq!(
+ p1.meta.created_at, 1_736_400_000_000,
+ "数字 id 就是创建时刻"
+ );
+ assert_eq!(p1.meta.updated_at, 1_736_400_006_000);
+ let t1 = legacy.parse_transcript(&r1).unwrap();
+ assert_eq!(
+ roles_kinds(&t1.mainline),
+ vec![
+ (Role::User, MessageKind::Text),
+ (Role::Assistant, MessageKind::Text),
+ (Role::System, MessageKind::Meta),
+ (Role::Assistant, MessageKind::Text),
+ (Role::System, MessageKind::Meta),
+ (Role::User, MessageKind::Text),
+ (Role::Assistant, MessageKind::Text),
+ ]
+ );
+ assert_eq!(t1.mainline[0].text, "修复二维码扫描的内存泄漏");
+ assert_eq!(
+ t1.mainline[1].thinking.as_deref(),
+ Some("先看看组件里的 useEffect")
+ );
+ assert!(
+ t1.mainline[2].text.contains("scanner.watch()")
+ && t1.mainline[2].text.contains("not a user message"),
+ "XML 工具结果的本体跟着抬头折叠,不是用户说的话"
+ );
+ assert!(
+ !t1.mainline
+ .iter()
+ .any(|m| m.role == Role::User && m.text.contains("not a user message")),
+ "读到的文件里恰好有 <task> 标签,不算用户的话"
+ );
+ assert_eq!(
+ t1.mainline[3].text,
+ "清理函数里没有停止扫描。\n\n已修复:组件卸载时停止扫描。"
+ );
+ assert_eq!(t1.mainline[5].text, "再加一个回归测试");
+ assert!(
+ !t1.mainline
+ .iter()
+ .any(|m| m.text.contains("environment_details")),
+ "编辑器快照不进转录"
+ );
+ assert_eq!(t1.unknown_line_count, 0);
+
+ // T2:原生工具调用,history_item.json 给标题 / 工作区 / token
+ let r2 = kilo_task_ref(&env.kilo_tasks, KILO_T2);
+ let p2 = legacy.parse_session(&r2).unwrap();
+ assert_eq!(p2.meta.title, "Kilo 旧版:给二维码组件加单元测试");
+ assert_eq!(
+ p2.meta.project_path, "/Users/tester/Github/wakefx",
+ "history_item 压过编辑器快照"
+ );
+ assert_eq!(p2.meta.tokens_used, Some(1600), "输入 + 输出 + 缓存写入");
+ assert_eq!(p2.meta.created_at, 1_736_500_000_000, "UUID v7 的前 48 位");
+ assert_eq!(p2.unknown_line_count, 1, "表外的块要计数");
+ let t2 = legacy.parse_transcript(&r2).unwrap();
+ assert_eq!(
+ roles_kinds(&t2.mainline),
+ vec![
+ (Role::User, MessageKind::Text),
+ (Role::Assistant, MessageKind::Text),
+ (Role::Assistant, MessageKind::Text),
+ (Role::User, MessageKind::Text),
+ (Role::Assistant, MessageKind::Text),
+ (Role::Assistant, MessageKind::Text),
+ (Role::User, MessageKind::Text),
+ (Role::System, MessageKind::Meta),
+ ]
+ );
+ let first = &t2.mainline[1];
+ assert_eq!(
+ first.thinking.as_deref(),
+ Some("先确定测试框架"),
+ "独立的推理条目并进紧随的回答"
+ );
+ assert_eq!(first.tool_calls[0].name, "read_file");
+ assert!(first.tool_calls[0].is_error);
+ assert_eq!(
+ first.tool_calls[0].output.as_deref(),
+ Some("File not found: src/QrScanner.test.tsx")
+ );
+ assert_eq!(t2.mainline[2].tool_calls[0].name, "ask_followup_question");
+ assert_eq!(
+ t2.mainline[3].text, "vitest",
+ "追问的回答单独成一条用户消息"
+ );
+ let write = &t2.mainline[4];
+ assert_eq!(write.thinking.as_deref(), Some("写一个最小的卸载测试"));
+ assert!(write.tool_calls[0]
+ .output
+ .as_deref()
+ .unwrap()
+ .contains("wrote 1 file"));
+ assert!(
+ !t2.mainline
+ .iter()
+ .any(|m| m.role == Role::User && m.text.contains("not a user reply")),
+ "别的工具结果里出现 <answer> 不算用户的话"
+ );
+ assert_eq!(
+ t2.mainline[5].text, "测试已添加,vitest 跑通。",
+ "attempt_completion 的 result 是正文"
+ );
+ assert!(t2.mainline[5].tool_calls.is_empty());
+ // 完成后带截图的反馈:发起它的调用已转成正文,图归用户消息
+ assert_eq!(t2.mainline[6].text, "截图里按钮错位了");
+ assert_eq!(t2.mainline[6].images.len(), 1);
+ assert!(t2.mainline[7].text.starts_with("[ERROR]"));
+
+ // T3:T2 派出去的子任务,带一条上下文压缩的摘要
+ let t3 = legacy
+ .parse_transcript(&kilo_task_ref(&env.kilo_tasks, KILO_T3))
+ .unwrap();
+ assert_eq!(
+ roles_kinds(&t3.mainline),
+ vec![
+ (Role::User, MessageKind::Text),
+ (Role::Assistant, MessageKind::Text),
+ (Role::System, MessageKind::CompactSummary),
+ (Role::User, MessageKind::Text),
+ ]
+ );
+ assert_eq!(t3.mainline[3].text, "再跑一遍");
+ assert!(legacy.manages_parent_links() && legacy.parent_links_in_child());
+ let links = legacy.parent_links().expect("任务目录读得出来");
+ assert!(
+ links.contains(&(legacy_task_key(KILO_T3), legacy_task_key(KILO_T2))),
+ "{links:?}"
+ );
+
+ // 装在 Cursor 里的旧版:via 写的是 Cursor
+ let r7 = kilo_task_ref(&env.kilo_cursor_tasks, "cursor-task-0007");
+ assert_eq!(
+ legacy.parse_session(&r7).unwrap().meta.source.as_deref(),
+ Some("Cursor")
+ );
+
+ // 不进文件监听(任务目录里有整份 checkpoints 影子仓库);file_ref 只认正文文件
+ assert!(legacy.watch_paths().is_empty());
+ assert!(legacy
+ .file_ref(
+ &env.kilo_tasks
+ .join(KILO_T2)
+ .join("api_conversation_history.json")
+ )
+ .is_some());
+ for other in ["history_item.json", "ui_messages.json"] {
+ assert!(legacy
+ .file_ref(&env.kilo_tasks.join(KILO_T2).join(other))
+ .is_none());
+ }
+ // 删除:整个任务目录进废纸篓
+ assert_eq!(
+ legacy.session_paths(&p1.meta),
+ vec![env.kilo_tasks.join(KILO_T1).to_string_lossy().to_string()]
+ );
+}
+
+/// 索引读不出来(state.vscdb 坏了、也没有 _index.json)不等于父子关系都解除了:只记在
+/// 索引里的关系那一刻是"不知道",快照整份交 None,库里的关系原样留着
+#[test]
+fn kilo_unreadable_index_leaves_parent_links_unknown() {
+ let env = setup();
+ let dir = tempfile::tempdir().unwrap();
+ let storage = dir.path().join("Code").join("User").join("globalStorage");
+ let tasks = storage.join("kilocode.kilo-code").join("tasks");
+ // 子任务的关系只在 globalState 的 taskHistory 里(没有 history_item.json)
+ common::copy_tree(&env.kilo_tasks.join(KILO_T3), &tasks.join(KILO_T3));
+ fs::remove_file(tasks.join(KILO_T3).join("history_item.json")).unwrap();
+ fs::write(storage.join("state.vscdb"), b"not a sqlite database").unwrap();
+ let legacy = KiloLegacyAdapter::new().with_custom_root(tasks.clone());
+ assert_eq!(legacy.parent_links(), None);
+ // 会话照常列出(元数据退到从正文推)
+ assert_eq!(legacy.list_session_files().unwrap().len(), 1);
+}
+
+/// 缺 history_item.json 的老任务,标题等元数据来自索引:索引里那一条变了,任务的
+/// mtime / size 跟着变,增量扫描才会重解析(否则一直停在旧标题上)
+#[test]
+fn kilo_index_changes_mark_tasks_dirty() {
+ let env = setup();
+ let dir = tempfile::tempdir().unwrap();
+ let tasks = dir.path().join("tasks");
+ common::copy_tree(&env.kilo_tasks.join(KILO_T1), &tasks.join(KILO_T1));
+ let index = |title: &str| {
+ let entry = serde_json::json!({ "entries": [{ "id": KILO_T1, "ts": 1736400006000_i64, "task": title }] });
+ fs::write(tasks.join("_index.json"), entry.to_string()).unwrap();
+ };
+ let legacy = KiloLegacyAdapter::new().with_custom_root(tasks.clone());
+ let fingerprint = || {
+ let r = legacy.list_session_files().unwrap().pop().unwrap();
+ (r.mtime_ms, r.size)
+ };
+ index("old title");
+ let before = fingerprint();
+ index("a renamed title");
+ touch_forward(&tasks.join("_index.json"), 5);
+ assert_ne!(fingerprint(), before);
+ let p = legacy
+ .parse_session(&legacy.list_session_files().unwrap().pop().unwrap())
+ .unwrap();
+ assert_eq!(p.meta.title, "a renamed title");
+}
+
+/// 自定义 location 与远程挂载点按路径形状挑实例(`claims_custom_root`):扩展的任务目录
+/// 归旧版实例,其余归 kilo.db 那个
+#[test]
+fn kilo_custom_roots_route_by_shape() {
+ let env = setup();
+ let dir = tempfile::tempdir().unwrap();
+ let ext = env.kilo_tasks.parent().unwrap().to_path_buf();
+ let data = env.kilo_db.parent().unwrap().to_path_buf();
+ // 自定义实例追加在 roster 末尾
+ let custom = |picked: &Path| {
+ wake_core::adapters::create_adapters_with(&[(AgentId::Kilo, picked.to_path_buf())], &[])
+ .pop()
+ .expect("自定义实例")
+ };
+ // 旧版:选中任务目录、扩展目录、globalStorage 都认
+ for picked in [
+ env.kilo_tasks.clone(),
+ ext.clone(),
+ ext.parent().unwrap().to_path_buf(),
+ ] {
+ assert_eq!(
+ custom(&picked).data_roots(),
+ vec![env.kilo_tasks.clone()],
+ "{picked:?}"
+ );
+ }
+ // 新版:库文件、库所在目录、XDG data 根;认不出形状的也交给它
+ let nowhere = dir.path().join("nowhere");
+ for (picked, db) in [
+ (env.kilo_db.clone(), env.kilo_db.clone()),
+ (data.clone(), env.kilo_db.clone()),
+ (data.parent().unwrap().to_path_buf(), env.kilo_db.clone()),
+ (nowhere.clone(), nowhere.join("kilo.db")),
+ ] {
+ assert_eq!(custom(&picked).data_roots(), vec![db], "{picked:?}");
+ }
+ // 远程挂载点:同步前目录还不存在,按扩展 id 定形,挂的是旧版实例
+ let cache = dir.path().join("remotes").join("devbox");
+ let remote = wake_core::adapters::remote::create_remote_adapters(
+ &wake_core::adapters::create_adapters(),
+ "devbox",
+ &cache,
+ )
+ .into_iter()
+ .find(|a| a.agent() == AgentId::Kilo)
+ .expect("Kilo 的远程实例");
+ let mount = cache.join(".vscode-server/data/User/globalStorage/kilocode.kilo-code");
+ assert_eq!(remote.data_roots(), vec![mount.join("tasks")]);
+
+ // 自定义的旧版实例照样读得出会话;编辑器按路径认,认不出就没有 via
+ let legacy = custom(&env.kilo_tasks);
+ assert_eq!(legacy.list_session_files().unwrap().len(), 4);
+ let p = legacy
+ .parse_session(&kilo_task_ref(&env.kilo_tasks, KILO_T1))
+ .unwrap();
+ assert_eq!(p.meta.source.as_deref(), Some("VS Code"));
+ assert_eq!(p.meta.title, "修复二维码扫描的内存泄漏", "索引照样找得到");
+ let backup = dir.path().join("backup").join("tasks");
+ common::copy_tree(&env.kilo_tasks.join(KILO_T2), &backup.join(KILO_T2));
+ let p = custom(&backup)
+ .parse_session(&kilo_task_ref(&backup, KILO_T2))
+ .unwrap();
+ assert_eq!(p.meta.source, None);
+}
+
+#[test]
+fn kilo_two_sources_remove_and_route_independently() {
+ let env = setup();
+ let roster = wake_core::adapters::create_adapters();
+ let kilos: Vec<&Box<dyn AgentAdapter>> = roster
+ .iter()
+ .filter(|a| a.agent() == AgentId::Kilo)
+ .collect();
+ assert_eq!(kilos.len(), 2, "Kilo 应有新版库与旧版任务目录两个数据源");
+ let (db, legacy) = (kilos[0], kilos[1]);
+ assert_eq!(
+ db.data_roots(),
+ vec![env.kilo_db.clone()],
+ "kilo.db 在前:认不出形状的自定义 location 交给它"
+ );
+ // 导入过 kilo.db 的旧任务两边同 key,kilo.db 那份胜出(端到端见 scanner_finale)
+ let migrated = migrated_session_id("migrated-task-0004");
+ let db_copy = format!("{}#{migrated}", env.kilo_db.display());
+ let legacy_copy = env
+ .kilo_tasks
+ .join("migrated-task-0004")
+ .join("api_conversation_history.json");
+ assert!(db.dedup_rank(&db_copy) < legacy.dedup_rank(&legacy_copy.to_string_lossy()));
+ for a in &kilos {
+ assert!(a.supports_individual_root_removal());
+ }
+ // 移除 kilo.db:旧版实例的根原样;移除 VS Code 那条:Cursor 那条留着
+ assert!(db
+ .excluding_data_roots(std::slice::from_ref(&env.kilo_db))
+ .unwrap()
+ .data_roots()
+ .is_empty());
+ assert_eq!(
+ legacy
+ .excluding_data_roots(std::slice::from_ref(&env.kilo_db))
+ .unwrap()
+ .data_roots(),
+ legacy.data_roots()
+ );
+ assert_eq!(
+ legacy
+ .excluding_data_roots(std::slice::from_ref(&env.kilo_tasks))
+ .unwrap()
+ .data_roots(),
+ vec![env.kilo_cursor_tasks.clone()]
+ );
+ // 路由:任务文件归旧版实例(删除时交出的是任务目录),虚拟路径归库实例
+ let owner =
+ wake_core::adapters::adapter_for(&roster, AgentId::Kilo, &legacy_copy.to_string_lossy())
+ .expect("任务文件必须有实例认领");
+ assert_eq!(owner.data_roots(), legacy.data_roots());
+ let owner = wake_core::adapters::adapter_for(&roster, AgentId::Kilo, &db_copy)
+ .expect("库的虚拟路径必须有实例认领");
+ assert_eq!(owner.data_roots(), vec![env.kilo_db.clone()]);
+}
+
#[test]
fn hermes_parse_contract() {
let env = setup();
diff --git a/crates/wake-core/tests/common/mod.rs b/crates/wake-core/tests/common/mod.rs
index ce3bfef..eceb7fc 100644
--- a/crates/wake-core/tests/common/mod.rs
+++ b/crates/wake-core/tests/common/mod.rs
@@ -251,6 +251,11 @@ pub struct Sidecars {
pub cursor_ide_db: PathBuf,
pub zcode_db: PathBuf,
pub devin_db: PathBuf,
+ /// Kilo Code 新版的库
+ pub kilo_db: PathBuf,
+ /// Kilo Code 旧版扩展装在 VS Code / Cursor 里各自的任务目录
+ pub kilo_tasks: PathBuf,
+ pub kilo_cursor_tasks: PathBuf,
}
/// 侧档与 SQLite 型 fixture 库:copilot/opencode(两代)/antigravity 现建库,
@@ -359,6 +364,21 @@ pub fn stage_sidecars(home: &Path) -> Sidecars {
fs::create_dir_all(devin_db.parent().unwrap()).expect("mkdir devin cli dir");
build_devin_db(&devin_db);
+ let kilo_dir = home.join(".local").join("share").join("kilo");
+ fs::create_dir_all(&kilo_dir).expect("mkdir kilo data dir");
+ let kilo_db = kilo_dir.join("kilo.db");
+ build_kilo_db(&kilo_db);
+ // 旧版扩展:VS Code 里一份(带 globalState 的 taskHistory),Cursor 里一份
+ let code_storage = vscode_global_storage(home, "Code");
+ let kilo_tasks = code_storage.join("kilocode.kilo-code").join("tasks");
+ copy_tree(&fixture("kilo-legacy/Code/tasks"), &kilo_tasks);
+ build_kilo_global_state(
+ &code_storage.join("state.vscdb"),
+ r#"{"taskHistory":[{"id":"1736400000000","ts":1736400006000,"task":"旧标题(globalState)","workspace":"/Users/tester/Github/stale","tokensIn":10,"tokensOut":20}],"kilo-code.welcomed":true}"#,
+ );
+ let kilo_cursor_tasks = cursor_ide_dir.join("kilocode.kilo-code").join("tasks");
+ copy_tree(&fixture("kilo-legacy/Cursor/tasks"), &kilo_cursor_tasks);
+
Sidecars {
copilot_db,
opencode_db,
@@ -370,12 +390,16 @@ pub fn stage_sidecars(home: &Path) -> Sidecars {
cursor_ide_db,
zcode_db,
devin_db,
+ kilo_db,
+ kilo_tasks,
+ kilo_cursor_tasks,
}
}
-/// `<home>/…/Cursor/User/globalStorage`,与 adapters::cursor_ide::storage_dir
-/// 的平台分支逐条对应(改一处必须改另一处,契约测试会因路径不符而空列)
-pub fn cursor_ide_storage_dir(home: &Path) -> PathBuf {
+/// `<home>/…/<编辑器>/User/globalStorage`:VS Code 系编辑器的 globalStorage,与
+/// adapters::vscode_user_data 的平台分支逐条对应(改一处必须改另一处,契约测试会因路径
+/// 不符而空列)
+pub fn vscode_global_storage(home: &Path, editor: &str) -> PathBuf {
let base = if cfg!(target_os = "macos") {
home.join("Library").join("Application Support")
} else if cfg!(target_os = "windows") {
@@ -383,7 +407,175 @@ pub fn cursor_ide_storage_dir(home: &Path) -> PathBuf {
} else {
home.join(".config")
};
- base.join("Cursor").join("User").join("globalStorage")
+ base.join(editor).join("User").join("globalStorage")
+}
+
+/// `<home>/…/Cursor/User/globalStorage`
+pub fn cursor_ide_storage_dir(home: &Path) -> PathBuf {
+ vscode_global_storage(home, "Cursor")
+}
+
+/// 编辑器的 `globalStorage/state.vscdb`:扩展的 globalState 整份 JSON 存在 ItemTable 里、以
+/// 扩展 id 为 key(另放一条别家扩展的行和一条 secret 行陪着)
+fn build_kilo_global_state(path: &Path, global_state: &str) {
+ let conn = rusqlite::Connection::open(path).expect("create state.vscdb fixture");
+ conn.execute_batch(
+ r#"
+ CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB);
+ INSERT INTO ItemTable VALUES ('GitHub.copilot', '{"seen":true}');
+ INSERT INTO ItemTable VALUES ('secret://{"extensionId":"kilocode.kilo-code","key":"apiKey"}', X'00FF');
+ "#,
+ )
+ .expect("populate state.vscdb fixture");
+ conn.execute(
+ "INSERT INTO ItemTable VALUES ('kilocode.kilo-code', ?1)",
+ [global_state],
+ )
+ .expect("insert kilo globalState");
+}
+
+/// Kilo Code 新版的 `kilo.db`(OpenCode 分支,表与 OpenCode 同形,列按 Kilo 7.x 的真实
+/// schema 取子集):
+/// - `ses_kilo_0001`:正常会话,v1 两表;另有一条实验开关下双写的 session_message
+/// shell 记录——必须照旧读 message + part(OpenCode 的判据会只剩那一条);part 里带
+/// agent / retry 两种已知但不渲染的类型
+/// - `ses_kilo_0002`:用户敲 `/review` 派子代理(消息里只有 subtask 块)、一条 compaction
+/// 标记、压缩出的摘要
+/// - `ses_kilo_0003`:子代理会话(parent_id),不列
+/// - `ses_kilo_0004`:已归档
+/// - `ses_kilo_0005`:只有 session_message 的会话(v2 路径)
+/// - `ses_kilo_0006`:没有正文,不列
+/// - 旧任务 `migrated-task-0004` 导进来的那份(`ses_migrated_…`),与旧版任务目录里的
+/// 原件同 key,scanner 让这份胜出
+///
+/// 另有 credential 表与一行假凭证:真库就长这样,adapter 绝不读它
+pub fn build_kilo_db(path: &Path) {
+ let migrated = wake_core::adapters::kilo::migrated_session_id("migrated-task-0004");
+ let conn = rusqlite::Connection::open(path).expect("create kilo fixture db");
+ conn.execute_batch(&format!(
+ r#"
+ CREATE TABLE session (
+ id TEXT PRIMARY KEY, project_id TEXT NOT NULL, workspace_id TEXT, parent_id TEXT,
+ slug TEXT NOT NULL, directory TEXT NOT NULL, path TEXT, title TEXT NOT NULL,
+ version TEXT NOT NULL, share_url TEXT, metadata TEXT,
+ cost REAL NOT NULL DEFAULT 0,
+ tokens_input INTEGER NOT NULL DEFAULT 0, tokens_output INTEGER NOT NULL DEFAULT 0,
+ tokens_reasoning INTEGER NOT NULL DEFAULT 0, tokens_cache_read INTEGER NOT NULL DEFAULT 0,
+ tokens_cache_write INTEGER NOT NULL DEFAULT 0, agent TEXT, model TEXT,
+ time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL,
+ time_compacting INTEGER, time_archived INTEGER
+ );
+ CREATE TABLE message (
+ id TEXT PRIMARY KEY, session_id TEXT NOT NULL,
+ time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL
+ );
+ CREATE TABLE part (
+ id TEXT PRIMARY KEY, message_id TEXT NOT NULL, session_id TEXT NOT NULL,
+ time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL
+ );
+ CREATE TABLE session_message (
+ id TEXT PRIMARY KEY, session_id TEXT NOT NULL, type TEXT NOT NULL, seq INTEGER,
+ time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL
+ );
+ CREATE TABLE credential (
+ id TEXT PRIMARY KEY, integration_id TEXT, label TEXT NOT NULL, value TEXT NOT NULL,
+ connector_id TEXT, method_id TEXT, active INTEGER,
+ time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL
+ );
+ INSERT INTO credential VALUES
+ ('cred-1', 'kilo', 'default', '{{"type":"api","key":"NOT-A-REAL-SECRET"}}', NULL, NULL, 1, 0, 0);
+
+ INSERT INTO session (id, project_id, parent_id, slug, directory, title, version,
+ tokens_input, tokens_output, tokens_reasoning, agent, model,
+ time_created, time_updated, time_archived) VALUES
+ ('ses_kilo_0001', 'prj1', NULL, 'brave-otter', '/Users/tester/Github/wakefx',
+ 'Kilo 二维码泄漏排查', '7.8.8', 100, 40, 10, 'code',
+ '{{"id":"kilo-auto/free","providerID":"kilo"}}', 1786300000000, 1786300600000, NULL),
+ ('ses_kilo_0002', 'prj1', NULL, 'calm-pine', '/Users/tester/Github/wakefx',
+ 'Review the QR changes', '7.8.8', 0, 0, 0, 'code', NULL,
+ 1786301000000, 1786301600000, NULL),
+ ('ses_kilo_0003', 'prj1', 'ses_kilo_0001', 'sub-agent', '/Users/tester/Github/wakefx',
+ 'Subagent: grep the scanner', '7.8.8', 0, 0, 0, 'explore', NULL,
+ 1786300200000, 1786300300000, NULL),
+ ('ses_kilo_0004', 'prj1', NULL, 'old-lake', '/Users/tester/Github/wakefx',
+ 'Archived Kilo session', '7.8.8', 0, 0, 0, 'code', NULL,
+ 1786200000000, 1786200100000, 1786400000000),
+ ('ses_kilo_0005', 'prj1', NULL, 'next-wave', '/Users/tester/Github/wakefx',
+ 'Kilo v2 会话', '7.9.0', 0, 0, 0, 'code', NULL,
+ 1786500000000, 1786500100000, NULL),
+ ('ses_kilo_0006', 'prj1', NULL, 'empty-sky', '/Users/tester/Github/wakefx',
+ 'New session', '7.8.8', 0, 0, 0, 'code', NULL,
+ 1786600000000, 1786600000000, NULL),
+ ('{migrated}', 'prj1', NULL, 'migrated-task-0004', '/Users/tester/Github/wakefx',
+ '迁移过的旧任务', 'v2', 0, 0, 0, NULL, NULL,
+ 1736600001000, 1736600002000, NULL);
+
+ INSERT INTO message VALUES
+ ('msg_k1_a', 'ses_kilo_0001', 1786300050000, 1786300050000,
+ '{{"role":"user","time":{{"created":1786300050000}},"agent":"code"}}'),
+ ('msg_k1_b', 'ses_kilo_0001', 1786300100000, 1786300100000,
+ '{{"role":"assistant","time":{{"created":1786300100000}},"modelID":"kilo-auto/free","providerID":"kilo"}}'),
+ ('msg_k2_a', 'ses_kilo_0002', 1786301050000, 1786301050000,
+ '{{"role":"user","time":{{"created":1786301050000}}}}'),
+ ('msg_k2_b', 'ses_kilo_0002', 1786301100000, 1786301100000,
+ '{{"role":"assistant","time":{{"created":1786301100000}}}}'),
+ ('msg_k2_c', 'ses_kilo_0002', 1786301200000, 1786301200000,
+ '{{"role":"user","time":{{"created":1786301200000}}}}'),
+ ('msg_k2_d', 'ses_kilo_0002', 1786301300000, 1786301300000,
+ '{{"role":"assistant","summary":true,"time":{{"created":1786301300000}}}}'),
+ ('msg_k3_a', 'ses_kilo_0003', 1786300250000, 1786300250000,
+ '{{"role":"user","time":{{"created":1786300250000}}}}'),
+ ('msg_k4_a', 'ses_kilo_0004', 1786200050000, 1786200050000,
+ '{{"role":"user","time":{{"created":1786200050000}}}}'),
+ ('msg_m4_a', '{migrated}', 1736600001000, 1736600001000,
+ '{{"role":"user","time":{{"created":1736600001000}}}}'),
+ ('msg_m4_b', '{migrated}', 1736600002000, 1736600002000,
+ '{{"role":"assistant","time":{{"created":1736600002000}}}}');
+
+ INSERT INTO part VALUES
+ ('prt_k1_a1', 'msg_k1_a', 'ses_kilo_0001', 1786300050000, 1786300050000,
+ '{{"type":"text","text":"Kilo 修一下二维码扫描的 useEffect() 泄漏 @build"}}'),
+ ('prt_k1_a2', 'msg_k1_a', 'ses_kilo_0001', 1786300050000, 1786300050000,
+ '{{"type":"agent","name":"build"}}'),
+ ('prt_k1_b1', 'msg_k1_b', 'ses_kilo_0001', 1786300100000, 1786300100000,
+ '{{"type":"step-start"}}'),
+ ('prt_k1_b2', 'msg_k1_b', 'ses_kilo_0001', 1786300100000, 1786300100000,
+ '{{"type":"reasoning","text":"先看清理函数"}}'),
+ ('prt_k1_b3', 'msg_k1_b', 'ses_kilo_0001', 1786300100000, 1786300100000,
+ '{{"type":"retry","attempt":1,"error":{{"name":"APIError","data":{{"message":"overloaded"}}}},"time":{{"created":1786300100500}}}}'),
+ ('prt_k1_b4', 'msg_k1_b', 'ses_kilo_0001', 1786300100000, 1786300100000,
+ '{{"type":"tool","callID":"call_1","tool":"grep","state":{{"status":"completed","input":{{"pattern":"useEffect"}},"output":"src/QrScanner.tsx:42"}}}}'),
+ ('prt_k1_b5', 'msg_k1_b', 'ses_kilo_0001', 1786300100000, 1786300100000,
+ '{{"type":"text","text":"找到了:卸载时没有停止扫描。"}}'),
+ ('prt_k1_b6', 'msg_k1_b', 'ses_kilo_0001', 1786300100000, 1786300100000,
+ '{{"type":"step-finish","tokens":{{"input":100,"output":40}}}}'),
+ ('prt_k2_a1', 'msg_k2_a', 'ses_kilo_0002', 1786301050000, 1786301050000,
+ '{{"type":"subtask","command":"review","description":"Review the QR changes","agent":"reviewer","prompt":"Review the following changes carefully"}}'),
+ ('prt_k2_b1', 'msg_k2_b', 'ses_kilo_0002', 1786301100000, 1786301100000,
+ '{{"type":"text","text":"Review done: no leaks left."}}'),
+ ('prt_k2_c1', 'msg_k2_c', 'ses_kilo_0002', 1786301200000, 1786301200000,
+ '{{"type":"compaction","auto":true}}'),
+ ('prt_k2_d1', 'msg_k2_d', 'ses_kilo_0002', 1786301300000, 1786301300000,
+ '{{"type":"text","text":"Summary of the QR work so far."}}'),
+ ('prt_k3_a1', 'msg_k3_a', 'ses_kilo_0003', 1786300250000, 1786300250000,
+ '{{"type":"text","text":"grep the scanner"}}'),
+ ('prt_k4_a1', 'msg_k4_a', 'ses_kilo_0004', 1786200050000, 1786200050000,
+ '{{"type":"text","text":"an archived question"}}'),
+ ('prt_m4_a1', 'msg_m4_a', '{migrated}', 1736600001000, 1736600001000,
+ '{{"type":"text","text":"迁移过的旧任务"}}'),
+ ('prt_m4_b1', 'msg_m4_b', '{migrated}', 1736600002000, 1736600002000,
+ '{{"type":"text","text":"旧任务的回答(导入后)"}}');
+
+ INSERT INTO session_message VALUES
+ ('sm_k1_0', 'ses_kilo_0001', 'shell', 0, 1786300400000, 1786300400000,
+ '{{"callID":"sh-1","command":"pnpm test","output":"ok","time":{{"created":1786300400000}}}}'),
+ ('sm_k5_0', 'ses_kilo_0005', 'user', 0, 1786500000000, 1786500000000,
+ '{{"text":"Kilo v2 会话问一句","time":{{"created":1786500000000}}}}'),
+ ('sm_k5_1', 'ses_kilo_0005', 'assistant', 1, 1786500050000, 1786500050000,
+ '{{"model":{{"id":"kilo-auto/free","providerID":"kilo"}},"time":{{"created":1786500050000}},"content":[{{"type":"text","text":"v2 回答"}}]}}');
+ "#
+ ))
+ .expect("populate kilo fixture db");
}
/// Hermes `state.db` 最小同构库:sessions + messages(时间戳 unix 秒 REAL)。
@@ -826,6 +1018,9 @@ pub fn clear_agent_env_overrides() {
"CODEBUDDY_CONFIG_DIR",
"WORKBUDDY_CONFIG_DIR",
"ZCODE_STORAGE_DIR",
+ // 库路径的覆盖:指向现存文件时会被加进数据根,读到合成 HOME 之外的真实库
+ "OPENCODE_DB",
+ "KILO_DB",
] {
std::env::remove_var(var);
}
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f77-3500-7abc-8def-0123456789ab/api_conversation_history.json b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f77-3500-7abc-8def-0123456789ab/api_conversation_history.json
new file mode 100644
index 0000000..93c9585
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f77-3500-7abc-8def-0123456789ab/api_conversation_history.json
@@ -0,0 +1,180 @@
+[
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "<task>\nKilo 旧版:给二维码组件加单元测试\n</task>"
+ },
+ {
+ "type": "text",
+ "text": "<environment_details>\n# Current Workspace Directory (/Users/tester/Github/other) Files\n</environment_details>"
+ }
+ ],
+ "ts": 1736500001000
+ },
+ {
+ "type": "reasoning",
+ "summary": [
+ {
+ "type": "summary_text",
+ "text": "先确定测试框架"
+ }
+ ],
+ "encrypted_content": "gAAAAB-opaque",
+ "id": "rs_1",
+ "ts": 1736500001500
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "我先看看现有测试。"
+ },
+ {
+ "type": "tool_use",
+ "id": "toolu_1",
+ "name": "read_file",
+ "input": {
+ "path": "src/QrScanner.test.tsx"
+ }
+ }
+ ],
+ "ts": 1736500002000
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "toolu_1",
+ "content": [
+ {
+ "type": "text",
+ "text": "File not found: src/QrScanner.test.tsx"
+ }
+ ],
+ "is_error": true
+ }
+ ],
+ "ts": 1736500003000
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "toolu_2",
+ "name": "ask_followup_question",
+ "input": {
+ "question": "用 vitest 还是 jest?"
+ }
+ }
+ ],
+ "ts": 1736500004000
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "toolu_2",
+ "content": "<answer>\nvitest\n</answer>"
+ }
+ ],
+ "ts": 1736500005000
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "好,用 vitest。"
+ },
+ {
+ "type": "tool_use",
+ "id": "toolu_3",
+ "name": "write_to_file",
+ "input": {
+ "path": "src/QrScanner.test.tsx",
+ "content": "test('stops scanning', () => {})"
+ }
+ }
+ ],
+ "reasoning_content": "写一个最小的卸载测试",
+ "ts": 1736500006000
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "toolu_3",
+ "content": [
+ {
+ "type": "text",
+ "text": "<answer>not a user reply</answer> wrote 1 file"
+ }
+ ]
+ },
+ {
+ "type": "text",
+ "text": "<environment_details>\n</environment_details>"
+ }
+ ],
+ "ts": 1736500007000
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "toolu_4",
+ "name": "attempt_completion",
+ "input": {
+ "result": "测试已添加,vitest 跑通。"
+ }
+ }
+ ],
+ "ts": 1736500008000
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "toolu_4",
+ "content": [
+ {
+ "type": "text",
+ "text": "The user has provided feedback on the results. Consider their input to continue the task, and then attempt completion again.\n<feedback>\n截图里按钮错位了\n</feedback>"
+ },
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
+ }
+ }
+ ]
+ }
+ ],
+ "ts": 1736500009000
+ },
+ {
+ "role": "user",
+ "content": "[ERROR] You did not use a tool in your previous response! Please retry with a tool use.",
+ "ts": 1736500009500
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "wibble_block"
+ }
+ ],
+ "ts": 1736500010000
+ }
+]
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f77-3500-7abc-8def-0123456789ab/history_item.json b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f77-3500-7abc-8def-0123456789ab/history_item.json
new file mode 100644
index 0000000..9feadcf
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f77-3500-7abc-8def-0123456789ab/history_item.json
@@ -0,0 +1,14 @@
+{
+ "id": "01944f77-3500-7abc-8def-0123456789ab",
+ "number": 2,
+ "ts": 1736500010000,
+ "task": "Kilo 旧版:给二维码组件加单元测试",
+ "tokensIn": 1200,
+ "tokensOut": 300,
+ "cacheWrites": 100,
+ "cacheReads": 5000,
+ "totalCost": 0.012,
+ "size": 4096,
+ "workspace": "/Users/tester/Github/wakefx",
+ "mode": "code"
+}
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f78-bba0-7abc-8def-0123456789ac/api_conversation_history.json b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f78-bba0-7abc-8def-0123456789ac/api_conversation_history.json
new file mode 100644
index 0000000..54223d3
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f78-bba0-7abc-8def-0123456789ac/api_conversation_history.json
@@ -0,0 +1,43 @@
+[
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "<task>\n写 vitest 配置\n</task>"
+ }
+ ],
+ "ts": 1736500101000
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "配置写好了。"
+ }
+ ],
+ "ts": 1736500102000
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "Summary: 写好了 vitest 配置,等待确认。"
+ }
+ ],
+ "isSummary": true,
+ "ts": 1736500102500
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "<user_message>\n再跑一遍\n</user_message>"
+ }
+ ],
+ "ts": 1736500103000
+ }
+]
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f78-bba0-7abc-8def-0123456789ac/history_item.json b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f78-bba0-7abc-8def-0123456789ac/history_item.json
new file mode 100644
index 0000000..09cddc7
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/01944f78-bba0-7abc-8def-0123456789ac/history_item.json
@@ -0,0 +1,12 @@
+{
+ "id": "01944f78-bba0-7abc-8def-0123456789ac",
+ "number": 3,
+ "ts": 1736500103000,
+ "task": "写 vitest 配置",
+ "tokensIn": 10,
+ "tokensOut": 5,
+ "workspace": "/Users/tester/Github/wakefx",
+ "mode": "code",
+ "parentTaskId": "01944f77-3500-7abc-8def-0123456789ab",
+ "rootTaskId": "01944f77-3500-7abc-8def-0123456789ab"
+}
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/1736400000000/api_conversation_history.json b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/1736400000000/api_conversation_history.json
new file mode 100644
index 0000000..01adcdc
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/1736400000000/api_conversation_history.json
@@ -0,0 +1,82 @@
+[
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "<task>\n修复二维码扫描的内存泄漏\n</task>"
+ },
+ {
+ "type": "text",
+ "text": "<environment_details>\n# VSCode Visible Files\nsrc/QrScanner.tsx\n\n# Current Workspace Directory (/Users/tester/Github/wakefx) Files\nsrc/\n</environment_details>"
+ }
+ ],
+ "ts": 1736400001000
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "<thinking>先看看组件里的 useEffect</thinking>\n我先读一下组件。\n\n<read_file>\n<path>src/QrScanner.tsx</path>\n</read_file>"
+ }
+ ],
+ "ts": 1736400002000
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "[read_file for 'src/QrScanner.tsx'] Result:"
+ },
+ {
+ "type": "text",
+ "text": "// prompt template: <task>not a user message</task>\nuseEffect(() => { scanner.watch() }, [])"
+ },
+ {
+ "type": "text",
+ "text": "<environment_details>\n# VSCode Visible Files\nsrc/QrScanner.tsx\n\n# Current Workspace Directory (/Users/tester/Github/wakefx) Files\nsrc/\n</environment_details>"
+ }
+ ],
+ "ts": 1736400003000
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "清理函数里没有停止扫描。\n\n<attempt_completion>\n<result>\n已修复:组件卸载时停止扫描。\n</result>\n</attempt_completion>"
+ }
+ ],
+ "ts": 1736400004000
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "[attempt_completion] Result:"
+ },
+ {
+ "type": "text",
+ "text": "The user has provided feedback on the results. Consider their input to continue the task, and then attempt completion again.\n<feedback>\n再加一个回归测试\n</feedback>"
+ },
+ {
+ "type": "text",
+ "text": "<environment_details>\n</environment_details>"
+ }
+ ],
+ "ts": 1736400005000
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "回归测试也加上了。"
+ }
+ ],
+ "ts": 1736400006000
+ }
+]
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/1736400000000/ui_messages.json b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/1736400000000/ui_messages.json
new file mode 100644
index 0000000..ab5d250
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/1736400000000/ui_messages.json
@@ -0,0 +1,8 @@
+[
+ {
+ "ts": 1736400001000,
+ "type": "say",
+ "say": "task",
+ "text": "修复二维码扫描的内存泄漏"
+ }
+]
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/_index.json b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/_index.json
new file mode 100644
index 0000000..56c4be1
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/_index.json
@@ -0,0 +1,12 @@
+{
+ "entries": [
+ {
+ "id": "1736400000000",
+ "ts": 1736400006000,
+ "task": "修复二维码扫描的内存泄漏",
+ "workspace": "/Users/tester/Github/wakefx",
+ "tokensIn": 100,
+ "tokensOut": 50
+ }
+ ]
+}
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/empty-0006/api_conversation_history.json b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/empty-0006/api_conversation_history.json
new file mode 100644
index 0000000..0637a08
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/empty-0006/api_conversation_history.json
@@ -0,0 +1 @@
+[]
\ No newline at end of file
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/migrated-task-0004/api_conversation_history.json b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/migrated-task-0004/api_conversation_history.json
new file mode 100644
index 0000000..ebdb642
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/migrated-task-0004/api_conversation_history.json
@@ -0,0 +1,22 @@
+[
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "<task>\n迁移过的旧任务\n</task>"
+ }
+ ],
+ "ts": 1736600001000
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "旧任务的回答"
+ }
+ ],
+ "ts": 1736600002000
+ }
+]
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/migrated-task-0004/history_item.json b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/migrated-task-0004/history_item.json
new file mode 100644
index 0000000..51f8e16
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/migrated-task-0004/history_item.json
@@ -0,0 +1,6 @@
+{
+ "id": "migrated-task-0004",
+ "ts": 1736600002000,
+ "task": "迁移过的旧任务",
+ "workspace": "/Users/tester/Github/wakefx"
+}
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/ui-only-0005/ui_messages.json b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/ui-only-0005/ui_messages.json
new file mode 100644
index 0000000..e7cfa32
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Code/tasks/ui-only-0005/ui_messages.json
@@ -0,0 +1,8 @@
+[
+ {
+ "ts": 1736600100000,
+ "type": "say",
+ "say": "text",
+ "text": "hi"
+ }
+]
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Cursor/tasks/cursor-task-0007/api_conversation_history.json b/crates/wake-core/tests/fixtures/kilo-legacy/Cursor/tasks/cursor-task-0007/api_conversation_history.json
new file mode 100644
index 0000000..39b3762
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Cursor/tasks/cursor-task-0007/api_conversation_history.json
@@ -0,0 +1,22 @@
+[
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "text",
+ "text": "<task>\nCursor 里跑的旧任务\n</task>"
+ }
+ ],
+ "ts": 1736700001000
+ },
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "text",
+ "text": "好"
+ }
+ ],
+ "ts": 1736700002000
+ }
+]
diff --git a/crates/wake-core/tests/fixtures/kilo-legacy/Cursor/tasks/cursor-task-0007/history_item.json b/crates/wake-core/tests/fixtures/kilo-legacy/Cursor/tasks/cursor-task-0007/history_item.json
new file mode 100644
index 0000000..7b582a5
--- /dev/null
+++ b/crates/wake-core/tests/fixtures/kilo-legacy/Cursor/tasks/cursor-task-0007/history_item.json
@@ -0,0 +1,6 @@
+{
+ "id": "cursor-task-0007",
+ "ts": 1736700002000,
+ "task": "Cursor 里跑的旧任务",
+ "workspace": "/Users/tester/Github/wakefx"
+}
diff --git a/crates/wake-core/tests/remote_sync.rs b/crates/wake-core/tests/remote_sync.rs
index 50c90e3..3da31ff 100644
--- a/crates/wake-core/tests/remote_sync.rs
+++ b/crates/wake-core/tests/remote_sync.rs
@@ -55,8 +55,18 @@ fn build_remote_home(home: &Path) {
fs::remove_dir_all(home.join(".copilot")).unwrap();
// 凭证在白名单外,必须留在远端
touch(&home.join(".codex/auth.json"), "NOT-A-REAL-SECRET");
+ // Kilo 旧版扩展跑在 Remote-SSH 的远端:任务目录在 vscode-server 的用户数据里,
+ // 每个任务带一份检查点影子仓库(量大,exclude 挡掉)
+ let kilo_tasks = home.join(KILO_TASKS);
+ common::copy_tree(&common::fixture("kilo-legacy/Code/tasks"), &kilo_tasks);
+ touch(
+ &kilo_tasks.join("migrated-task-0004/checkpoints/.git/HEAD"),
+ "ref: refs/heads/main",
+ );
}
+const KILO_TASKS: &str = ".vscode-server/data/User/globalStorage/kilocode.kilo-code/tasks";
+
/// 假远端上装着的 agent(Copilot 故意缺席,见 build_remote_home)
fn remote_agents() -> impl Iterator<Item = AgentId> {
AgentId::ALL.into_iter().filter(|a| *a != AgentId::Copilot)
@@ -200,6 +210,20 @@ fn remote_pipeline_end_to_end() {
);
assert!(!cache.join(".codex/auth.json").exists(), "凭证进了缓存");
assert!(!cache.join(".copilot").exists());
+ // Kilo:旧版任务到位、检查点仓库挡在外面;新版的库里有 credential 表,整库不拉
+ let kilo_task = cache.join(KILO_TASKS).join("migrated-task-0004");
+ assert!(
+ kilo_task.join("api_conversation_history.json").is_file(),
+ "Kilo 旧版任务没同步到缓存"
+ );
+ assert!(
+ !kilo_task.join("checkpoints").exists(),
+ "检查点仓库进了缓存"
+ );
+ assert!(
+ !cache.join(".local/share/kilo").exists(),
+ "带凭证的 kilo.db 进了缓存"
+ );
// Craft Agents:会话与回合锚点(认领要读)到位;源配置(可能带 client secret)、
// 附件、引擎原料与原子写的中间文件被带层级的 exclude 挡在外面
let craft_ws = cache.join(".craft-agent/workspaces/wakefx-ws");
diff --git a/crates/wake-core/tests/scanner_finale.rs b/crates/wake-core/tests/scanner_finale.rs
index ac7898e..4dafde9 100644
--- a/crates/wake-core/tests/scanner_finale.rs
+++ b/crates/wake-core/tests/scanner_finale.rs
@@ -1385,6 +1385,82 @@ fn cursor_transcript_outranks_ide_copy() {
assert_eq!(taken_over.title, "CLI twin");
}
+/// Kilo Code 新版扩展把旧任务导进 kilo.db 时,会话 id 是 sha1(任务 id) 派生的
+/// `ses_migrated_…`;旧任务在 Wake 里用的就是这个 id,两份同 key,kilo.db 那份胜出
+/// (不看 mtime 与 roster 顺序),旧任务文件留作回退:kilo.db 里那份没了,它顶上来,
+/// key 不变。没导过的旧任务照常列出,子任务挂回父任务
+#[test]
+fn kilo_migrated_task_prefers_the_database_copy() {
+ use wake_core::adapters::kilo::{legacy_task_key, migrated_session_id, KiloLegacyAdapter};
+ use wake_core::adapters::opencode::OpencodeAdapter;
+
+ let dir = tempfile::tempdir().unwrap();
+ let ext = dir.path().join("globalStorage").join("kilocode.kilo-code");
+ let tasks = ext.join("tasks");
+ common::copy_tree(&common::fixture("kilo-legacy/Code/tasks"), &tasks);
+ let db = dir.path().join("kilo").join("kilo.db");
+ std::fs::create_dir_all(db.parent().unwrap()).unwrap();
+ common::build_kilo_db(&db);
+ let migrated_id = migrated_session_id("migrated-task-0004");
+ let migrated = legacy_task_key("migrated-task-0004");
+ let legacy_copy = tasks
+ .join("migrated-task-0004")
+ .join("api_conversation_history.json");
+
+ for legacy_first in [true, false] {
+ let from_db: Box<dyn AgentAdapter> = OpencodeAdapter::kilo().with_custom_root(db.clone());
+ let from_tasks: Box<dyn AgentAdapter> =
+ KiloLegacyAdapter::new().with_custom_root(tasks.clone());
+ let adapters: Vec<Box<dyn AgentAdapter>> = if legacy_first {
+ vec![from_tasks, from_db]
+ } else {
+ vec![from_db, from_tasks]
+ };
+ let store = temp_store(&dir.path().join(format!("store-{legacy_first}")));
+ run_scan(&adapters, &store, &Recorder::new(), true).unwrap();
+ let row = store
+ .get_session(&migrated)
+ .unwrap()
+ .expect("导入过的旧任务在库");
+ assert!(
+ row.file_path.contains("kilo.db#"),
+ "legacy_first={legacy_first}:kilo.db 里那份胜出,得到 {}",
+ row.file_path
+ );
+ let legacy_only = store
+ .get_session(&legacy_task_key("1736400000000"))
+ .unwrap()
+ .expect("没导过的旧任务照常列出");
+ assert_eq!(legacy_only.title, "修复二维码扫描的内存泄漏");
+ let child = store
+ .get_session(&legacy_task_key("01944f78-bba0-7abc-8def-0123456789ac"))
+ .unwrap()
+ .expect("子任务在库");
+ assert_eq!(
+ store.parent_key_of(&child.key).unwrap().as_deref(),
+ Some(legacy_task_key("01944f77-3500-7abc-8def-0123456789ab").as_str()),
+ "legacy_first={legacy_first}:子任务挂回父任务"
+ );
+ }
+
+ // kilo.db 里那份没了(用户在 Kilo 里删了它):旧任务文件顶上来,key 不变
+ let conn = rusqlite::Connection::open(&db).unwrap();
+ conn.execute("DELETE FROM session WHERE id = ?1", [&migrated_id])
+ .unwrap();
+ drop(conn);
+ let adapters: Vec<Box<dyn AgentAdapter>> = vec![
+ OpencodeAdapter::kilo().with_custom_root(db.clone()),
+ KiloLegacyAdapter::new().with_custom_root(tasks.clone()),
+ ];
+ let store = temp_store(&dir.path().join("store-false"));
+ run_scan(&adapters, &store, &Recorder::new(), true).unwrap();
+ let row = store
+ .get_session(&migrated)
+ .unwrap()
+ .expect("库里那份没了,旧任务还在");
+ assert_eq!(Path::new(&row.file_path), legacy_copy.as_path());
+}
+
/// 跨 agent 重叠根:文件只归**最长根**的实例(与 watcher 分派同一语义)。
/// 旧行为两家轮流认领——先写的一家留下错误归属,后写的撞 file_path UNIQUE
#[test]
diff --git a/crates/wake/assets/brands/kilo-light.png b/crates/wake/assets/brands/kilo-light.png
new file mode 100644
index 0000000..efaabeb
Binary files /dev/null and b/crates/wake/assets/brands/kilo-light.png differ
diff --git a/crates/wake/assets/brands/kilo.png b/crates/wake/assets/brands/kilo.png
new file mode 100644
index 0000000..2d28e1d
Binary files /dev/null and b/crates/wake/assets/brands/kilo.png differ
diff --git a/crates/wake/src/assets.rs b/crates/wake/src/assets.rs
index 159fb6e..a85eb02 100644
--- a/crates/wake/src/assets.rs
+++ b/crates/wake/src/assets.rs
@@ -65,6 +65,8 @@ brands!(
"craft-agents",
"devin",
"devin-light",
+ "kilo",
+ "kilo-light",
);
fn lookup_product(path: &str) -> Option<&'static [u8]> {
diff --git a/crates/wake/src/theme.rs b/crates/wake/src/theme.rs
index d8e8c08..a6f6e8f 100644
--- a/crates/wake/src/theme.rs
+++ b/crates/wake/src/theme.rs
@@ -113,6 +113,9 @@ pub fn agent_series_color(agent: wake_core::models::AgentId) -> u32 {
// 标志是单色的,给一档天蓝(Devin Desktop 的主色系),蓝色家族里离 Gemini、
// Cursor 都最远的一档
Devin => 0x3BB3F1,
+ // 品牌柠檬黄 #F7F569 在白底上几乎看不见(对比 1.15),压深一档;离 Hermes 的
+ // 金色 ΔE00 11.9(色板里最近的一对只有 5.4)
+ Kilo => 0xC8C035,
}
}
diff --git a/crates/wake/src/workbench.rs b/crates/wake/src/workbench.rs
index ab57ea7..03fcec9 100644
--- a/crates/wake/src/workbench.rs
+++ b/crates/wake/src/workbench.rs
@@ -2344,7 +2344,7 @@ impl UsageBoard {
}
}
- /// Agents 全量列出(总共二十一家);项目/模型长尾长,取前 6
+ /// Agents 全量列出(总共二十二家);项目/模型长尾长,取前 6
fn limit(self) -> usize {
match self {
Self::Agents => usize::MAX,
diff --git a/docs/cli.md b/docs/cli.md
index 476cd2f..61b7de0 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -303,7 +303,7 @@ Numeric options outside their range are clamped, not rejected: `--limit 999` on
## Agent ids
-`claude-code`, `codex`, `grok`, `dsh`, `cursor`, `opencode`, `pi`, `omp`, `kiro`, `kimi`, `gemini`, `copilot`, `antigravity`, `qoder`, `hermes`, `openclaw`, `codebuddy`, `workbuddy`, `zcode`, `craft-agents`, `devin`. Display names (`"Claude Code"`) and a few aliases (`claude`, `deepseek`, `craft`) work too.
+`claude-code`, `codex`, `grok`, `dsh`, `cursor`, `opencode`, `pi`, `omp`, `kiro`, `kimi`, `gemini`, `copilot`, `antigravity`, `qoder`, `hermes`, `openclaw`, `codebuddy`, `workbuddy`, `zcode`, `craft-agents`, `devin`, `kilo`. Display names (`"Claude Code"`) and a few aliases (`claude`, `deepseek`, `craft`) work too.
## Session keys and references
diff --git a/docs/mcp.md b/docs/mcp.md
index 2cb0f00..41aa17d 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -132,7 +132,7 @@ All five tools are read-only and return Markdown text (`content[0].text`). Param
| Parameter | Type | Meaning |
|---|---|---|
| `project` | string | Scope to one project. Pass an absolute path — the agent's working directory is ideal — or a project name. Path matching is three-tier: an exact match of an indexed project path; otherwise the longest indexed project that contains the path (you are in a subdirectory); otherwise every indexed project below the path (a monorepo root or a parent folder). A bare name matches the project name case-insensitively. When nothing matches, the reply lists the known projects instead of erroring. |
-| `agents` | string[] | Only these agents. Ids: `claude-code`, `codex`, `grok`, `dsh`, `cursor`, `opencode`, `pi`, `omp`, `kiro`, `kimi`, `gemini`, `copilot`, `antigravity`, `qoder`, `hermes`, `openclaw`, `codebuddy`, `workbuddy`, `zcode`, `craft-agents`, `devin`. Display names (`"Claude Code"`, `"Gemini CLI"`) and a few aliases (`claude`, `deepseek`, `opencode2`, `craft`) are accepted too. |
+| `agents` | string[] | Only these agents. Ids: `claude-code`, `codex`, `grok`, `dsh`, `cursor`, `opencode`, `pi`, `omp`, `kiro`, `kimi`, `gemini`, `copilot`, `antigravity`, `qoder`, `hermes`, `openclaw`, `codebuddy`, `workbuddy`, `zcode`, `craft-agents`, `devin`, `kilo`. Display names (`"Claude Code"`, `"Gemini CLI"`) and a few aliases (`claude`, `deepseek`, `opencode2`, `craft`) are accepted too. |
| `since` | string | Only sessions updated at or after this time. Relative: `30m`, `24h`, `7d`, `2w`. Absolute: `2026-09-01`, `2026-09-01 09:30`, `2026-09-01T09:30:00Z`. Naive date-times are read in local time. |
| `limit` | integer | Maximum items to return; values outside the allowed range are clamped. |