pi-web-ui 0.113.1 → 0.114.1

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 (280) hide show
  1. package/CHANGELOG.md +71 -1
  2. package/README.md +187 -316
  3. package/README.zh-CN.md +227 -299
  4. package/README.zh-TW.md +227 -299
  5. package/bin/device-hub-cli.mjs +577 -0
  6. package/bin/frp-manager.mjs +1573 -1573
  7. package/bin/pi-device-hub.mjs +9 -0
  8. package/bin/pi-web-ui.mjs +4081 -4041
  9. package/deploy/nginx-subpath.conf +100 -100
  10. package/deploy/pi-web-ui.service +36 -36
  11. package/dist/server/agent-service-daemon.js +102 -24
  12. package/dist/server/agent-service.js +2419 -1174
  13. package/dist/server/approval-rules.js +29 -3
  14. package/dist/server/ask-user-question-tool.js +8 -8
  15. package/dist/server/atomic-file.js +35 -14
  16. package/dist/server/attachment-store.js +71 -35
  17. package/dist/server/attachments.js +69 -13
  18. package/dist/server/canvas/canvas-agent-tool.js +68 -18
  19. package/dist/server/canvas/canvas-cards.js +1 -1
  20. package/dist/server/canvas/canvas-dispatch.js +61 -20
  21. package/dist/server/canvas/canvas-orchestrator.js +519 -202
  22. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  23. package/dist/server/canvas/canvas-scheduler.js +99 -0
  24. package/dist/server/canvas/canvas-store.js +107 -54
  25. package/dist/server/canvas/canvas-validation.js +131 -0
  26. package/dist/server/canvas/canvas-workspace.js +284 -0
  27. package/dist/server/client-id-utils.js +8 -0
  28. package/dist/server/client-state.js +110 -24
  29. package/dist/server/communicate-tool.js +76 -0
  30. package/dist/server/compact-context-tool.js +2 -3
  31. package/dist/server/compaction-instructions.js +75 -0
  32. package/dist/server/compaction-markers.js +7 -2
  33. package/dist/server/compaction-state.js +84 -0
  34. package/dist/server/composer-drafts.js +43 -40
  35. package/dist/server/context-evidence.js +346 -0
  36. package/dist/server/conversation-communication.js +368 -0
  37. package/dist/server/conversation-read-tool.js +3 -4
  38. package/dist/server/conversation-tool-names.js +14 -0
  39. package/dist/server/conversation-tool.js +57 -0
  40. package/dist/server/delegate-mode.js +17 -4
  41. package/dist/server/device-center/bot-catalog.js +88 -0
  42. package/dist/server/device-center/bot-execution.js +106 -0
  43. package/dist/server/device-center/bots.js +170 -0
  44. package/dist/server/device-center/collab-service.js +153 -0
  45. package/dist/server/device-center/collab-tool.js +184 -0
  46. package/dist/server/device-center/connector.js +351 -0
  47. package/dist/server/device-center/desktop-linux.js +372 -0
  48. package/dist/server/device-center/desktop-native.js +413 -0
  49. package/dist/server/device-center/desktop-page.js +232 -0
  50. package/dist/server/device-center/desktop-setup.js +30 -0
  51. package/dist/server/device-center/desktop.js +387 -0
  52. package/dist/server/device-center/device-portals.js +241 -0
  53. package/dist/server/device-center/execution-failure.js +70 -0
  54. package/dist/server/device-center/executor.js +371 -0
  55. package/dist/server/device-center/file-sync.js +493 -0
  56. package/dist/server/device-center/hub-auth.js +69 -0
  57. package/dist/server/device-center/hub-page.js +68 -0
  58. package/dist/server/device-center/hub-setup.js +214 -0
  59. package/dist/server/device-center/hub.js +830 -0
  60. package/dist/server/device-center/local-hub.js +92 -0
  61. package/dist/server/device-center/local.js +529 -0
  62. package/dist/server/device-center/main.js +118 -0
  63. package/dist/server/device-center/native-desktop/macos.js +192 -0
  64. package/dist/server/device-center/native-desktop/windows.js +118 -0
  65. package/dist/server/device-center/path-portal.js +120 -0
  66. package/dist/server/device-center/relay.js +996 -0
  67. package/dist/server/device-center/runtime.js +253 -0
  68. package/dist/server/device-center/store.js +122 -0
  69. package/dist/server/device-center/task-error.js +14 -0
  70. package/dist/server/device-center/transfers.js +293 -0
  71. package/dist/server/device-center/workspaces.js +45 -0
  72. package/dist/server/dispatch-domain-handlers.js +84 -27
  73. package/dist/server/dsh/dsh-agent-service.js +282 -159
  74. package/dist/server/dsh/dsh-client.js +12 -2
  75. package/dist/server/dsh/runtime/cordis.yml +1 -1
  76. package/dist/server/dsh/runtime/custom-prompt.mjs +33 -33
  77. package/dist/server/dsh/runtime/goal-rpc.mjs +1309 -1309
  78. package/dist/server/dsh/runtime/launcher.mjs +235 -235
  79. package/dist/server/dsh/runtime/override.patch.yml +89 -89
  80. package/dist/server/dsh/runtime/runtime-root.mjs +405 -405
  81. package/dist/server/durable/durable-agent-service.js +1 -1
  82. package/dist/server/engine-probe.js +36 -6
  83. package/dist/server/eval-tool.js +135 -135
  84. package/dist/server/evidence-tool-hooks.js +49 -0
  85. package/dist/server/file-save.js +95 -0
  86. package/dist/server/file-transfer-routes.js +97 -47
  87. package/dist/server/files-service.js +38 -26
  88. package/dist/server/global-loader.js +40 -2
  89. package/dist/server/goal-review-gate.js +16 -6
  90. package/dist/server/goal-service.js +54 -30
  91. package/dist/server/http-proxy.js +120 -0
  92. package/dist/server/index.js +285 -255
  93. package/dist/server/load-timing.js +31 -0
  94. package/dist/server/mcp-bridge.js +219 -94
  95. package/dist/server/mcp-hot-reload.js +31 -5
  96. package/dist/server/mcp-manager.js +192 -93
  97. package/dist/server/mcp-oauth-login.js +169 -0
  98. package/dist/server/mcp-oauth-ui.js +137 -0
  99. package/dist/server/mcp-oauth.js +395 -0
  100. package/dist/server/mcp-project-runtime.js +207 -0
  101. package/dist/server/message-window.js +74 -21
  102. package/dist/server/net-guard.js +122 -20
  103. package/dist/server/patch-bash-process.js +125 -0
  104. package/dist/server/patch-tool.js +9 -9
  105. package/dist/server/patch-turn-end-boundary.js +3 -3
  106. package/dist/server/payload-limits.js +17 -0
  107. package/dist/server/pending-question.js +82 -0
  108. package/dist/server/persona-chain.js +8 -8
  109. package/dist/server/plan-mode.js +338 -137
  110. package/dist/server/plugin-assets.js +8 -4
  111. package/dist/server/plugin-chat-attachments.js +48 -0
  112. package/dist/server/plugin-facilities.js +67 -220
  113. package/dist/server/plugin-installer.js +2 -1
  114. package/dist/server/plugin-removal.js +49 -0
  115. package/dist/server/plugin-secrets.js +179 -0
  116. package/dist/server/plugins.js +288 -94
  117. package/dist/server/preset-fields.js +56 -0
  118. package/dist/server/preset-plugin-dependencies.js +57 -0
  119. package/dist/server/preset-share.js +113 -72
  120. package/dist/server/prompt-templates.js +106 -0
  121. package/dist/server/protocol-version.js +1 -1
  122. package/dist/server/queue-modes.js +10 -0
  123. package/dist/server/remote-ssh-service.js +199 -106
  124. package/dist/server/request-context.js +164 -0
  125. package/dist/server/resolve-global-sdk.js +2 -0
  126. package/dist/server/sandbox-data.js +655 -0
  127. package/dist/server/sandbox-engines.js +7 -0
  128. package/dist/server/sandbox-runtime-gate.js +41 -0
  129. package/dist/server/sandbox-service.js +139 -698
  130. package/dist/server/sandbox-tool.js +21 -4
  131. package/dist/server/schedule-agent-tool.js +39 -21
  132. package/dist/server/scheduler-tasks.js +106 -55
  133. package/dist/server/scm-commitmsg.js +10 -10
  134. package/dist/server/serialize.js +48 -19
  135. package/dist/server/session-branch.js +25 -3
  136. package/dist/server/session-parser.js +28 -18
  137. package/dist/server/session-scan.js +130 -0
  138. package/dist/server/session-search.js +51 -37
  139. package/dist/server/settings-service.js +273 -111
  140. package/dist/server/setup-config.js +58 -0
  141. package/dist/server/setup-page.js +620 -620
  142. package/dist/server/skill-maintenance.js +112 -24
  143. package/dist/server/subagent-helpers.js +4 -1
  144. package/dist/server/subagent-notify.js +4 -1
  145. package/dist/server/subagent-security-gate.js +52 -11
  146. package/dist/server/subagent-task.js +27 -0
  147. package/dist/server/subagents.js +217 -46
  148. package/dist/server/tabs.js +9 -1
  149. package/dist/server/terminals.js +467 -363
  150. package/dist/server/text-quote.js +9 -0
  151. package/dist/server/tool-guards.js +42 -6
  152. package/dist/server/tool-manager.js +48 -20
  153. package/dist/server/tool-overrides.js +13 -11
  154. package/dist/server/tool-prompt-overrides.js +32 -2
  155. package/dist/server/tool-prompts.js +1 -1
  156. package/dist/server/turn-timing.js +11 -0
  157. package/dist/server/universal/drivers/claude-code.js +5 -0
  158. package/dist/server/universal/drivers/codex.js +336 -0
  159. package/dist/server/universal/index.js +1 -0
  160. package/dist/server/universal/session-store.js +48 -6
  161. package/dist/server/universal/universal-attachments.js +24 -1
  162. package/dist/server/universal/universal-service.js +1 -1
  163. package/dist/server/universal/universal-session.js +357 -231
  164. package/dist/server/uploads.js +64 -5
  165. package/dist/server/vision-bridge.js +18 -18
  166. package/dist/server/worktree-service.js +32 -24
  167. package/dist/server/ws-pending-queue.js +73 -27
  168. package/docs/device-center.md +148 -0
  169. package/docs/device-desktop.md +48 -0
  170. package/docs/dsh-engine.md +493 -493
  171. package/extensions/webui.ts +335 -335
  172. package/package.json +5 -2
  173. package/plugin-sdk/README.md +174 -174
  174. package/plugin-sdk/client-utils.mjs +279 -279
  175. package/plugin-sdk/import-check.mjs +210 -210
  176. package/plugin-sdk/index.d.ts +698 -676
  177. package/plugin-sdk/index.mjs +696 -696
  178. package/plugin-sdk/package.json +13 -13
  179. package/plugin-sdk/ssh-host-trust.mjs +225 -0
  180. package/plugins/catalog.json +11 -1
  181. package/themes/aetheris.css +501 -607
  182. package/themes/ayu-light.css +116 -140
  183. package/themes/bases/flow-base.css +1357 -1363
  184. package/themes/bases/obsidian-base.css +895 -895
  185. package/themes/bases/statusbar-flat-base.css +112 -0
  186. package/themes/bases/zhujian-base.css +688 -687
  187. package/themes/bases/zhupi-base.css +660 -659
  188. package/themes/catppuccin-latte.css +119 -142
  189. package/themes/catppuccin.css +116 -147
  190. package/themes/claude-code-dark.css +147 -146
  191. package/themes/codex.css +114 -138
  192. package/themes/cyberpunk.css +50 -108
  193. package/themes/dark-teal.css +264 -265
  194. package/themes/dazzle.css +38 -108
  195. package/themes/everforest-light.css +115 -138
  196. package/themes/flow-light.css +164 -164
  197. package/themes/flow.css +161 -161
  198. package/themes/geist.css +114 -138
  199. package/themes/gruvbox-light.css +115 -138
  200. package/themes/kanagawa-lotus.css +115 -138
  201. package/themes/md-preview.css +24 -234
  202. package/themes/mist.css +166 -186
  203. package/themes/nord.css +107 -138
  204. package/themes/one-dark.css +106 -139
  205. package/themes/paper.css +174 -186
  206. package/themes/rose-pine-dawn.css +114 -138
  207. package/themes/sakura.css +166 -186
  208. package/themes/solarized-light.css +114 -137
  209. package/themes/tokyo-night.css +115 -146
  210. package/themes/translucent.css +85 -85
  211. package/themes/transparent.css +116 -116
  212. package/themes/vs-code-dark.css +147 -147
  213. package/themes/wallpaper-flow.css +382 -382
  214. package/themes/wallpaper-obsidian.css +74 -74
  215. package/themes/white.css +164 -186
  216. package/themes/zhujian-dark.css +115 -114
  217. package/themes/zhujian.css +114 -114
  218. package/themes/zhupi-dark.css +115 -114
  219. package/themes/zhupi.css +114 -114
  220. package/web/dist/.build-assets.json +1 -0
  221. package/web/dist/assets/BgTasksModal-BcXJ20RO.js +1 -0
  222. package/web/dist/assets/BgTasksModal-DjQmiKnE.js +1 -0
  223. package/web/dist/assets/CanvasStudio-PI9pid0Y.js +1579 -0
  224. package/web/dist/assets/CanvasStudio-nf5-HxLM.js +1579 -0
  225. package/web/dist/assets/DeviceCenter-CYttJw2a.js +3 -0
  226. package/web/dist/assets/DeviceCenter-DPe4sz74.js +3 -0
  227. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  228. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  229. package/web/dist/assets/FilePreview-C9Ut4Lq6.js +2 -0
  230. package/web/dist/assets/FilePreview-CvK3ZzX5.js +2 -0
  231. package/web/dist/assets/GlobalSearchModal-C5e-OCw2.js +1 -0
  232. package/web/dist/assets/GlobalSearchModal-H7pFK2UC.js +1 -0
  233. package/web/dist/assets/GroupConversation-C2wNM0dQ.js +1 -0
  234. package/web/dist/assets/GroupConversation-ChN3TWQK.js +1 -0
  235. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  236. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  237. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  238. package/web/dist/assets/SCMPanel-buTGziDB.js +2 -0
  239. package/web/dist/assets/SCMPanel-kx-SCL2s.js +2 -0
  240. package/web/dist/assets/SettingsModal-BsUF8jqr.js +20 -0
  241. package/web/dist/assets/SettingsModal-D357Ky7P.js +20 -0
  242. package/web/dist/assets/TerminalPanel-BBuM_Sez.js +3 -0
  243. package/web/dist/assets/TerminalPanel-D6x6xz8Q.js +3 -0
  244. package/web/dist/assets/TuiOverlayModal-CdbGV3Za.js +1 -0
  245. package/web/dist/assets/TuiOverlayModal-d6x9u25n.js +1 -0
  246. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  247. package/web/dist/assets/desktop-YguLbrX1.js +1 -0
  248. package/web/dist/assets/es-DWMIuDU2.js +2 -0
  249. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  250. package/web/dist/assets/index-BPvpea8t.js +85 -0
  251. package/web/dist/assets/index-D6u8xH0o.js +85 -0
  252. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  253. package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
  254. package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
  255. package/web/dist/assets/math-1uRJCsA9.js +257 -0
  256. package/web/dist/assets/math-BorAY7qD.css +1 -0
  257. package/web/dist/assets/plugin-host-BRBg6zmQ.js +1 -0
  258. package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
  259. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  260. package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
  261. package/web/dist/index.html +42 -35
  262. package/web/dist/sw.js +179 -179
  263. package/web/public/sw.js +179 -179
  264. package/dist/gh-comment-781.md +0 -5
  265. package/dist/server/durable/durable-capabilities.js +0 -11
  266. package/dist/server/markers/builtins/services.js +0 -123
  267. package/dist/server/markers/builtins/todo.js +0 -189
  268. package/dist/server/markers-list-tool.js +0 -34
  269. package/dist/server/orchestrator.js +0 -109
  270. package/dist/server/system-prompt-soul.js +0 -41
  271. package/dist/server/univer-service.js +0 -448
  272. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  273. package/dist/test-artifact.md +0 -9
  274. package/dist/test-preview-modal.md +0 -11
  275. package/dist/test-report.html +0 -20
  276. package/web/dist/assets/TerminalPanel-Ci55JtJL.js +0 -3
  277. package/web/dist/assets/index-ByiO9f-N.js +0 -2008
  278. package/web/dist/assets/index-ycGLh4a4.css +0 -1
  279. package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
  280. package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
