pi-web-ui 0.99.0 → 0.101.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.
- package/CHANGELOG.md +90 -1
- package/README.md +48 -45
- package/README.zh-CN.md +43 -40
- package/bin/pi-web-ui.mjs +172 -40
- package/dist/server/agent-formatters.js +191 -0
- package/dist/server/agent-service-daemon.js +1266 -0
- package/dist/server/agent-service.js +9851 -11892
- package/dist/server/approval-default-rules.js +158 -0
- package/dist/server/approval-rules.js +130 -184
- package/dist/server/ask-user-question-tool.js +94 -0
- package/dist/server/attachment-store.js +38 -1
- package/dist/server/attachments.js +55 -0
- package/dist/server/bash-tool.js +83 -0
- package/dist/server/bg-servers.js +82 -2
- package/dist/server/browser-page-tool.js +207 -0
- package/dist/server/claim-files-tool.js +4 -4
- package/dist/server/client-id-utils.js +51 -0
- package/dist/server/client-state.js +63 -1
- package/dist/server/compact-context-tool.js +10 -9
- package/dist/server/compaction-markers.js +34 -1
- package/dist/server/context-budget-runner.js +43 -0
- package/dist/server/conversation-read-tool.js +7 -8
- package/dist/server/conversation-touches.js +19 -0
- package/dist/server/dangling-tools.js +18 -5
- package/dist/server/delegate-mode.js +1 -0
- package/dist/server/delegate-task.js +10 -14
- package/dist/server/dispatch-domain-handlers.js +631 -0
- package/dist/server/dispatch-plugin-handlers.js +300 -0
- package/dist/server/dsh/dsh-agent-service.js +125 -13
- package/dist/server/edit-soft-tool.js +10 -12
- package/dist/server/eval-tool.js +4 -5
- package/dist/server/goal-evidence.js +180 -0
- package/dist/server/goal-service.js +49 -9
- package/dist/server/hashline-engine.js +199 -32
- package/dist/server/index.js +212 -944
- package/dist/server/left-panel-running.js +115 -0
- package/dist/server/load-tools-tool.js +100 -0
- package/dist/server/lsp-tool.js +50 -28
- package/dist/server/marker-service.js +53 -12
- package/dist/server/markers/builtins/action.js +108 -0
- package/dist/server/markers/index.js +4 -1
- package/dist/server/markers-list-tool.js +34 -0
- package/dist/server/market-service.js +277 -0
- package/dist/server/mcp-bridge.js +137 -30
- package/dist/server/mcp-hot-reload.js +84 -27
- package/dist/server/mcp-manager.js +215 -0
- package/dist/server/message-entry-resolver.js +32 -0
- package/dist/server/orphan-manager.js +44 -0
- package/dist/server/patch-remote-catalog.js +28 -10
- package/dist/server/patch-tool.js +9 -8
- package/dist/server/persona-chain.js +63 -0
- package/dist/server/plan-mode.js +9 -6
- package/dist/server/plan-update-tool.js +96 -0
- package/dist/server/plugin-api-catalog.js +30 -3
- package/dist/server/plugin-conversation-view.js +47 -0
- package/dist/server/plugin-facilities.js +13 -3
- package/dist/server/plugin-ui-slots.js +39 -0
- package/dist/server/plugins.js +183 -63
- package/dist/server/present-files-tool.js +10 -11
- package/dist/server/preset-fields.js +700 -0
- package/dist/server/preset-share.js +1179 -0
- package/dist/server/process-utils.js +30 -0
- package/dist/server/prompt-assembler.js +80 -0
- package/dist/server/prompt-composer.js +23 -9
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/read-tool.js +8 -10
- package/dist/server/resolve-global-sdk.js +80 -18
- package/dist/server/schedule-agent-tool.js +147 -146
- package/dist/server/scm-commitmsg.js +74 -0
- package/dist/server/sdk-origin.js +125 -37
- package/dist/server/serialize.js +97 -7
- package/dist/server/session-branch.js +367 -0
- package/dist/server/session-parser.js +235 -0
- package/dist/server/session-search.js +158 -0
- package/dist/server/settings-service.js +115 -84
- package/dist/server/skill-content-filler.js +33 -0
- package/dist/server/skill-tool.js +3 -4
- package/dist/server/subagent-handoff.js +18 -0
- package/dist/server/subagent-helpers.js +88 -0
- package/dist/server/subagents.js +15 -22
- package/dist/server/terminals.js +171 -91
- package/dist/server/tool-approval.js +3 -1
- package/dist/server/tool-guards.js +527 -0
- package/dist/server/tool-host-factories.js +217 -0
- package/dist/server/tool-manager.js +84 -23
- package/dist/server/tool-prompt-overrides.js +158 -0
- package/dist/server/tool-prompts.js +42 -0
- package/dist/server/tool-signature.js +104 -0
- package/dist/server/wait-subscription-scan.js +46 -1
- package/dist/server/workspace-snapshot.js +60 -11
- package/extensions/webui.ts +90 -24
- package/package.json +5 -3
- package/plugin-sdk/README.md +25 -4
- package/plugin-sdk/import-check.mjs +210 -0
- package/plugin-sdk/index.d.ts +21 -1
- package/plugin-sdk/index.mjs +6 -0
- package/plugins/catalog.json +53 -2
- package/themes/aetheris.css +3 -1
- package/themes/translucent.css +8 -1
- package/themes/transparent.css +9 -1
- package/themes/zhupi-dark.css +1 -1
- package/themes/zhupi.css +1 -1
- package/web/dist/assets/{TerminalPanel-NerrJlTS.js → TerminalPanel-DD7I5_aC.js} +2 -2
- package/web/dist/assets/index-CpjA1YdT.css +1 -0
- package/web/dist/assets/index-nKn87VuM.js +678 -0
- package/web/dist/index.html +2 -2
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/index-BdMaGCcs.css +0 -1
- package/web/dist/assets/index-ByCBN4Kt.js +0 -368
package/dist/server/terminals.js
CHANGED
|
@@ -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";
|
|
@@ -24,6 +25,7 @@ import "./patch-node-pty.js";
|
|
|
24
25
|
import { spawn } from "node-pty";
|
|
25
26
|
import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
26
27
|
import { Type } from "typebox";
|
|
28
|
+
import { BASH_DESCRIPTION, BASH_PARAMETERS, BASH_PROMPT_GUIDELINES, BASH_PROMPT_SNIPPET } from "./tool-prompts.js";
|
|
27
29
|
import { pick } from "./i18n.js";
|
|
28
30
|
/** Location of the command list for a project: <workspaceRoot>/.pi/commands.json */
|
|
29
31
|
export function commandsFilePath(workspaceRoot) {
|
|
@@ -144,9 +146,20 @@ export function terminalIdleNotifyLines() {
|
|
|
144
146
|
// ---------------------------------------------------------------------------
|
|
145
147
|
// 终端接管 bash(terminal-backed bash tool)
|
|
146
148
|
// ---------------------------------------------------------------------------
|
|
147
|
-
/** 哨兵行:命令执行完后由 shell
|
|
148
|
-
*
|
|
149
|
-
|
|
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
|
+
}
|
|
150
163
|
/** bash 阻塞循环 collected 的累积上限:超限丢最旧一半(见 bash 工具执行循环)。 */
|
|
151
164
|
const BASH_COLLECT_MAX = 2 * 1024 * 1024;
|
|
152
165
|
/**
|
|
@@ -156,7 +169,7 @@ const BASH_COLLECT_MAX = 2 * 1024 * 1024;
|
|
|
156
169
|
* 后续哨兵;也避开交互 shell 的 bracketed-paste 对多行输入的特殊处理。
|
|
157
170
|
* 多行脚本用 `$'...'` ANSI-C 引号转义后交给 eval(bash/zsh/busybox ash 都支持)。
|
|
158
171
|
*/
|
|
159
|
-
export function buildTerminalBashLine(command, tailFile) {
|
|
172
|
+
export function buildTerminalBashLine(command, tailFile, nonce = newSentinelNonce()) {
|
|
160
173
|
const trimmed = command.replace(/\s+$/, "");
|
|
161
174
|
// 退出码取【第一个】命令(真正干活的那个)而非管道末尾命令:`head`/`grep`/`tail`
|
|
162
175
|
// 在管道末尾会把退出码吞成自己的(head 恒 0、grep 无命恒 1)。`${PIPESTATUS:-$?}`
|
|
@@ -169,7 +182,7 @@ export function buildTerminalBashLine(command, tailFile) {
|
|
|
169
182
|
? `; tail -n ${Math.max(1, Math.floor(tailFile.lines))} -- '${tailFile.file.replace(/'/g, `'\\''`)}'`
|
|
170
183
|
: "";
|
|
171
184
|
// eslint-disable-next-line no-useless-escape -- \$? must reach the shell literally
|
|
172
|
-
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"`;
|
|
173
186
|
if (trimmed.includes("\n")) {
|
|
174
187
|
// 多行路径(行为保持):$'...' 转义后是一行物理输入,引号/换行全部字面化,
|
|
175
188
|
// 以 `'` 收尾——`; ` 同行拼接哨兵不会被尾注释/尾管道/续行吞掉。
|
|
@@ -194,6 +207,7 @@ export function buildTerminalBashLine(command, tailFile) {
|
|
|
194
207
|
*
|
|
195
208
|
* - 尾随续行符 `\`:下一行被并入本命令,哨兵行成为命令的一部分。
|
|
196
209
|
* - 未闭合引号:哨兵行被吞进字符串字面量,永远不会作为代码执行。
|
|
210
|
+
* - 未闭合的 `{}` / `()` 组:shell 停在 PS2 续行,哨兵永远不会执行(#573)。
|
|
197
211
|
* - 多行命令:经 `$'...'` 转义单行化后引号/换行全部字面化,总是安全 → null。
|
|
198
212
|
*
|
|
199
213
|
* 扫描按 POSIX 引号语义跟踪 `'`/`"`/`` ` `` 三种引号与转义;`$'...'`(ANSI-C
|
|
@@ -207,6 +221,8 @@ export function sentinelUnsafeReason(command) {
|
|
|
207
221
|
// 当前单引号是否 $' 开头(ANSI-C 引号,内含转义语义)
|
|
208
222
|
let ansiC = false;
|
|
209
223
|
let escaped = false;
|
|
224
|
+
// `{` / `(` 未闭合深度:残句(如 `{ a; b | tail -3`)注入后 shell 停在 PS2、哨兵永不执行(#573)
|
|
225
|
+
let depth = 0;
|
|
210
226
|
for (let i = 0; i < trimmed.length; i++) {
|
|
211
227
|
const ch = trimmed[i];
|
|
212
228
|
if (quote) {
|
|
@@ -228,6 +244,8 @@ export function sentinelUnsafeReason(command) {
|
|
|
228
244
|
escaped = false;
|
|
229
245
|
continue;
|
|
230
246
|
}
|
|
247
|
+
if (ch === "#" && (i === 0 || /\s/.test(trimmed[i - 1])))
|
|
248
|
+
break; // 注释到行尾,不再计引号/括号
|
|
231
249
|
if (ch === "\\") {
|
|
232
250
|
escaped = true;
|
|
233
251
|
continue;
|
|
@@ -235,36 +253,73 @@ export function sentinelUnsafeReason(command) {
|
|
|
235
253
|
if (ch === "'" || ch === '"' || ch === "`") {
|
|
236
254
|
quote = ch;
|
|
237
255
|
ansiC = ch === "'" && i > 0 && trimmed[i - 1] === "$";
|
|
256
|
+
continue;
|
|
238
257
|
}
|
|
258
|
+
if (ch === "(" || ch === "{")
|
|
259
|
+
depth++;
|
|
260
|
+
else if ((ch === ")" || ch === "}") && depth > 0)
|
|
261
|
+
depth--;
|
|
239
262
|
}
|
|
240
263
|
if (quote !== null)
|
|
241
264
|
return "unclosed_quote";
|
|
242
265
|
// 扫描结束仍在转义态 = 最后一个字符是引号外的 `\`(尾随续行符)
|
|
243
266
|
if (escaped)
|
|
244
267
|
return "trailing_backslash";
|
|
268
|
+
if (depth > 0)
|
|
269
|
+
return "unclosed_group";
|
|
245
270
|
return null;
|
|
246
271
|
}
|
|
247
|
-
/**
|
|
272
|
+
/** 顶层(引号/反引号/转义外、且不在 `()` / `{}` 组内)按 `|` 拆分的管道元素。
|
|
273
|
+
* 组内的 `|`(`{ a; b | tail; }`)属于组本身,不是顶层管道(#573)。 */
|
|
248
274
|
export function splitTopLevelPipes(cmd) {
|
|
275
|
+
return scanTopLevel(cmd).parts;
|
|
276
|
+
}
|
|
277
|
+
/** 顶层管道扫描:引号 / ANSI-C 引号 / 转义 / `||` 不拆;`()` `{}` 组内的 `|` 不拆。
|
|
278
|
+
* openGroups > 0 = 结尾仍有未闭合的组(调用方据此放弃拆管 / 拒注入)。 */
|
|
279
|
+
function scanTopLevel(cmd) {
|
|
249
280
|
const parts = [];
|
|
250
281
|
let cur = "";
|
|
251
282
|
let quote = null;
|
|
283
|
+
// 当前单引号是否 $' 开头(ANSI-C 引号:内含 \' 等转义,不闭合引号)
|
|
284
|
+
let ansiC = false;
|
|
285
|
+
let depth = 0;
|
|
252
286
|
for (let i = 0; i < cmd.length; i++) {
|
|
253
287
|
const ch = cmd[i];
|
|
254
288
|
if (quote) {
|
|
255
289
|
cur += ch;
|
|
256
|
-
if (ch === "\\" && quote !== "
|
|
290
|
+
if (ch === "\\" && quote !== "`" && (quote !== "'" || ansiC) && i + 1 < cmd.length)
|
|
257
291
|
cur += cmd[++i];
|
|
258
292
|
else if (ch === quote)
|
|
259
293
|
quote = null;
|
|
260
294
|
continue;
|
|
261
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
|
+
}
|
|
262
306
|
if (ch === "'" || ch === '"' || ch === "`") {
|
|
263
307
|
quote = ch;
|
|
308
|
+
ansiC = ch === "'" && i > 0 && cmd[i - 1] === "$";
|
|
264
309
|
cur += ch;
|
|
265
310
|
continue;
|
|
266
311
|
}
|
|
267
|
-
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) {
|
|
268
323
|
parts.push(cur.trimEnd());
|
|
269
324
|
cur = "";
|
|
270
325
|
continue;
|
|
@@ -272,7 +327,7 @@ export function splitTopLevelPipes(cmd) {
|
|
|
272
327
|
cur += ch;
|
|
273
328
|
}
|
|
274
329
|
parts.push(cur.trimEnd());
|
|
275
|
-
return parts;
|
|
330
|
+
return { parts, openGroups: depth };
|
|
276
331
|
}
|
|
277
332
|
/** 从 tail 参数里解析行数:`-n 15` / `-n15` / `-15` / `--lines=15` / `--lines 15`。 */
|
|
278
333
|
function parseTailLines(rest) {
|
|
@@ -300,8 +355,9 @@ export function detectTrailingLimiter(command) {
|
|
|
300
355
|
// 管道段,拆掉后直接破坏命令语义。保守正确优先,宁可少优化。
|
|
301
356
|
if (/\$\(|`/.test(command))
|
|
302
357
|
return null;
|
|
303
|
-
const parts =
|
|
304
|
-
|
|
358
|
+
const { parts, openGroups } = scanTopLevel(command);
|
|
359
|
+
// 结尾仍有未闭合的 `{` / `(`:这条命令本身就是残的,拆管只会把组截断(#573)。
|
|
360
|
+
if (parts.length < 2 || openGroups > 0)
|
|
305
361
|
return null;
|
|
306
362
|
// 管道分隔处可能在 `|` 后留前导空白(`| tail`),trim 掉再匹配。
|
|
307
363
|
const last = parts[parts.length - 1].trim();
|
|
@@ -809,7 +865,6 @@ export class TerminalManager {
|
|
|
809
865
|
// last known size so the replacement matches the xterm's dimensions.
|
|
810
866
|
if (!existing.exited) {
|
|
811
867
|
this.flushPending(existing);
|
|
812
|
-
existing.exited = true;
|
|
813
868
|
this.killNative(existing);
|
|
814
869
|
}
|
|
815
870
|
cols = existing.cols || cols;
|
|
@@ -955,6 +1010,7 @@ export class TerminalManager {
|
|
|
955
1010
|
this.queueOut(entry, data);
|
|
956
1011
|
});
|
|
957
1012
|
pty.onExit(({ exitCode }) => {
|
|
1013
|
+
entry.exited = true;
|
|
958
1014
|
if (this.terms.get(id) !== entry)
|
|
959
1015
|
return;
|
|
960
1016
|
this.exit(id, exitCode);
|
|
@@ -1177,7 +1233,9 @@ export class TerminalManager {
|
|
|
1177
1233
|
.filter((entry) => entry.output.length > 0)
|
|
1178
1234
|
.map((entry) => ({ terminalId: entry.id, data: entry.output }));
|
|
1179
1235
|
}
|
|
1180
|
-
/** Read output after an absolute cursor.
|
|
1236
|
+
/** Read output after an absolute cursor.
|
|
1237
|
+
* commandPending:终端接管 bash 注入的命令是否仍未见到退出码哨兵(即 shell 级 running
|
|
1238
|
+
* 之外的「这条命令结束了没有」)。手工 terminal_input 的命令没有哨兵,不计入。 */
|
|
1181
1239
|
read(id, cursor = 0, maxBytes = 20_000) {
|
|
1182
1240
|
const entry = this.find(id);
|
|
1183
1241
|
if (!entry)
|
|
@@ -1189,6 +1247,7 @@ export class TerminalManager {
|
|
|
1189
1247
|
cursor: end,
|
|
1190
1248
|
running: !entry.exited,
|
|
1191
1249
|
exitCode: entry.exitCode,
|
|
1250
|
+
commandPending: entry.sentinelPending === true,
|
|
1192
1251
|
};
|
|
1193
1252
|
}
|
|
1194
1253
|
async waitForOutput(id, cursor, timeoutMs, signal) {
|
|
@@ -1408,7 +1467,6 @@ export class TerminalManager {
|
|
|
1408
1467
|
for (const w of killedWatches)
|
|
1409
1468
|
w.cb(null);
|
|
1410
1469
|
this.flushPending(entry);
|
|
1411
|
-
entry.exited = true;
|
|
1412
1470
|
this.killNative(entry);
|
|
1413
1471
|
this.terms.delete(id);
|
|
1414
1472
|
this.emit({ type: "terminal_exit", terminalId: id, exitCode: null });
|
|
@@ -1473,6 +1531,7 @@ export class TerminalManager {
|
|
|
1473
1531
|
const t = setTimeout(() => {
|
|
1474
1532
|
if (entry.exited)
|
|
1475
1533
|
return;
|
|
1534
|
+
entry.exited = true;
|
|
1476
1535
|
try {
|
|
1477
1536
|
entry.pty.kill();
|
|
1478
1537
|
}
|
|
@@ -1502,7 +1561,6 @@ export class TerminalManager {
|
|
|
1502
1561
|
this.disarmIdleWatch(entry);
|
|
1503
1562
|
if (entry.exited)
|
|
1504
1563
|
continue;
|
|
1505
|
-
entry.exited = true;
|
|
1506
1564
|
this.killNative(entry, shutdown);
|
|
1507
1565
|
}
|
|
1508
1566
|
for (const entry of this.terms.values()) {
|
|
@@ -1526,36 +1584,64 @@ export class TerminalManager {
|
|
|
1526
1584
|
// ---------------------------------------------------------------------------
|
|
1527
1585
|
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1528
1586
|
/** 取 collected 尾部里最后一个哨兵匹配(哨兵只可能出现在新输出的尾部)。 */
|
|
1529
|
-
function lastSentinel(collected) {
|
|
1587
|
+
function lastSentinel(collected, nonce) {
|
|
1530
1588
|
const tail = collected.length > 8000 ? collected.slice(-8000) : collected;
|
|
1531
|
-
|
|
1532
|
-
return [...tail.matchAll(BASH_SENTINEL_RE)].pop() ?? null;
|
|
1589
|
+
return [...tail.matchAll(sentinelReFor(nonce))].pop() ?? null;
|
|
1533
1590
|
}
|
|
1534
|
-
/**
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
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
|
+
}
|
|
1546
1622
|
}
|
|
1547
|
-
//
|
|
1548
|
-
|
|
1623
|
+
// 最后一个本次哨兵之后的内容全是 shell 新提示符——整段截掉。
|
|
1624
|
+
const text = lines.join("\n");
|
|
1625
|
+
const re = sentinelReFor(nonce);
|
|
1549
1626
|
let last = null;
|
|
1550
|
-
for (let m =
|
|
1627
|
+
for (let m = re.exec(text); m; m = re.exec(text)) {
|
|
1551
1628
|
last = m;
|
|
1552
1629
|
}
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
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());
|
|
1559
1645
|
}
|
|
1560
1646
|
/**
|
|
1561
1647
|
* 终端接管的 bash 工具:覆盖 SDK 内置 bash,执行体把命令写进可见终端并等哨兵
|
|
@@ -1623,33 +1709,31 @@ export function makeTerminalBashTool(terminals, opts) {
|
|
|
1623
1709
|
return defineTool({
|
|
1624
1710
|
name: "bash",
|
|
1625
1711
|
label: "Run bash command",
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
promptSnippet: "run shell commands (persist=true keeps the terminal alive across calls)",
|
|
1633
|
-
parameters: Type.Object({
|
|
1634
|
-
command: Type.String({ description: "The shell command to run" }),
|
|
1635
|
-
timeout: Type.Optional(Type.Number({ description: "Optional timeout in seconds" })),
|
|
1636
|
-
persist: Type.Optional(Type.Boolean({
|
|
1637
|
-
description: "true → run in the persistent 'ai-bash' terminal: shell state (cd/venv/ssh) is retained across calls. " +
|
|
1638
|
-
"false (default) → one-shot terminal that exits when the command finishes; output stays viewable.",
|
|
1639
|
-
})),
|
|
1640
|
-
head: Type.Optional(Type.Integer({
|
|
1641
|
-
minimum: 1,
|
|
1642
|
-
maximum: 5000,
|
|
1643
|
-
description: "Only return the FIRST N lines of output (like `| head -N`); prefer this over piping through head.",
|
|
1644
|
-
})),
|
|
1645
|
-
tail: Type.Optional(Type.Integer({
|
|
1646
|
-
minimum: 1,
|
|
1647
|
-
maximum: 5000,
|
|
1648
|
-
description: "Only return the LAST N lines of output (like `| tail -N`); prefer this over piping through tail.",
|
|
1649
|
-
})),
|
|
1650
|
-
}),
|
|
1712
|
+
// 提示词单源:模型看到的 bash 定义由 makeAdaptiveBashTool 从 tool-prompts.ts 取,
|
|
1713
|
+
// 本定义只提供终端这条执行路径(description/schema 必须与另两条一致,不另写一套)。
|
|
1714
|
+
description: BASH_DESCRIPTION,
|
|
1715
|
+
promptSnippet: BASH_PROMPT_SNIPPET,
|
|
1716
|
+
promptGuidelines: BASH_PROMPT_GUIDELINES,
|
|
1717
|
+
parameters: BASH_PARAMETERS,
|
|
1651
1718
|
execute: async (_id, p, signal) => {
|
|
1652
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
|
+
}
|
|
1653
1737
|
const persist = p.persist ?? opts.defaultPersist();
|
|
1654
1738
|
// create() 对已存活的同名终端原样返回、对已退出的原地重启。
|
|
1655
1739
|
// forceBash:该终端永远跑 bash(而非用户登录 shell),模型写的
|
|
@@ -1707,17 +1791,10 @@ export function makeTerminalBashTool(terminals, opts) {
|
|
|
1707
1791
|
let collected = "";
|
|
1708
1792
|
let cursor = start;
|
|
1709
1793
|
let lastDataAt = Date.now();
|
|
1710
|
-
|
|
1711
|
-
//
|
|
1712
|
-
|
|
1713
|
-
const
|
|
1714
|
-
? 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")
|
|
1715
|
-
: "";
|
|
1716
|
-
// 标记「有哨兵命令在跑」:terminal_wait 据此区分等待与空闲。
|
|
1717
|
-
// 无哨兵命令没有可等待的哨兵,标记反而误导 terminal_wait。
|
|
1718
|
-
if (!sentinelUnsafe)
|
|
1719
|
-
terminals.setSentinelPending(termId, true);
|
|
1720
|
-
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");
|
|
1721
1798
|
if (inputErr)
|
|
1722
1799
|
throw new Error(inputErr);
|
|
1723
1800
|
for (;;) {
|
|
@@ -1741,11 +1818,11 @@ export function makeTerminalBashTool(terminals, opts) {
|
|
|
1741
1818
|
collected = collected.slice(collected.length - BASH_COLLECT_MAX / 2);
|
|
1742
1819
|
}
|
|
1743
1820
|
}
|
|
1744
|
-
const m = lastSentinel(collected);
|
|
1821
|
+
const m = lastSentinel(collected, nonce);
|
|
1745
1822
|
if (m) {
|
|
1746
1823
|
terminals.setSentinelPending(termId, false);
|
|
1747
1824
|
closeOneShot();
|
|
1748
|
-
const text = applyHeadTail(cleanBashOutput(collected), p.head, effectiveTail, lang);
|
|
1825
|
+
const text = applyHeadTail(cleanBashOutput(collected, nonce, runCommand), p.head, effectiveTail, lang);
|
|
1749
1826
|
return {
|
|
1750
1827
|
content: [
|
|
1751
1828
|
{
|
|
@@ -1761,15 +1838,15 @@ export function makeTerminalBashTool(terminals, opts) {
|
|
|
1761
1838
|
terminals.inputChecked(termId, "\x03");
|
|
1762
1839
|
closeOneShot();
|
|
1763
1840
|
const timeoutPartial = truncateMiddle(stripAnsi(collected), 4000);
|
|
1764
|
-
throw new Error(pick(lang, `Command timed out after ${p.timeout}s(已发 Ctrl+C;已有输出:${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 }));
|
|
1765
1842
|
}
|
|
1766
1843
|
// 静默解阻(仅持久终端):转后台 + 注册完成观察器,立即把控制权还给模型。
|
|
1767
1844
|
if (persist && idleMs > 0 && Date.now() - lastDataAt >= idleMs) {
|
|
1768
|
-
return backgroundResult(terminals, opts, runCommand, applyHeadTail(cleanBashOutput(collected), p.head, effectiveTail, lang)
|
|
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");
|
|
1769
1846
|
}
|
|
1770
1847
|
// 总时长解阻(持久与一次性终端):前台运行达到上限,转入后台继续执行,避免卡死。
|
|
1771
1848
|
if (maxForegroundMs > 0 && Date.now() - startTime >= maxForegroundMs) {
|
|
1772
|
-
return backgroundResult(terminals, opts, runCommand, applyHeadTail(cleanBashOutput(collected), p.head, effectiveTail, lang)
|
|
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");
|
|
1773
1850
|
}
|
|
1774
1851
|
}
|
|
1775
1852
|
}
|
|
@@ -1780,8 +1857,8 @@ export function makeTerminalBashTool(terminals, opts) {
|
|
|
1780
1857
|
});
|
|
1781
1858
|
}
|
|
1782
1859
|
/** 静默 / 总时长解阻路径:注册完成观察器后立即返回「仍在后台运行」。 */
|
|
1783
|
-
function backgroundResult(terminals, opts, command, partialText, durationSeconds, lang, termId = "ai-bash", persist = true, reason = "idle") {
|
|
1784
|
-
terminals.watchOutput(termId,
|
|
1860
|
+
function backgroundResult(terminals, opts, command, partialText, durationSeconds, lang, nonce, termId = "ai-bash", persist = true, reason = "idle") {
|
|
1861
|
+
terminals.watchOutput(termId, sentinelReFor(nonce), (m) => {
|
|
1785
1862
|
// 后台命令最终结束(或终端被关)→ 清除待决标记,terminal_wait 不再适用。
|
|
1786
1863
|
terminals.setSentinelPending(termId, false);
|
|
1787
1864
|
opts.notifyBackgroundDone({
|
|
@@ -1884,10 +1961,11 @@ lang, options) {
|
|
|
1884
1961
|
defineTool({
|
|
1885
1962
|
name: "terminal_create",
|
|
1886
1963
|
label: "Create terminal",
|
|
1887
|
-
description: "Create a named persistent interactive PTY. Interact via terminal_input / terminal_key
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
"
|
|
1964
|
+
description: "Create a named persistent interactive PTY. Interact via terminal_input / terminal_key; inspect output via terminal_read.",
|
|
1965
|
+
promptSnippet: "drive interactive programs or long-running servers in a PTY",
|
|
1966
|
+
promptGuidelines: [
|
|
1967
|
+
"Use this for full-screen TUIs (vim/htop) and servers you need to observe or interrupt; prefer bash for one-shot commands",
|
|
1968
|
+
],
|
|
1891
1969
|
parameters: Type.Object({
|
|
1892
1970
|
terminalId: Type.String({ description: "Stable terminal name" }),
|
|
1893
1971
|
cwd: Type.Optional(Type.String({ description: "Workspace-relative directory" })),
|
|
@@ -1977,7 +2055,9 @@ lang, options) {
|
|
|
1977
2055
|
label: "Read terminal output",
|
|
1978
2056
|
description: "Read incremental output from a persistent PTY. " +
|
|
1979
2057
|
"Keep the returned cursor and pass it on the next read; " +
|
|
1980
|
-
"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).",
|
|
1981
2061
|
parameters: Type.Object({
|
|
1982
2062
|
terminalId: Type.String(),
|
|
1983
2063
|
cursor: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
@@ -2000,10 +2080,10 @@ lang, options) {
|
|
|
2000
2080
|
defineTool({
|
|
2001
2081
|
name: "terminal_wait",
|
|
2002
2082
|
label: "Wait for terminal command",
|
|
2003
|
-
description: "Block until a command
|
|
2004
|
-
"
|
|
2005
|
-
"
|
|
2006
|
-
promptSnippet: "
|
|
2083
|
+
description: "Block until a bash-tool command finishes (exit marker) or timeout — no polling. " +
|
|
2084
|
+
"Returns {finished, exitCode} plus output produced meanwhile; finished=false = still running (call again). " +
|
|
2085
|
+
"terminal_input commands have no completion marker — use terminal_read(waitMs=…) for those.",
|
|
2086
|
+
promptSnippet: "avoid polling: wait for a long bash command to finish",
|
|
2007
2087
|
parameters: Type.Object({
|
|
2008
2088
|
terminalId: Type.String(),
|
|
2009
2089
|
cursor: Type.Optional(Type.Integer({
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
* - 本对话「允许同类」→ 该对话内同一规则档位(category)不再弹。
|
|
18
18
|
* 策略只活在内存里(挂在 Conversation 上,过户随对话搬走),重启/新对话即恢复询问。
|
|
19
19
|
*/
|
|
20
|
-
import { DEFAULT_APPROVAL_RULES, evaluateApprovalRules } from "./approval-rules.js";
|
|
20
|
+
import { DEFAULT_APPROVAL_RULES, evaluateApprovalRules, } from "./approval-rules.js";
|
|
21
21
|
/** 策略为空(既没全部允许也没记同类):调用方据此不挂空策略、面板据此不显示撤销区。 */
|
|
22
22
|
export function isApprovalPolicyEmpty(policy) {
|
|
23
23
|
return !policy || (!policy.allowAll && policy.categories.size === 0);
|
|
@@ -63,6 +63,7 @@ export function checkDangerousToolCall(toolName, params, cwd, workspaceRoots = [
|
|
|
63
63
|
reason: res.reason,
|
|
64
64
|
reasonEn: res.reasonEn,
|
|
65
65
|
category: res.category,
|
|
66
|
+
hits: res.hits,
|
|
66
67
|
};
|
|
67
68
|
}
|
|
68
69
|
if (res.action === "allow") {
|
|
@@ -78,6 +79,7 @@ export function checkDangerousToolCall(toolName, params, cwd, workspaceRoots = [
|
|
|
78
79
|
reason: res.reason,
|
|
79
80
|
reasonEn: res.reasonEn,
|
|
80
81
|
category: res.category,
|
|
82
|
+
hits: res.hits,
|
|
81
83
|
};
|
|
82
84
|
}
|
|
83
85
|
return { dangerous: false };
|