keel-agent 0.129.0 → 0.130.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +31 -1
  2. package/README.md +12 -16
  3. package/README.zh-CN.md +12 -16
  4. package/README.zh-TW.md +74 -189
  5. package/bin/keel.mjs +295 -55
  6. package/dist/packages/keel/src/adapters/sdk/prompt-render.js +3 -1
  7. package/dist/packages/keel/src/adapters/sdk/session-opener.js +2 -1
  8. package/dist/packages/keel/src/adapters/tools/guarded.js +31 -4
  9. package/dist/packages/keel/src/adapters/tools/patch.js +16 -0
  10. package/dist/packages/keel/src/app/client-assembly.js +43 -24
  11. package/dist/packages/keel/src/app/client-runtime.js +37 -2
  12. package/dist/packages/keel/src/app/connection-init.js +4 -2
  13. package/dist/packages/keel/src/app/conversation-content.js +14 -0
  14. package/dist/packages/keel/src/app/core-engine.js +6 -2
  15. package/dist/packages/keel/src/app/engine-coordination.js +4 -0
  16. package/dist/packages/keel/src/app/engine-elsewhere.js +8 -2
  17. package/dist/packages/keel/src/app/engine-orphans.js +8 -1
  18. package/dist/packages/keel/src/app/engine-sessions.js +26 -22
  19. package/dist/packages/keel/src/app/engine-takeover.js +13 -8
  20. package/dist/packages/keel/src/app/extra-handlers.js +8 -5
  21. package/dist/packages/keel/src/app/host-faces.js +1 -0
  22. package/dist/packages/keel/src/app/host-tool-mounts.js +12 -0
  23. package/dist/packages/keel/src/app/note-delivery.js +2 -2
  24. package/dist/packages/keel/src/app/session-registry.js +3 -1
  25. package/dist/packages/keel/src/app/session-surface.js +2 -1
  26. package/dist/packages/keel/src/app/subagent-model-choice.js +44 -30
  27. package/dist/packages/keel/src/bg-job-notice.js +1 -0
  28. package/dist/packages/keel/src/composer-complete-settings.js +43 -0
  29. package/dist/packages/keel/src/conversation-rows.js +8 -0
  30. package/dist/packages/keel/src/domains/background/handlers.js +1 -0
  31. package/dist/packages/keel/src/domains/bots/chat.js +1 -1
  32. package/dist/packages/keel/src/domains/snapshots/builders.js +4 -0
  33. package/dist/packages/keel/src/domains/turns/turn-runner.js +18 -0
  34. package/dist/packages/keel/src/settings-schema.js +9 -0
  35. package/dist/packages/keel/src/subagent-model-policy.js +49 -0
  36. package/dist/packages/keel/src/subagent-templates-hant.js +3 -3
  37. package/dist/packages/keel/src/subagent-templates.js +6 -6
  38. package/dist/packages/keel/src/tool-catalog.js +9 -0
  39. package/dist/packages/keel/src/tool-names.js +2 -0
  40. package/dist/server/background-task-service.js +61 -22
  41. package/dist/server/bg-tasks/client.js +5 -4
  42. package/dist/server/bg-tasks/registry.js +29 -18
  43. package/dist/server/bot-memory-tool.js +15 -3
  44. package/dist/server/client-state.js +65 -0
  45. package/dist/server/composer-complete-settings.js +1 -0
  46. package/dist/server/composer-complete.js +243 -0
  47. package/dist/server/control-socket.js +13 -1
  48. package/dist/server/conversation-import/engines/agy.js +222 -0
  49. package/dist/server/conversation-import/engines/claude.js +171 -0
  50. package/dist/server/conversation-import/engines/codex.js +178 -0
  51. package/dist/server/conversation-import/engines/dsh.js +240 -0
  52. package/dist/server/conversation-import/engines/opencode.js +160 -0
  53. package/dist/server/conversation-import/index.js +183 -0
  54. package/dist/server/conversation-import/jsonl.js +100 -0
  55. package/dist/server/conversation-import/messages.js +147 -0
  56. package/dist/server/conversation-import/sqlite.js +47 -0
  57. package/dist/server/conversation-import/types.js +8 -0
  58. package/dist/server/conversation-import-routes.js +53 -0
  59. package/dist/server/core-bot-adapter.js +5 -1
  60. package/dist/server/core-plugin-adapter.js +4 -1
  61. package/dist/server/core-settings-adapter.js +19 -9
  62. package/dist/server/custom-cli-routes.js +59 -0
  63. package/dist/server/custom-cli-store.js +134 -0
  64. package/dist/server/delegate-task.js +18 -7
  65. package/dist/server/device-center/bot-chat.js +34 -17
  66. package/dist/server/device-center/bot-creation-tool.js +8 -64
  67. package/dist/server/device-center/bot-drafts.js +24 -0
  68. package/dist/server/device-center/bot-memory.js +101 -12
  69. package/dist/server/device-center/bot-tool-face.js +24 -20
  70. package/dist/server/device-center/local.js +59 -9
  71. package/dist/server/durable/durable-agent-service.js +27 -0
  72. package/dist/server/engine-owner-route.js +43 -0
  73. package/dist/server/files-service.js +10 -6
  74. package/dist/server/index.js +236 -47
  75. package/dist/server/marker-service.js +19 -0
  76. package/dist/server/message-window.js +2 -2
  77. package/dist/server/multi-engine.js +1 -0
  78. package/dist/server/native-cli.js +3 -1
  79. package/dist/server/obs-recall-tool.js +173 -0
  80. package/dist/server/plugin-facilities.js +9 -1
  81. package/dist/server/plugins.js +11 -4
  82. package/dist/server/preset-fields.js +9 -0
  83. package/dist/server/protocol-version.js +1 -1
  84. package/dist/server/remote-ssh-service.js +13 -0
  85. package/dist/server/schedule-agent-tool.js +2 -0
  86. package/dist/server/scheduler-tasks.js +5 -0
  87. package/dist/server/settings-commit.js +2 -0
  88. package/dist/server/settings-service.js +2 -0
  89. package/dist/server/shell-activate.js +118 -1
  90. package/dist/server/slash-commands.js +48 -12
  91. package/dist/server/tool-bridge-host.js +5 -0
  92. package/dist/server/universal/acp/acp-driver.js +96 -22
  93. package/dist/server/universal/drivers/claude-acp-driver.js +3 -0
  94. package/dist/server/universal/internal-mcp.js +7 -3
  95. package/dist/server/universal/seat-takeover.js +145 -0
  96. package/dist/server/universal/subagent-slash.js +54 -0
  97. package/dist/server/universal/universal-service.js +28 -0
  98. package/dist/server/universal/universal-session.js +242 -88
  99. package/dist/server/update-service.js +12 -8
  100. package/package.json +20 -15
  101. package/plugins/catalog.json +128 -90
  102. package/plugins/superagent/manifest.json +2 -2
  103. package/themes/flow-zurich.css +2 -2
  104. package/web/dist/.build-assets.json +1 -1
  105. package/web/dist/assets/ApprovalRulesTab-QmzsJItk.js +1 -0
  106. package/web/dist/assets/BgTasksModal-COLmy-4E.js +1 -0
  107. package/web/dist/assets/{BotDraftSettings-BcXWHOSd.js → BotDraftSettings-nP4g1fge.js} +1 -1
  108. package/web/dist/assets/BottomDock-BZXSlOom.js +1 -0
  109. package/web/dist/assets/{CanvasStudio-KZ0MmCL7.js → CanvasStudio-BL1BWXpp.js} +3 -3
  110. package/web/dist/assets/CommunityThemesSection-BLd_oox1.js +1 -0
  111. package/web/dist/assets/DesktopAppSettings-Dn18vrLK.js +1 -0
  112. package/web/dist/assets/DeviceCenter-DxoAwlTt.js +3 -0
  113. package/web/dist/assets/{DeviceExecutionSettings-VONJ-2Ns.js → DeviceExecutionSettings-B1mya5TJ.js} +1 -1
  114. package/web/dist/assets/{DeviceGroups-DUq2YZ8O.js → DeviceGroups-C-xwewog.js} +1 -1
  115. package/web/dist/assets/DisplayTab-DRGFt78v.js +1 -0
  116. package/web/dist/assets/{FieldRow-CHxkNX2z.js → FieldRow-DHxAXFtL.js} +1 -1
  117. package/web/dist/assets/FilePreview-DcyP9paf.js +2 -0
  118. package/web/dist/assets/GlobalSearchModal-Cs6hB5KO.js +1 -0
  119. package/web/dist/assets/GroupConversation-B7NfTB89.js +9 -0
  120. package/web/dist/assets/{GroupWorkItems-B-wweVMR.js → GroupWorkItems-CSUjIxDT.js} +1 -1
  121. package/web/dist/assets/{HintTip-lXOOr9p3.js → HintTip-CKxIx9CD.js} +1 -1
  122. package/web/dist/assets/LayoutTab-9popvCLQ.js +1 -0
  123. package/web/dist/assets/McpServersPanel-dRwq7Wjq.js +1 -0
  124. package/web/dist/assets/ModelConfigModal-C0CXhSl0.js +2 -0
  125. package/web/dist/assets/{ModelsTab-CMSi1MT-.js → ModelsTab-CyG2rYeY.js} +1 -1
  126. package/web/dist/assets/{NativeCliPanel-DotHqKv_.js → NativeCliPanel-mlB4dw42.js} +2 -2
  127. package/web/dist/assets/{PiSetupModal-Dd0w2Koi.js → PiSetupModal-D7PjlTVx.js} +1 -1
  128. package/web/dist/assets/PluginsTab-0s0qClcC.js +2 -0
  129. package/web/dist/assets/PresetShareModal-Dw4t6p6s.js +11 -0
  130. package/web/dist/assets/{PresetsTab-BnFFB24b.js → PresetsTab-DdXvpc2d.js} +1 -1
  131. package/web/dist/assets/{PromptHistoryTab-CNUzjdJl.js → PromptHistoryTab-DirJHaH6.js} +1 -1
  132. package/web/dist/assets/{PromptOverrideEditor-DZOQdWy3.js → PromptOverrideEditor-ldLRCp0e.js} +1 -1
  133. package/web/dist/assets/PromptTab-SV01BMC0.js +11 -0
  134. package/web/dist/assets/{ProviderOAuthControls-BSqBp-QA.js → ProviderOAuthControls-Clyn3fnw.js} +1 -1
  135. package/web/dist/assets/QuestionTab-Bi1NYK5U.js +1 -0
  136. package/web/dist/assets/{QuickAskSettings-DICkDFsE.js → QuickAskSettings-dzG95DYl.js} +2 -2
  137. package/web/dist/assets/QuickTab-C8bknYDU.js +5 -0
  138. package/web/dist/assets/{ReviewTab-DRMQoVjL.js → ReviewTab-D9lbphZe.js} +1 -1
  139. package/web/dist/assets/SCMPanel-BfrlvHxI.js +7 -0
  140. package/web/dist/assets/SchedulerPanel-DDDWOSsw.js +2 -0
  141. package/web/dist/assets/SettingsModal-BqzfvDlI.js +2 -0
  142. package/web/dist/assets/SkillsTab-D8C-kghN.js +1 -0
  143. package/web/dist/assets/{SoundTab-BR6gVIOZ.js → SoundTab-CXcWmvkX.js} +1 -1
  144. package/web/dist/assets/{SubagentTemplatesTab-BonIA-lD.js → SubagentTemplatesTab-KjPMnYN4.js} +1 -1
  145. package/web/dist/assets/{TermXterm-EHBR2avX.js → TermXterm-B7klZwgq.js} +1 -1
  146. package/web/dist/assets/TerminalDockControls-lbPY2V5U.js +1 -0
  147. package/web/dist/assets/TerminalPanel-ERotdy8I.js +1 -0
  148. package/web/dist/assets/{ThemeMarketModal-CGaoF3NZ.js → ThemeMarketModal-BZJZ7doZ.js} +1 -1
  149. package/web/dist/assets/{ToggleRow-DvouPLLK.js → ToggleRow-irywH1NJ.js} +1 -1
  150. package/web/dist/assets/ToolBridgeSettings-CG1HleEp.js +1 -0
  151. package/web/dist/assets/ToolsTab-_OJA76Sw.js +4 -0
  152. package/web/dist/assets/TuiOverlayModal-CDqXNwW-.js +1 -0
  153. package/web/dist/assets/{VisionTab-HDlpKVeq.js → VisionTab-B580SGpU.js} +1 -1
  154. package/web/dist/assets/{api-client-J4QrjRw8.js → api-client-B2iSv9kK.js} +1 -1
  155. package/web/dist/assets/{canvas-client-BsNp2mr3.js → canvas-client-DRiwRbfy.js} +1 -1
  156. package/web/dist/assets/{desktop-BcTQigaN.js → desktop-DRyQQXnx.js} +1 -1
  157. package/web/dist/assets/host-icon-DMg5PU4C.js +1 -0
  158. package/web/dist/assets/i18n-D2DJ-AHq.js +225 -0
  159. package/web/dist/assets/index-CP0EEOA0.js +423 -0
  160. package/web/dist/assets/index-Ds_pheLF.css +1 -0
  161. package/web/dist/assets/plugin-host-VU6JOOPu.js +1 -0
  162. package/web/dist/assets/{theme-7DF4yEv3.js → theme-ZteIcUdF.js} +1 -1
  163. package/web/dist/assets/{tool-inventory-D2UKR8Ja.js → tool-inventory-DnzKVLYq.js} +1 -1
  164. package/web/dist/index.html +10 -9
  165. package/web/dist/sw.js +1 -1
  166. package/web/dist/assets/ApprovalRulesTab-BlcxVgms.js +0 -1
  167. package/web/dist/assets/BgTasksModal-wL4p27CE.js +0 -1
  168. package/web/dist/assets/BottomDock-CUnQsIDW.js +0 -1
  169. package/web/dist/assets/CommunityThemesSection-BAcS2VQK.js +0 -1
  170. package/web/dist/assets/DesktopAppSettings-BeikxSqV.js +0 -1
  171. package/web/dist/assets/DeviceCenter-BWKRVpWt.js +0 -3
  172. package/web/dist/assets/DisplayTab-B5x4nQh5.js +0 -1
  173. package/web/dist/assets/FilePreview-0IDddE5F.js +0 -2
  174. package/web/dist/assets/GlobalSearchModal-BaXs1zRG.js +0 -1
  175. package/web/dist/assets/GroupConversation-EaMawnF-.js +0 -9
  176. package/web/dist/assets/LayoutTab-8N74U83U.js +0 -1
  177. package/web/dist/assets/McpServersPanel-BAhwoE87.js +0 -1
  178. package/web/dist/assets/ModelConfigModal-i3m9glTy.js +0 -2
  179. package/web/dist/assets/PluginsTab-DL8j6LEI.js +0 -2
  180. package/web/dist/assets/PresetShareModal-BGhCpas6.js +0 -11
  181. package/web/dist/assets/PromptTab-DPYuPM07.js +0 -11
  182. package/web/dist/assets/QuestionTab-C7oF1MYO.js +0 -1
  183. package/web/dist/assets/QuickTab-DDaxH3XV.js +0 -1
  184. package/web/dist/assets/SCMPanel-CfOxsL8H.js +0 -7
  185. package/web/dist/assets/SchedulerPanel-BLaVSPXj.js +0 -2
  186. package/web/dist/assets/SettingsModal-6jgsnLF0.js +0 -2
  187. package/web/dist/assets/SkillsTab-C5XuZ4a-.js +0 -1
  188. package/web/dist/assets/TerminalDockControls-Dn51FqM9.js +0 -1
  189. package/web/dist/assets/TerminalPanel-D2Bpt0f_.js +0 -1
  190. package/web/dist/assets/ToolBridgeSettings-8vlLWWvW.js +0 -1
  191. package/web/dist/assets/ToolsTab-Byx7wDZe.js +0 -4
  192. package/web/dist/assets/TuiOverlayModal-Bj6jyAvr.js +0 -1
  193. package/web/dist/assets/i18n-CaWsBwiA.js +0 -225
  194. package/web/dist/assets/index-2jVkYOYt.css +0 -1
  195. package/web/dist/assets/index-KuttBaFw.js +0 -420
  196. package/web/dist/assets/plugin-host-C2Iki5ig.js +0 -1