@@ -0,0 +1,336 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { delimiter, join } from "node:path";
5
+ import { StringDecoder } from "node:string_decoder";
6
+ import { BaseAgentDriver } from "../driver-base.js";
7
+ import { probeGlobalPackage } from "../../global-loader.js";
8
+ import { killPidTree } from "../../process-utils.js";
9
+ import { formatUnavailableCanvasReference } from "../universal-attachments.js";
10
+ /** Resolve the npm launcher before PATH so Windows does not require a command shell. */
11
+ function codexCommand(executablePath) {
12
+ if (executablePath)
13
+ return { command: executablePath, args: [] };
14
+ const pkg = probeGlobalPackage("@openai/codex");
15
+ if (pkg.packagePath) {
16
+ const launcher = join(pkg.packagePath, "bin", "codex.js");
17
+ if (existsSync(launcher))
18
+ return { command: process.execPath, args: [launcher] };
19
+ }
20
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
21
+ const exe = join(dir, process.platform === "win32" ? "codex.exe" : "codex");
22
+ if (existsSync(exe))
23
+ return { command: exe, args: [] };
24
+ }
25
+ return { command: "codex", args: [] };
26
+ }
27
+ export async function probeCodex(executablePath) {
28
+ const cmd = codexCommand(executablePath);
29
+ return new Promise((resolve) => {
30
+ execFile(cmd.command, [...cmd.args, "--version"], { timeout: 4000, windowsHide: true, maxBuffer: 8192 }, (err, stdout) => {
31
+ resolve(err
32
+ ? { available: false, error: err.message }
33
+ : { available: true, version: stdout.trim().replace(/^codex(?:-cli)?\s+/i, "") });
34
+ });
35
+ });
36
+ }
37
+ export class CodexDriver extends BaseAgentDriver {
38
+ options;
39
+ id = "codex";
40
+ name = "Codex";
41
+ capabilities = {
42
+ supportsTreeFork: false,
43
+ supportsHistoryEdit: false,
44
+ supportsToolPromptOverride: false,
45
+ supportsModelSwitch: true,
46
+ supportsThinkingLevels: true,
47
+ supportsAskUser: false,
48
+ supportsSubagents: true,
49
+ };
50
+ sessionId = "";
51
+ model = "default";
52
+ effort = "medium";
53
+ active;
54
+ disposed = false;
55
+ constructor(cwd, options = {}) {
56
+ super(cwd);
57
+ this.options = options;
58
+ }
59
+ async createSession() {
60
+ this.sessionId = "";
61
+ return "";
62
+ }
63
+ async resumeSession(sessionId) {
64
+ this.sessionId = sessionId;
65
+ }
66
+ getActiveSessionId() {
67
+ return this.sessionId;
68
+ }
69
+ async setModel(modelId) {
70
+ this.model = modelId.replace(/^codex\//, "");
71
+ }
72
+ setThinkingLevel(level) {
73
+ this.effort = this.getSupportedThinkingLevels().includes(level) ? level : "medium";
74
+ }
75
+ getSupportedThinkingLevels() {
76
+ return ["minimal", "low", "medium", "high", "xhigh"];
77
+ }
78
+ async listModels() {
79
+ const rows = [{ id: "default", name: "Codex config default" }];
80
+ try {
81
+ const cache = JSON.parse(readFileSync(join(process.env.CODEX_HOME || join(homedir(), ".codex"), "models_cache.json"), "utf8"));
82
+ for (const model of cache.models ?? []) {
83
+ if (typeof model.slug === "string" && !rows.some((row) => row.id === model.slug))
84
+ rows.push({ id: model.slug, name: model.display_name || model.slug });
85
+ }
86
+ }
87
+ catch {
88
+ /* CLI populates the catalog after login. */
89
+ }
90
+ return rows;
91
+ }
92
+ async sendPrompt(prompt, attachments, sink) {
93
+ if (this.disposed)
94
+ throw new Error("Codex driver disposed");
95
+ if (this.active)
96
+ throw new Error("Codex is already running");
97
+ const cwd = this.cwd;
98
+ let imageDir;
99
+ const imageArgs = [];
100
+ let input = prompt;
101
+ try {
102
+ for (const att of attachments ?? []) {
103
+ if (att.mode === "canvas") {
104
+ input += `\n${formatUnavailableCanvasReference(att)}`;
105
+ continue;
106
+ }
107
+ if (att.mode === "page" || att.mode === "conversation") {
108
+ input += `\nReferenced ${att.mode}: ${JSON.stringify(att.path)} (host access unavailable in Codex).`;
109
+ continue;
110
+ }
111
+ if (att.imageData) {
112
+ const match = /^data:(image\/(?:png|jpeg|webp|gif));base64,([\s\S]+)$/.exec(att.imageData);
113
+ const mime = match?.[1] ?? att.mimeType;
114
+ if (!mime || !["image/png", "image/jpeg", "image/webp", "image/gif"].includes(mime))
115
+ throw new Error("Unsupported Codex image format");
116
+ const encoded = match?.[2] ?? att.imageData;
117
+ if (encoded.length > 28 * 1024 * 1024)
118
+ throw new Error("Codex image exceeds size limit");
119
+ imageDir ??= mkdtempSync(join(tmpdir(), "pi-codex-images-"));
120
+ const path = join(imageDir, `${imageArgs.length}.${mime.split("/")[1]}`);
121
+ writeFileSync(path, Buffer.from(encoded, "base64"), { mode: 0o600 });
122
+ imageArgs.push("--image", path);
123
+ }
124
+ else if (att.mode === "quote" && att.quote)
125
+ input += `\n<quote>\n${att.quote.text}\n</quote>`;
126
+ else
127
+ input += `\nFile reference: ${JSON.stringify(att.path)}${att.mode === "lines" ? ` (lines ${att.lines?.start ?? ""}-${att.lines?.end ?? ""})` : ""}`;
128
+ }
129
+ const cmd = codexCommand(this.options.executablePath);
130
+ const args = [
131
+ ...cmd.args,
132
+ "--ask-for-approval",
133
+ "never",
134
+ "exec",
135
+ "--json",
136
+ "--skip-git-repo-check",
137
+ "--sandbox",
138
+ "workspace-write",
139
+ "--color",
140
+ "never",
141
+ "-c",
142
+ `model_reasoning_effort=${JSON.stringify(this.effort)}`,
143
+ ];
144
+ if (this.model !== "default")
145
+ args.push("--model", this.model);
146
+ if (this.sessionId)
147
+ args.push("resume", this.sessionId);
148
+ args.push(...imageArgs, "-");
149
+ const child = spawn(cmd.command, args, {
150
+ cwd,
151
+ windowsHide: true,
152
+ detached: process.platform !== "win32",
153
+ stdio: ["pipe", "pipe", "pipe"],
154
+ env: { ...process.env, NO_COLOR: "1" },
155
+ });
156
+ let finish;
157
+ const run = {
158
+ child,
159
+ cancelled: false,
160
+ done: new Promise((resolve) => {
161
+ finish = resolve;
162
+ }),
163
+ };
164
+ this.active = run;
165
+ const decoder = new StringDecoder("utf8");
166
+ let pending = "", stderr = "", error, completed = false, settled = false;
167
+ let usage;
168
+ const texts = new Map();
169
+ const tools = new Set();
170
+ const parse = (line) => {
171
+ if (!line.trim() || run.cancelled)
172
+ return;
173
+ let event;
174
+ try {
175
+ event = JSON.parse(line);
176
+ }
177
+ catch {
178
+ throw new Error("Invalid Codex JSON event");
179
+ }
180
+ if (event.type === "thread.started" && typeof event.thread_id === "string") {
181
+ this.sessionId = event.thread_id;
182
+ sink.onSessionStarted?.(event.thread_id);
183
+ }
184
+ else if (event.type === "turn.completed") {
185
+ completed = true;
186
+ const u = event.usage ?? {};
187
+ const cached = u.cached_input_tokens ?? 0;
188
+ usage = {
189
+ inputTokens: Math.max(0, (u.input_tokens ?? 0) - cached),
190
+ cacheReadTokens: cached,
191
+ outputTokens: u.output_tokens ?? 0,
192
+ };
193
+ }
194
+ else if (event.type === "turn.failed")
195
+ error = new Error(event.error?.message || "Codex turn failed");
196
+ else if (event.type === "error")
197
+ error = new Error(event.message || "Codex error");
198
+ else if (event.type?.startsWith("item.") && event.item) {
199
+ const item = event.item, id = String(item.id);
200
+ if (item.type === "agent_message" || item.type === "reasoning") {
201
+ const text = typeof item.text === "string" ? item.text : "";
202
+ const previous = texts.get(id) ?? "";
203
+ const delta = text.startsWith(previous) ? text.slice(previous.length) : text;
204
+ texts.set(id, text);
205
+ if (delta) {
206
+ if (item.type === "reasoning")
207
+ sink.onThinkingDelta(delta);
208
+ else
209
+ sink.onTextDelta(delta);
210
+ }
211
+ }
212
+ else if (["command_execution", "file_change", "mcp_tool_call", "web_search", "todo_list"].includes(item.type)) {
213
+ if (!tools.has(id)) {
214
+ tools.add(id);
215
+ sink.onToolStart(id, item.type, item.type === "command_execution" ? { command: item.command } : { ...item });
216
+ }
217
+ if (event.type === "item.completed")
218
+ sink.onToolEnd(id, {
219
+ output: item.aggregated_output ?? JSON.stringify(item),
220
+ ...(item.status === "failed" || (typeof item.exit_code === "number" && item.exit_code !== 0)
221
+ ? { error: item.error?.message || `Codex ${item.type} failed (${item.exit_code ?? item.status})` }
222
+ : {}),
223
+ });
224
+ }
225
+ }
226
+ };
227
+ const fail = (err) => {
228
+ error = err instanceof Error ? err : new Error(String(err));
229
+ void this.stopRun(run);
230
+ };
231
+ child.stdout?.on("data", (chunk) => {
232
+ try {
233
+ pending += decoder.write(chunk);
234
+ if (pending.length > 8 * 1024 * 1024)
235
+ throw new Error("Codex output event exceeds limit");
236
+ let newline;
237
+ while ((newline = pending.indexOf("\n")) >= 0) {
238
+ const line = pending.slice(0, newline);
239
+ pending = pending.slice(newline + 1);
240
+ parse(line);
241
+ }
242
+ }
243
+ catch (err) {
244
+ fail(err);
245
+ }
246
+ });
247
+ child.stderr?.on("data", (chunk) => {
248
+ stderr = (stderr + chunk.toString()).slice(-8000);
249
+ });
250
+ child.stdin?.on("error", (err) => {
251
+ if (!run.cancelled)
252
+ error = err;
253
+ });
254
+ const settle = (code) => {
255
+ if (settled)
256
+ return;
257
+ settled = true;
258
+ try {
259
+ pending += decoder.end();
260
+ if (pending.trim() && !run.cancelled)
261
+ parse(pending);
262
+ if (this.active === run)
263
+ this.active = undefined;
264
+ if (run.cancelled) {
265
+ if (error)
266
+ sink.onError(error);
267
+ }
268
+ else if (error || code !== 0 || !completed)
269
+ sink.onError(error ?? new Error(stderr.trim() || `Codex exited before completion (${code})`));
270
+ else
271
+ sink.onTurnComplete({ usage });
272
+ }
273
+ catch (err) {
274
+ sink.onError(err instanceof Error ? err : String(err));
275
+ }
276
+ finally {
277
+ if (this.active === run)
278
+ this.active = undefined;
279
+ finish();
280
+ }
281
+ };
282
+ child.on("error", (err) => {
283
+ error = err;
284
+ settle(null);
285
+ });
286
+ child.on("close", settle);
287
+ child.stdin?.end(input);
288
+ await run.done;
289
+ }
290
+ finally {
291
+ if (imageDir)
292
+ rmSync(imageDir, { recursive: true, force: true });
293
+ }
294
+ }
295
+ stopRun(run) {
296
+ if (run.stop)
297
+ return run.stop;
298
+ run.cancelled = true;
299
+ run.stop = (async () => {
300
+ if (run.child.pid) {
301
+ let timer;
302
+ try {
303
+ await Promise.race([
304
+ killPidTree(run.child.pid),
305
+ new Promise((resolve) => {
306
+ timer = setTimeout(resolve, 3000);
307
+ }),
308
+ ]);
309
+ }
310
+ finally {
311
+ if (timer)
312
+ clearTimeout(timer);
313
+ }
314
+ }
315
+ else
316
+ run.child.kill();
317
+ await Promise.race([
318
+ run.done,
319
+ new Promise((resolve) => {
320
+ const timer = setTimeout(resolve, 3000);
321
+ timer.unref();
322
+ run.done.then(() => clearTimeout(timer));
323
+ }),
324
+ ]);
325
+ })();
326
+ return run.stop;
327
+ }
328
+ async abort() {
329
+ if (this.active)
330
+ await this.stopRun(this.active);
331
+ }
332
+ async dispose() {
333
+ this.disposed = true;
334
+ await this.abort();
335
+ }
336
+ }
@@ -5,5 +5,6 @@ export { BaseAgentDriver } from "./driver-base.js";
5
5
  export { UniversalSessionStore } from "./session-store.js";
6
6
  export { UniversalSession } from "./universal-session.js";
7
7
  export { UniversalAgentService } from "./universal-service.js";
8
+ export { CodexDriver, probeCodex } from "./drivers/codex.js";
8
9
  export { MockAgentDriver } from "./drivers/mock-driver.js";
9
10
  export { ClaudeCodeDriver, probeClaudeCode } from "./drivers/claude-code.js";
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * session-store.ts — 通用 Agent 会话的轻量级磁盘持久化。
3
3
  *
4
- * 会话存储在 <dataDir>/universal-sessions/<cwdHash>/<convId>.json 下。
4
+ * 会话存储在 <dataDir>/universal-sessions/<engine>/<cwdHash>/<convId>.json 下。
5
5
  * 格式为纯 JSON,严格线性结构,便于直读、回放与恢复。
6
6
  */
7
7
  import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync } from "node:fs";
