pi-web-ui 0.110.0 → 0.112.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 (110) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/bin/frp-manager.mjs +92 -7
  3. package/dist/server/agent-formatters.js +10 -6
  4. package/dist/server/agent-service-daemon.js +27 -9
  5. package/dist/server/agent-service.js +1442 -489
  6. package/dist/server/approval-audit.js +119 -0
  7. package/dist/server/approval-default-rules.js +4 -4
  8. package/dist/server/approval-rules.js +42 -17
  9. package/dist/server/attachment-store.js +8 -8
  10. package/dist/server/attachments.js +114 -31
  11. package/dist/server/canvas/canvas-agent-tool.js +593 -0
  12. package/dist/server/canvas/canvas-cards.js +144 -0
  13. package/dist/server/canvas/canvas-dispatch.js +155 -0
  14. package/dist/server/canvas/canvas-orchestrator.js +1094 -0
  15. package/dist/server/canvas/canvas-store.js +260 -0
  16. package/dist/server/client-id-utils.js +2 -2
  17. package/dist/server/client-state.js +52 -0
  18. package/dist/server/context-budget.js +6 -3
  19. package/dist/server/delegate-mode.js +6 -3
  20. package/dist/server/delegate-task.js +18 -3
  21. package/dist/server/dispatch-domain-handlers.js +3 -0
  22. package/dist/server/dsh/dsh-agent-service.js +357 -20
  23. package/dist/server/dsh/dsh-client.js +10 -1
  24. package/dist/server/dsh/dsh-serialize.js +1 -1
  25. package/dist/server/dsh/runtime/goal-rpc.mjs +128 -3
  26. package/dist/server/dsh/runtime/launcher.mjs +59 -5
  27. package/dist/server/dsh/runtime/runtime-root.mjs +353 -40
  28. package/dist/server/durable/durable-agent-service.js +3 -0
  29. package/dist/server/durable/durable-driver.js +75 -9
  30. package/dist/server/durable/durable-loader.js +1 -14
  31. package/dist/server/durable/durable-models.js +107 -0
  32. package/dist/server/durable/index.js +0 -4
  33. package/dist/server/engine-probe.js +76 -37
  34. package/dist/server/eval-tool.js +28 -3
  35. package/dist/server/file-transfer-routes.js +8 -2
  36. package/dist/server/files-service.js +10 -2
  37. package/dist/server/goal-service.js +7 -0
  38. package/dist/server/index.js +480 -59
  39. package/dist/server/json-utils.js +57 -0
  40. package/dist/server/marker-service.js +11 -1
  41. package/dist/server/markers/marker.js +45 -4
  42. package/dist/server/markers/registry.js +31 -0
  43. package/dist/server/message-window.js +44 -8
  44. package/dist/server/model-admin.js +68 -106
  45. package/dist/server/model-resolver.js +66 -44
  46. package/dist/server/office-parse.js +394 -7
  47. package/dist/server/plan-manager.js +3 -6
  48. package/dist/server/plugin-api-catalog.js +7 -0
  49. package/dist/server/plugin-assets.js +238 -0
  50. package/dist/server/plugin-facilities.js +22 -0
  51. package/dist/server/plugin-ui-slots.js +1 -0
  52. package/dist/server/plugins.js +296 -25
  53. package/dist/server/preset-fields.js +60 -2
  54. package/dist/server/preset-share.js +8 -2
  55. package/dist/server/prompt-assembler.js +9 -2
  56. package/dist/server/prompt-composer.js +84 -44
  57. package/dist/server/protocol-version.js +1 -1
  58. package/dist/server/queue-utils.js +156 -0
  59. package/dist/server/remote-ssh-service.js +16 -4
  60. package/dist/server/sdk-builtin-extensions.js +85 -0
  61. package/dist/server/server-config.js +66 -0
  62. package/dist/server/session-parser.js +49 -13
  63. package/dist/server/session-search.js +4 -3
  64. package/dist/server/settings-service.js +56 -7
  65. package/dist/server/soft-cap.js +8 -6
  66. package/dist/server/subagent-helpers.js +22 -1
  67. package/dist/server/subagent-notify.js +93 -0
  68. package/dist/server/subagent-security-gate.js +282 -0
  69. package/dist/server/subagent-templates.js +8 -0
  70. package/dist/server/subagents.js +144 -17
  71. package/dist/server/terminals.js +196 -8
  72. package/dist/server/text-quote.js +61 -0
  73. package/dist/server/tool-approval.js +63 -4
  74. package/dist/server/tool-guards.js +208 -0
  75. package/dist/server/tool-host-factories.js +46 -10
  76. package/dist/server/tool-manager.js +30 -0
  77. package/dist/server/tool-overrides.js +21 -11
  78. package/dist/server/univer-service.js +448 -0
  79. package/dist/server/universal/driver-base.js +8 -0
  80. package/dist/server/universal/drivers/claude-code.js +39 -5
  81. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  82. package/dist/server/universal/index.js +0 -1
  83. package/dist/server/universal/universal-attachments.js +5 -0
  84. package/dist/server/universal/universal-service.js +5 -0
  85. package/dist/server/universal/universal-session.js +114 -21
  86. package/dist/server/update-check.js +90 -5
  87. package/dist/server/workspace-snapshot.js +33 -2
  88. package/dist/server/worktree-service.js +189 -1
  89. package/docs/dsh-engine.md +493 -0
  90. package/package.json +5 -4
  91. package/plugin-sdk/client-utils.mjs +192 -5
  92. package/plugin-sdk/index.d.ts +80 -1
  93. package/plugin-sdk/index.mjs +99 -0
  94. package/plugin-sdk/package.json +5 -1
  95. package/plugins/catalog.json +33 -0
  96. package/themes/aetheris.css +114 -0
  97. package/themes/bases/obsidian-base.css +216 -0
  98. package/themes/md-preview.css +113 -0
  99. package/themes/wallpaper-flow.css +182 -0
  100. package/web/dist/assets/{TerminalPanel-BHjM6pzY.js → TerminalPanel-Dqr1dK28.js} +2 -2
  101. package/web/dist/assets/index-Dh8BX-lP.js +720 -0
  102. package/web/dist/assets/index-DqrC1I_a.css +1 -0
  103. package/web/dist/assets/{markdown-DXwnfD9T.js → markdown-BJZlfvdP.js} +24 -24
  104. package/web/dist/assets/markdown-DSNUiDzp.css +1 -0
  105. package/web/dist/index.html +13 -4
  106. package/web/dist/sw.js +1 -1
  107. package/web/dist/assets/es-DIDZppIF.js +0 -2
  108. package/web/dist/assets/index-DwInT7-a.css +0 -1
  109. package/web/dist/assets/index-GfVFIgIL.js +0 -693
  110. package/web/dist/assets/markdown-CCeVCbci.css +0 -1
