pi-web-ui 0.114.0 → 0.114.2

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 (122) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/bin/pi-web-ui.mjs +15 -7
  3. package/dist/server/agent-service.js +190 -65
  4. package/dist/server/attachments.js +48 -2
  5. package/dist/server/canvas/canvas-agent-tool.js +3 -3
  6. package/dist/server/canvas/canvas-cards.js +1 -1
  7. package/dist/server/canvas/canvas-scheduled-task.js +45 -0
  8. package/dist/server/canvas/canvas-validation.js +1 -1
  9. package/dist/server/client-state.js +6 -2
  10. package/dist/server/communicate-tool.js +37 -11
  11. package/dist/server/device-center/connector.js +33 -14
  12. package/dist/server/device-center/hub-page.js +1 -1
  13. package/dist/server/device-center/hub.js +2 -1
  14. package/dist/server/device-center/local-hub.js +92 -0
  15. package/dist/server/device-center/local.js +60 -7
  16. package/dist/server/device-center/path-portal.js +1 -1
  17. package/dist/server/device-center/relay.js +45 -8
  18. package/dist/server/dispatch-domain-handlers.js +1 -0
  19. package/dist/server/dsh/dsh-agent-service.js +5 -1
  20. package/dist/server/durable/durable-event-projector.js +19 -3
  21. package/dist/server/durable/durable-models.js +134 -65
  22. package/dist/server/engine-probe.js +36 -6
  23. package/dist/server/global-loader.js +40 -2
  24. package/dist/server/index.js +56 -32
  25. package/dist/server/model-resolver.js +4 -1
  26. package/dist/server/patch-bash-process.js +125 -0
  27. package/dist/server/plugins.js +26 -2
  28. package/dist/server/preset-fields.js +7 -0
  29. package/dist/server/preset-share.js +1 -0
  30. package/dist/server/prompt-templates.js +106 -0
  31. package/dist/server/protocol-version.js +1 -1
  32. package/dist/server/resolve-global-sdk.js +2 -0
  33. package/dist/server/schedule-agent-tool.js +49 -26
  34. package/dist/server/scheduler-tasks.js +129 -11
  35. package/dist/server/settings-service.js +6 -0
  36. package/dist/server/text-quote.js +9 -0
  37. package/dist/server/tool-manager.js +2 -1
  38. package/dist/server/universal/drivers/claude-code.js +5 -0
  39. package/dist/server/universal/drivers/codex.js +336 -0
  40. package/dist/server/universal/index.js +1 -0
  41. package/dist/server/universal/universal-attachments.js +24 -1
  42. package/dist/server/universal/universal-session.js +42 -18
  43. package/docs/device-center.md +9 -3
  44. package/package.json +2 -2
  45. package/plugins/catalog.json +10 -0
  46. package/web/dist/.build-assets.json +1 -1
  47. package/web/dist/assets/BgTasksModal-BIlQ89vr.js +1 -0
  48. package/web/dist/assets/BgTasksModal-Ck2sjlPM.js +1 -0
  49. package/web/dist/assets/{CanvasStudio-BEJZE5BI.js → CanvasStudio-B3W6b_rA.js} +3 -3
  50. package/web/dist/assets/{CanvasStudio-CgUNHqos.js → CanvasStudio-Csv1Sj1-.js} +3 -3
  51. package/web/dist/assets/DeviceCenter-BQdDcO8A.js +3 -0
  52. package/web/dist/assets/DeviceCenter-CHRKL0Vy.js +3 -0
  53. package/web/dist/assets/DeviceGroups-D2rogxEN.js +1 -0
  54. package/web/dist/assets/Dropdown-ZLS04O8p.js +1 -0
  55. package/web/dist/assets/FilePreview-B9xoU6ON.js +2 -0
  56. package/web/dist/assets/FilePreview-DUQpVZkH.js +2 -0
  57. package/web/dist/assets/GlobalSearchModal-BXEGvUZq.js +1 -0
  58. package/web/dist/assets/GlobalSearchModal-CnVPmfOI.js +1 -0
  59. package/web/dist/assets/GroupConversation-CyIpQzDd.js +1 -0
  60. package/web/dist/assets/GroupConversation-DgYV3uYS.js +1 -0
  61. package/web/dist/assets/ModelConfigModal-DDZccDYt.js +2 -0
  62. package/web/dist/assets/PiSetupModal-DHbqfx8T.js +1 -0
  63. package/web/dist/assets/ProviderOAuthControls-C-MK36Dk.js +1 -0
  64. package/web/dist/assets/SCMPanel-imYI2Ecw.js +2 -0
  65. package/web/dist/assets/SCMPanel-sVZcV7dR.js +2 -0
  66. package/web/dist/assets/SettingsModal-Xw1Yoi3_.js +20 -0
  67. package/web/dist/assets/SettingsModal-mb4e34-0.js +20 -0
  68. package/web/dist/assets/{TerminalPanel-DL20uKgU.js → TerminalPanel-CLkJJvxg.js} +2 -2
  69. package/web/dist/assets/{TerminalPanel-D6cPRFei.js → TerminalPanel-DpcIellm.js} +2 -2
  70. package/web/dist/assets/TuiOverlayModal-4-fFAZe7.js +1 -0
  71. package/web/dist/assets/TuiOverlayModal-DCu01lks.js +1 -0
  72. package/web/dist/assets/app-globals-DcyO0UPi.js +1 -0
  73. package/web/dist/assets/{desktop-DPyTy4M3.js → desktop-YguLbrX1.js} +1 -1
  74. package/web/dist/assets/fi-DaSO0Q-m.js +325 -0
  75. package/web/dist/assets/index-Cdh3sibd.js +85 -0
  76. package/web/dist/assets/index-DDZMv6LO.css +1 -0
  77. package/web/dist/assets/index-DWw_SxRq.js +85 -0
  78. package/web/dist/assets/{plugin-host-CqA4yW6w.js → plugin-host-BRBg6zmQ.js} +1 -1
  79. package/web/dist/assets/theme-DDl-Oy1b.js +1 -0
  80. package/web/dist/index.html +10 -9
  81. package/web/dist/sw.js +1 -1
  82. package/dist/gh-comment-781.md +0 -5
  83. package/dist/server/device-center/local-page.js +0 -17
  84. package/dist/server/device-center/smoke-preview.js +0 -3
  85. package/dist/server/durable/durable-capabilities.js +0 -11
  86. package/dist/server/markers/builtins/services.js +0 -123
  87. package/dist/server/markers/builtins/todo.js +0 -189
  88. package/dist/server/markers-list-tool.js +0 -34
  89. package/dist/server/orchestrator.js +0 -109
  90. package/dist/server/system-prompt-soul.js +0 -41
  91. package/dist/server/univer-service.js +0 -448
  92. package/dist/server/universal/drivers/dsh-driver.js +0 -379
  93. package/dist/test-artifact.md +0 -9
  94. package/dist/test-preview-modal.md +0 -11
  95. package/dist/test-report.html +0 -20
  96. package/web/dist/assets/BgTasksModal-CS7UNzcw.js +0 -1
  97. package/web/dist/assets/BgTasksModal-Dk-tp78W.js +0 -1
  98. package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +0 -3
  99. package/web/dist/assets/DeviceCenter-CVblvhNX.js +0 -3
  100. package/web/dist/assets/Dropdown-Oug0DDte.js +0 -1
  101. package/web/dist/assets/FilePreview-CvdX6nr6.js +0 -2
  102. package/web/dist/assets/FilePreview-kCZhfBAF.js +0 -2
  103. package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +0 -1
  104. package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +0 -1
  105. package/web/dist/assets/GroupConversation-Cgo4xbpa.js +0 -1
  106. package/web/dist/assets/GroupConversation-DZ71jEi8.js +0 -1
  107. package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +0 -2
  108. package/web/dist/assets/PiSetupModal-mkWPSxMj.js +0 -1
  109. package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +0 -1
  110. package/web/dist/assets/SCMPanel-BP1TUT-V.js +0 -2
  111. package/web/dist/assets/SCMPanel-BscPm9kf.js +0 -2
  112. package/web/dist/assets/SettingsModal-C8UgMjVM.js +0 -20
  113. package/web/dist/assets/SettingsModal-VynB7jNb.js +0 -20
  114. package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +0 -1
  115. package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +0 -1
  116. package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +0 -1
  117. package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +0 -1
  118. package/web/dist/assets/app-globals-CnO6KlEM.js +0 -325
  119. package/web/dist/assets/index-CPgAH5q7.js +0 -83
  120. package/web/dist/assets/index-Cje8iugL.js +0 -83
  121. package/web/dist/assets/index-DnKeiDbj.css +0 -1
  122. package/web/dist/assets/theme-BqdAjEjF.js +0 -1
