pi-web-ui 0.100.0 → 0.102.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 (82) hide show
  1. package/CHANGELOG.md +53 -1
  2. package/README.md +46 -44
  3. package/README.zh-CN.md +41 -39
  4. package/bin/pi-web-ui.mjs +17 -19
  5. package/dist/server/agent-formatters.js +191 -0
  6. package/dist/server/agent-service-daemon.js +1266 -0
  7. package/dist/server/agent-service.js +9884 -12815
  8. package/dist/server/approval-default-rules.js +158 -0
  9. package/dist/server/approval-rules.js +41 -167
  10. package/dist/server/ask-user-question-tool.js +104 -0
  11. package/dist/server/attachment-store.js +38 -1
  12. package/dist/server/bash-tool.js +83 -0
  13. package/dist/server/browser-page-tool.js +207 -0
  14. package/dist/server/client-id-utils.js +51 -0
  15. package/dist/server/client-state.js +38 -2
  16. package/dist/server/compaction-markers.js +34 -1
  17. package/dist/server/context-budget-runner.js +43 -0
  18. package/dist/server/dangling-tools.js +18 -5
  19. package/dist/server/delegate-mode.js +1 -0
  20. package/dist/server/dispatch-domain-handlers.js +631 -0
  21. package/dist/server/dispatch-plugin-handlers.js +300 -0
  22. package/dist/server/dsh/dsh-agent-service.js +30 -5
  23. package/dist/server/dsh/runtime/goal-rpc.mjs +5 -1
  24. package/dist/server/goal-evidence.js +9 -2
  25. package/dist/server/goal-service.js +1 -1
  26. package/dist/server/hashline-engine.js +1 -1
  27. package/dist/server/index.js +191 -969
  28. package/dist/server/left-panel-running.js +115 -0
  29. package/dist/server/lsp-tool.js +40 -12
  30. package/dist/server/markers-list-tool.js +34 -0
  31. package/dist/server/market-service.js +277 -0
  32. package/dist/server/mcp-bridge.js +137 -30
  33. package/dist/server/mcp-hot-reload.js +84 -27
  34. package/dist/server/mcp-manager.js +215 -0
  35. package/dist/server/message-entry-resolver.js +32 -0
  36. package/dist/server/orphan-manager.js +44 -0
  37. package/dist/server/persona-chain.js +63 -0
  38. package/dist/server/plan-mode.js +2 -0
  39. package/dist/server/plan-update-tool.js +96 -0
  40. package/dist/server/plugin-api-catalog.js +20 -0
  41. package/dist/server/plugin-facilities.js +13 -3
  42. package/dist/server/plugin-installer.js +6 -1
  43. package/dist/server/plugin-ui-slots.js +39 -0
  44. package/dist/server/plugins.js +72 -38
  45. package/dist/server/preset-fields.js +35 -0
  46. package/dist/server/preset-share.js +9 -0
  47. package/dist/server/process-utils.js +30 -0
  48. package/dist/server/prompt-assembler.js +80 -0
  49. package/dist/server/protocol-version.js +1 -1
  50. package/dist/server/scm-commitmsg.js +74 -0
  51. package/dist/server/serialize.js +97 -7
  52. package/dist/server/session-branch.js +367 -0
  53. package/dist/server/session-parser.js +235 -0
  54. package/dist/server/session-search.js +158 -0
  55. package/dist/server/settings-service.js +28 -1
  56. package/dist/server/skill-content-filler.js +33 -0
  57. package/dist/server/subagent-handoff.js +18 -0
  58. package/dist/server/subagent-helpers.js +88 -0
  59. package/dist/server/terminals.js +155 -58
  60. package/dist/server/tool-guards.js +527 -0
  61. package/dist/server/tool-host-factories.js +217 -0
  62. package/dist/server/tool-manager.js +30 -5
  63. package/dist/server/wait-subscription-scan.js +46 -1
  64. package/dist/server/workspace-snapshot.js +18 -0
  65. package/extensions/webui.ts +90 -24
  66. package/package.json +1 -1
  67. package/plugin-sdk/README.md +17 -0
  68. package/plugin-sdk/index.d.ts +17 -0
  69. package/plugin-sdk/index.mjs +5 -0
  70. package/plugins/catalog.json +20 -0
  71. package/themes/aetheris.css +3 -1
  72. package/themes/translucent.css +8 -1
  73. package/themes/transparent.css +9 -1
  74. package/themes/zhupi-dark.css +3 -14
  75. package/themes/zhupi.css +2 -16
  76. package/web/dist/assets/{TerminalPanel-C3I1Mc-C.js → TerminalPanel-CYGOzbPT.js} +1 -1
  77. package/web/dist/assets/index-CP71PHb6.js +680 -0
  78. package/web/dist/assets/index-ytRwL6j0.css +1 -0
  79. package/web/dist/index.html +2 -2
  80. package/web/dist/sw.js +1 -1
  81. package/web/dist/assets/index-B-E2EM_0.css +0 -1
  82. package/web/dist/assets/index-BYumAaGi.js +0 -379