@@ -10,9 +10,13 @@ import { createHash } from "node:crypto";
10
10
  import { writeJsonAtomicSync } from "../atomic-file.js";
11
11
  import { normalizePathKey } from "../client-state.js";
12
12
  export class UniversalSessionStore {
13
+ engine;
13
14
  baseDir;
14
- constructor(dataDir) {
15
- this.baseDir = join(dataDir, "universal-sessions");
15
+ constructor(dataDir, engine = "claude") {
16
+ this.engine = engine;
17
+ if (!/^[a-zA-Z0-9_-]+$/.test(engine))
18
+ throw new Error("Invalid engine namespace");
19
+ this.baseDir = join(dataDir, "universal-sessions", engine);
16
20
  try {
17
21
  mkdirSync(this.baseDir, { recursive: true });
18
22
  }
@@ -34,6 +38,7 @@ export class UniversalSessionStore {
34
38
  return join(this.cwdDir(cwd), `${safeId}.json`);
35
39
  }
36
40
  listConversations(cwd) {
41
+ this.importLegacy(cwd);
37
42
  const dir = this.cwdDir(cwd);
38
43
  if (!existsSync(dir))
39
44
  return [];
@@ -44,7 +49,7 @@ export class UniversalSessionStore {
44
49
  try {
45
50
  const full = join(dir, file);
46
51
  const data = JSON.parse(readFileSync(full, "utf-8"));
47
- if (data && data.id && Array.isArray(data.messages)) {
52
+ if (data && data.engine === this.engine && data.id && Array.isArray(data.messages)) {
48
53
  list.push(data);
49
54
  }
50
55
  }
@@ -56,11 +61,13 @@ export class UniversalSessionStore {
56
61
  return list.sort((a, b) => b.updatedAt - a.updatedAt);
57
62
  }
58
63
  loadConversation(cwd, convId) {
64
+ this.importLegacy(cwd);
59
65
  const p = this.convPath(cwd, convId);
60
66
  if (!existsSync(p))
61
67
  return null;
62
68
  try {
63
- return JSON.parse(readFileSync(p, "utf-8"));
69
+ const data = JSON.parse(readFileSync(p, "utf-8"));
70
+ return data.engine === this.engine && data.id === convId && Array.isArray(data.messages) ? data : null;
64
71
  }
65
72
  catch {
66
73
  return null;
@@ -68,9 +75,44 @@ export class UniversalSessionStore {
68
75
  }
69
76
  saveConversation(cwd, conv) {
70
77
  const p = this.convPath(cwd, conv.id);
71
- writeJsonAtomicSync(p, conv);
78
+ writeJsonAtomicSync(p, { ...conv, engine: this.engine });
79
+ }
80
+ /** Import legacy messages; ambiguous driver identities never cross engine boundaries. */
81
+ importLegacy(cwd) {
82
+ const hash = createHash("sha256").update(normalizePathKey(cwd)).digest("hex").slice(0, 16);
83
+ const legacyDir = join(this.baseDir, "..", hash);
84
+ if (!existsSync(legacyDir))
85
+ return;
86
+ for (const file of readdirSync(legacyDir)) {
87
+ if (!file.endsWith(".json"))
88
+ continue;
89
+ const path = join(legacyDir, file);
90
+ try {
91
+ const conv = JSON.parse(readFileSync(path, "utf-8"));
92
+ if ((conv.engine && conv.engine !== this.engine) || !conv.id || !Array.isArray(conv.messages))
93
+ continue;
94
+ if (!conv.engine) {
95
+ // Ambiguous legacy transcripts are message-only imports. Never resume a foreign driver.
96
+ const marker = `${this.convPath(cwd, conv.id)}.legacy-imported`;
97
+ if (existsSync(marker))
98
+ continue;
99
+ const imported = { ...conv, driverSessionId: undefined };
100
+ if (!existsSync(this.convPath(cwd, conv.id)))
101
+ this.saveConversation(cwd, imported);
102
+ writeJsonAtomicSync(marker, { imported: true });
103
+ continue;
104
+ }
105
+ if (!existsSync(this.convPath(cwd, conv.id)))
106
+ this.saveConversation(cwd, conv);
107
+ unlinkSync(path);
108
+ }
109
+ catch {
110
+ /* Leave unreadable or failed imports untouched. */
111
+ }
112
+ }
72
113
  }
73
114
  deleteConversation(cwd, convId) {
115
+ this.importLegacy(cwd);
74
116
  const p = this.convPath(cwd, convId);
75
117
  if (existsSync(p)) {
76
118
  try {
@@ -12,6 +12,11 @@ import { existsSync, statSync } from "node:fs";
12
12
  import { basename, isAbsolute, relative, resolve } from "node:path";
13
13
  import { readSkillInstruction } from "../skill-discovery.js";
14
14
  import { isRemoteWorkspaceUri } from "../remote-ssh-service.js";
15
+ /** Canvas ids are not workspace paths; unsupported engines must say so. */
16
+ export function formatUnavailableCanvasReference(att) {
17
+ const escape = (s) => s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
18
+ return `<canvas-ref id="${escape(att.path)}" title="${escape(att.name || att.path)}">Canvas tooling is unavailable in this engine. This is a graph identifier, not a file path; do not read it as a file or start a run.</canvas-ref>`;
19
+ }
15
20
  /**
16
21
  * 扫描用户提问文本中的 `@` 词元:
17
22
  * - `@skill:foo` 或匹配已知技能名的 `@foo`
@@ -42,7 +47,14 @@ export function scanAtMentions(text, cwd, availableSkills = [], existingAttachme
42
47
  const pathRegex = /(?:^|\s)@([^\s@:"'<>|?*]+)/g;
43
48
  let pm;
44
49
  const root = resolve(cwd);
45
- while ((pm = pathRegex.exec(text)) !== null) {
50
+ let pathText = text;
51
+ for (const att of existingAttachments) {
52
+ if (att.mode !== "canvas" || !att.name)
53
+ continue;
54
+ const escaped = att.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
55
+ pathText = pathText.replace(new RegExp(`(^|\\s)@${escaped}(?=$|\\s)`, "g"), "$1");
56
+ }
57
+ while ((pm = pathRegex.exec(pathText)) !== null) {
46
58
  const rawCandidate = pm[1].trim();
47
59
  if (!rawCandidate || rawCandidate.startsWith("skill:"))
48
60
  continue;
@@ -125,6 +137,17 @@ export function createAttachmentUiMessages(attachments, timestamp = Date.now())
125
137
  });
126
138
  continue;
127
139
  }
140
+ if (att.mode === "canvas") {
141
+ out.push({
142
+ id: cardId,
143
+ role: "custom",
144
+ customType: "file",
145
+ timestamp,
146
+ content: [{ type: "text", text: formatUnavailableCanvasReference(att) }],
147
+ details: { mode: "canvas", path: att.path, name: att.name || att.path, title: att.name || att.path },
148
+ });
149
+ continue;
150
+ }
128
151
  // 4. 工作区文件/目录/行范围
129
152
  if (att.path) {
130
153
  const isLines = att.mode === "lines" && att.lines;
@@ -31,7 +31,7 @@ export class UniversalAgentService {
31
31
  this.dataDir = opts.dataDir;
32
32
  this.agentDir = opts.agentDir;
33
33
  this.engine = opts.engine ?? "claude";
34
- this.store = new UniversalSessionStore(opts.dataDir);
34
+ this.store = new UniversalSessionStore(opts.dataDir, this.engine);
35
35
  this.stateStore = opts.stateStore;
36
36
  // 默认使用 MockDriver;接入 Claude Code 时可替换
37
37
  this.driverFactory = opts.driverFactory ?? ((cwd) => new MockAgentDriver(cwd));