@@ -0,0 +1,160 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { ImportedMessages, argumentsText, cleanImportedUserText } from "../messages.js";
4
+ import { asRecord, asString, pathKind, summarize } from "../jsonl.js";
5
+ import { queryReadonly, sqlNumber, sqlString } from "../sqlite.js";
6
+ /** OpenCode 的数据根(XDG:`~/.local/share/opencode`),会话存在 `opencode.db` 里。 */
7
+ export function opencodeDbPath() {
8
+ const dataHome = process.env.XDG_DATA_HOME?.trim() || join(homedir(), ".local", "share");
9
+ return join(dataHome, "opencode", "opencode.db");
10
+ }
11
+ function jsonOf(value) {
12
+ if (typeof value !== "string" || !value.trim())
13
+ return undefined;
14
+ try {
15
+ return asRecord(JSON.parse(value));
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ async function listRows(limit) {
22
+ const rows = await queryReadonly(opencodeDbPath(),
23
+ // `parent_id is null`:子会话是 task 派生出来的,不属于「我在终端里开的对话」。
24
+ `select id, title, directory, time_created, time_updated from session
25
+ where parent_id is null order by time_updated desc limit ?`, [Math.max(1, Math.min(limit, 500))]);
26
+ if (!rows)
27
+ return [];
28
+ const out = [];
29
+ for (const row of rows) {
30
+ const id = sqlString(row, "id");
31
+ const cwd = sqlString(row, "directory");
32
+ if (!id || !cwd)
33
+ continue;
34
+ out.push({
35
+ id,
36
+ title: sqlString(row, "title"),
37
+ cwd,
38
+ createdAt: sqlNumber(row, "time_created"),
39
+ updatedAt: sqlNumber(row, "time_updated"),
40
+ });
41
+ }
42
+ return out;
43
+ }
44
+ /** 首条用户文本:列表预览用(只查一段,不整会话)。 */
45
+ async function peekFirstUserText(sessionId) {
46
+ const rows = await queryReadonly(opencodeDbPath(), `select p.data from part p join message m on m.id = p.message_id
47
+ where p.session_id = ? and p.data like '%"type":"text"%' order by m.time_created, p.time_created limit 20`, [sessionId]);
48
+ if (!rows)
49
+ return "";
50
+ for (const row of rows) {
51
+ const data = jsonOf(row.data);
52
+ if (!data || data.type !== "text")
53
+ continue;
54
+ const text = cleanImportedUserText(asString(data.text));
55
+ if (text)
56
+ return text;
57
+ }
58
+ return "";
59
+ }
60
+ export const opencodeImportSource = {
61
+ engine: "opencode",
62
+ available() {
63
+ return pathKind(opencodeDbPath()) === "file";
64
+ },
65
+ async list(limit) {
66
+ const rows = await listRows(limit);
67
+ const out = [];
68
+ for (const row of rows) {
69
+ const text = await peekFirstUserText(row.id);
70
+ if (!text)
71
+ continue;
72
+ out.push({
73
+ engine: "opencode",
74
+ externalId: row.id,
75
+ title: summarize(row.title || text, 80),
76
+ cwd: row.cwd,
77
+ createdAt: row.createdAt || row.updatedAt,
78
+ updatedAt: row.updatedAt || row.createdAt,
79
+ preview: summarize(text),
80
+ sourcePath: opencodeDbPath(),
81
+ });
82
+ }
83
+ return out;
84
+ },
85
+ async read(meta) {
86
+ const db = opencodeDbPath();
87
+ const messageRows = await queryReadonly(db, "select id, data, time_created from message where session_id = ? order by time_created", [meta.externalId]);
88
+ const partRows = await queryReadonly(db, "select message_id, data, time_created from part where session_id = ? order by time_created", [meta.externalId]);
89
+ if (!messageRows || !partRows)
90
+ return [];
91
+ const partsByMessage = new Map();
92
+ for (const row of partRows) {
93
+ const id = sqlString(row, "message_id");
94
+ const data = jsonOf(row.data);
95
+ if (!id || !data)
96
+ continue;
97
+ const list = partsByMessage.get(id) ?? [];
98
+ list.push(data);
99
+ partsByMessage.set(id, list);
100
+ }
101
+ const messages = new ImportedMessages(`imp-opencode-${meta.externalId}`);
102
+ for (const row of messageRows) {
103
+ const id = sqlString(row, "id");
104
+ const data = jsonOf(row.data);
105
+ if (!id || !data)
106
+ continue;
107
+ const role = asString(data.role);
108
+ if (role !== "user" && role !== "assistant")
109
+ continue;
110
+ const timestamp = sqlNumber(row, "time_created");
111
+ const model = asRecord(data.model) ? asString(data.model.modelID) : "";
112
+ const content = [];
113
+ const userParts = [];
114
+ const toolResults = [];
115
+ for (const part of partsByMessage.get(id) ?? []) {
116
+ const type = asString(part.type);
117
+ if (type === "text") {
118
+ const text = asString(part.text).trim();
119
+ if (!text)
120
+ continue;
121
+ if (role === "user")
122
+ userParts.push(text);
123
+ else
124
+ content.push({ type: "text", text });
125
+ }
126
+ else if (type === "reasoning") {
127
+ const thinking = asString(part.text).trim();
128
+ if (thinking)
129
+ content.push({ type: "thinking", thinking });
130
+ }
131
+ else if (type === "tool") {
132
+ const state = asRecord(part.state) ?? {};
133
+ const callId = asString(part.callID) || asString(part.callId);
134
+ const name = asString(part.tool) || "tool";
135
+ content.push({
136
+ type: "toolCall",
137
+ id: callId,
138
+ name,
139
+ argumentsText: argumentsText(state.input),
140
+ });
141
+ const status = asString(state.status);
142
+ if (status === "completed" || status === "error") {
143
+ const output = asString(state.output) || asString(state.error);
144
+ toolResults.push({ callId, output, isError: status === "error" });
145
+ }
146
+ }
147
+ }
148
+ if (role === "user") {
149
+ if (userParts.length > 0)
150
+ messages.userText(userParts, timestamp);
151
+ continue;
152
+ }
153
+ if (content.length > 0)
154
+ messages.push(role, content, timestamp, model ? { model } : undefined);
155
+ for (const result of toolResults)
156
+ messages.toolResult(result.callId, result.output, result.isError, timestamp);
157
+ }
158
+ return messages.toArray();
159
+ },
160
+ };
@@ -0,0 +1,183 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { UniversalSessionStore } from "../universal/session-store.js";
3
+ import { normalizePathKey } from "../../packages/keel/src/projects-schema.js";
4
+ import { agyImportSource } from "./engines/agy.js";
5
+ import { claudeImportSource } from "./engines/claude.js";
6
+ import { codexImportSource } from "./engines/codex.js";
7
+ import { dshImportSource } from "./engines/dsh.js";
8
+ import { opencodeImportSource } from "./engines/opencode.js";
9
+ import { IMPORT_ENGINES } from "./types.js";
10
+ export { IMPORT_ENGINES, isImportEngineId } from "./types.js";
11
+ /** 每次扫描/导入的候选上限:外部引擎目录可能很大,一次请求只做有界的一份。 */
12
+ export const MAX_SCAN_SESSIONS = 200;
13
+ export const MAX_IMPORT_PER_REQUEST = 100;
14
+ /** 引擎 → 适配器。新增引擎只在这里多一行,路由与 UI 自动跟上。 */
15
+ const SOURCES = {
16
+ claude: claudeImportSource,
17
+ codex: codexImportSource,
18
+ agy: agyImportSource,
19
+ opencode: opencodeImportSource,
20
+ dsh: dshImportSource,
21
+ };
22
+ export function importEngineInfos() {
23
+ return IMPORT_ENGINES.map((engine) => ({ engine, available: SOURCES[engine].available() }));
24
+ }
25
+ function clampLimit(value, max, fallback) {
26
+ if (!Number.isFinite(value ?? NaN))
27
+ return fallback;
28
+ return Math.max(1, Math.min(max, Math.floor(value)));
29
+ }
30
+ /** 同一引擎同目录下「引擎原生会话 ID → keel 对话」的映射:导入去重的唯一判据。 */
31
+ function existingByDriverSession(store, cwd) {
32
+ const map = new Map();
33
+ for (const conv of store.listConversations(cwd)) {
34
+ if (conv.driverSessionId)
35
+ map.set(conv.driverSessionId, conv);
36
+ }
37
+ return map;
38
+ }
39
+ function statusOf(meta, existing) {
40
+ if (!existing)
41
+ return "new";
42
+ // 引擎侧最后写入时间比 keel 里的更新时间更晚 → 外面续聊过,需要覆盖。
43
+ return (existing.updatedAt ?? 0) + 1000 < meta.updatedAt ? "behind" : "same";
44
+ }
45
+ export async function scanImportCandidates(options) {
46
+ const limit = clampLimit(options.limit, MAX_SCAN_SESSIONS, MAX_SCAN_SESSIONS);
47
+ const source = SOURCES[options.engine];
48
+ if (!source.available()) {
49
+ return { engine: options.engine, available: false, candidates: [] };
50
+ }
51
+ let listed;
52
+ try {
53
+ listed = await source.list(limit);
54
+ }
55
+ catch (error) {
56
+ return {
57
+ engine: options.engine,
58
+ available: true,
59
+ candidates: [],
60
+ warning: error instanceof Error ? error.message : String(error),
61
+ };
62
+ }
63
+ const wanted = options.cwd ? normalizePathKey(options.cwd) : "";
64
+ const filtered = listed.filter((meta) => {
65
+ if (!meta.cwd)
66
+ return false;
67
+ if (wanted && normalizePathKey(meta.cwd) !== wanted)
68
+ return false;
69
+ return true;
70
+ });
71
+ const store = new UniversalSessionStore(options.dataDir, options.engine);
72
+ const cache = new Map();
73
+ const candidates = [];
74
+ for (const meta of filtered) {
75
+ const cwdKey = normalizePathKey(meta.cwd);
76
+ let index = cache.get(cwdKey);
77
+ if (!index) {
78
+ index = existingByDriverSession(store, meta.cwd);
79
+ cache.set(cwdKey, index);
80
+ }
81
+ const existing = index.get(meta.externalId);
82
+ candidates.push({
83
+ ...meta,
84
+ ...(existing ? { importedId: existing.id } : {}),
85
+ status: statusOf(meta, existing),
86
+ });
87
+ }
88
+ candidates.sort((a, b) => b.updatedAt - a.updatedAt);
89
+ return { engine: options.engine, available: true, candidates };
90
+ }
91
+ /**
92
+ * 把选中的引擎会话写进 keel 的 universal 存储(`dataDir/universal-sessions/<engine>/…`)。
93
+ *
94
+ * 三条不可动摇的规矩:
95
+ * 1. **只在引擎自己的 cwd 下落地**:resume 靠「同目录 + 原生会话 ID」定位转录,写到别的项目等于断链;
96
+ * 2. **保留 `driverSessionId`**:导入后接着聊仍然走引擎原生 `--resume`(issue #1053 的做法);
97
+ * 3. **原地覆盖只刷新正文**:已有对话的 id / 标题 / 置顶沿用,避免导入把用户整理过的左栏重置。
98
+ */
99
+ export async function applyConversationImport(options) {
100
+ const source = SOURCES[options.engine];
101
+ const wanted = new Set(options.externalIds.slice(0, MAX_IMPORT_PER_REQUEST));
102
+ const result = { engine: options.engine, applied: [], failed: [] };
103
+ if (wanted.size === 0)
104
+ return result;
105
+ if (!source.available()) {
106
+ for (const externalId of wanted)
107
+ result.failed.push({ externalId, error: "engine store not found" });
108
+ return result;
109
+ }
110
+ const scanned = await scanImportCandidates({ dataDir: options.dataDir, engine: options.engine });
111
+ const byId = new Map(scanned.candidates.map((candidate) => [candidate.externalId, candidate]));
112
+ const store = new UniversalSessionStore(options.dataDir, options.engine);
113
+ const existingCache = new Map();
114
+ for (const externalId of wanted) {
115
+ const meta = byId.get(externalId);
116
+ if (!meta) {
117
+ result.failed.push({ externalId, error: "session not found in engine store" });
118
+ continue;
119
+ }
120
+ const cwdKey = normalizePathKey(meta.cwd);
121
+ let index = existingCache.get(cwdKey);
122
+ if (!index) {
123
+ index = existingByDriverSession(store, meta.cwd);
124
+ existingCache.set(cwdKey, index);
125
+ }
126
+ const existing = index.get(externalId);
127
+ const status = statusOf(meta, existing);
128
+ if (status === "same") {
129
+ result.applied.push({
130
+ externalId,
131
+ id: existing.id,
132
+ title: existing.title,
133
+ cwd: meta.cwd,
134
+ status,
135
+ messages: existing.messages.length,
136
+ });
137
+ continue;
138
+ }
139
+ let messages;
140
+ try {
141
+ messages = await source.read(meta);
142
+ }
143
+ catch (error) {
144
+ result.failed.push({
145
+ externalId,
146
+ error: error instanceof Error ? error.message : String(error),
147
+ });
148
+ continue;
149
+ }
150
+ if (messages.length === 0) {
151
+ result.failed.push({ externalId, error: "transcript has no readable messages" });
152
+ continue;
153
+ }
154
+ const conv = {
155
+ engine: options.engine,
156
+ cwd: meta.cwd,
157
+ id: existing?.id ?? randomUUID(),
158
+ title: existing?.title || meta.title || "Imported conversation",
159
+ driverSessionId: externalId,
160
+ createdAt: existing?.createdAt ?? (meta.createdAt || meta.updatedAt || Date.now()),
161
+ updatedAt: Math.max(meta.updatedAt || 0, existing?.updatedAt ?? 0, messages[messages.length - 1]?.timestamp ?? 0),
162
+ messages,
163
+ ...(existing?.pinned ? { pinned: true } : {}),
164
+ };
165
+ try {
166
+ await store.saveConversation(meta.cwd, conv);
167
+ }
168
+ catch (error) {
169
+ result.failed.push({ externalId, error: error instanceof Error ? error.message : String(error) });
170
+ continue;
171
+ }
172
+ index.set(externalId, conv);
173
+ result.applied.push({
174
+ externalId,
175
+ id: conv.id,
176
+ title: conv.title,
177
+ cwd: meta.cwd,
178
+ status,
179
+ messages: messages.length,
180
+ });
181
+ }
182
+ return result;
183
+ }
@@ -0,0 +1,100 @@
1
+ import { createReadStream, statSync } from "node:fs";
2
+ import { createInterface } from "node:readline";
3
+ /** 单份 transcript 的读取上限:超过就当「无法安全导入」跳过,避免一个畸形文件拖死服务端。 */
4
+ export const MAX_TRANSCRIPT_BYTES = 64 * 1024 * 1024;
5
+ export function fileSize(file) {
6
+ try {
7
+ return statSync(file).size;
8
+ }
9
+ catch {
10
+ return 0;
11
+ }
12
+ }
13
+ /**
14
+ * 流式逐行读取 JSONL,坏行静默跳过(外部引擎的 transcript 允许半行/坏行)。
15
+ * 这是所有导入适配器读 transcript 的唯一入口:一次性口径、一次性上限。
16
+ */
17
+ export async function readJsonl(file, onValue, opts = {}) {
18
+ const maxBytes = opts.maxBytes ?? MAX_TRANSCRIPT_BYTES;
19
+ let read = 0;
20
+ const stream = createReadStream(file, { encoding: "utf8" });
21
+ const rl = createInterface({ input: stream, crlfDelay: Infinity });
22
+ try {
23
+ for await (const line of rl) {
24
+ read += Buffer.byteLength(line) + 1;
25
+ if (read > maxBytes)
26
+ break;
27
+ const trimmed = line.trim();
28
+ if (!trimmed)
29
+ continue;
30
+ let parsed;
31
+ try {
32
+ parsed = JSON.parse(trimmed);
33
+ }
34
+ catch {
35
+ continue;
36
+ }
37
+ if (!parsed || typeof parsed !== "object")
38
+ continue;
39
+ if (onValue(parsed, trimmed) === false)
40
+ break;
41
+ }
42
+ }
43
+ finally {
44
+ rl.close();
45
+ stream.destroy();
46
+ }
47
+ }
48
+ /** 只读头 `maxLines` 行(列表扫描用,避免整份解析)。 */
49
+ export async function peekJsonl(file, maxLines = 40) {
50
+ const out = [];
51
+ await readJsonl(file, (value) => {
52
+ out.push(value);
53
+ return out.length < maxLines;
54
+ }, { maxBytes: 2 * 1024 * 1024 });
55
+ return out;
56
+ }
57
+ export function pathKind(path) {
58
+ try {
59
+ const info = statSync(path);
60
+ if (info.isDirectory())
61
+ return "dir";
62
+ return info.isFile() ? "file" : "none";
63
+ }
64
+ catch {
65
+ return "none";
66
+ }
67
+ }
68
+ export function asRecord(value) {
69
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
70
+ }
71
+ export function asString(value) {
72
+ return typeof value === "string" ? value : "";
73
+ }
74
+ export function asArray(value) {
75
+ return Array.isArray(value) ? value : [];
76
+ }
77
+ /** 毫秒时间戳规整:接受数字、ISO 字符串、`2026-11-26 04:36:17.8+00:00` 这类变体。 */
78
+ export function toMillis(value) {
79
+ if (typeof value === "number" && Number.isFinite(value)) {
80
+ return value < 1e11 ? Math.round(value * 1000) : Math.round(value);
81
+ }
82
+ if (typeof value === "string" && value.trim()) {
83
+ const raw = value.trim();
84
+ const normalized = /^\d{4}-\d{2}-\d{2} \d/.test(raw) ? raw.replace(" ", "T") : raw;
85
+ // JS 只认 3 位毫秒:把 6 位微秒裁掉再解析。
86
+ const parsed = Date.parse(normalized.replace(/(\.\d{3})\d+/, "$1"));
87
+ if (Number.isFinite(parsed))
88
+ return parsed;
89
+ }
90
+ return 0;
91
+ }
92
+ /** 单行文本摘要(列表里的预览/标题用)。 */
93
+ export function summarize(text, max = 120) {
94
+ const flat = text.replace(/\s+/g, " ").trim();
95
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
96
+ }
97
+ export function stripAnsi(text) {
98
+ // eslint-disable-next-line no-control-regex
99
+ return text.replace(/[\u001b\u009b][[()#;?]*(?:\d{1,4}(?:;\d{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "");
100
+ }
@@ -0,0 +1,147 @@
1
+ import { stripAnsi } from "./jsonl.js";
2
+ /** 单条工具结果文本上限:导入是「读历史」,没必要把整份 grep 输出塞进会话。 */
3
+ export const MAX_TOOL_OUTPUT_CHARS = 4000;
4
+ /** 导入会话的消息总数上限:超出的部分截掉并留一条说明,避免一次性把历史顶格塞进快照。 */
5
+ export const MAX_IMPORTED_MESSAGES = 4000;
6
+ /** 会话消息收集器:id 按引擎前缀 + 序号生成,保证同一会话内唯一且稳定。 */
7
+ export class ImportedMessages {
8
+ prefix;
9
+ items = [];
10
+ constructor(prefix) {
11
+ this.prefix = prefix;
12
+ }
13
+ get length() {
14
+ return this.items.length;
15
+ }
16
+ push(role, content, timestamp, extra) {
17
+ if (content.length === 0)
18
+ return;
19
+ const message = {
20
+ id: `${this.prefix}-${this.items.length}`,
21
+ role,
22
+ content,
23
+ };
24
+ if (timestamp && Number.isFinite(timestamp))
25
+ message.timestamp = timestamp;
26
+ if (extra)
27
+ Object.assign(message, extra);
28
+ this.items.push(message);
29
+ }
30
+ text(role, text, timestamp, extra) {
31
+ const trimmed = role === "user" ? cleanImportedUserText(text) : stripAnsi(text).trim();
32
+ if (!trimmed)
33
+ return;
34
+ this.push(role, [{ type: "text", text: trimmed }], timestamp, extra);
35
+ }
36
+ /** 用户消息专用:多条文本块拼成一条,并丢掉注入消息(AGENTS.md / system-reminder 等)。 */
37
+ userText(parts, timestamp) {
38
+ this.text("user", parts.join("\n"), timestamp);
39
+ }
40
+ toolResult(callId, output, isError, timestamp) {
41
+ if (!callId)
42
+ return;
43
+ const trimmed = stripAnsi(output).trim();
44
+ const content = [];
45
+ if (trimmed) {
46
+ const truncated = trimmed.length > MAX_TOOL_OUTPUT_CHARS;
47
+ content.push({
48
+ type: "text",
49
+ text: truncated ? `${trimmed.slice(0, MAX_TOOL_OUTPUT_CHARS)}…` : trimmed,
50
+ ...(truncated ? { truncated: true } : {}),
51
+ });
52
+ }
53
+ this.push("toolResult", content, timestamp, { toolCallId: callId, isError });
54
+ }
55
+ toArray() {
56
+ return this.items.slice(-MAX_IMPORTED_MESSAGES);
57
+ }
58
+ }
59
+ /** 把 JSON 值安全地缩成一行,供 toolCall 的 `argumentsText` 使用。 */
60
+ export function argumentsText(value) {
61
+ if (typeof value === "string")
62
+ return value;
63
+ if (value === undefined)
64
+ return "";
65
+ try {
66
+ return JSON.stringify(value);
67
+ }
68
+ catch {
69
+ return "";
70
+ }
71
+ }
72
+ /**
73
+ * 从 `file:///a/b` 这类 workspace URI 取本地路径。
74
+ * 外部引擎把 cwd 存成 URI(agy)或直接存路径(claude/codex/dsh/opencode),两者都收。
75
+ */
76
+ export function cwdFromUri(value) {
77
+ if (typeof value === "string")
78
+ return decodeFileUri(value);
79
+ if (Array.isArray(value)) {
80
+ for (const item of value) {
81
+ const path = decodeFileUri(item);
82
+ if (path)
83
+ return path;
84
+ }
85
+ }
86
+ return "";
87
+ }
88
+ function decodeFileUri(value) {
89
+ if (typeof value !== "string" || !value.trim())
90
+ return "";
91
+ const raw = value.trim();
92
+ if (!raw.startsWith("file://"))
93
+ return raw;
94
+ const withoutScheme = raw.slice("file://".length);
95
+ // `file:///path` → `/path`;`file://host/path` 视为远程 URI,不收。
96
+ if (!withoutScheme.startsWith("/"))
97
+ return "";
98
+ try {
99
+ return decodeURIComponent(withoutScheme);
100
+ }
101
+ catch {
102
+ return withoutScheme;
103
+ }
104
+ }
105
+ /**
106
+ * 外部引擎的 transcript 里混着大量「不是人说的话」:Codex 的 AGENTS.md/环境注入、
107
+ * DSH 的 system-reminder、以及 keel 自己的 Inline Markers 前导横幅。
108
+ * 导入要的是人话,所以统一在这里筛掉——每个适配器只管映射,不各写一套过滤。
109
+ */
110
+ const INJECTED_USER_PREFIXES = [
111
+ "# AGENTS.md instructions",
112
+ "<user_instructions>",
113
+ "<environment_context>",
114
+ "<INSTRUCTIONS>",
115
+ "<skills_instructions>",
116
+ "<system-reminder>",
117
+ "<world_state>",
118
+ "<multi_agent_",
119
+ ];
120
+ export function isInjectedUserText(text) {
121
+ const head = text.trimStart();
122
+ return INJECTED_USER_PREFIXES.some((prefix) => head.startsWith(prefix));
123
+ }
124
+ const RULE_LINE = /^\s*[─-]{4,}\s*$/;
125
+ /** 去掉 keel 客户端注入的「Inline Markers」前导横幅(它出现在每条用户消息的最前面)。 */
126
+ export function stripPromptPreamble(text) {
127
+ const normalized = text.replace(/\r\n/g, "\n");
128
+ const lines = normalized.split("\n");
129
+ const first = lines[0] ?? "";
130
+ if (!/^\s*[─-]{3,}.*Inline Markers/i.test(first))
131
+ return text;
132
+ for (let index = 1; index < lines.length; index++) {
133
+ if (RULE_LINE.test(lines[index]))
134
+ return lines
135
+ .slice(index + 1)
136
+ .join("\n")
137
+ .trim();
138
+ }
139
+ return text;
140
+ }
141
+ /** 导入用的用户正文规整:去前导横幅、去注入消息、去首尾空白。 */
142
+ export function cleanImportedUserText(text) {
143
+ const cleaned = stripPromptPreamble(stripAnsi(text)).trim();
144
+ if (!cleaned || isInjectedUserText(cleaned))
145
+ return "";
146
+ return cleaned;
147
+ }
@@ -0,0 +1,47 @@
1
+ import { pathKind } from "./jsonl.js";
2
+ /**
3
+ * 只读打开外部引擎的 SQLite 存储(agy / opencode 都用它存会话索引)。
4
+ *
5
+ * 两个约束:
6
+ * 1. `node:sqlite` 在 Node 22.13 之前需要 flag,桌面壳里可能没有 —— 动态 import + 失败返回 `null`,
7
+ * 让「这个引擎扫不了」退化成一条可读的 unavailable,而不是把整个服务打挂;
8
+ * 2. 引擎进程可能正持有写锁(WAL),读不到就当作没有候选,绝不写对方的库。
9
+ */
10
+ async function openReadonly(file) {
11
+ if (pathKind(file) !== "file")
12
+ return null;
13
+ try {
14
+ const module = await import("node:sqlite");
15
+ return new module.DatabaseSync(file, { readOnly: true });
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ export async function queryReadonly(file, sql, params = []) {
22
+ const db = await openReadonly(file);
23
+ if (!db)
24
+ return null;
25
+ try {
26
+ const statement = db.prepare(sql);
27
+ const rows = statement.all(...params);
28
+ return Array.isArray(rows) ? rows : [];
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ finally {
34
+ try {
35
+ db.close();
36
+ }
37
+ catch { }
38
+ }
39
+ }
40
+ export function sqlString(row, key) {
41
+ const value = row[key];
42
+ return typeof value === "string" ? value : "";
43
+ }
44
+ export function sqlNumber(row, key) {
45
+ const value = row[key];
46
+ return typeof value === "number" && Number.isFinite(value) ? value : Number(value) || 0;
47
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * 可导入的外部引擎对话:只收「本机另有一份 transcript 存储」的引擎。
3
+ * `pi` 与 `durable` 不在其中——它们的会话本来就落在 keel 自己的目录里,导入等于复制自己。
4
+ */
5
+ export const IMPORT_ENGINES = ["claude", "codex", "agy", "opencode", "dsh"];
6
+ export function isImportEngineId(value) {
7
+ return typeof value === "string" && IMPORT_ENGINES.includes(value);
8
+ }