@@ -12,6 +12,7 @@
12
12
  * `${pwd}` inside cwd/command resolves to the agent session's current working
13
13
  * directory (the same directory the agent operates in — see set_cwd).
14
14
  */
15
+ import { randomBytes } from "node:crypto";
15
16
  import { chmodSync, existsSync, readdirSync, realpathSync, statSync } from "node:fs";
16
17
  import { mkdir, readFile, writeFile } from "node:fs/promises";
17
18
  import { createRequire } from "node:module";
@@ -145,9 +146,20 @@ export function terminalIdleNotifyLines() {
145
146
  // ---------------------------------------------------------------------------
146
147
  // 终端接管 bash(terminal-backed bash tool)
147
148
  // ---------------------------------------------------------------------------
148
- /** 哨兵行:命令执行完后由 shell 打印,携带真实退出码。正则只匹配数字,
149
- * 因此不会误匹配回显里的 printf 格式串 `[pi-exit:%s]`。 */
150
- const BASH_SENTINEL_RE = /\[pi-exit:(\d+)\]/g;
149
+ /** 哨兵行:命令执行完后由 shell 打印,形如 `[pi-exit-<nonce>:<退出码>]`。
150
+ * nonce 每次调用随机生成(12 位 hex):回显里的 printf 格式串(`%s`)、真实输出里
151
+ * 的 `[pi-exit:42]` 之类字面量都不会与本次哨兵混淆(#572)。 */
152
+ const SENTINEL_NONCE_SRC = "[0-9a-f]{12}";
153
+ /** 任意 nonce 的哨兵(终端级通用等待用)。bash 工具自己的完成判定请用 sentinelReFor。 */
154
+ const BASH_SENTINEL_RE = new RegExp(`\\[pi-exit-${SENTINEL_NONCE_SRC}:(\\d+)\\]`, "g");
155
+ /** 本次调用的哨兵 nonce。 */
156
+ export function newSentinelNonce() {
157
+ return randomBytes(6).toString("hex");
158
+ }
159
+ /** 只匹配本次 nonce 的哨兵(bash 工具的完成判定只认自己注入的那一个)。 */
160
+ function sentinelReFor(nonce) {
161
+ return new RegExp(`\\[pi-exit-${nonce}:(\\d+)\\]`, "g");
162
+ }
151
163
  /** bash 阻塞循环 collected 的累积上限:超限丢最旧一半(见 bash 工具执行循环)。 */
152
164
  const BASH_COLLECT_MAX = 2 * 1024 * 1024;
153
165
  /**
@@ -157,7 +169,7 @@ const BASH_COLLECT_MAX = 2 * 1024 * 1024;
157
169
  * 后续哨兵;也避开交互 shell 的 bracketed-paste 对多行输入的特殊处理。
158
170
  * 多行脚本用 `$'...'` ANSI-C 引号转义后交给 eval(bash/zsh/busybox ash 都支持)。
159
171
  */
160
- export function buildTerminalBashLine(command, tailFile) {
172
+ export function buildTerminalBashLine(command, tailFile, nonce = newSentinelNonce()) {
161
173
  const trimmed = command.replace(/\s+$/, "");
162
174
  // 退出码取【第一个】命令(真正干活的那个)而非管道末尾命令:`head`/`grep`/`tail`
163
175
  // 在管道末尾会把退出码吞成自己的(head 恒 0、grep 无命恒 1)。`${PIPESTATUS:-$?}`
@@ -170,7 +182,7 @@ export function buildTerminalBashLine(command, tailFile) {
170
182
  ? `; tail -n ${Math.max(1, Math.floor(tailFile.lines))} -- '${tailFile.file.replace(/'/g, `'\\''`)}'`
171
183
  : "";
172
184
  // eslint-disable-next-line no-useless-escape -- \$? must reach the shell literally
173
- const sentinel = `__pi_rc=\${PIPESTATUS:-\$?}; [ "$__pi_rc" -eq 141 ] && __pi_rc=0${tailPart}; printf '\\n[pi-exit:%s]\\n' "$__pi_rc"`;
185
+ const sentinel = `__pi_rc=\${PIPESTATUS:-\$?}; [ "$__pi_rc" -eq 141 ] && __pi_rc=0${tailPart}; printf '\\n[pi-exit-${nonce}:%s]\\n' "$__pi_rc"`;
174
186
  if (trimmed.includes("\n")) {
175
187
  // 多行路径(行为保持):$'...' 转义后是一行物理输入,引号/换行全部字面化,
176
188
  // 以 `'` 收尾——`; ` 同行拼接哨兵不会被尾注释/尾管道/续行吞掉。
@@ -195,6 +207,7 @@ export function buildTerminalBashLine(command, tailFile) {
195
207
  *
196
208
  * - 尾随续行符 `\`:下一行被并入本命令,哨兵行成为命令的一部分。
197
209
  * - 未闭合引号:哨兵行被吞进字符串字面量,永远不会作为代码执行。
210
+ * - 未闭合的 `{}` / `()` 组:shell 停在 PS2 续行,哨兵永远不会执行(#573)。
198
211
  * - 多行命令:经 `$'...'` 转义单行化后引号/换行全部字面化,总是安全 → null。
199
212
  *
200
213
  * 扫描按 POSIX 引号语义跟踪 `'`/`"`/`` ` `` 三种引号与转义;`$'...'`(ANSI-C
@@ -208,6 +221,8 @@ export function sentinelUnsafeReason(command) {
208
221
  // 当前单引号是否 $' 开头(ANSI-C 引号,内含转义语义)
209
222
  let ansiC = false;
210
223
  let escaped = false;
224
+ // `{` / `(` 未闭合深度:残句(如 `{ a; b | tail -3`)注入后 shell 停在 PS2、哨兵永不执行(#573)
225
+ let depth = 0;
211
226
  for (let i = 0; i < trimmed.length; i++) {
212
227
  const ch = trimmed[i];
213
228
  if (quote) {
@@ -229,6 +244,8 @@ export function sentinelUnsafeReason(command) {
229
244
  escaped = false;
230
245
  continue;
231
246
  }
247
+ if (ch === "#" && (i === 0 || /\s/.test(trimmed[i - 1])))
248
+ break; // 注释到行尾,不再计引号/括号
232
249
  if (ch === "\\") {
233
250
  escaped = true;
234
251
  continue;
@@ -236,36 +253,73 @@ export function sentinelUnsafeReason(command) {
236
253
  if (ch === "'" || ch === '"' || ch === "`") {
237
254
  quote = ch;
238
255
  ansiC = ch === "'" && i > 0 && trimmed[i - 1] === "$";
256
+ continue;
239
257
  }
258
+ if (ch === "(" || ch === "{")
259
+ depth++;
260
+ else if ((ch === ")" || ch === "}") && depth > 0)
261
+ depth--;
240
262
  }
241
263
  if (quote !== null)
242
264
  return "unclosed_quote";
243
265
  // 扫描结束仍在转义态 = 最后一个字符是引号外的 `\`(尾随续行符)
244
266
  if (escaped)
245
267
  return "trailing_backslash";
268
+ if (depth > 0)
269
+ return "unclosed_group";
246
270
  return null;
247
271
  }
248
- /** 顶层(引号/反引号/转义外)按 `|` 拆分的管道元素。 */
272
+ /** 顶层(引号/反引号/转义外、且不在 `()` / `{}` 组内)按 `|` 拆分的管道元素。
273
+ * 组内的 `|`(`{ a; b | tail; }`)属于组本身,不是顶层管道(#573)。 */
249
274
  export function splitTopLevelPipes(cmd) {
275
+ return scanTopLevel(cmd).parts;
276
+ }
277
+ /** 顶层管道扫描:引号 / ANSI-C 引号 / 转义 / `||` 不拆;`()` `{}` 组内的 `|` 不拆。
278
+ * openGroups > 0 = 结尾仍有未闭合的组(调用方据此放弃拆管 / 拒注入)。 */
279
+ function scanTopLevel(cmd) {
250
280
  const parts = [];
251
281
  let cur = "";
252
282
  let quote = null;
283
+ // 当前单引号是否 $' 开头(ANSI-C 引号:内含 \' 等转义,不闭合引号)
284
+ let ansiC = false;
285
+ let depth = 0;
253
286
  for (let i = 0; i < cmd.length; i++) {
254
287
  const ch = cmd[i];
255
288
  if (quote) {
256
289
  cur += ch;
257
- if (ch === "\\" && quote !== "'" && quote !== "`" && i + 1 < cmd.length)
290
+ if (ch === "\\" && quote !== "`" && (quote !== "'" || ansiC) && i + 1 < cmd.length)
258
291
  cur += cmd[++i];
259
292
  else if (ch === quote)
260
293
  quote = null;
261
294
  continue;
262
295
  }
296
+ if (ch === "#" && (i === 0 || /\s/.test(cmd[i - 1]))) {
297
+ // 词首的 # 注释到行尾:之后的 | 和引号都不是 shell 结构(否则 `echo hi # don't` 会被当成未闭合引号)
298
+ cur += cmd.slice(i);
299
+ break;
300
+ }
301
+ if (ch === "\\" && i + 1 < cmd.length) {
302
+ // 引号外的转义:被转义字符原样保留(`\|` 是字面竖线,不是管道)
303
+ cur += ch + cmd[++i];
304
+ continue;
305
+ }
263
306
  if (ch === "'" || ch === '"' || ch === "`") {
264
307
  quote = ch;
308
+ ansiC = ch === "'" && i > 0 && cmd[i - 1] === "$";
265
309
  cur += ch;
266
310
  continue;
267
311
  }
268
- if (ch === "|") {
312
+ if (ch === "(" || ch === "{")
313
+ depth++;
314
+ else if ((ch === ")" || ch === "}") && depth > 0)
315
+ depth--;
316
+ if (ch === "|" && cmd[i + 1] === "|") {
317
+ // `||` 是逻辑或,不是管道
318
+ cur += "||";
319
+ i++;
320
+ continue;
321
+ }
322
+ if (ch === "|" && depth === 0) {
269
323
  parts.push(cur.trimEnd());
270
324
  cur = "";
271
325
  continue;
@@ -273,7 +327,7 @@ export function splitTopLevelPipes(cmd) {
273
327
  cur += ch;
274
328
  }
275
329
  parts.push(cur.trimEnd());
276
- return parts;
330
+ return { parts, openGroups: depth };
277
331
  }
278
332
  /** 从 tail 参数里解析行数:`-n 15` / `-n15` / `-15` / `--lines=15` / `--lines 15`。 */
279
333
  function parseTailLines(rest) {
@@ -301,8 +355,9 @@ export function detectTrailingLimiter(command) {
301
355
  // 管道段,拆掉后直接破坏命令语义。保守正确优先,宁可少优化。
302
356
  if (/\$\(|`/.test(command))
303
357
  return null;
304
- const parts = splitTopLevelPipes(command);
305
- if (parts.length < 2)
358
+ const { parts, openGroups } = scanTopLevel(command);
359
+ // 结尾仍有未闭合的 `{` / `(`:这条命令本身就是残的,拆管只会把组截断(#573)。
360
+ if (parts.length < 2 || openGroups > 0)
306
361
  return null;
307
362
  // 管道分隔处可能在 `|` 后留前导空白(`| tail`),trim 掉再匹配。
308
363
  const last = parts[parts.length - 1].trim();
@@ -810,7 +865,6 @@ export class TerminalManager {
810
865
  // last known size so the replacement matches the xterm's dimensions.
811
866
  if (!existing.exited) {
812
867
  this.flushPending(existing);
813
- existing.exited = true;
814
868
  this.killNative(existing);
815
869
  }
816
870
  cols = existing.cols || cols;
@@ -956,6 +1010,7 @@ export class TerminalManager {
956
1010
  this.queueOut(entry, data);
957
1011
  });
958
1012
  pty.onExit(({ exitCode }) => {
1013
+ entry.exited = true;
959
1014
  if (this.terms.get(id) !== entry)
960
1015
  return;
961
1016
  this.exit(id, exitCode);
@@ -1178,7 +1233,9 @@ export class TerminalManager {
1178
1233
  .filter((entry) => entry.output.length > 0)
1179
1234
  .map((entry) => ({ terminalId: entry.id, data: entry.output }));
1180
1235
  }
1181
- /** Read output after an absolute cursor. */
1236
+ /** Read output after an absolute cursor.
1237
+ * commandPending:终端接管 bash 注入的命令是否仍未见到退出码哨兵(即 shell 级 running
1238
+ * 之外的「这条命令结束了没有」)。手工 terminal_input 的命令没有哨兵,不计入。 */
1182
1239
  read(id, cursor = 0, maxBytes = 20_000) {
1183
1240
  const entry = this.find(id);
1184
1241
  if (!entry)
@@ -1190,6 +1247,7 @@ export class TerminalManager {
1190
1247
  cursor: end,
1191
1248
  running: !entry.exited,
1192
1249
  exitCode: entry.exitCode,
1250
+ commandPending: entry.sentinelPending === true,
1193
1251
  };
1194
1252
  }
1195
1253
  async waitForOutput(id, cursor, timeoutMs, signal) {
@@ -1409,7 +1467,6 @@ export class TerminalManager {
1409
1467
  for (const w of killedWatches)
1410
1468
  w.cb(null);
1411
1469
  this.flushPending(entry);
1412
- entry.exited = true;
1413
1470
  this.killNative(entry);
1414
1471
  this.terms.delete(id);
1415
1472
  this.emit({ type: "terminal_exit", terminalId: id, exitCode: null });
@@ -1474,6 +1531,7 @@ export class TerminalManager {
1474
1531
  const t = setTimeout(() => {
1475
1532
  if (entry.exited)
1476
1533
  return;
1534
+ entry.exited = true;
1477
1535
  try {
1478
1536
  entry.pty.kill();
1479
1537
  }
@@ -1503,7 +1561,6 @@ export class TerminalManager {
1503
1561
  this.disarmIdleWatch(entry);
1504
1562
  if (entry.exited)
1505
1563
  continue;
1506
- entry.exited = true;
1507
1564
  this.killNative(entry, shutdown);
1508
1565
  }
1509
1566
  for (const entry of this.terms.values()) {
@@ -1527,36 +1584,64 @@ export class TerminalManager {
1527
1584
  // ---------------------------------------------------------------------------
1528
1585
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1529
1586
  /** 取 collected 尾部里最后一个哨兵匹配(哨兵只可能出现在新输出的尾部)。 */
1530
- function lastSentinel(collected) {
1587
+ function lastSentinel(collected, nonce) {
1531
1588
  const tail = collected.length > 8000 ? collected.slice(-8000) : collected;
1532
- BASH_SENTINEL_RE.lastIndex = 0;
1533
- return [...tail.matchAll(BASH_SENTINEL_RE)].pop() ?? null;
1589
+ return [...tail.matchAll(sentinelReFor(nonce))].pop() ?? null;
1534
1590
  }
1535
- /** 去掉输入回显、哨兵及其后的 shell 提示符垃圾与 ANSI 序列,还原 bash 风格纯文本。 */
1536
- function cleanBashOutput(raw) {
1537
- let text = stripAnsi(raw).replace(/\r\n/g, "\n");
1538
- // 回显的命令行可能被 readline 折行拆成多行,按行剥不可靠——改为锚定
1539
- // printf 格式串字面量 [pi-exit:%s](真哨兵是数字版),连同其所在整行丢弃。
1540
- // 注意:同一命令会被回显两次(PTY 输入回显 + readline 提示符回显),需循环。
1541
- for (;;) {
1542
- const fmtIdx = text.indexOf("[pi-exit:%s]");
1543
- if (fmtIdx < 0)
1544
- break;
1545
- const nl = text.indexOf("\n", fmtIdx);
1546
- text = nl >= 0 ? text.slice(nl + 1) : "";
1591
+ /**
1592
+ * 去掉注入回显、哨兵及其后的 shell 提示符垃圾与 ANSI 序列,还原 bash 风格纯文本。
1593
+ *
1594
+ * 清洗只依赖两个与时序无关的锚点,不再假定「哨兵回显一定在真实输出之前」——那个假定
1595
+ * 在 Windows ConPTY 下不成立:shell 读到哨兵行才回显它,于是哨兵回显排在真实输出之后,
1596
+ * 旧实现按它截断会把输出整段吃掉、只剩 `[exit:0]`(#572 ①)。
1597
+ *
1598
+ * ① 含本次 nonce 哨兵格式串的行(`printf '…[pi-exit-<nonce>:%s]…'` 的回显,
1599
+ * 无论出现在输出前还是后)整行删除——nonce 随机,真实输出不可能与之相同。
1600
+ * ② 命令回显:第一次出现的命令首行(及其之前的提示符)整段丢弃——它总在真实输出之前。
1601
+ * 最后一个本次哨兵之后的内容是 shell 新提示符,整段截掉。
1602
+ */
1603
+ export function cleanBashOutput(raw, nonce, command = "") {
1604
+ const fmt = `[pi-exit-${nonce}:%s]`;
1605
+ let lines = stripAnsi(raw)
1606
+ .replace(/\r\n/g, "\n")
1607
+ .split("\n")
1608
+ .filter((line) => !line.includes(fmt));
1609
+ const anchor = (command.split("\n")[0] ?? "").trim().slice(0, 80);
1610
+ // 命令回显前那一行提示符(如 `user@host MINGW64 /cwd`):收尾时用它识别「哨兵前残留的新提示符」。
1611
+ let promptLine = "";
1612
+ if (anchor) {
1613
+ const echoIdx = lines.findIndex((line) => line.includes(anchor));
1614
+ if (echoIdx >= 0) {
1615
+ for (let i = echoIdx - 1; i >= 0 && !promptLine; i--) {
1616
+ const t = lines[i].trim();
1617
+ if (t && t !== "$")
1618
+ promptLine = t;
1619
+ }
1620
+ lines = lines.slice(echoIdx + 1);
1621
+ }
1547
1622
  }
1548
- // 最后一个哨兵之后的内容全是 shell 新提示符——整段截掉。
1549
- BASH_SENTINEL_RE.lastIndex = 0;
1623
+ // 最后一个本次哨兵之后的内容全是 shell 新提示符——整段截掉。
1624
+ const text = lines.join("\n");
1625
+ const re = sentinelReFor(nonce);
1550
1626
  let last = null;
1551
- for (let m = BASH_SENTINEL_RE.exec(text); m; m = BASH_SENTINEL_RE.exec(text)) {
1627
+ for (let m = re.exec(text); m; m = re.exec(text)) {
1552
1628
  last = m;
1553
1629
  }
1554
- if (last)
1555
- text = text.slice(0, last.index);
1556
- const lines = text.split("\n");
1557
- while (lines.length > 0 && !lines[lines.length - 1].trim())
1558
- lines.pop();
1559
- return truncateMiddle(lines.join("\n").trim());
1630
+ const kept = (last ? text.slice(0, last.index) : text).split("\n").map((line) => line.trimEnd());
1631
+ // 收尾残留:空行、裸 `$`、与命令前相同的提示符行(ConPTY 在哨兵回显前重打了一次提示符)。
1632
+ // 提示符的 `user@host` 段:让 cd 之后路径变了的提示符也能识别。
1633
+ const promptHead = promptLine.match(/^\S+@\S+/)?.[0] ?? "";
1634
+ const isResidue = (line) => {
1635
+ const t = line.trim();
1636
+ if (t === "" || t === "$")
1637
+ return true;
1638
+ if (promptLine !== "" && t === promptLine)
1639
+ return true;
1640
+ return promptHead !== "" && t.startsWith(`${promptHead} `);
1641
+ };
1642
+ while (kept.length > 0 && isResidue(kept[kept.length - 1]))
1643
+ kept.pop();
1644
+ return truncateMiddle(kept.join("\n").trim());
1560
1645
  }
1561
1646
  /**
1562
1647
  * 终端接管的 bash 工具:覆盖 SDK 内置 bash,执行体把命令写进可见终端并等哨兵
@@ -1632,6 +1717,23 @@ export function makeTerminalBashTool(terminals, opts) {
1632
1717
  parameters: BASH_PARAMETERS,
1633
1718
  execute: async (_id, p, signal) => {
1634
1719
  const lang = opts.lang?.() ?? "en";
1720
+ // 语法不完整的命令(续行符结尾 / 未闭合引号 / 未闭合括号组):交互 shell 会停在续行提示符
1721
+ // (PS2)零执行,且无法注入退出码哨兵——没有任何办法得知它何时结束。直接拒绝,不建终端、
1722
+ // 不注入,避免空等 60 秒后回报「仍在后台运行」这种与事实相反的状态(#571)。
1723
+ const incomplete = sentinelUnsafeReason(detectTrailingLimiter(p.command)?.base ?? p.command);
1724
+ if (incomplete) {
1725
+ const reasonZh = incomplete === "trailing_backslash"
1726
+ ? "以续行符 \\ 结尾"
1727
+ : incomplete === "unclosed_quote"
1728
+ ? "存在未闭合引号"
1729
+ : "存在未闭合的 { } / ( ) 组";
1730
+ const reasonEn = incomplete === "trailing_backslash"
1731
+ ? "ends with a line-continuation backslash"
1732
+ : incomplete === "unclosed_quote"
1733
+ ? "has an unclosed quote"
1734
+ : "has an unclosed { } / ( ) group";
1735
+ throw new Error(pick(lang, `命令语法不完整(${reasonZh}),未执行。终端接管 bash 无法为它注入退出码哨兵,残句还会让 shell 停在续行提示符、零执行。请补全引号 / 续行符 / 括号后重试。`, `Command is syntactically incomplete (${reasonEn}); nothing was executed. The terminal bash path cannot inject an exit-code sentinel here, and the leftover fragment would leave the shell waiting at a continuation prompt. Complete the quote / continuation / bracket and retry.`, "terminals.bash.incomplete"));
1736
+ }
1635
1737
  const persist = p.persist ?? opts.defaultPersist();
1636
1738
  // create() 对已存活的同名终端原样返回、对已退出的原地重启。
1637
1739
  // forceBash:该终端永远跑 bash(而非用户登录 shell),模型写的
@@ -1689,17 +1791,10 @@ export function makeTerminalBashTool(terminals, opts) {
1689
1791
  let collected = "";
1690
1792
  let cursor = start;
1691
1793
  let lastDataAt = Date.now();
1692
- // 尾随续行符/未闭合引号的命令无法安全注入哨兵(哨兵行会被并入命令或
1693
- // 吞进字符串):按无退出码模式执行,靠静默/超时/总时长解阻收尾并注明。
1694
- const sentinelUnsafe = sentinelUnsafeReason(runCommand);
1695
- const sentinelNote = sentinelUnsafe
1696
- ? pick(lang, `\n[注:命令以${sentinelUnsafe === "trailing_backslash" ? "续行符 \\" : "未闭合引号"}结尾,无法注入退出码哨兵——已按无退出码模式执行,拿不到真实 exit code。建议拆分成更简单的单行命令重试。]`, `\n[Note: the command ends with ${sentinelUnsafe === "trailing_backslash" ? "a line-continuation backslash" : "an unclosed quote"}; the exit-code sentinel could not be injected — it ran without exit-code detection. Prefer splitting it into simpler single-line commands.]`, "terminals.bash.nosentinel.note")
1697
- : "";
1698
- // 标记「有哨兵命令在跑」:terminal_wait 据此区分等待与空闲。
1699
- // 无哨兵命令没有可等待的哨兵,标记反而误导 terminal_wait。
1700
- if (!sentinelUnsafe)
1701
- terminals.setSentinelPending(termId, true);
1702
- const inputErr = terminals.inputChecked(termId, buildTerminalBashLine(runCommand, tailFile) + "\r");
1794
+ const nonce = newSentinelNonce();
1795
+ // 标记「有哨兵命令在跑」:terminal_wait / terminal_read 据此区分等待与空闲。
1796
+ terminals.setSentinelPending(termId, true);
1797
+ const inputErr = terminals.inputChecked(termId, buildTerminalBashLine(runCommand, tailFile, nonce) + "\r");
1703
1798
  if (inputErr)
1704
1799
  throw new Error(inputErr);
1705
1800
  for (;;) {
@@ -1723,11 +1818,11 @@ export function makeTerminalBashTool(terminals, opts) {
1723
1818
  collected = collected.slice(collected.length - BASH_COLLECT_MAX / 2);
1724
1819
  }
1725
1820
  }
1726
- const m = lastSentinel(collected);
1821
+ const m = lastSentinel(collected, nonce);
1727
1822
  if (m) {
1728
1823
  terminals.setSentinelPending(termId, false);
1729
1824
  closeOneShot();
1730
- const text = applyHeadTail(cleanBashOutput(collected), p.head, effectiveTail, lang);
1825
+ const text = applyHeadTail(cleanBashOutput(collected, nonce, runCommand), p.head, effectiveTail, lang);
1731
1826
  return {
1732
1827
  content: [
1733
1828
  {
@@ -1743,15 +1838,15 @@ export function makeTerminalBashTool(terminals, opts) {
1743
1838
  terminals.inputChecked(termId, "\x03");
1744
1839
  closeOneShot();
1745
1840
  const timeoutPartial = truncateMiddle(stripAnsi(collected), 4000);
1746
- throw new Error(pick(lang, `Command timed out after ${p.timeout}s(已发 Ctrl+C;已有输出:${timeoutPartial})${sentinelNote}`, `Command timed out after ${p.timeout}s (sent Ctrl+C; partial output: ${timeoutPartial})${sentinelNote}`, "terminals.bash.timeout", { "p.timeout": p.timeout, timeoutPartial }));
1841
+ throw new Error(pick(lang, `Command timed out after ${p.timeout}s(已发 Ctrl+C;已有输出:${timeoutPartial})`, `Command timed out after ${p.timeout}s (sent Ctrl+C; partial output: ${timeoutPartial})`, "terminals.bash.timeout", { "p.timeout": p.timeout, timeoutPartial }));
1747
1842
  }
1748
1843
  // 静默解阻(仅持久终端):转后台 + 注册完成观察器,立即把控制权还给模型。
1749
1844
  if (persist && idleMs > 0 && Date.now() - lastDataAt >= idleMs) {
1750
- return backgroundResult(terminals, opts, runCommand, applyHeadTail(cleanBashOutput(collected), p.head, effectiveTail, lang) + sentinelNote, Math.round((Date.now() - lastDataAt) / 1000), lang, termId, persist, "idle");
1845
+ return backgroundResult(terminals, opts, runCommand, applyHeadTail(cleanBashOutput(collected, nonce, runCommand), p.head, effectiveTail, lang), Math.round((Date.now() - lastDataAt) / 1000), lang, nonce, termId, persist, "idle");
1751
1846
  }
1752
1847
  // 总时长解阻(持久与一次性终端):前台运行达到上限,转入后台继续执行,避免卡死。
1753
1848
  if (maxForegroundMs > 0 && Date.now() - startTime >= maxForegroundMs) {
1754
- return backgroundResult(terminals, opts, runCommand, applyHeadTail(cleanBashOutput(collected), p.head, effectiveTail, lang) + sentinelNote, Math.round((Date.now() - startTime) / 1000), lang, termId, persist, "elapsed");
1849
+ return backgroundResult(terminals, opts, runCommand, applyHeadTail(cleanBashOutput(collected, nonce, runCommand), p.head, effectiveTail, lang), Math.round((Date.now() - startTime) / 1000), lang, nonce, termId, persist, "elapsed");
1755
1850
  }
1756
1851
  }
1757
1852
  }
@@ -1762,8 +1857,8 @@ export function makeTerminalBashTool(terminals, opts) {
1762
1857
  });
1763
1858
  }
1764
1859
  /** 静默 / 总时长解阻路径:注册完成观察器后立即返回「仍在后台运行」。 */
1765
- function backgroundResult(terminals, opts, command, partialText, durationSeconds, lang, termId = "ai-bash", persist = true, reason = "idle") {
1766
- terminals.watchOutput(termId, BASH_SENTINEL_RE, (m) => {
1860
+ function backgroundResult(terminals, opts, command, partialText, durationSeconds, lang, nonce, termId = "ai-bash", persist = true, reason = "idle") {
1861
+ terminals.watchOutput(termId, sentinelReFor(nonce), (m) => {
1767
1862
  // 后台命令最终结束(或终端被关)→ 清除待决标记,terminal_wait 不再适用。
1768
1863
  terminals.setSentinelPending(termId, false);
1769
1864
  opts.notifyBackgroundDone({
@@ -1960,7 +2055,9 @@ lang, options) {
1960
2055
  label: "Read terminal output",
1961
2056
  description: "Read incremental output from a persistent PTY. " +
1962
2057
  "Keep the returned cursor and pass it on the next read; " +
1963
- "optionally wait for new output or process exit.",
2058
+ "optionally wait for new output or process exit. " +
2059
+ "commandPending=true means a bash-tool command has not reported its exit code yet " +
2060
+ "(manual terminal_input commands are not tracked).",
1964
2061
  parameters: Type.Object({
1965
2062
  terminalId: Type.String(),
1966
2063
  cursor: Type.Optional(Type.Integer({ minimum: 0 })),