@@ -21,6 +21,7 @@ import { botExecutionMessageAllowed } from "./device-center/bot-execution.js";
21
21
  import "./patch-remote-catalog.js";
22
22
  import "./patch-turn-end-boundary.js";
23
23
  import { existsSync, mkdirSync, readFileSync, readdirSync, statSync } from "node:fs";
24
+ import { registerPromptTemplateRoutes } from "./prompt-templates.js";
24
25
  import { readFile, stat } from "node:fs/promises";
25
26
  import { createServer } from "node:http";
26
27
  import { proxyHttp } from "./http-proxy.js";
@@ -77,6 +78,7 @@ import { handleFileMessage, handleScmMessage, handleBgServerMessage, handlePrese
77
78
  import { RemoteSshService, isRemoteWorkspaceUri, serveRemoteWorkspaceFile, setGlobalRemoteSshService, } from "./remote-ssh-service.js";
78
79
  import { handlePluginMessage } from "./dispatch-plugin-handlers.js";
79
80
  import { CanvasOrchestrator } from "./canvas/canvas-orchestrator.js";
81
+ import { executeScheduledCanvas, validateScheduledCanvas } from "./canvas/canvas-scheduled-task.js";
80
82
  import { setCanvasBroadcaster, setCanvasRuntime } from "./canvas/canvas-agent-tool.js";
81
83
  import { handleCanvasMessage } from "./canvas/canvas-dispatch.js";
82
84
  /** Strip npm-injected env (`npm start` exports `npm_config_*` / `npm_package_*` /
@@ -525,17 +527,20 @@ app.use((req, res, next) => {
525
527
  });
526
528
  /** 共享客户端持久化存储:双引擎(pi + dsh)共用同一份内存缓存与落盘通道,避免互相覆盖。 */
527
529
  const sharedStateStore = new ClientStateStore(join(DATA_DIR, "client-state.json"));
528
- /** 启动参数显式指定的引擎(--engine pi|dsh|claude|durable 或 PI_WEB_ENGINE)。未显式传则优先读持久化默认引擎。 */
530
+ registerPromptTemplateRoutes(app, DATA_DIR);
531
+ /** 启动参数显式指定的引擎(--engine pi|dsh|codex|claude|durable 或 PI_WEB_ENGINE)。未显式传则优先读持久化默认引擎。 */
529
532
  const EXPLICIT_ENGINE_ARG = cliFlag("--engine") ?? process.env.PI_WEB_ENGINE;
530
- let currentDefaultEngine = EXPLICIT_ENGINE_ARG === "durable"
531
- ? "durable"
532
- : EXPLICIT_ENGINE_ARG === "claude"
533
- ? "claude"
534
- : EXPLICIT_ENGINE_ARG === "dsh"
535
- ? "dsh"
536
- : EXPLICIT_ENGINE_ARG === "pi"
537
- ? "pi"
538
- : (sharedStateStore.getDefaultEngine() ?? "pi");
533
+ let currentDefaultEngine = EXPLICIT_ENGINE_ARG === "codex"
534
+ ? "codex"
535
+ : EXPLICIT_ENGINE_ARG === "durable"
536
+ ? "durable"
537
+ : EXPLICIT_ENGINE_ARG === "claude"
538
+ ? "claude"
539
+ : EXPLICIT_ENGINE_ARG === "dsh"
540
+ ? "dsh"
541
+ : EXPLICIT_ENGINE_ARG === "pi"
542
+ ? "pi"
543
+ : (sharedStateStore.getDefaultEngine() ?? "pi");
539
544
  /** 默认引擎标识(兼容 /api/health 等读取)。 */
540
545
  /** 每个客户端(浏览器标签页 clientId)当前激活的引擎。支持多标签页同时跑不同引擎 + 零重启热切。 */
541
546
  const clientEngines = new Map();
@@ -1353,12 +1358,13 @@ heartbeatTimer.unref?.();
1353
1358
  // PI_WEB_ENGINE=durable 时使用 Pi Durable 引擎(server/durable/),
1354
1359
  // 默认 pi 引擎。同一 wire 协议,前端无感知(ready/health 携带 engine 字段)。
1355
1360
  import { DshAgentService } from "./dsh/dsh-agent-service.js";
1356
- import { UniversalAgentService, ClaudeCodeDriver, probeClaudeCode } from "./universal/index.js";
1361
+ import { UniversalAgentService, ClaudeCodeDriver, probeClaudeCode, CodexDriver } from "./universal/index.js";
1357
1362
  import { DurableAgentService } from "./durable/index.js";
1358
1363
  import { probeAllEngines, probeEngine, getCachedEngineStatuses, updateEngineBackground, isEngineUpdating, ENGINE_PACKAGES, } from "./engine-probe.js";
1359
1364
  let piServiceInstance = null;
1360
1365
  let dshServiceInstance = null;
1361
1366
  let claudeServiceInstance = null;
1367
+ let codexServiceInstance = null;
1362
1368
  let durableServiceInstance = null;
1363
1369
  let wireEngineHooks = null;
1364
1370
  let sharedSocketCount = 0;
@@ -1371,11 +1377,31 @@ function activeEngines() {
1371
1377
  list.push(dshServiceInstance);
1372
1378
  if (claudeServiceInstance)
1373
1379
  list.push(claudeServiceInstance);
1380
+ if (codexServiceInstance)
1381
+ list.push(codexServiceInstance);
1374
1382
  if (durableServiceInstance)
1375
1383
  list.push(durableServiceInstance);
1376
1384
  return list;
1377
1385
  }
1378
1386
  function ensureEngine(engine) {
1387
+ if (engine === "codex") {
1388
+ if (!codexServiceInstance) {
1389
+ codexServiceInstance = new UniversalAgentService({
1390
+ cwd: CWD,
1391
+ dataDir: DATA_DIR,
1392
+ agentDir: getAgentDir(),
1393
+ stateStore: sharedStateStore,
1394
+ engine: "codex",
1395
+ driverFactory: (cwd) => new CodexDriver(cwd),
1396
+ });
1397
+ for (let i = 0; i < sharedSocketCount; i++)
1398
+ codexServiceInstance.noteSocketOpen();
1399
+ if (sharedQuiesced)
1400
+ codexServiceInstance.quiesce();
1401
+ wireEngineHooks?.(codexServiceInstance);
1402
+ }
1403
+ return codexServiceInstance;
1404
+ }
1379
1405
  if (engine === "durable") {
1380
1406
  if (!durableServiceInstance) {
1381
1407
  durableServiceInstance = new DurableAgentService({
@@ -1763,7 +1789,11 @@ canvasOrchestrator.setBroadcaster((msg) => {
1763
1789
  // 客户端(chatFromScheduler);单次任务触发后自动删除。DSH 引擎无这俩方法时
1764
1790
  // executor 回 not-supported(历史里记失败,不炸进程)。
1765
1791
  const scheduler = new SchedulerStore(DATA_DIR, {
1792
+ validateTask: (task) => validateScheduledCanvas(DATA_DIR, task),
1766
1793
  executor: async (task) => {
1794
+ if (task.target === "canvas") {
1795
+ return executeScheduledCanvas(DATA_DIR, canvasOrchestrator, task);
1796
+ }
1767
1797
  let result;
1768
1798
  try {
1769
1799
  const svc = ensureEngine("pi");
@@ -1854,15 +1884,6 @@ const scheduler = new SchedulerStore(DATA_DIR, {
1854
1884
  catch (err) {
1855
1885
  result = { ok: false, error: err.message };
1856
1886
  }
1857
- // 单次任务:触发一次后自动删除(历史随任务一起走,成败已由上面的 notify 播报)。
1858
- if (task.oneShot) {
1859
- try {
1860
- scheduler.remove(task.id);
1861
- }
1862
- catch {
1863
- // 删除失败不影响已记录的执行结果
1864
- }
1865
- }
1866
1887
  return result;
1867
1888
  },
1868
1889
  onChange: () => pushSchedulerTasks(),
@@ -2282,21 +2303,23 @@ wss.on("connection", (ws) => {
2282
2303
  .catch(() => { });
2283
2304
  };
2284
2305
  const handleSwitchEngine = async (msg) => {
2285
- const targetEngine = msg.engine === "durable"
2286
- ? "durable"
2287
- : msg.engine === "claude"
2288
- ? "claude"
2289
- : msg.engine === "dsh"
2290
- ? "dsh"
2291
- : msg.engine === "pi"
2292
- ? "pi"
2293
- : null;
2306
+ const targetEngine = msg.engine === "codex"
2307
+ ? "codex"
2308
+ : msg.engine === "durable"
2309
+ ? "durable"
2310
+ : msg.engine === "claude"
2311
+ ? "claude"
2312
+ : msg.engine === "dsh"
2313
+ ? "dsh"
2314
+ : msg.engine === "pi"
2315
+ ? "pi"
2316
+ : null;
2294
2317
  if (!targetEngine) {
2295
2318
  send({
2296
2319
  type: "notice",
2297
2320
  level: "error",
2298
- text: `无效的引擎类型:${String(msg.engine)}(仅支持 pi / dsh / claude / durable)`,
2299
- textEn: `Invalid engine "${String(msg.engine)}" (supported: pi, dsh, claude, durable)`,
2321
+ text: `无效的引擎类型:${String(msg.engine)}(仅支持 pi / dsh / codex / claude / durable)`,
2322
+ textEn: `Invalid engine "${String(msg.engine)}" (supported: pi, dsh, codex, claude, durable)`,
2300
2323
  });
2301
2324
  return;
2302
2325
  }
@@ -2440,6 +2463,7 @@ wss.on("connection", (ws) => {
2440
2463
  pi: { zh: "Pi", en: "Pi" },
2441
2464
  dsh: { zh: "DSH", en: "DSH" },
2442
2465
  claude: { zh: "Claude Code", en: "Claude Code" },
2466
+ codex: { zh: "Codex", en: "Codex" },
2443
2467
  durable: { zh: "Pi Durable", en: "Pi Durable" },
2444
2468
  };
2445
2469
  const displayName = engineDisplayNames[targetEngine] ?? {
@@ -2646,7 +2670,7 @@ wss.on("connection", (ws) => {
2646
2670
  void cs.abort();
2647
2671
  break;
2648
2672
  case "abort_bash":
2649
- void cs.abortBash();
2673
+ void cs.abortBash(msg.conversationId);
2650
2674
  break;
2651
2675
  case "retry_last":
2652
2676
  void cs.retryLast();
@@ -209,6 +209,8 @@ export function resolveModelProtocol(api, providerId, modelId) {
209
209
  if (pid === "anthropic" || pid.includes("claude") || pid.includes("anthropic")) {
210
210
  return "anthropic-messages";
211
211
  }
212
+ if (pid === "google-vertex")
213
+ return "google-vertex";
212
214
  if (pid === "google" || pid === "gemini") {
213
215
  return "google-generative-ai";
214
216
  }
@@ -256,7 +258,8 @@ export function isProtocolSupportedByEngine(engine, api, providerId, modelId) {
256
258
  return (protocol === "openai-completions" ||
257
259
  protocol === "openai-responses" ||
258
260
  protocol === "anthropic-messages" ||
259
- protocol === "google-generative-ai");
261
+ protocol === "google-generative-ai" ||
262
+ protocol === "google-vertex");
260
263
  }
261
264
  return true;
262
265
  }
@@ -0,0 +1,125 @@
1
+ /** Bound native shell output draining without changing shell selection (issue #794). */
2
+ import { registerHooks } from "node:module";
3
+ export const SENTINEL = "// pi-web-ui #794: bounded shell lifecycle v1";
4
+ // Kept as JavaScript source because this compatibility patch runs inside the SDK.
5
+ // The SDK still owns shell discovery, environment, process groups and tree killing.
6
+ export const SHELL_WAIT_SOURCE = `function waitForShellLifecycle(child, { onData, signal, timeout, timeoutMs, kill }) {
7
+ return new Promise((resolve, reject) => {
8
+ let settled = false;
9
+ let exited = false;
10
+ let exitCode = null;
11
+ let stopError;
12
+ let executionTimer;
13
+ let drainTimer;
14
+ let idleTimer;
15
+ let stopTimer;
16
+ const cleanup = () => {
17
+ clearTimeout(executionTimer);
18
+ clearTimeout(drainTimer);
19
+ clearTimeout(idleTimer);
20
+ clearTimeout(stopTimer);
21
+ signal?.removeEventListener("abort", onAbort);
22
+ child.removeListener("exit", onExit);
23
+ child.removeListener("close", onClose);
24
+ child.removeListener("error", onError);
25
+ for (const stream of [child.stdout, child.stderr]) {
26
+ stream?.removeListener("data", onOutput);
27
+ stream?.destroy();
28
+ }
29
+ };
30
+ const finish = (error) => {
31
+ if (settled) return;
32
+ settled = true;
33
+ cleanup();
34
+ if (error) reject(error);
35
+ else resolve(exitCode);
36
+ };
37
+ const stop = (error) => {
38
+ if (settled || stopError) return;
39
+ stopError = error;
40
+ clearTimeout(executionTimer);
41
+ clearTimeout(drainTimer);
42
+ clearTimeout(idleTimer);
43
+ // Killing is best effort; inherited handles must never prevent settlement.
44
+ stopTimer = setTimeout(() => finish(stopError), 1000);
45
+ try { kill(); } catch { /* preserve the original timeout/cancellation */ }
46
+ };
47
+ const onAbort = () => stop(new Error("aborted"));
48
+ const armIdle = () => {
49
+ clearTimeout(idleTimer);
50
+ idleTimer = setTimeout(() => finish(stopError), 100);
51
+ };
52
+ const onOutput = (data) => {
53
+ if (settled || stopError) return;
54
+ try { onData(data); } catch (error) { stop(error); return; }
55
+ if (exited) armIdle();
56
+ };
57
+ const onExit = (code) => {
58
+ exited = true;
59
+ exitCode = code;
60
+ clearTimeout(executionTimer);
61
+ if (stopError) { finish(stopError); return; }
62
+ // Preserve the SDK's quiet-period drain, but never extend this hard cap.
63
+ drainTimer = setTimeout(() => {
64
+ try { onData(Buffer.from("\\n[Output collection stopped: inherited pipes remained open after the shell exited.]\\n")); }
65
+ catch (error) { finish(error); return; }
66
+ finish();
67
+ }, 1000);
68
+ armIdle();
69
+ };
70
+ const onClose = (code) => {
71
+ exitCode = code;
72
+ finish(stopError);
73
+ };
74
+ const onError = (error) => finish(stopError ?? error);
75
+ child.once("exit", onExit);
76
+ child.once("close", onClose);
77
+ child.once("error", onError);
78
+ child.stdout?.on("data", onOutput);
79
+ child.stderr?.on("data", onOutput);
80
+ if (timeoutMs !== undefined) {
81
+ executionTimer = setTimeout(() => stop(new Error("timeout:" + timeout)), timeoutMs);
82
+ }
83
+ signal?.addEventListener("abort", onAbort, { once: true });
84
+ if (signal?.aborted) onAbort();
85
+ });
86
+ }`;
87
+ const OLD_LIFECYCLE = / let timedOut = false;\r?\n[\s\S]*? finally \{[\s\S]*?signal\.removeEventListener\("abort", onAbort\);\r?\n \}/;
88
+ const REPLACEMENT = ` try {
89
+ const exitCode = await waitForShellLifecycle(child, {
90
+ onData, signal, timeout, timeoutMs,
91
+ kill: () => { if (child.pid) killProcessTree(child.pid); },
92
+ });
93
+ const signalCode = child.signalCode;
94
+ return { exitCode: exitCode ?? (signalCode ? 128 + (osConstants.signals[signalCode] ?? 0) : 1) };
95
+ } finally {
96
+ if (child.pid) untrackDetachedChildPid(child.pid);
97
+ }`;
98
+ export function patchBashProcessSource(source) {
99
+ if (source.includes(SENTINEL))
100
+ return { code: source, status: "already" };
101
+ if (!source.includes('from "../../utils/child-process.js"') || !OLD_LIFECYCLE.test(source)) {
102
+ return { code: source, status: "unsupported" };
103
+ }
104
+ const code = source
105
+ .replace(/import \{ waitForChildProcess \} from "\.\.\/\.\.\/utils\/child-process\.js";\r?\n/, "")
106
+ .replace(OLD_LIFECYCLE, REPLACEMENT);
107
+ return { code: `${code}\n${SENTINEL}\n${SHELL_WAIT_SOURCE}\n`, status: "patched" };
108
+ }
109
+ /* SDK sources are transformed in memory before compilation, never on disk. */
110
+ export function registerBashProcessPatch() {
111
+ registerHooks({
112
+ load(url, context, nextLoad) {
113
+ const loaded = nextLoad(url, context);
114
+ if (!url.replaceAll("\\\\", "/").endsWith("/@earendil-works/pi-coding-agent/dist/core/tools/bash.js"))
115
+ return loaded;
116
+ if (loaded.source == null)
117
+ return loaded;
118
+ const source = typeof loaded.source === "string" ? loaded.source : new TextDecoder().decode(loaded.source);
119
+ const result = patchBashProcessSource(source);
120
+ if (result.status === "unsupported")
121
+ console.warn(`[bash-process] SDK lifecycle patch not applied (unrecognized source): ${url}`);
122
+ return { ...loaded, source: result.code };
123
+ },
124
+ });
125
+ }
@@ -733,6 +733,28 @@ function parseSettingsSchema(raw) {
733
733
  const type = (typeof o.type === "string" && o.type ? o.type : optionsFrom ? "select" : "");
734
734
  if (!key || !SETTING_TYPES.has(type) || out.some((x) => x.key === key))
735
735
  continue;
736
+ let options;
737
+ if (Array.isArray(o.options)) {
738
+ const parsed = [];
739
+ for (const opt of o.options) {
740
+ if (typeof opt === "string") {
741
+ parsed.push(opt);
742
+ }
743
+ else if (opt && typeof opt === "object" && typeof opt.value === "string") {
744
+ const val = opt.value;
745
+ const item = { value: val };
746
+ if (typeof opt.label === "string") {
747
+ item.label = opt.label;
748
+ }
749
+ if (typeof opt.labelEn === "string") {
750
+ item.labelEn = opt.labelEn;
751
+ }
752
+ parsed.push(item);
753
+ }
754
+ }
755
+ if (parsed.length > 0)
756
+ options = parsed;
757
+ }
736
758
  const field = {
737
759
  key,
738
760
  type: type,
@@ -740,7 +762,7 @@ function parseSettingsSchema(raw) {
740
762
  ...(o.default !== undefined ? { default: o.default } : {}),
741
763
  ...(typeof o.min === "number" ? { min: o.min } : {}),
742
764
  ...(typeof o.max === "number" ? { max: o.max } : {}),
743
- ...(Array.isArray(o.options) ? { options: o.options.filter((x) => typeof x === "string") } : {}),
765
+ ...(options ? { options } : {}),
744
766
  ...(type === "select" && optionsFrom ? { optionsFrom } : {}),
745
767
  ...(typeof o.hint === "string" ? { hint: o.hint } : {}),
746
768
  };
@@ -896,7 +918,9 @@ function cleanNonSecretSettingsField(f, v, lang) {
896
918
  }
897
919
  return { value: v === undefined ? (f.default ?? "") : s };
898
920
  }
899
- if (v !== undefined && !f.options?.includes(s))
921
+ const hasOptions = Array.isArray(f.options);
922
+ const allowedValues = f.options?.map((opt) => (typeof opt === "string" ? opt : opt.value));
923
+ if (v !== undefined && (!hasOptions || !allowedValues?.includes(s)))
900
924
  return {
901
925
  error: pick(lang, `${f.label} 值非法`, `Invalid value for ${f.label}`, "plugins.settings.invalid.value", {
902
926
  "f.label": f.label,
@@ -47,6 +47,7 @@ export const PRESET_FIELD_GROUPS = {
47
47
  "toolWatchdogTimeoutMs",
48
48
  "questionnaireEnabled",
49
49
  "questionPresentation",
50
+ "toolApprovalPresentation",
50
51
  "questionTimeoutSeconds",
51
52
  "editSoftEnabled",
52
53
  "terminalToolsEnabled",
@@ -280,6 +281,12 @@ export const PRESET_FIELD_META = {
280
281
  hintZh: "当前对话弹出、全部弹出或仅队列",
281
282
  hintEn: "Current conversation, all popups, or manual queue",
282
283
  },
284
+ toolApprovalPresentation: {
285
+ labelZh: "工具审批提醒方式",
286
+ labelEn: "Tool approval reminders",
287
+ hintZh: "当前对话弹出、全部弹出或仅队列",
288
+ hintEn: "Current conversation, all popups, or manual queue",
289
+ },
283
290
  questionTimeoutSeconds: {
284
291
  labelZh: "子代理问卷等待期限",
285
292
  labelEn: "Subagent question timeout",
@@ -248,6 +248,7 @@ const PRESET_FIELD_KINDS = {
248
248
  toolWatchdogTimeoutMs: "number",
249
249
  questionnaireEnabled: "bool",
250
250
  questionPresentation: "questionPresentation",
251
+ toolApprovalPresentation: "questionPresentation",
251
252
  questionTimeoutSeconds: "questionTimeout",
252
253
  editSoftEnabled: "bool",
253
254
  terminalToolsEnabled: "bool",
@@ -0,0 +1,106 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { writeJsonAtomicSync } from "./atomic-file.js";
4
+ export function parseStoredTemplate(value) {
5
+ if (!value || typeof value !== "object")
6
+ throw new Error("Invalid template");
7
+ const raw = value;
8
+ if (typeof raw.id !== "string" || !raw.id || raw.id.length > 200)
9
+ throw new Error("Invalid template id");
10
+ if (raw.hidden === true)
11
+ return { id: raw.id, hidden: true };
12
+ const result = { id: raw.id };
13
+ for (const key of ["icon", "title", "desc", "prompt", "command"]) {
14
+ if (raw[key] !== undefined) {
15
+ if (typeof raw[key] !== "string" || raw[key].length > (key === "prompt" ? 100_000 : 1000)) {
16
+ throw new Error(`Invalid template ${key}`);
17
+ }
18
+ result[key] = raw[key];
19
+ }
20
+ }
21
+ if (!result.title?.trim() || !result.prompt?.trim())
22
+ throw new Error("Title and prompt are required");
23
+ if (result.command) {
24
+ result.command = result.command.trim().replace(/^\//, "").toLowerCase();
25
+ if (!/^[a-z][a-z0-9_-]*$/.test(result.command))
26
+ throw new Error("Invalid template command");
27
+ }
28
+ return result;
29
+ }
30
+ /** Mutations read the latest file and commit atomically before returning new state. */
31
+ export function registerPromptTemplateRoutes(app, dataDir) {
32
+ const file = join(dataDir, "prompt-templates.json");
33
+ const load = () => {
34
+ try {
35
+ const data = JSON.parse(readFileSync(file, "utf8"));
36
+ if (!Array.isArray(data))
37
+ throw new Error("Invalid template file");
38
+ return data.map(parseStoredTemplate);
39
+ }
40
+ catch (error) {
41
+ if (error.code === "ENOENT")
42
+ return [];
43
+ throw error;
44
+ }
45
+ };
46
+ app.get("/api/prompt-templates", (_req, res) => {
47
+ try {
48
+ res.setHeader("Cache-Control", "no-store");
49
+ res.json({ templates: load() });
50
+ }
51
+ catch (error) {
52
+ res.status(500).json({ error: String(error) });
53
+ }
54
+ });
55
+ app.post("/api/prompt-templates", (req, res) => {
56
+ // Browser writes must be JSON, preventing cross-origin form submissions.
57
+ if (!req.is("application/json") || req.headers["sec-fetch-site"] === "cross-site") {
58
+ res.status(403).json({ error: "Cross-site template write rejected" });
59
+ return;
60
+ }
61
+ try {
62
+ const body = req.body ?? {};
63
+ let templates = load();
64
+ switch (body.action) {
65
+ case "upsert": {
66
+ const tpl = parseStoredTemplate(body.template);
67
+ if (tpl.command && templates.some((t) => t.id !== tpl.id && t.command === tpl.command)) {
68
+ throw new Error("Template command already exists");
69
+ }
70
+ templates = [...templates.filter((t) => t.id !== tpl.id), tpl];
71
+ break;
72
+ }
73
+ case "remove":
74
+ if (typeof body.id !== "string")
75
+ throw new Error("Invalid template id");
76
+ templates = templates.filter((t) => t.id !== body.id);
77
+ break;
78
+ case "reset":
79
+ templates = [];
80
+ break;
81
+ case "migrate": {
82
+ if (!Array.isArray(body.templates))
83
+ throw new Error("Invalid migration");
84
+ for (const value of body.templates) {
85
+ const tpl = parseStoredTemplate(value);
86
+ if (templates.some((t) => t.id === tpl.id))
87
+ continue;
88
+ if (tpl.command && templates.some((t) => t.command === tpl.command))
89
+ tpl.command = "";
90
+ templates.push(tpl);
91
+ }
92
+ break;
93
+ }
94
+ default:
95
+ throw new Error("Unknown template action");
96
+ }
97
+ if (templates.length > 500)
98
+ throw new Error("Too many templates");
99
+ writeJsonAtomicSync(file, templates);
100
+ res.json({ templates });
101
+ }
102
+ catch (error) {
103
+ res.status(400).json({ error: String(error) });
104
+ }
105
+ });
106
+ }
@@ -8,4 +8,4 @@
8
8
  * its own copy in web/src/protocol-version.ts; scripts/check-protocol-sync.mjs
9
9
  * verifies the two never drift.
10
10
  */
11
- export const PROTOCOL_VERSION = 38;
11
+ export const PROTOCOL_VERSION = 39;
@@ -25,6 +25,7 @@
25
25
  * 让服务起不来。它必须在任何 SDK 静态 import **之前**被加载(`--import <本文件>`,
26
26
  * 或前台启动时在 import 服务入口之前先 import 它)。
27
27
  */
28
+ import { registerBashProcessPatch } from "./patch-bash-process.js";
28
29
  import { existsSync, readFileSync } from "node:fs";
29
30
  import { registerHooks } from "node:module";
30
31
  import { dirname, join } from "node:path";
@@ -149,6 +150,7 @@ export function registerGlobalSdkPreference(mode = process.env.PI_WEB_SDK, fromF
149
150
  }
150
151
  }
151
152
  // ---- 副作用:被 `--import` 加载时立刻生效 --------------------------------
153
+ registerBashProcessPatch();
152
154
  const used = registerGlobalSdkPreference();
153
155
  if (used) {
154
156
  console.log(`[pi-web-ui] following a newer pi SDK on this machine: ${used.path} (v${used.version}; ` +