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
@@ -70,9 +70,18 @@ export function makeSandboxTool(host, getLang) {
70
70
  const cwd = host.getCwd();
71
71
  const activeSbx = host.sandboxes.getByCwd(cwd);
72
72
  try {
73
+ if (activeSbx) {
74
+ if (!["list", "persist"].includes(params.action)) {
75
+ throw new Error("Sandbox control and source comparison must be requested from outside the sandbox");
76
+ }
77
+ const target = params.sandbox?.trim();
78
+ if (target && target !== activeSbx.id && target !== activeSbx.path) {
79
+ throw new Error("Sandbox tools cannot access another sandbox");
80
+ }
81
+ }
73
82
  switch (params.action) {
74
83
  case "list": {
75
- const list = host.sandboxes.list();
84
+ const list = activeSbx ? [activeSbx] : host.sandboxes.list();
76
85
  if (list.length === 0) {
77
86
  return {
78
87
  content: [
@@ -183,7 +192,9 @@ export function makeSandboxTool(host, getLang) {
183
192
  }
184
193
  case "reset": {
185
194
  const target = params.sandbox?.trim() || activeSbx?.id || cwd;
186
- const { sandbox, copiedFiles } = await host.sandboxes.reset(target);
195
+ if (activeSbx)
196
+ throw new Error("Reset must be requested from outside the sandbox");
197
+ const { sandbox, copiedFiles } = await host.resetSandbox(target);
187
198
  await host.onSandboxesChanged();
188
199
  return {
189
200
  content: [
@@ -297,7 +308,9 @@ export function makeSandboxTool(host, getLang) {
297
308
  };
298
309
  }
299
310
  }
300
- const res = await host.sandboxes.applyToSource(diff.sandbox.id);
311
+ if (activeSbx)
312
+ throw new Error("Apply must be requested from outside the sandbox");
313
+ const res = await host.applySandboxToSource(diff.sandbox.id, diff.expectedRevision);
301
314
  await host.onSandboxesChanged();
302
315
  return {
303
316
  content: [
@@ -374,7 +387,11 @@ export function makeSandboxTool(host, getLang) {
374
387
  if (activeSbx?.id === targetInfo.id) {
375
388
  await host.setCwd(targetInfo.sourcePath && existsSync(targetInfo.sourcePath) ? targetInfo.sourcePath : homedir());
376
389
  }
377
- const destroyed = await host.sandboxes.destroy(targetInfo.id);
390
+ if (activeSbx)
391
+ throw new Error("Destroy must be requested from outside the sandbox");
392
+ const destroyed = await host.destroySandbox(targetInfo.id);
393
+ if (!destroyed)
394
+ throw new Error("Sandbox was not destroyed");
378
395
  await host.onSandboxesChanged();
379
396
  return {
380
397
  content: [
@@ -85,13 +85,17 @@ function taskLine(t, lang) {
85
85
  ? "启用"
86
86
  : "on";
87
87
  const once = t.oneShot ? (lang === "zh" ? " · 单次" : " · one-shot") : "";
88
- const target = t.conversationId
88
+ const target = t.target === "canvas"
89
89
  ? lang === "zh"
90
- ? ` · 汇报→对话${t.conversationId}`
91
- : ` · reports→${t.conversationId}`
92
- : lang === "zh"
93
- ? " · 无头执行"
94
- : " · headless";
90
+ ? ` · 画布→${t.graphId}`
91
+ : ` · canvas→${t.graphId}`
92
+ : t.conversationId
93
+ ? lang === "zh"
94
+ ? ` · 汇报→对话${t.conversationId}`
95
+ : ` · reports→${t.conversationId}`
96
+ : lang === "zh"
97
+ ? " · 无头执行"
98
+ : " · headless";
95
99
  const last = t.lastRun
96
100
  ? lang === "zh"
97
101
  ? ` · 上次${t.lastRun.ok ? "成功" : `失败(${t.lastRun.error ?? "未知错误"})`}`
@@ -109,11 +113,12 @@ export function makeScheduleTool(host, ownerConversationId, lang) {
109
113
  const noStore = () => text(pick(getLang(), "当前引擎不支持定时任务(调度存储未接入)。", "Scheduled tasks are not wired for the current engine.", "sched.not.wired"));
110
114
  return defineTool({
111
115
  name: SCHEDULE_TOOL_NAME,
112
- label: "Manage scheduled wake-ups",
113
- description: "Create, list, or cancel built-in scheduled wake-ups in the CURRENT conversation: on create your prompt is delivered " +
114
- "back into this conversation at the cron time or after the delay you give, so you continue and report. One-shot by default; recurring=true repeats. " +
115
- "Survives compaction/restart; if the conversation is gone it falls back to the project's active conversation when one exists, headless otherwise.",
116
- promptSnippet: "create/list/cancel scheduled wake-ups",
116
+ label: "Manage scheduled tasks",
117
+ description: "Create, list, or cancel persistent scheduled tasks. Without graphId, delivers a required prompt to the current conversation; " +
118
+ "if unavailable, falls back to the project's active conversation or a headless run. With graphId, runs that existing canvas; " +
119
+ "prompt is optional and otherwise uses the graph's input. Canvas tasks do not bind a conversation or override node models. " +
120
+ "One-shot by default; recurring=true repeats. Minimum delay 60s.",
121
+ promptSnippet: "Create, list, or cancel conversation or canvas schedules",
117
122
  promptGuidelines: [
118
123
  "Use action=create for periodic checks, delayed reminders, and scheduled summaries — never sleep loops (they cannot push messages back)",
119
124
  "Use action=list to inspect existing tasks and action=cancel to stop one by id",
@@ -127,8 +132,11 @@ export function makeScheduleTool(host, ownerConversationId, lang) {
127
132
  schedule: Type.Optional(Type.String({
128
133
  description: 'create: when to fire — 5-field cron ("0 * * * *" hourly) or relative delay ("in 30m", "in 1h", "30m"). Minimum 60s.',
129
134
  })),
135
+ graphId: Type.Optional(Type.String({
136
+ description: "create: existing canvas graph id; when provided, targets the canvas instead of a conversation.",
137
+ })),
130
138
  prompt: Type.Optional(Type.String({
131
- description: "create: instruction delivered into this conversation on fire (e.g. what to check and report). Max 8000 chars.",
139
+ description: "create: instruction for the conversation or canvas. Required for conversations; omit for canvas to use graph input. Max 8000 chars.",
132
140
  })),
133
141
  label: Type.Optional(Type.String({
134
142
  description: "create: short name shown in the background-tasks panel. Defaults to the prompt head.",
@@ -159,8 +167,10 @@ export function makeScheduleTool(host, ownerConversationId, lang) {
159
167
  if (parsed.kind === "interval" && Number(parsed.spec) < SCHEDULER_MIN_INTERVAL_MS) {
160
168
  return text(pick(getLang(), `间隔太短(最短 60s,防 token 烧穿)。`, `Interval too short (minimum 60s, prevents token burn).`, "sched.task.interval.too.short"));
161
169
  }
170
+ const isCanvas = p.graphId !== undefined;
171
+ const graphId = String(p.graphId ?? "").trim();
162
172
  const prompt = String(p.prompt ?? "").trim();
163
- if (!prompt) {
173
+ if (!prompt && !isCanvas) {
164
174
  return text(pick(getLang(), "触发指令(prompt)不能为空:写清楚触发时要检查什么、汇报什么。", "Prompt must not be empty: say what to check and report on fire.", "sched.task.empty.prompt"));
165
175
  }
166
176
  const cwd = String(host.cwd() ?? "").trim();
@@ -168,14 +178,16 @@ export function makeScheduleTool(host, ownerConversationId, lang) {
168
178
  return text(pick(getLang(), "当前没有工作目录,无法创建定时任务。", "No working directory, cannot create the scheduled task.", "sched.task.no.cwd"));
169
179
  }
170
180
  const labelRaw = typeof p.label === "string" ? p.label.trim().slice(0, 80) : "";
171
- const name = labelRaw || prompt.split("\n")[0].slice(0, 40) || "定时任务";
181
+ const name = labelRaw || prompt.split("\n")[0].slice(0, 40) || (isCanvas ? `Canvas ${graphId}` : "定时任务");
172
182
  const convId = (ownerConversationId ?? "").trim() || String(host.activeConversationId() ?? "").trim();
173
183
  // 稳定绑定(issue #231):owner 对话的落盘会话文件 —— 压缩/重启后靠它重认同一会话,
174
184
  // 内存对话 id(c1/c2…)只做首选唤醒键。宿主没实现 conversationInfo 时按原来只绑 id。
175
185
  let bindCwd = cwd;
176
186
  let bindSessionFile = "";
177
187
  try {
178
- const info = host.conversationInfo?.((ownerConversationId ?? "").trim() || convId || undefined);
188
+ const info = isCanvas
189
+ ? undefined
190
+ : host.conversationInfo?.((ownerConversationId ?? "").trim() || convId || undefined);
179
191
  if (info) {
180
192
  if (String(info.cwd ?? "").trim())
181
193
  bindCwd = String(info.cwd).trim();
@@ -192,6 +204,8 @@ export function makeScheduleTool(host, ownerConversationId, lang) {
192
204
  try {
193
205
  task = store.upsert({
194
206
  name,
207
+ target: isCanvas ? "canvas" : "conversation",
208
+ ...(isCanvas ? { graphId } : {}),
195
209
  cwd: bindCwd,
196
210
  kind: parsed.kind,
197
211
  spec: parsed.spec,
@@ -216,13 +230,17 @@ export function makeScheduleTool(host, ownerConversationId, lang) {
216
230
  const whenLine = L === "zh"
217
231
  ? `触发:${parsed.kind === "cron" ? `cron ${parsed.spec}` : describeIntervalMs(Number(parsed.spec))},下次 ${fmtTime(next, L)}${recurring ? "(周期)" : "(单次,触发后自动删除)"}`
218
232
  : `Fires: ${parsed.kind === "cron" ? `cron ${parsed.spec}` : `every ${Math.round(Number(parsed.spec) / 1000)}s`}, next ${fmtTime(next, L)}${recurring ? " (recurring)" : " (one-shot, auto-deleted after firing)"}`;
219
- const targetLine = convId
233
+ const targetLine = isCanvas
220
234
  ? L === "zh"
221
- ? `汇报:触发时自动唤醒本对话(${convId});压缩/重启后按会话文件自动重绑,原对话不在时先回落同项目活跃对话(明确提示),无存活对话才无头执行。`
222
- : `Reports: wakes this conversation (${convId}) on fire; re-binds by session file after compaction/restart, falls back to the project's active conversation (with a visible note), headless only with no live conversation.`
223
- : L === "zh"
224
- ? "汇报:无头执行,报告进调度面板历史(创建时没拿到对话 id)。"
225
- : "Reports: headless run, report in panel history (no conversation id captured at creation).";
235
+ ? `目标:画布 ${graphId};${prompt ? "使用提供的触发指令" : "使用图自带输入"},模型由画布节点配置。`
236
+ : `Target: canvas ${graphId}; ${prompt ? "uses the supplied instruction" : "uses the graph's input"}, with models configured by canvas nodes.`
237
+ : convId
238
+ ? L === "zh"
239
+ ? `汇报:触发时自动唤醒本对话(${convId});压缩/重启后按会话文件自动重绑,原对话不在时先回落同项目活跃对话(明确提示),无存活对话才无头执行。`
240
+ : `Reports: wakes this conversation (${convId}) on fire; re-binds by session file after compaction/restart, falls back to the project's active conversation (with a visible note), headless only with no live conversation.`
241
+ : L === "zh"
242
+ ? "汇报:无头执行,报告进调度面板历史(创建时没拿到对话 id)。"
243
+ : "Reports: headless run, report in panel history (no conversation id captured at creation).";
226
244
  const tail = L === "zh"
227
245
  ? `取消:schedule(action="cancel", id="${task.id}"),或后台任务面板手动取消;查看:schedule(action="list")。`
228
246
  : `Cancel: schedule(action="cancel", id="${task.id}"), or from the background-tasks panel; inspect: schedule(action="list").`;
@@ -86,18 +86,26 @@ export function normalizeSchedulerInput(input, now = Date.now()) {
86
86
  }
87
87
  spec = String(ms);
88
88
  }
89
+ if (input.target !== undefined && input.target !== "conversation" && input.target !== "canvas") {
90
+ throw new SchedulerValidationError("invalid_target", "任务目标非法", "Invalid task target");
91
+ }
92
+ const graphId = String(input.graphId ?? "").trim();
93
+ const target = input.target ?? (graphId ? "canvas" : "conversation");
94
+ if (target === "canvas" && (!/^[A-Za-z0-9._-]{1,64}$/.test(graphId) || graphId === "." || graphId === "..")) {
95
+ throw new SchedulerValidationError("invalid_graph_id", "画布工程 id 非法或为空", "Invalid or missing canvas graph id");
96
+ }
89
97
  const prompt = String(input.prompt ?? "").trim();
90
- if (!prompt) {
98
+ if (!prompt && target === "conversation") {
91
99
  throw new SchedulerValidationError("empty_prompt", "触发指令(prompt)不能为空", "Trigger instruction (prompt) cannot be empty");
92
100
  }
93
101
  if (prompt.length > 8000) {
94
102
  throw new SchedulerValidationError("prompt_too_long", "触发指令超长(>8000 字),请裁剪后重试", "Trigger instruction too long (>8000 characters), please shorten and retry");
95
103
  }
96
- const model = String(input.model ?? "").trim();
104
+ const model = target === "canvas" ? "" : String(input.model ?? "").trim();
97
105
  if (model && !model.includes("/")) {
98
106
  throw new SchedulerValidationError("invalid_model", "模型格式非法(应为 provider/id)", "Invalid model format (expected provider/id)");
99
107
  }
100
- const thinkingLevel = String(input.thinkingLevel ?? "").trim();
108
+ const thinkingLevel = target === "canvas" ? "" : String(input.thinkingLevel ?? "").trim();
101
109
  const catchUp = input.catchUp === "once" ? "once" : "skip";
102
110
  const conversationId = String(input.conversationId ?? "")
103
111
  .trim()
@@ -109,6 +117,8 @@ export function normalizeSchedulerInput(input, now = Date.now()) {
109
117
  .slice(0, 1024);
110
118
  return {
111
119
  id,
120
+ target,
121
+ ...(target === "canvas" ? { graphId } : {}),
112
122
  name,
113
123
  description,
114
124
  cwd,
@@ -119,8 +129,8 @@ export function normalizeSchedulerInput(input, now = Date.now()) {
119
129
  model,
120
130
  thinkingLevel,
121
131
  catchUp,
122
- conversationId,
123
- sessionFile,
132
+ conversationId: target === "canvas" ? "" : conversationId,
133
+ sessionFile: target === "canvas" ? "" : sessionFile,
124
134
  oneShot: input.oneShot === true,
125
135
  createdAt: now,
126
136
  updatedAt: now,
@@ -175,6 +185,9 @@ function sanitizeHistory(v) {
175
185
  ok: rec.ok === true,
176
186
  durationMs: typeof rec.durationMs === "number" && Number.isFinite(rec.durationMs) ? rec.durationMs : 0,
177
187
  ...(typeof rec.conversationId === "string" && rec.conversationId ? { conversationId: rec.conversationId } : {}),
188
+ ...(rec.target === "canvas" || rec.target === "conversation" ? { target: rec.target } : {}),
189
+ ...(typeof rec.graphId === "string" && rec.graphId ? { graphId: rec.graphId.slice(0, 64) } : {}),
190
+ ...(typeof rec.runId === "string" && rec.runId ? { runId: rec.runId.slice(0, 128) } : {}),
178
191
  ...(typeof rec.error === "string" && rec.error ? { error: rec.error.slice(0, 500) } : {}),
179
192
  ...(rec.manual === true ? { manual: true } : {}),
180
193
  });
@@ -224,7 +237,7 @@ export class SchedulerStore {
224
237
  if (next <= now && task.catchUp === "once" && lastAt < now) {
225
238
  // 重启发现漏跑:补一次,补完按这次重排。
226
239
  this.nextFire.set(task.id, now + 5000);
227
- void this.fire(task.id, false);
240
+ void this.fire(task.id, false).catch((err) => this.reportFailure(err));
228
241
  }
229
242
  else if (next <= now) {
230
243
  this.nextFire.set(task.id, computeNextFire(task, now) ?? now + TICK_MS);
@@ -233,7 +246,7 @@ export class SchedulerStore {
233
246
  this.nextFire.set(task.id, next);
234
247
  }
235
248
  }
236
- this.timer = setInterval(() => void this.tick(), TICK_MS);
249
+ this.timer = setInterval(() => void this.tick().catch((err) => this.reportFailure(err)), TICK_MS);
237
250
  this.timer.unref?.();
238
251
  }
239
252
  stop() {
@@ -259,6 +272,8 @@ export class SchedulerStore {
259
272
  try {
260
273
  const task = normalizeSchedulerInput({
261
274
  id,
275
+ target: r.target,
276
+ graphId: r.graphId,
262
277
  name: r.name,
263
278
  description: r.description,
264
279
  cwd: r.cwd,
@@ -288,15 +303,20 @@ export class SchedulerStore {
288
303
  this.tasks = new Map();
289
304
  }
290
305
  }
291
- save() {
306
+ save(next) {
307
+ const tasks = Object.fromEntries(next);
308
+ writeJsonAtomicSync(schedulerFile(this.dataDir), { v: 1, tasks });
309
+ this.tasks = next;
310
+ }
311
+ reportFailure(err) {
312
+ console.error("[scheduler] execution failed:", err);
313
+ }
314
+ notify(...args) {
292
315
  try {
293
- const tasks = {};
294
- for (const [id, t] of this.tasks)
295
- tasks[id] = t;
296
- writeJsonAtomicSync(schedulerFile(this.dataDir), { v: 1, tasks });
316
+ this.opts.notify?.(...args);
297
317
  }
298
318
  catch (err) {
299
- console.error("[scheduler] persist failed:", err);
319
+ this.reportFailure(err);
300
320
  }
301
321
  }
302
322
  changed() {
@@ -314,6 +334,8 @@ export class SchedulerStore {
314
334
  const history = sanitizeHistory(t.history);
315
335
  return {
316
336
  id: t.id,
337
+ target: t.target ?? "conversation",
338
+ ...(t.graphId ? { graphId: t.graphId } : {}),
317
339
  name: t.name,
318
340
  description: t.description,
319
341
  cwd: t.cwd,
@@ -343,28 +365,38 @@ export class SchedulerStore {
343
365
  * 字段显式出现(含空串)仍按全量语义覆盖。 */
344
366
  upsert(input) {
345
367
  const prev = this.tasks.get(String(input.id ?? "").trim());
346
- const task = normalizeSchedulerInput(input);
368
+ const task = normalizeSchedulerInput({
369
+ ...input,
370
+ ...(prev && input.target === undefined && input.graphId === undefined
371
+ ? { target: prev.target, graphId: prev.graphId }
372
+ : {}),
373
+ });
347
374
  if (prev) {
348
375
  task.createdAt = prev.createdAt;
349
376
  task.updatedAt = Date.now();
350
- if (input.conversationId === undefined && input.sessionFile === undefined) {
377
+ if (task.target !== "canvas" &&
378
+ prev.target !== "canvas" &&
379
+ input.conversationId === undefined &&
380
+ input.sessionFile === undefined) {
351
381
  task.conversationId = prev.conversationId;
352
382
  task.sessionFile = prev.sessionFile ?? "";
353
383
  }
354
384
  }
385
+ this.opts.validateTask?.(task);
355
386
  const history = prev?.history ? sanitizeHistory(prev.history) : [];
356
- this.tasks.set(task.id, { ...task, history });
387
+ this.save(new Map(this.tasks).set(task.id, { ...task, history }));
357
388
  // spec/cwd/开关变了 → 按现在重排下次触发
358
389
  this.nextFire.set(task.id, computeNextFire(task, Date.now()) ?? Date.now() + TICK_MS);
359
- this.save();
360
390
  this.changed();
361
391
  return task;
362
392
  }
363
393
  remove(id) {
364
- const ok = this.tasks.delete(id);
365
- this.nextFire.delete(id);
394
+ const ok = this.tasks.has(id);
366
395
  if (ok) {
367
- this.save();
396
+ const next = new Map(this.tasks);
397
+ next.delete(id);
398
+ this.save(next);
399
+ this.nextFire.delete(id);
368
400
  this.changed();
369
401
  try {
370
402
  this.opts.onTaskRemoved?.(id);
@@ -376,23 +408,23 @@ export class SchedulerStore {
376
408
  return ok;
377
409
  }
378
410
  setEnabled(id, enabled) {
379
- const t = this.tasks.get(id);
380
- if (!t)
411
+ const prev = this.tasks.get(id);
412
+ if (!prev)
381
413
  return null;
382
- t.enabled = enabled;
383
- t.updatedAt = Date.now();
414
+ const t = { ...prev, enabled, updatedAt: Date.now() };
415
+ this.save(new Map(this.tasks).set(id, t));
384
416
  this.nextFire.set(id, computeNextFire(t, Date.now()) ?? Date.now() + TICK_MS);
385
- this.save();
386
417
  this.changed();
387
- return t;
418
+ return { ...t };
388
419
  }
389
420
  /** 会话重绑定(issue #231):触发时按稳定键找到了新的对话句柄,把任务的
390
421
  * 投递目标迁移过去(只改 conversationId/sessionFile/updatedAt,不碰下次触发
391
422
  * 与历史)。无变化回 false(调用方免一次落盘+推送);未知任务回 false。 */
392
423
  rebind(id, binding) {
393
- const t = this.tasks.get(id);
394
- if (!t)
424
+ const prev = this.tasks.get(id);
425
+ if (!prev || prev.target === "canvas")
395
426
  return false;
427
+ const t = { ...prev };
396
428
  let dirty = false;
397
429
  if (binding.conversationId !== undefined) {
398
430
  const v = String(binding.conversationId ?? "")
@@ -415,7 +447,7 @@ export class SchedulerStore {
415
447
  if (!dirty)
416
448
  return false;
417
449
  t.updatedAt = Date.now();
418
- this.save();
450
+ this.save(new Map(this.tasks).set(id, t));
419
451
  this.changed();
420
452
  return true;
421
453
  }
@@ -447,52 +479,71 @@ export class SchedulerStore {
447
479
  if (!task)
448
480
  return { ok: false, error: "任务不存在" };
449
481
  const executor = this.opts.executor;
450
- if (!executor) {
451
- const err = "调度器执行器未接入(当前引擎不支持定时任务)";
452
- this.recordRun(id, { at: Date.now(), ok: false, durationMs: 0, error: err, ...(manual ? { manual } : {}) });
453
- return { ok: false, error: err };
454
- }
455
482
  this.running.add(id);
456
483
  this.changed();
457
484
  const startedAt = Date.now();
458
485
  let result;
459
486
  try {
460
- result = await executor({ ...task });
487
+ result = executor
488
+ ? await executor({ ...task })
489
+ : { ok: false, error: "调度器执行器未接入(当前引擎不支持定时任务)" };
461
490
  }
462
491
  catch (err) {
463
- result = { ok: false, error: err.message };
492
+ result = { ok: false, error: String(err instanceof Error ? err.message : err) };
464
493
  }
465
494
  const durationMs = Date.now() - startedAt;
466
- this.running.delete(id);
467
- this.recordRun(id, {
468
- at: Date.now(),
469
- ok: result.ok,
470
- durationMs,
471
- ...(result.conversationId ? { conversationId: result.conversationId } : {}),
472
- ...(result.error ? { error: result.error.slice(0, 500) } : {}),
473
- ...(manual ? { manual } : {}),
474
- });
475
- // 按这次完成时间重排下次触发(间隔任务从完成起算,避免长任务连击)。
476
- const cur = this.tasks.get(id);
477
- if (cur && cur.enabled && !manual) {
478
- this.nextFire.set(id, computeNextFire(cur, Date.now()) ?? Date.now() + TICK_MS);
479
- this.save();
495
+ try {
496
+ this.recordRun(id, {
497
+ at: Date.now(),
498
+ ok: result.ok,
499
+ durationMs,
500
+ target: task.target ?? "conversation",
501
+ ...(task.graphId ? { graphId: task.graphId } : {}),
502
+ ...(result.runId ? { runId: result.runId } : {}),
503
+ ...(result.conversationId ? { conversationId: result.conversationId } : {}),
504
+ ...(result.error ? { error: result.error.slice(0, 500) } : {}),
505
+ ...(manual ? { manual } : {}),
506
+ });
507
+ if (task.oneShot)
508
+ this.remove(id);
509
+ }
510
+ catch (err) {
511
+ result = {
512
+ ok: false,
513
+ error: `Failed to persist scheduled-task run: ${String(err instanceof Error ? err.message : err)}`,
514
+ };
515
+ this.reportFailure(err);
516
+ }
517
+ finally {
518
+ // 执行可能已产生外部副作用;记录写失败也不能在每个 tick 立即重试。
519
+ // 仅推进内存调度,使用执行期间更新后的配置,不伪造成功历史。
520
+ // 进程重启后仍可能补跑:本地记录与外部副作用不保证跨进程 exactly-once。
521
+ const cur = this.tasks.get(id);
522
+ if (cur && task.oneShot) {
523
+ // A failed history/removal write must not repeat an already attempted one-shot.
524
+ this.tasks.set(id, { ...cur, enabled: false });
525
+ this.nextFire.delete(id);
526
+ }
527
+ else if (cur && cur.enabled && !manual) {
528
+ this.nextFire.set(id, computeNextFire(cur, Date.now()) ?? Date.now() + TICK_MS);
529
+ }
530
+ this.running.delete(id);
531
+ this.changed();
480
532
  }
481
533
  const label = `⏰ ${task.name}`;
482
534
  if (result.ok) {
483
- this.opts.notify?.("info", `定时任务「${task.name}」${manual ? "手动" : "定时"}触发完成(${(durationMs / 1000).toFixed(0)}s)——${label}`, `Scheduled task "${task.name}" ${manual ? "manually" : "automatically"} finished (${Math.round(durationMs / 1000)}s) — ${label}`);
535
+ this.notify("info", `定时任务「${task.name}」${manual ? "手动" : "定时"}触发完成(${(durationMs / 1000).toFixed(0)}s)——${label}`, `Scheduled task "${task.name}" ${manual ? "manually" : "automatically"} finished (${Math.round(durationMs / 1000)}s) — ${label}`);
484
536
  }
485
537
  else {
486
- this.opts.notify?.("warning", `定时任务「${task.name}」${manual ? "手动" : "定时"}触发失败:${result.error ?? "未知错误"}`, `Scheduled task "${task.name}" ${manual ? "manual" : "automatic"} run failed: ${result.error ?? "unknown error"}`);
538
+ this.notify("warning", `定时任务「${task.name}」${manual ? "手动" : "定时"}触发失败:${result.error ?? "未知错误"}`, `Scheduled task "${task.name}" ${manual ? "manual" : "automatic"} run failed: ${result.error ?? "unknown error"}`);
487
539
  }
488
- this.changed();
489
540
  return result;
490
541
  }
491
542
  recordRun(id, run) {
492
543
  const t = this.tasks.get(id);
493
544
  if (!t)
494
545
  return;
495
- t.history = [run, ...sanitizeHistory(t.history)].slice(0, SCHEDULER_HISTORY_MAX);
496
- this.save();
546
+ const next = { ...t, history: [run, ...sanitizeHistory(t.history)].slice(0, SCHEDULER_HISTORY_MAX) };
547
+ this.save(new Map(this.tasks).set(id, next));
497
548
  }
498
549
  }
@@ -28,16 +28,16 @@ export const MAX_COMMITMSG_LEN = 200;
28
28
  /** File list cap inside the prompt (porcelain lines); the diffs carry the
29
29
  * details, the list is orientation only. */
30
30
  const MAX_FILE_LINES = 200;
31
- export const COMMITMSG_SYSTEM_PROMPT = `You write git commit messages. You receive the pending changes of a repository and output exactly one commit message: a single subject line.
32
-
33
- Rules:
34
- 1. Match the style, format and language of the repository's recent commit subjects when provided — conventional commits ("type(scope): summary"), prefixes, punctuation, language: copy what the repo actually does.
35
- 2. Describe what the change does at a glance (the user-facing effect), not a file-by-file listing.
36
- 3. The staged diff is the subject of the commit. Describe staged changes when any exist; otherwise describe the unstaged and untracked changes shown.
37
- 4. One line. No quotes, no markdown, no code fences, no "Commit message:" label, no explanation. Under 72 characters when the repository's language allows it (CJK text may naturally be shorter).
38
- 5. Never invent scope names, issue numbers or details not visible in the provided material.
39
- 6. If the repository has no commits yet, write the message in the language stated in the request.
40
-
31
+ export const COMMITMSG_SYSTEM_PROMPT = `You write git commit messages. You receive the pending changes of a repository and output exactly one commit message: a single subject line.
32
+
33
+ Rules:
34
+ 1. Match the style, format and language of the repository's recent commit subjects when provided — conventional commits ("type(scope): summary"), prefixes, punctuation, language: copy what the repo actually does.
35
+ 2. Describe what the change does at a glance (the user-facing effect), not a file-by-file listing.
36
+ 3. The staged diff is the subject of the commit. Describe staged changes when any exist; otherwise describe the unstaged and untracked changes shown.
37
+ 4. One line. No quotes, no markdown, no code fences, no "Commit message:" label, no explanation. Under 72 characters when the repository's language allows it (CJK text may naturally be shorter).
38
+ 5. Never invent scope names, issue numbers or details not visible in the provided material.
39
+ 6. If the repository has no commits yet, write the message in the language stated in the request.
40
+
41
41
  Output ONLY the subject line.`;
42
42
  /**
43
43
  * Assemble the effective system prompt from the settings-panel prefs (same
@@ -278,6 +278,19 @@ export function findEntryByUiId(entries, messageId, seqOf) {
278
278
  }
279
279
  return null;
280
280
  }
281
+ function serializeAssistantMessage(m, id, streaming = false) {
282
+ return {
283
+ id,
284
+ role: "assistant",
285
+ content: serializeAssistantContent(m.content, streaming),
286
+ timestamp: m.timestamp,
287
+ model: m.model,
288
+ provider: m.provider,
289
+ usageCost: typeof m.usage?.cost?.total === "number" ? m.usage.cost.total : undefined,
290
+ stopReason: m.stopReason,
291
+ errorMessage: m.errorMessage,
292
+ };
293
+ }
281
294
  export function serializeMessage(m, seq) {
282
295
  // SDK 的 system 消息是 prompt sections 的内部差量
283
296
  // (content 空串 + sections 结构化内存)、compaction 的
@@ -318,26 +331,41 @@ export function serializeMessage(m, seq) {
318
331
  };
319
332
  }
320
333
  case "assistant":
321
- return {
322
- id,
323
- role: "assistant",
324
- content: serializeAssistantContent(m.content),
325
- timestamp: m.timestamp,
326
- model: m.model,
327
- provider: m.provider,
328
- usageCost: typeof m.usage?.cost?.total === "number" ? m.usage.cost.total : undefined,
329
- stopReason: m.stopReason,
330
- errorMessage: m.errorMessage,
331
- };
334
+ return serializeAssistantMessage(m, id);
332
335
  case "toolResult": {
333
336
  // 工具结果里的图片(web_shot 截图、read 读到的图……)要下发浏览器:
334
337
  // 卡片里直接显示缩略图、点开放大(见 ToolCallBlock)。以前这里统一丢成
335
338
  // "[image result]",用户只能看到占位文本。超限/超数的图仍回落占位文本。
336
339
  const textParts = [];
340
+ let textLength = 0;
341
+ let hasTextPart = false;
342
+ let truncated = false;
343
+ const appendChunk = (chunk) => {
344
+ if (truncated)
345
+ return;
346
+ const remaining = TOOL_OUTPUT_CAP - textLength;
347
+ if (chunk.length > remaining) {
348
+ if (remaining > 0)
349
+ textParts.push(chunk.slice(0, remaining));
350
+ textLength = TOOL_OUTPUT_CAP;
351
+ truncated = true;
352
+ }
353
+ else if (chunk.length > 0) {
354
+ textParts.push(chunk);
355
+ textLength += chunk.length;
356
+ }
357
+ };
358
+ const appendText = (part) => {
359
+ // Empty parts still contribute join separators, even at the cap.
360
+ if (hasTextPart)
361
+ appendChunk("\n");
362
+ hasTextPart = true;
363
+ appendChunk(part);
364
+ };
337
365
  const images = [];
338
366
  for (const c of m.content) {
339
367
  if (c.type === "text") {
340
- textParts.push(c.text);
368
+ appendText(c.text);
341
369
  continue;
342
370
  }
343
371
  if (c.type === "image" && images.length < TOOL_RESULT_IMAGE_MAX) {
@@ -347,10 +375,10 @@ export function serializeMessage(m, seq) {
347
375
  continue;
348
376
  }
349
377
  }
350
- textParts.push("[image result]");
378
+ appendText("[image result]");
351
379
  }
352
- const raw = textParts.join("\n");
353
- const { text, truncated } = truncate(raw, TOOL_OUTPUT_CAP);
380
+ const raw = textParts.join("");
381
+ const text = truncated ? `${raw}\n\n… [truncated]` : raw;
354
382
  const content = raw || images.length === 0 ? [{ type: "text", text, truncated }, ...images] : [...images];
355
383
  const msg = {
356
384
  id,
@@ -467,9 +495,10 @@ export function serializeMessage(m, seq) {
467
495
  * constant for the whole stream.
468
496
  */
469
497
  export function serializeStreamingMessage(m) {
498
+ const id = `stream-${m.timestamp ?? 0}`;
499
+ // Streamed assistant blocks must be converted only once per snapshot.
500
+ if (m.role === "assistant")
501
+ return serializeAssistantMessage(m, id, true);
470
502
  const msg = serializeMessage(m, 0);
471
- if (!msg)
472
- return null;
473
- const content = m.role === "assistant" ? serializeAssistantContent(m.content, true) : msg.content;
474
- return { ...msg, id: `stream-${m.timestamp ?? 0}`, content };
503
+ return msg ? { ...msg, id } : null;
475
504
  }