@@ -0,0 +1,593 @@
1
+ /**
2
+ * canvas-agent-tool —— 对话 AI 直接编辑画布流水线的单 action 工具。
3
+ *
4
+ * 动作:list(工程摘要)/ get(整图 JSON)/ create_graph(新建工程)/ delete_graph(删除工程)/
5
+ * add_node / update_node / delete_node / add_edge / delete_edge / apply_dag(整图节点边替换,角色白名单+环检测)。
6
+ * 运行与调试(run_all/run_node/stop/steer/review/get_log)暂不在 AI 工具内:运行态活在 CanvasOrchestrator
7
+ * 内存里,工具 host 只有 dataDir,够不着;前端 Canvas Studio 已有全套运行/日志/审查 UI,见 canvas-dispatch.ts。
8
+ * 直接读写 canvas-store 落盘文件;前端画布下次 load 即见,聊天里即时回执。
9
+ */
10
+ import { Type } from "typebox";
11
+ import { defineTool } from "@earendil-works/pi-coding-agent";
12
+ import { pick } from "../i18n.js";
13
+ import { CANVAS_TOOL_NAME } from "../tool-manager.js";
14
+ import { deleteCanvasGraph, listCanvasGraphs, loadCanvasGraph, saveCanvasGraph } from "./canvas-store.js";
15
+ import { addCustomCard, deleteCustomCard, listCustomCards, updateCustomCard } from "./canvas-cards.js";
16
+ /** 新节点 cwd:显式参数 > 当前项目 > 服务启动目录(".") */
17
+ function defaultNodeCwd(host, p) {
18
+ const explicit = typeof p.cwd === "string" ? p.cwd.trim().slice(0, 256) : "";
19
+ if (explicit)
20
+ return explicit;
21
+ try {
22
+ const cur = host.getCwd?.()?.trim();
23
+ if (cur)
24
+ return cur;
25
+ }
26
+ catch {
27
+ // 读不到就回落 "."
28
+ }
29
+ return ".";
30
+ }
31
+ let canvasRuntime = null;
32
+ export function setCanvasRuntime(rt) {
33
+ canvasRuntime = rt;
34
+ }
35
+ /** 广播钩子:index.ts 注入 WS 广播,工具改图后开着的画布实时可见,不用刷新。 */
36
+ let canvasBroadcaster = null;
37
+ export function setCanvasBroadcaster(fn) {
38
+ canvasBroadcaster = fn;
39
+ }
40
+ /** 落盘 + 广播(开着的 Canvas Studio 实时刷新)。 */
41
+ /** 自定义卡片变更广播:开着的画布工具栏实时刷新,无需重进。 */
42
+ function pushCards(dataDir) {
43
+ try {
44
+ canvasBroadcaster?.({ type: "canvas_cards_state", cards: listCustomCards(dataDir) });
45
+ }
46
+ catch {
47
+ // 忽略
48
+ }
49
+ }
50
+ function saveAndPush(dataDir, graph) {
51
+ saveCanvasGraph(dataDir, graph);
52
+ try {
53
+ canvasBroadcaster?.({ type: "canvas_graph_state", graph });
54
+ }
55
+ catch {
56
+ // 广播失败不影响落盘
57
+ }
58
+ }
59
+ const VALID_ROLES = new Set([
60
+ "trigger",
61
+ "cron",
62
+ "webhook",
63
+ "transform",
64
+ "architect",
65
+ "planner",
66
+ "coder",
67
+ "researcher",
68
+ "writer",
69
+ "analyst",
70
+ "reviewer",
71
+ "tester",
72
+ "devops",
73
+ "evaluator",
74
+ "custom",
75
+ "condition",
76
+ "ai_judge",
77
+ "loop",
78
+ "human",
79
+ "merge",
80
+ "subflow",
81
+ "tool",
82
+ "knowledge",
83
+ "code",
84
+ "api",
85
+ "memory",
86
+ "end",
87
+ ]);
88
+ const canvasSchema = Type.Object({
89
+ action: Type.Union([
90
+ Type.Literal("list"),
91
+ Type.Literal("get"),
92
+ Type.Literal("create_graph"),
93
+ Type.Literal("delete_graph"),
94
+ Type.Literal("run_all"),
95
+ Type.Literal("run_node"),
96
+ Type.Literal("stop_node"),
97
+ Type.Literal("stop_all"),
98
+ Type.Literal("steer_node"),
99
+ Type.Literal("review_node"),
100
+ Type.Literal("get_log"),
101
+ Type.Literal("reset_status"),
102
+ Type.Literal("layout_graph"),
103
+ Type.Literal("card_list"),
104
+ Type.Literal("card_add"),
105
+ Type.Literal("card_update"),
106
+ Type.Literal("card_delete"),
107
+ Type.Literal("card_place"),
108
+ Type.Literal("add_node"),
109
+ Type.Literal("update_node"),
110
+ Type.Literal("delete_node"),
111
+ Type.Literal("add_edge"),
112
+ Type.Literal("delete_edge"),
113
+ Type.Literal("apply_dag"),
114
+ ]),
115
+ graphId: Type.Optional(Type.String({ description: "Target canvas graph id (list omits it)" })),
116
+ title: Type.Optional(Type.String()),
117
+ role: Type.Optional(Type.String()),
118
+ instruction: Type.Optional(Type.String()),
119
+ nodeId: Type.Optional(Type.String()),
120
+ cardId: Type.Optional(Type.String({ description: "Custom card id (card_list shows them)" })),
121
+ cwd: Type.Optional(Type.String({
122
+ description: "Working directory for a new node (absolute path pins a project; omit = current project)",
123
+ })),
124
+ message: Type.Optional(Type.String()),
125
+ prompt: Type.Optional(Type.String()),
126
+ decision: Type.Optional(Type.String()),
127
+ comment: Type.Optional(Type.String()),
128
+ patch: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
129
+ sourceNodeId: Type.Optional(Type.String()),
130
+ targetNodeId: Type.Optional(Type.String()),
131
+ edgeId: Type.Optional(Type.String()),
132
+ nodes: Type.Optional(Type.Array(Type.Record(Type.String(), Type.Unknown()))),
133
+ edges: Type.Optional(Type.Array(Type.Record(Type.String(), Type.Unknown()))),
134
+ });
135
+ function hasCycle(n, edges) {
136
+ const adj = Array.from({ length: n }, () => []);
137
+ edges.forEach((e) => adj[e.from]?.push(e.to));
138
+ const color = new Array(n).fill(0);
139
+ const dfs = (u) => {
140
+ color[u] = 1;
141
+ for (const v of adj[u] ?? []) {
142
+ if (color[v] === 1)
143
+ return true;
144
+ if (color[v] === 0 && dfs(v))
145
+ return true;
146
+ }
147
+ color[u] = 2;
148
+ return false;
149
+ };
150
+ for (let i = 0; i < n; i++)
151
+ if (color[i] === 0 && dfs(i))
152
+ return true;
153
+ return false;
154
+ }
155
+ export function makeCanvasTool(host, lang) {
156
+ const getLang = lang ?? host.lang ?? (() => "en");
157
+ const text = (t, details = {}) => ({
158
+ content: [{ type: "text", text: t }],
159
+ details,
160
+ });
161
+ return defineTool({
162
+ name: CANVAS_TOOL_NAME,
163
+ label: "Canvas pipeline",
164
+ description: "Read and edit canvas workflow graphs: list/get/create/delete graphs, add/update/delete nodes and edges, replace the DAG, layout/rearrange nodes on a tidy grid, run all or one node, stop, steer a running node, approve/reject review gates, read node logs, reset status, manage reusable custom cards. Use it when the user asks to create, change, run, or debug a pipeline.",
165
+ promptSnippet: "create or edit a canvas workflow pipeline",
166
+ promptGuidelines: [
167
+ "Always get the graph first before editing so node ids and roles are real",
168
+ "Running nodes costs tokens/time: prefer run_node for single-node debug, run_all only when the user asks",
169
+ "After steering or review, use get_log to confirm the node state before summarizing",
170
+ "New nodes default their cwd to the user's current project (getCwd); pass an absolute cwd only to pin another project",
171
+ "After apply_dag or structural edits, summarize nodes and edges for the user to confirm on canvas",
172
+ "Never invent role names: only use roles already present in the graph or the known role set",
173
+ "Save repeating teammates as custom cards (card_add) and reuse them via card_place",
174
+ ],
175
+ parameters: canvasSchema,
176
+ execute: async (_id, params, _signal, _onUpdate, _ctx) => {
177
+ const p = (params ?? {});
178
+ const action = p.action;
179
+ const dataDir = host.dataDir;
180
+ try {
181
+ if (action === "list") {
182
+ const graphs = listCanvasGraphs(dataDir);
183
+ return text(pick(getLang(), `画布工程 ${graphs.length} 个:${graphs.map((g) => `${g.name}(${g.id}, ${g.nodeCount}节点/${g.edgeCount}边)`).join(";")}`, `Canvas graphs (${graphs.length}): ${graphs.map((g) => `${g.name} (${g.id}, ${g.nodeCount} nodes/${g.edgeCount} edges)`).join("; ")}`, "canvas.listed", {}), { graphs });
184
+ }
185
+ const cardId = typeof p.cardId === "string" ? p.cardId : "";
186
+ const cardInput = {
187
+ title: p.title,
188
+ role: p.role,
189
+ instruction: p.instruction,
190
+ systemPrompt: p.patch?.systemPrompt,
191
+ model: p.patch?.model,
192
+ engine: p.patch?.engine,
193
+ config: p.patch?.config,
194
+ };
195
+ const isCardRole = (r) => VALID_ROLES.has(r);
196
+ if (action === "card_list") {
197
+ const cards = listCustomCards(dataDir);
198
+ return text(pick(getLang(), `自定义卡片 ${cards.length} 张:${cards.map((c) => `${c.title}(${c.id}, ${c.role})`).join(";") || "(空)"}`, `Custom cards (${cards.length}): ${cards.map((c) => `${c.title} (${c.id}, ${c.role})`).join("; ") || "(empty)"}`, "canvas.cards.listed", {}), { cards });
199
+ }
200
+ if (action === "card_add") {
201
+ const card = addCustomCard(dataDir, cardInput, isCardRole);
202
+ pushCards(dataDir);
203
+ return text(pick(getLang(), `已保存自定义卡片 ${card.title}(${card.id}),已同步到画布工具栏。`, `Saved custom card ${card.title} (${card.id}); toolbar updated.`, "canvas.card.added", {}), { card });
204
+ }
205
+ if (action === "card_update") {
206
+ if (!cardId)
207
+ return text(pick(getLang(), "缺少 cardId,先 card_list 查看。", "Missing cardId; call card_list first.", "canvas.card.missing", {}), { ok: false });
208
+ const card = updateCustomCard(dataDir, cardId, cardInput, isCardRole);
209
+ pushCards(dataDir);
210
+ return text(pick(getLang(), `已更新卡片 ${card.title}。`, `Updated card ${card.title}.`, "canvas.card.updated", {}), { card });
211
+ }
212
+ if (action === "card_delete") {
213
+ if (!cardId)
214
+ return text(pick(getLang(), "缺少 cardId,先 card_list 查看。", "Missing cardId; call card_list first.", "canvas.card.missing", {}), { ok: false });
215
+ const ok = deleteCustomCard(dataDir, cardId);
216
+ if (ok)
217
+ pushCards(dataDir);
218
+ return text(pick(getLang(), ok ? `已删除卡片 ${cardId}。` : `卡片不存在:${cardId}。`, ok ? `Deleted card ${cardId}.` : `Card not found: ${cardId}.`, "canvas.card.deleted", {}), { ok });
219
+ }
220
+ const graphId = typeof p.graphId === "string" ? p.graphId : "";
221
+ if (action === "create_graph") {
222
+ const name = (typeof p.title === "string" && p.title.slice(0, 48)) || "新工程";
223
+ const now = Date.now();
224
+ const safeBase = name.replace(/[^A-Za-z0-9_-]+/g, "-").slice(0, 32) || "graph";
225
+ const id = `graph_${now}_${safeBase}`.slice(0, 64);
226
+ const graph = {
227
+ id,
228
+ name,
229
+ viewport: { x: 50, y: 50, zoom: 1 },
230
+ status: "idle",
231
+ createdAt: now,
232
+ updatedAt: now,
233
+ nodes: [
234
+ {
235
+ id: `n_${now}_trigger`,
236
+ title: "触发器",
237
+ role: "trigger",
238
+ x: 80,
239
+ y: 180,
240
+ width: 300,
241
+ engine: "pi",
242
+ model: "pi/default",
243
+ cwd: ".",
244
+ useWorktree: false,
245
+ status: "idle",
246
+ ...(typeof p.instruction === "string" && p.instruction ? { instruction: p.instruction } : {}),
247
+ },
248
+ {
249
+ id: `n_${now}_end`,
250
+ title: "结束输出",
251
+ role: "end",
252
+ x: 480,
253
+ y: 180,
254
+ width: 300,
255
+ engine: "pi",
256
+ model: "pi/default",
257
+ cwd: ".",
258
+ useWorktree: false,
259
+ status: "idle",
260
+ },
261
+ ],
262
+ edges: [
263
+ {
264
+ id: `e_${now}_0`,
265
+ sourceNodeId: `n_${now}_trigger`,
266
+ targetNodeId: `n_${now}_end`,
267
+ type: "handoff",
268
+ },
269
+ ],
270
+ };
271
+ saveAndPush(dataDir, graph);
272
+ return text(pick(getLang(), `已新建工程 ${name}(${id}),含触发器→结束初始链。`, `Created graph ${name} (${id}) with trigger->end starter chain.`, "canvas.graph.created", {}), { graph });
273
+ }
274
+ if (action === "delete_graph") {
275
+ if (!graphId)
276
+ return text(pick(getLang(), "缺少 graphId,先用 action=list 查看工程。", "Missing graphId; call action=list first.", "canvas.missing.id", {}), { ok: false });
277
+ if (graphId === "default")
278
+ return text(pick(getLang(), "默认工程不可删。", "The default graph cannot be deleted.", "canvas.graph.protected", {}), { ok: false });
279
+ const ok = deleteCanvasGraph(dataDir, graphId);
280
+ if (ok) {
281
+ try {
282
+ canvasBroadcaster?.({ type: "canvas_list_result", graphs: listCanvasGraphs(dataDir) });
283
+ }
284
+ catch {
285
+ // 忽略
286
+ }
287
+ }
288
+ return text(pick(getLang(), ok ? `已删除工程 ${graphId}。` : `工程不存在:${graphId}。`, ok ? `Deleted graph ${graphId}.` : `Graph not found: ${graphId}.`, "canvas.graph.deleted", {}), { ok });
289
+ }
290
+ if (!graphId)
291
+ return text(pick(getLang(), "缺少 graphId,先用 action=list 查看工程。", "Missing graphId; call action=list first.", "canvas.missing.id", {}), { ok: false });
292
+ if (action === "get") {
293
+ const g = loadCanvasGraph(dataDir, graphId);
294
+ const summary = `图 ${g.name}:${g.nodes.map((n) => `${n.title}[${n.role}](${n.id})`).join("、")};边 ${g.edges.map((e) => `${e.sourceNodeId}->${e.targetNodeId}`).join("、") || "无"}`;
295
+ return text(summary, { graph: g });
296
+ }
297
+ const graph = loadCanvasGraph(dataDir, graphId);
298
+ if (action === "card_place") {
299
+ if (!cardId)
300
+ return text(pick(getLang(), "缺少 cardId,先 card_list 查看。", "Missing cardId; call card_list first.", "canvas.card.missing", {}), { ok: false });
301
+ const card = listCustomCards(dataDir).find((c) => c.id === cardId);
302
+ if (!card)
303
+ return text(pick(getLang(), `卡片不存在:${cardId}。`, `Card not found: ${cardId}.`, "canvas.card.missing", {}), { ok: false });
304
+ const role = VALID_ROLES.has(card.role) ? card.role : "coder";
305
+ const node = {
306
+ id: `n_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
307
+ title: card.title,
308
+ role,
309
+ x: 80 + (graph.nodes.length % 3) * 380,
310
+ y: 80 + Math.floor(graph.nodes.length / 3) * 260,
311
+ width: 300,
312
+ engine: ["pi", "dsh", "claude", "durable"].includes(card.engine)
313
+ ? card.engine
314
+ : "pi",
315
+ model: card.model || graph.nodes[0]?.model || "pi/default",
316
+ cwd: defaultNodeCwd(host, p),
317
+ useWorktree: false,
318
+ status: "idle",
319
+ ...(card.instruction ? { instruction: card.instruction } : {}),
320
+ ...(card.systemPrompt ? { systemPromptOverride: card.systemPrompt } : {}),
321
+ ...(card.config ? { config: { ...card.config } } : {}),
322
+ };
323
+ graph.nodes.push(node);
324
+ const src = typeof p.sourceNodeId === "string" ? p.sourceNodeId : "";
325
+ if (src && graph.nodes.some((x) => x.id === src)) {
326
+ graph.edges.push({
327
+ id: `e_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
328
+ sourceNodeId: src,
329
+ targetNodeId: node.id,
330
+ type: "handoff",
331
+ });
332
+ }
333
+ saveAndPush(dataDir, graph);
334
+ return text(pick(getLang(), `已落卡片 ${card.title} → 节点 ${node.id},画布实时可见。`, `Placed card ${card.title} as node ${node.id}.`, "canvas.card.placed", {}), { node });
335
+ }
336
+ if (action === "add_node") {
337
+ const role = typeof p.role === "string" && VALID_ROLES.has(p.role) ? p.role : "coder";
338
+ const node = {
339
+ id: `n_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
340
+ title: (typeof p.title === "string" && p.title.slice(0, 24)) || "新节点",
341
+ role,
342
+ x: 80 + (graph.nodes.length % 3) * 380,
343
+ y: 80 + Math.floor(graph.nodes.length / 3) * 260,
344
+ width: 300,
345
+ engine: "pi",
346
+ model: graph.nodes[0]?.model ?? "pi/default",
347
+ cwd: defaultNodeCwd(host, p),
348
+ useWorktree: false,
349
+ status: "idle",
350
+ ...(typeof p.instruction === "string" && p.instruction ? { instruction: p.instruction } : {}),
351
+ };
352
+ graph.nodes.push(node);
353
+ saveAndPush(dataDir, graph);
354
+ return text(pick(getLang(), `已加节点 ${node.title}(${node.id}),画布刷新可见。`, `Added node ${node.title} (${node.id}).`, "canvas.node.added", {}), { node });
355
+ }
356
+ if (action === "update_node") {
357
+ const nodeId = p.nodeId;
358
+ const n = graph.nodes.find((x) => x.id === nodeId);
359
+ if (!n)
360
+ return text(pick(getLang(), `节点不存在:${nodeId}`, `Node not found: ${nodeId}`, "canvas.node.missing", {}), { ok: false });
361
+ const patch = (p.patch ?? {});
362
+ for (const [k, v] of Object.entries(patch)) {
363
+ if (["id", "status", "activeConvId"].includes(k))
364
+ continue;
365
+ if (k === "role" && typeof v === "string" && !VALID_ROLES.has(v))
366
+ continue;
367
+ n[k] = v;
368
+ }
369
+ saveAndPush(dataDir, graph);
370
+ return text(pick(getLang(), `已更新节点 ${n.title}。`, `Updated node ${n.title}.`, "canvas.node.updated", {}), { node: n });
371
+ }
372
+ if (action === "delete_node") {
373
+ const nodeId = p.nodeId;
374
+ graph.nodes = graph.nodes.filter((x) => x.id !== nodeId);
375
+ graph.edges = graph.edges.filter((e) => e.sourceNodeId !== nodeId && e.targetNodeId !== nodeId);
376
+ saveAndPush(dataDir, graph);
377
+ return text(pick(getLang(), `已删节点 ${nodeId}(连带边)。`, `Deleted node ${nodeId} with its edges.`, "canvas.node.deleted", {}), { ok: true });
378
+ }
379
+ if (action === "add_edge") {
380
+ const s = p.sourceNodeId;
381
+ const t = p.targetNodeId;
382
+ if (s === t) {
383
+ return text(pick(getLang(), "不能连接自环边(源与目标相同)。", "Self-loop edges are not allowed (source equals target).", "canvas.edge.self", {}), { ok: false });
384
+ }
385
+ if (!graph.nodes.some((x) => x.id === s) || !graph.nodes.some((x) => x.id === t)) {
386
+ return text(pick(getLang(), "边的端点节点不存在,先 get 确认 id。", "Edge endpoint not found; get the graph first.", "canvas.edge.missing", {}), { ok: false });
387
+ }
388
+ if (graph.edges.some((e) => e.sourceNodeId === s && e.targetNodeId === t)) {
389
+ return text(pick(getLang(), `两节点间已存在连接(${s} → ${t})。`, `Edge already exists between ${s} and ${t}.`, "canvas.edge.duplicate", {}), { ok: false });
390
+ }
391
+ const edge = {
392
+ id: `e_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
393
+ sourceNodeId: s,
394
+ targetNodeId: t,
395
+ type: "handoff",
396
+ };
397
+ graph.edges.push(edge);
398
+ saveAndPush(dataDir, graph);
399
+ return text(pick(getLang(), `已连边 ${s} → ${t}。`, `Connected ${s} -> ${t}.`, "canvas.edge.added", {}), {
400
+ edge,
401
+ });
402
+ }
403
+ if (action === "delete_edge") {
404
+ const edgeId = p.edgeId;
405
+ graph.edges = graph.edges.filter((e) => e.id !== edgeId);
406
+ saveAndPush(dataDir, graph);
407
+ return text(pick(getLang(), `已删边 ${edgeId}。`, `Deleted edge ${edgeId}.`, "canvas.edge.deleted", {}), {
408
+ ok: true,
409
+ });
410
+ }
411
+ if (action === "apply_dag") {
412
+ const rawNodes = (p.nodes ?? []);
413
+ const rawEdges = (p.edges ?? []);
414
+ if (rawNodes.length === 0 || rawNodes.length > 20)
415
+ return text(pick(getLang(), "nodes 非法(需 1-20 个)。", "nodes must be 1-20.", "canvas.dag.bad", {}), {
416
+ ok: false,
417
+ });
418
+ for (const n of rawNodes) {
419
+ if (typeof n.title !== "string" || typeof n.role !== "string" || !VALID_ROLES.has(n.role)) {
420
+ return text(pick(getLang(), `非法节点 role:${String(n.role)}`, `Invalid node role: ${String(n.role)}`, "canvas.dag.role", {}), { ok: false });
421
+ }
422
+ }
423
+ const idx = rawNodes.map((_, i) => i);
424
+ const normEdges = rawEdges.map((e) => ({ from: Number(e.from ?? e.source), to: Number(e.to ?? e.target) }));
425
+ for (const e of normEdges) {
426
+ if (!idx.includes(e.from) || !idx.includes(e.to) || e.from === e.to) {
427
+ return text(pick(getLang(), "边下标非法。", "Invalid edge indices.", "canvas.dag.edge", {}), {
428
+ ok: false,
429
+ });
430
+ }
431
+ }
432
+ if (hasCycle(rawNodes.length, normEdges))
433
+ return text(pick(getLang(), "DAG 含环,拒绝落图。", "DAG has a cycle; rejected.", "canvas.dag.cycle", {}), {
434
+ ok: false,
435
+ });
436
+ const now = Date.now();
437
+ const nodes = rawNodes.map((n, i) => ({
438
+ id: `n_${now}_${i}`,
439
+ cwd: defaultNodeCwd(host, n),
440
+ title: String(n.title).slice(0, 24),
441
+ role: n.role,
442
+ x: 80 + i * 120,
443
+ y: 80 + (i % 3) * 260,
444
+ width: 300,
445
+ engine: "pi",
446
+ model: graph.nodes[0]?.model ?? "pi/default",
447
+ useWorktree: false,
448
+ status: "idle",
449
+ ...(typeof n.instruction === "string" && n.instruction ? { instruction: n.instruction } : {}),
450
+ }));
451
+ const edges = normEdges.map((e, i) => ({
452
+ id: `e_${now}_${i}`,
453
+ sourceNodeId: nodes[e.from].id,
454
+ targetNodeId: nodes[e.to].id,
455
+ type: "handoff",
456
+ }));
457
+ const next = { ...graph, nodes, edges, updatedAt: now };
458
+ saveAndPush(dataDir, next);
459
+ return text(pick(getLang(), `已替换整图:${nodes.length} 节点 / ${edges.length} 边。`, `Replaced graph: ${nodes.length} nodes / ${edges.length} edges.`, "canvas.dag.applied", {}), { graph: next });
460
+ }
461
+ // —— 运行态接管:需 index.ts 注入 canvasRuntime ——
462
+ const needRuntime = new Set([
463
+ "run_all",
464
+ "run_node",
465
+ "stop_node",
466
+ "stop_all",
467
+ "steer_node",
468
+ "review_node",
469
+ "get_log",
470
+ "reset_status",
471
+ "layout_graph",
472
+ ]);
473
+ if (needRuntime.has(action)) {
474
+ if (!canvasRuntime)
475
+ return text(pick(getLang(), "运行态未就绪(服务刚启动/未注入),请稍后重试或在 Canvas Studio 里操作。", "Canvas runtime not ready; retry later or use Canvas Studio.", "canvas.runtime.missing", {}), { ok: false });
476
+ const nodeId = typeof p.nodeId === "string" ? p.nodeId : "";
477
+ if (action === "run_all") {
478
+ void canvasRuntime.runAll(graph, typeof p.prompt === "string" ? p.prompt : undefined, host.getCwd?.());
479
+ return text(pick(getLang(), `已启动整图运行:${graph.name},进度在 Canvas Studio 看直播。`, `Started run-all for ${graph.name}; watch progress in Canvas Studio.`, "canvas.run.started", {}), { ok: true, graphId });
480
+ }
481
+ if (action === "run_node") {
482
+ if (!nodeId)
483
+ return text(pick(getLang(), "缺少 nodeId。", "Missing nodeId.", "canvas.node.missing", {}), {
484
+ ok: false,
485
+ });
486
+ void canvasRuntime.runNode(graph, nodeId, typeof p.prompt === "string" ? p.prompt : undefined, host.getCwd?.());
487
+ return text(pick(getLang(), `已启动节点 ${nodeId},日志可用 get_log 查看。`, `Started node ${nodeId}; use get_log to inspect.`, "canvas.node.started", {}), { ok: true, graphId, nodeId });
488
+ }
489
+ if (action === "stop_node") {
490
+ canvasRuntime.stopNode(graphId, nodeId);
491
+ return text(pick(getLang(), `已停止节点 ${nodeId}。`, `Stopped node ${nodeId}.`, "canvas.node.stopped", {}), { ok: true });
492
+ }
493
+ if (action === "stop_all") {
494
+ canvasRuntime.stopAll(graphId);
495
+ return text(pick(getLang(), "已停止整图运行。", "Stopped all runs.", "canvas.run.stopped", {}), {
496
+ ok: true,
497
+ });
498
+ }
499
+ if (action === "steer_node") {
500
+ const message = typeof p.message === "string" ? p.message : "";
501
+ if (!nodeId || !message)
502
+ return text(pick(getLang(), "steer 需要 nodeId + message。", "steer needs nodeId + message.", "canvas.steer.bad", {}), { ok: false });
503
+ canvasRuntime.steerNode(graphId, nodeId, message);
504
+ return text(pick(getLang(), `已向节点 ${nodeId} 追问/转向。`, `Steered node ${nodeId}.`, "canvas.steered", {}), { ok: true });
505
+ }
506
+ if (action === "review_node") {
507
+ const decision = p.decision === "reject" ? "reject" : "approve";
508
+ canvasRuntime.reviewNode(graphId, nodeId, decision, typeof p.comment === "string" ? p.comment : undefined);
509
+ return text(pick(getLang(), `已${decision === "approve" ? "批准" : "驳回"}节点 ${nodeId}。`, `${decision === "approve" ? "Approved" : "Rejected"} node ${nodeId}.`, "canvas.reviewed", {}), { ok: true });
510
+ }
511
+ if (action === "get_log") {
512
+ const entries = canvasRuntime.getNodeLog(graphId, nodeId);
513
+ const tail = entries.slice(-30).map((e) => String(e?.text ?? e).slice(0, 500));
514
+ return text(pick(getLang(), `节点 ${nodeId} 日志 ${entries.length} 条(尾部 ${tail.length}):\n${tail.join("\n") || "(空)"}`, `Node ${nodeId} logs (${entries.length}, last ${tail.length}):\n${tail.join("\n") || "(empty)"}`, "canvas.log", {}), { entries: tail, count: entries.length });
515
+ }
516
+ if (action === "layout_graph") {
517
+ // 拓扑分层:按边 BFS 定深度,同层按序排,卡片 300 宽 + 80 间距
518
+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));
519
+ const indeg = new Map(graph.nodes.map((n) => [n.id, 0]));
520
+ for (const e of graph.edges) {
521
+ if (byId.has(e.sourceNodeId) && byId.has(e.targetNodeId)) {
522
+ indeg.set(e.targetNodeId, (indeg.get(e.targetNodeId) ?? 0) + 1);
523
+ }
524
+ }
525
+ const depth = new Map();
526
+ const queue = [];
527
+ for (const [id, d] of indeg)
528
+ if (d === 0) {
529
+ depth.set(id, 0);
530
+ queue.push(id);
531
+ }
532
+ if (queue.length === 0 && graph.nodes[0]) {
533
+ depth.set(graph.nodes[0].id, 0);
534
+ queue.push(graph.nodes[0].id);
535
+ }
536
+ const succ = new Map();
537
+ for (const e of graph.edges) {
538
+ if (!succ.has(e.sourceNodeId))
539
+ succ.set(e.sourceNodeId, []);
540
+ succ.get(e.sourceNodeId).push(e.targetNodeId);
541
+ }
542
+ while (queue.length > 0) {
543
+ const cur = queue.shift();
544
+ for (const nx of succ.get(cur) ?? []) {
545
+ const nd = (depth.get(cur) ?? 0) + 1;
546
+ if (nd > (depth.get(nx) ?? -1))
547
+ depth.set(nx, nd);
548
+ const left = (indeg.get(nx) ?? 1) - 1;
549
+ indeg.set(nx, left);
550
+ if (left <= 0 && !queue.includes(nx))
551
+ queue.push(nx);
552
+ }
553
+ }
554
+ // 环内/不可达节点:按数组顺序排在主链之后,不再叠在第 0 列
555
+ let tail = depth.size > 0 ? Math.max(...depth.values()) : 0;
556
+ for (const n of graph.nodes) {
557
+ if (!depth.has(n.id)) {
558
+ tail += 1;
559
+ depth.set(n.id, tail);
560
+ }
561
+ }
562
+ const layers = new Map();
563
+ for (const n of graph.nodes) {
564
+ const d = depth.get(n.id) ?? 0;
565
+ if (!layers.has(d))
566
+ layers.set(d, []);
567
+ layers.get(d).push(n);
568
+ }
569
+ for (const [, arr] of layers) {
570
+ arr.forEach((n, i) => {
571
+ n.x = 80 + (depth.get(n.id) ?? 0) * 380;
572
+ n.y = 80 + i * 260;
573
+ });
574
+ }
575
+ saveAndPush(dataDir, graph);
576
+ return text(pick(getLang(), `已重排 ${graph.nodes.length} 个节点(按连线分层,卡片不再叠)。`, `Rearranged ${graph.nodes.length} nodes into layers; no more overlap.`, "canvas.layout.done", {}), { ok: true });
577
+ }
578
+ if (action === "reset_status") {
579
+ canvasRuntime.resetStatus(graph);
580
+ return text(pick(getLang(), "已重置整图状态。", "Reset graph status.", "canvas.reset", {}), { ok: true });
581
+ }
582
+ }
583
+ return text(pick(getLang(), `未知动作:${action}`, `Unknown action: ${action}`, "canvas.unknown", {}), {
584
+ ok: false,
585
+ });
586
+ }
587
+ catch (err) {
588
+ const msg = err instanceof Error ? err.message : String(err);
589
+ return text(pick(getLang(), `画布操作失败:${msg}`, `Canvas op failed: ${msg}`, "canvas.failed", { error: msg }), { ok: false });
590
+ }
591
+ },
592
+ });
593
+ }