pi-web-ui 0.113.0 → 0.114.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 +69 -1
- package/README.md +117 -252
- package/README.zh-CN.md +145 -223
- package/README.zh-TW.md +145 -223
- package/bin/device-hub-cli.mjs +577 -0
- package/bin/pi-device-hub.mjs +9 -0
- package/bin/pi-web-ui.mjs +145 -20
- package/dist/gh-comment-781.md +5 -0
- package/dist/server/agent-service-daemon.js +102 -24
- package/dist/server/agent-service.js +2296 -1121
- package/dist/server/approval-rules.js +29 -3
- package/dist/server/ask-user-question-tool.js +8 -8
- package/dist/server/atomic-file.js +35 -14
- package/dist/server/attachment-store.js +71 -35
- package/dist/server/attachments.js +18 -8
- package/dist/server/canvas/canvas-agent-tool.js +65 -15
- package/dist/server/canvas/canvas-dispatch.js +61 -20
- package/dist/server/canvas/canvas-orchestrator.js +516 -199
- package/dist/server/canvas/canvas-scheduler.js +99 -0
- package/dist/server/canvas/canvas-store.js +107 -54
- package/dist/server/canvas/canvas-validation.js +131 -0
- package/dist/server/canvas/canvas-workspace.js +284 -0
- package/dist/server/client-id-utils.js +8 -0
- package/dist/server/client-state.js +104 -22
- package/dist/server/communicate-tool.js +76 -0
- package/dist/server/compact-context-tool.js +2 -3
- package/dist/server/compaction-instructions.js +75 -0
- package/dist/server/compaction-markers.js +7 -2
- package/dist/server/compaction-state.js +84 -0
- package/dist/server/composer-drafts.js +43 -40
- package/dist/server/context-evidence.js +346 -0
- package/dist/server/control-socket.js +6 -2
- package/dist/server/conversation-communication.js +368 -0
- package/dist/server/conversation-read-tool.js +3 -4
- package/dist/server/conversation-tool-names.js +14 -0
- package/dist/server/conversation-tool.js +57 -0
- package/dist/server/delegate-mode.js +17 -4
- package/dist/server/device-center/bot-catalog.js +88 -0
- package/dist/server/device-center/bot-execution.js +106 -0
- package/dist/server/device-center/bots.js +170 -0
- package/dist/server/device-center/collab-service.js +153 -0
- package/dist/server/device-center/collab-tool.js +184 -0
- package/dist/server/device-center/connector.js +332 -0
- package/dist/server/device-center/desktop-linux.js +372 -0
- package/dist/server/device-center/desktop-native.js +413 -0
- package/dist/server/device-center/desktop-page.js +232 -0
- package/dist/server/device-center/desktop-setup.js +30 -0
- package/dist/server/device-center/desktop.js +387 -0
- package/dist/server/device-center/device-portals.js +241 -0
- package/dist/server/device-center/execution-failure.js +70 -0
- package/dist/server/device-center/executor.js +371 -0
- package/dist/server/device-center/file-sync.js +493 -0
- package/dist/server/device-center/hub-auth.js +69 -0
- package/dist/server/device-center/hub-page.js +68 -0
- package/dist/server/device-center/hub-setup.js +214 -0
- package/dist/server/device-center/hub.js +829 -0
- package/dist/server/device-center/local-page.js +17 -0
- package/dist/server/device-center/local.js +476 -0
- package/dist/server/device-center/main.js +118 -0
- package/dist/server/device-center/native-desktop/macos.js +192 -0
- package/dist/server/device-center/native-desktop/windows.js +118 -0
- package/dist/server/device-center/path-portal.js +120 -0
- package/dist/server/device-center/relay.js +959 -0
- package/dist/server/device-center/runtime.js +253 -0
- package/dist/server/device-center/smoke-preview.js +3 -0
- package/dist/server/device-center/store.js +122 -0
- package/dist/server/device-center/task-error.js +14 -0
- package/dist/server/device-center/transfers.js +293 -0
- package/dist/server/device-center/workspaces.js +45 -0
- package/dist/server/dispatch-domain-handlers.js +83 -27
- package/dist/server/dsh/dsh-agent-service.js +277 -158
- package/dist/server/dsh/dsh-client.js +12 -2
- package/dist/server/durable/durable-agent-service.js +1 -1
- package/dist/server/evidence-tool-hooks.js +49 -0
- package/dist/server/file-save.js +95 -0
- package/dist/server/file-transfer-routes.js +97 -47
- package/dist/server/files-service.js +110 -34
- package/dist/server/goal-review-gate.js +16 -6
- package/dist/server/goal-service.js +54 -30
- package/dist/server/http-proxy.js +120 -0
- package/dist/server/index.js +236 -232
- package/dist/server/load-timing.js +31 -0
- package/dist/server/mcp-bridge.js +219 -94
- package/dist/server/mcp-hot-reload.js +31 -5
- package/dist/server/mcp-manager.js +192 -93
- package/dist/server/mcp-oauth-login.js +169 -0
- package/dist/server/mcp-oauth-ui.js +137 -0
- package/dist/server/mcp-oauth.js +395 -0
- package/dist/server/mcp-project-runtime.js +207 -0
- package/dist/server/message-window.js +74 -21
- package/dist/server/net-guard.js +122 -20
- package/dist/server/payload-limits.js +17 -0
- package/dist/server/pending-question.js +82 -0
- package/dist/server/plan-mode.js +338 -137
- package/dist/server/plugin-assets.js +8 -4
- package/dist/server/plugin-chat-attachments.js +48 -0
- package/dist/server/plugin-facilities.js +67 -220
- package/dist/server/plugin-installer.js +2 -1
- package/dist/server/plugin-removal.js +49 -0
- package/dist/server/plugin-secrets.js +179 -0
- package/dist/server/plugins.js +262 -92
- package/dist/server/preset-fields.js +49 -0
- package/dist/server/preset-plugin-dependencies.js +57 -0
- package/dist/server/preset-share.js +112 -72
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/queue-modes.js +10 -0
- package/dist/server/remote-ssh-service.js +160 -67
- package/dist/server/request-context.js +164 -0
- package/dist/server/sandbox-data.js +655 -0
- package/dist/server/sandbox-engines.js +7 -0
- package/dist/server/sandbox-runtime-gate.js +41 -0
- package/dist/server/sandbox-service.js +139 -698
- package/dist/server/sandbox-tool.js +21 -4
- package/dist/server/scheduler-tasks.js +63 -48
- package/dist/server/serialize.js +48 -19
- package/dist/server/session-branch.js +25 -3
- package/dist/server/session-parser.js +28 -18
- package/dist/server/session-scan.js +130 -0
- package/dist/server/session-search.js +51 -37
- package/dist/server/settings-service.js +267 -111
- package/dist/server/setup-config.js +58 -0
- package/dist/server/skill-maintenance.js +112 -24
- package/dist/server/subagent-helpers.js +4 -1
- package/dist/server/subagent-notify.js +4 -1
- package/dist/server/subagent-security-gate.js +52 -11
- package/dist/server/subagent-task.js +27 -0
- package/dist/server/subagents.js +217 -46
- package/dist/server/tabs.js +9 -1
- package/dist/server/terminals.js +467 -363
- package/dist/server/tool-guards.js +42 -6
- package/dist/server/tool-manager.js +47 -20
- package/dist/server/tool-overrides.js +13 -11
- package/dist/server/tool-prompt-overrides.js +32 -2
- package/dist/server/tool-prompts.js +1 -1
- package/dist/server/turn-timing.js +11 -0
- package/dist/server/universal/session-store.js +48 -6
- package/dist/server/universal/universal-service.js +1 -1
- package/dist/server/universal/universal-session.js +334 -231
- package/dist/server/uploads.js +64 -5
- package/dist/server/webui-context.js +6 -6
- package/dist/server/worktree-service.js +32 -24
- package/dist/server/ws-pending-queue.js +73 -27
- package/dist/test-artifact.md +9 -0
- package/dist/test-preview-modal.md +11 -0
- package/dist/test-report.html +20 -0
- package/docs/device-center.md +142 -0
- package/docs/device-desktop.md +48 -0
- package/package.json +4 -1
- package/plugin-sdk/index.d.ts +45 -9
- package/plugin-sdk/ssh-host-trust.mjs +225 -0
- package/plugins/catalog.json +1 -1
- package/themes/aetheris.css +1 -107
- package/themes/ayu-light.css +5 -29
- package/themes/bases/flow-base.css +0 -6
- package/themes/bases/statusbar-flat-base.css +112 -0
- package/themes/bases/zhujian-base.css +1 -0
- package/themes/bases/zhupi-base.css +1 -0
- package/themes/catppuccin-latte.css +4 -27
- package/themes/catppuccin.css +4 -35
- package/themes/claude-code-dark.css +1 -0
- package/themes/codex.css +4 -28
- package/themes/cyberpunk.css +3 -61
- package/themes/dark-teal.css +0 -1
- package/themes/dazzle.css +3 -73
- package/themes/everforest-light.css +4 -27
- package/themes/geist.css +4 -28
- package/themes/gruvbox-light.css +4 -27
- package/themes/kanagawa-lotus.css +4 -27
- package/themes/md-preview.css +3 -213
- package/themes/mist.css +4 -24
- package/themes/nord.css +4 -35
- package/themes/one-dark.css +4 -37
- package/themes/paper.css +4 -16
- package/themes/rose-pine-dawn.css +4 -28
- package/themes/sakura.css +4 -24
- package/themes/solarized-light.css +4 -27
- package/themes/tokyo-night.css +3 -34
- package/themes/white.css +4 -26
- package/themes/zhujian-dark.css +1 -0
- package/themes/zhupi-dark.css +1 -0
- package/web/dist/.build-assets.json +1 -0
- package/web/dist/assets/BgTasksModal-CS7UNzcw.js +1 -0
- package/web/dist/assets/BgTasksModal-Dk-tp78W.js +1 -0
- package/web/dist/assets/CanvasStudio-BEJZE5BI.js +1579 -0
- package/web/dist/assets/CanvasStudio-CgUNHqos.js +1579 -0
- package/web/dist/assets/DeviceCenter-C8_CbxQ3.js +3 -0
- package/web/dist/assets/DeviceCenter-CVblvhNX.js +3 -0
- package/web/dist/assets/Dropdown-Oug0DDte.js +1 -0
- package/web/dist/assets/FilePreview-CvdX6nr6.js +2 -0
- package/web/dist/assets/FilePreview-kCZhfBAF.js +2 -0
- package/web/dist/assets/GlobalSearchModal-BLH63yYP.js +1 -0
- package/web/dist/assets/GlobalSearchModal-DAkvlvp6.js +1 -0
- package/web/dist/assets/GroupConversation-Cgo4xbpa.js +1 -0
- package/web/dist/assets/GroupConversation-DZ71jEi8.js +1 -0
- package/web/dist/assets/ModelConfigModal-BpWdFdQC.js +2 -0
- package/web/dist/assets/PiSetupModal-mkWPSxMj.js +1 -0
- package/web/dist/assets/ProviderOAuthControls-VK_jqXYS.js +1 -0
- package/web/dist/assets/SCMPanel-BP1TUT-V.js +2 -0
- package/web/dist/assets/SCMPanel-BscPm9kf.js +2 -0
- package/web/dist/assets/SettingsModal-C8UgMjVM.js +20 -0
- package/web/dist/assets/SettingsModal-VynB7jNb.js +20 -0
- package/web/dist/assets/TerminalPanel-D6cPRFei.js +3 -0
- package/web/dist/assets/TerminalPanel-DL20uKgU.js +3 -0
- package/web/dist/assets/TuiOverlayModal-Dst3BmT8.js +1 -0
- package/web/dist/assets/TuiOverlayModal-NCkpNtTp.js +1 -0
- package/web/dist/assets/UniversalPathPicker-CfQFc_c3.js +1 -0
- package/web/dist/assets/UniversalPathPicker-DwxwNcFw.js +1 -0
- package/web/dist/assets/app-globals-CnO6KlEM.js +325 -0
- package/web/dist/assets/desktop-DPyTy4M3.js +1 -0
- package/web/dist/assets/es-DWMIuDU2.js +2 -0
- package/web/dist/assets/index-CPgAH5q7.js +83 -0
- package/web/dist/assets/index-Cje8iugL.js +83 -0
- package/web/dist/assets/index-DnKeiDbj.css +1 -0
- package/web/dist/assets/markdown-BggnuQ4H.js +40 -0
- package/web/dist/assets/markdown-C8LL_u4z.css +1 -0
- package/web/dist/assets/math-1uRJCsA9.js +257 -0
- package/web/dist/assets/math-BorAY7qD.css +1 -0
- package/web/dist/assets/plugin-host-CqA4yW6w.js +1 -0
- package/web/dist/assets/shortcut-stack-hhrDyRBn.js +1 -0
- package/web/dist/assets/theme-BqdAjEjF.js +1 -0
- package/web/dist/assets/uuid-BzDIGCwP.js +1 -0
- package/web/dist/index.html +15 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/TerminalPanel-3wojLfLk.js +0 -3
- package/web/dist/assets/index-A8YXwnpZ.js +0 -2008
- package/web/dist/assets/index-BwL7qBh6.css +0 -1
- package/web/dist/assets/markdown-BJZlfvdP.js +0 -296
- package/web/dist/assets/markdown-DSNUiDzp.css +0 -1
package/dist/server/terminals.js
CHANGED
|
@@ -27,6 +27,7 @@ import { defineTool } from "@earendil-works/pi-coding-agent";
|
|
|
27
27
|
import { Type } from "typebox";
|
|
28
28
|
import { BASH_DESCRIPTION, BASH_PARAMETERS, BASH_PROMPT_GUIDELINES, BASH_PROMPT_SNIPPET } from "./tool-prompts.js";
|
|
29
29
|
import { pick } from "./i18n.js";
|
|
30
|
+
import { armDelay } from "./plugin-schedule.js";
|
|
30
31
|
import { getGlobalRemoteSshService, isRemoteWorkspaceUri, parseRemoteWorkspaceUri, resolveWorkspaceSessionDir, } from "./remote-ssh-service.js";
|
|
31
32
|
/** Location of the command list for a project: <workspaceRoot>/.pi/commands.json */
|
|
32
33
|
export function commandsFilePath(workspaceRoot) {
|
|
@@ -178,36 +179,25 @@ const BASH_COLLECT_MAX = 2 * 1024 * 1024;
|
|
|
178
179
|
*/
|
|
179
180
|
export function buildTerminalBashLine(command, tailFile, nonce = newSentinelNonce()) {
|
|
180
181
|
const trimmed = command.replace(/\s+$/, "");
|
|
181
|
-
//
|
|
182
|
-
// 在管道末尾会把退出码吞成自己的(head 恒 0、grep 无命恒 1)。`${PIPESTATUS:-$?}`
|
|
183
|
-
// 在 bash 里取 PIPESTATUS[0](首命令),busybox ash/dash 无 PIPESTATUS 时退化为 `$?`。
|
|
184
|
-
// SIGPIPE(141) 归 0:`cmd | head` 里 head 读够 N 行就主动关管道,把首命令“截断杀掉”
|
|
185
|
-
// 留下的 141 不是真失败,而是“按要求截断=成功”。只有恰好 141 才转 0,真失败照报。
|
|
182
|
+
// Preserve bash's status, including the caller's pipefail setting and SIGPIPE.
|
|
186
183
|
// tailFile:`cmd > log 2>&1 | tail -N`——拆掉 tail 后 stdout 进文件、终端为空;
|
|
187
184
|
// 在哨兵前补一个 `tail -N log` 让模型看到日志尾部,退出码仍是底层命令的。
|
|
188
185
|
const tailPart = tailFile
|
|
189
186
|
? `; tail -n ${Math.max(1, Math.floor(tailFile.lines))} -- '${tailFile.file.replace(/'/g, `'\\''`)}'`
|
|
190
187
|
: "";
|
|
191
188
|
// eslint-disable-next-line no-useless-escape -- \$? must reach the shell literally
|
|
192
|
-
const sentinel = `__pi_rc
|
|
193
|
-
if (trimmed.includes("\n")) {
|
|
194
|
-
// 多行路径(行为保持):$'...' 转义后是一行物理输入,引号/换行全部字面化,
|
|
195
|
-
// 以 `'` 收尾——`; ` 同行拼接哨兵不会被尾注释/尾管道/续行吞掉。
|
|
196
|
-
const body = `eval $'${trimmed
|
|
197
|
-
.replace(/\\/g, "\\\\")
|
|
198
|
-
.replace(/'/g, "\\'")
|
|
199
|
-
.replace(/\r/g, "\\r")
|
|
200
|
-
.replace(/\n/g, "\\n")
|
|
201
|
-
.replace(/\t/g, "\\t")}'`;
|
|
202
|
-
return `${body}; ${sentinel}`;
|
|
203
|
-
}
|
|
204
|
-
// 单行路径:哨兵独占一行追加。行内 `; ` 拼接会被常见形态吞掉——
|
|
205
|
-
// 尾注释(`cmd # note; printf…` 整段进注释)、尾管道(`cmd |; …` 语法错误)。
|
|
206
|
-
// 独占一行后这两类安全;尾随续行符/未闭合引号仍会把哨兵行并入命令或吞进
|
|
207
|
-
// 字符串——这类形态无法安全续行,直接拒注入(调用方按无退出码模式执行并注明)。
|
|
189
|
+
const sentinel = `__pi_rc=$?${tailPart}; printf '\\n[pi-exit-${nonce}:%s]\\n' "$__pi_rc"`;
|
|
208
190
|
if (sentinelUnsafeReason(trimmed))
|
|
209
191
|
return trimmed;
|
|
210
|
-
|
|
192
|
+
// Parse the whole physical line before a command can read stdin. The eval
|
|
193
|
+
// boundary isolates trailing comments, multiline scripts and heredocs.
|
|
194
|
+
const body = `eval $'${trimmed
|
|
195
|
+
.replace(/\\/g, "\\\\")
|
|
196
|
+
.replace(/'/g, "\\'")
|
|
197
|
+
.replace(/\r/g, "\\r")
|
|
198
|
+
.replace(/\n/g, "\\n")
|
|
199
|
+
.replace(/\t/g, "\\t")}'`;
|
|
200
|
+
return `${body}; ${sentinel}`;
|
|
211
201
|
}
|
|
212
202
|
/**
|
|
213
203
|
* 判定命令能否安全追加「独占一行的退出码哨兵」;返回拒注入原因或 null(可注入)。
|
|
@@ -957,9 +947,9 @@ export function isTerminalQueryResponse(data) {
|
|
|
957
947
|
return TERMINAL_QUERY_RESPONSE_RE.test(data);
|
|
958
948
|
}
|
|
959
949
|
export class TerminalManager {
|
|
960
|
-
|
|
961
|
-
workspaceRoot;
|
|
950
|
+
rootSource;
|
|
962
951
|
lang;
|
|
952
|
+
ownerKind;
|
|
963
953
|
/** Live PTYs only. Exited entries move to history so they no longer consume
|
|
964
954
|
* the live-terminal limit while their output remains readable/replayable. */
|
|
965
955
|
terms = new Map();
|
|
@@ -985,17 +975,41 @@ export class TerminalManager {
|
|
|
985
975
|
if (entry)
|
|
986
976
|
entry.agentPendingLine = "";
|
|
987
977
|
}
|
|
988
|
-
|
|
978
|
+
emit;
|
|
979
|
+
constructor(emit, rootSource,
|
|
989
980
|
// issue #91:按键/输入校验错误按客户端 UI 语言出中英(英文默认)。
|
|
990
|
-
lang) {
|
|
991
|
-
this.
|
|
992
|
-
this.workspaceRoot = workspaceRoot;
|
|
981
|
+
lang, ownerKind = "conversation") {
|
|
982
|
+
this.rootSource = rootSource;
|
|
993
983
|
this.lang = lang;
|
|
984
|
+
this.ownerKind = ownerKind;
|
|
985
|
+
this.emit = this.ownedEmit(emit);
|
|
986
|
+
}
|
|
987
|
+
get workspaceRoot() {
|
|
988
|
+
return typeof this.rootSource === "function" ? this.rootSource() : this.rootSource;
|
|
989
|
+
}
|
|
990
|
+
ownedEmit(emit) {
|
|
991
|
+
return (msg) => {
|
|
992
|
+
if (msg.type === "terminal_output" || msg.type === "terminal_exit") {
|
|
993
|
+
emit({ ...msg, ownerKind: this.ownerKind });
|
|
994
|
+
}
|
|
995
|
+
else
|
|
996
|
+
emit(msg);
|
|
997
|
+
};
|
|
994
998
|
}
|
|
995
999
|
/** 过户:对话整体搬到另一个 ClientSession 时,把输出/退出事件改发给新宿主。
|
|
996
1000
|
* PTY 本体不动(进程不重启,输出缓冲保留),只换投递地址. */
|
|
997
1001
|
rebindEmit(emit) {
|
|
998
|
-
this.emit = emit;
|
|
1002
|
+
this.emit = this.ownedEmit(emit);
|
|
1003
|
+
}
|
|
1004
|
+
/** Attach to an existing PTY or retained history; never spawn or restart. */
|
|
1005
|
+
attach(id, cols, rows) {
|
|
1006
|
+
const entry = this.find(id);
|
|
1007
|
+
if (!entry)
|
|
1008
|
+
return false;
|
|
1009
|
+
this.resize(id, cols, rows);
|
|
1010
|
+
this.flushPending(entry);
|
|
1011
|
+
this.emit({ type: "terminal_output", terminalId: id, data: entry.output, reset: true });
|
|
1012
|
+
return true;
|
|
999
1013
|
}
|
|
1000
1014
|
/** Start a plain interactive shell in the given directory. */
|
|
1001
1015
|
create(id, cwd, cols, rows, fallbackCwd, title, opts) {
|
|
@@ -1070,8 +1084,7 @@ export class TerminalManager {
|
|
|
1070
1084
|
// process group) and start a fresh shell with the same id. Keep the
|
|
1071
1085
|
// last known size so the replacement matches the xterm's dimensions.
|
|
1072
1086
|
if (!existing.exited) {
|
|
1073
|
-
this.
|
|
1074
|
-
this.killNative(existing);
|
|
1087
|
+
this.retireTaskEntry(existing);
|
|
1075
1088
|
}
|
|
1076
1089
|
cols = existing.cols || cols;
|
|
1077
1090
|
rows = existing.rows || rows;
|
|
@@ -1349,10 +1362,10 @@ export class TerminalManager {
|
|
|
1349
1362
|
const hits = [];
|
|
1350
1363
|
for (const w of entry.watches) {
|
|
1351
1364
|
w.buf += data;
|
|
1352
|
-
if (w.buf.length > 64_000)
|
|
1353
|
-
w.buf = w.buf.slice(-32_000);
|
|
1354
1365
|
w.re.lastIndex = 0;
|
|
1355
1366
|
const m = w.re.exec(w.buf);
|
|
1367
|
+
if (w.buf.length > 64_000)
|
|
1368
|
+
w.buf = w.buf.slice(-32_000);
|
|
1356
1369
|
if (m)
|
|
1357
1370
|
hits.push({ w, m }); // 命中 → 移出(cb 在下面统一触发)
|
|
1358
1371
|
else
|
|
@@ -1408,7 +1421,11 @@ export class TerminalManager {
|
|
|
1408
1421
|
return null;
|
|
1409
1422
|
if (cand.username !== root.username || cand.host !== root.host || cand.port !== root.port)
|
|
1410
1423
|
return null;
|
|
1411
|
-
|
|
1424
|
+
const candidatePath = posix.normalize(cand.remotePath);
|
|
1425
|
+
const rootPath = posix.normalize(root.remotePath).replace(/\/+$/, "") || "/";
|
|
1426
|
+
if (candidatePath !== rootPath && !candidatePath.startsWith(rootPath === "/" ? "/" : `${rootPath}/`))
|
|
1427
|
+
return null;
|
|
1428
|
+
return `ssh://${cand.username}@${cand.host}:${cand.port}${candidatePath}`;
|
|
1412
1429
|
}
|
|
1413
1430
|
// 相对/本地写法一律挂到远程根下解析(与本地分支 resolve(root, raw) 同语义)
|
|
1414
1431
|
const rel = String(raw).replace(/\\/g, "/").replace(/^\/+/, "");
|
|
@@ -1442,6 +1459,7 @@ export class TerminalManager {
|
|
|
1442
1459
|
exitCode: entry.exitCode,
|
|
1443
1460
|
command: entry.command,
|
|
1444
1461
|
agentBash: entry.agentBash,
|
|
1462
|
+
ownerKind: this.ownerKind,
|
|
1445
1463
|
};
|
|
1446
1464
|
}
|
|
1447
1465
|
has(id) {
|
|
@@ -1497,6 +1515,9 @@ export class TerminalManager {
|
|
|
1497
1515
|
}
|
|
1498
1516
|
/** Replay the retained output window after switching back to this conversation. */
|
|
1499
1517
|
replay() {
|
|
1518
|
+
// Deliver coalesced live output before resetting viewers to the retained window.
|
|
1519
|
+
for (const entry of this.terms.values())
|
|
1520
|
+
this.flushPending(entry);
|
|
1500
1521
|
return [...this.terms.values(), ...this.history.values()]
|
|
1501
1522
|
.filter((entry) => entry.output.length > 0)
|
|
1502
1523
|
.map((entry) => ({ terminalId: entry.id, data: entry.output }));
|
|
@@ -1602,14 +1623,14 @@ export class TerminalManager {
|
|
|
1602
1623
|
// 命令可能在调用前就已结束:先扫 afterCursor 之后的存量缓冲。
|
|
1603
1624
|
const relStart = Math.max(0, afterCursor - entry.outputOffset);
|
|
1604
1625
|
const segment = entry.output.slice(relStart);
|
|
1605
|
-
const
|
|
1606
|
-
scan
|
|
1607
|
-
const existing =
|
|
1626
|
+
const completionRe = entry.sentinelNonce ? sentinelReFor(entry.sentinelNonce) : BASH_SENTINEL_RE;
|
|
1627
|
+
const scan = new RegExp(completionRe.source, completionRe.flags);
|
|
1628
|
+
const existing = scan.exec(segment);
|
|
1608
1629
|
if (existing) {
|
|
1609
1630
|
resolve({ finished: true, exitCode: Number(existing[1]) });
|
|
1610
1631
|
return;
|
|
1611
1632
|
}
|
|
1612
|
-
if (entry.exited) {
|
|
1633
|
+
if (entry.exited || entry.retired) {
|
|
1613
1634
|
resolve({ finished: true, exitCode: entry.exitCode });
|
|
1614
1635
|
return;
|
|
1615
1636
|
}
|
|
@@ -1627,20 +1648,32 @@ export class TerminalManager {
|
|
|
1627
1648
|
unwatch();
|
|
1628
1649
|
resolve(r);
|
|
1629
1650
|
};
|
|
1630
|
-
unwatch = this.watchOutput(id,
|
|
1651
|
+
unwatch = this.watchOutput(id, completionRe, (m) => {
|
|
1631
1652
|
// m=null = 终端被关闭/退出 → 命令肯定结束了(退出码未知)。
|
|
1632
|
-
done({ finished: true, exitCode: m ? Number(m[1]) :
|
|
1653
|
+
done({ finished: true, exitCode: m ? Number(m[1]) : entry.exitCode });
|
|
1633
1654
|
});
|
|
1655
|
+
if (settled)
|
|
1656
|
+
return;
|
|
1634
1657
|
timer = setTimeout(() => done({ finished: false, exitCode: null }), Math.max(1, Math.min(timeoutMs, 600_000)));
|
|
1635
1658
|
timer.unref?.();
|
|
1636
1659
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1660
|
+
if (signal?.aborted)
|
|
1661
|
+
onAbort();
|
|
1637
1662
|
});
|
|
1638
1663
|
}
|
|
1639
1664
|
/** 标记/清除「哨兵待决」状态(终端接管 bash 工具专用)。 */
|
|
1640
|
-
setSentinelPending(id, pending) {
|
|
1665
|
+
setSentinelPending(id, pending, nonce) {
|
|
1641
1666
|
const entry = this.find(id);
|
|
1642
|
-
if (entry)
|
|
1643
|
-
|
|
1667
|
+
if (!entry || (!pending && nonce !== undefined && entry.sentinelNonce !== nonce))
|
|
1668
|
+
return;
|
|
1669
|
+
entry.sentinelPending = pending;
|
|
1670
|
+
if (pending)
|
|
1671
|
+
entry.sentinelNonce = nonce;
|
|
1672
|
+
}
|
|
1673
|
+
/** Snapshot task termination without confusing a closed shell with silence. */
|
|
1674
|
+
bashTaskState(id) {
|
|
1675
|
+
const entry = this.find(id);
|
|
1676
|
+
return { exited: !entry || entry.exited || entry.retired === true, exitCode: entry?.exitCode ?? null };
|
|
1644
1677
|
}
|
|
1645
1678
|
/** 是否有带哨兵的命令尚未结束(terminal_wait 的适用性判断)。 */
|
|
1646
1679
|
isSentinelPending(id) {
|
|
@@ -1649,7 +1682,7 @@ export class TerminalManager {
|
|
|
1649
1682
|
/** 注册一次性输出观察器:命中 re 或终端退出时回调一次。返回注销函数。 */
|
|
1650
1683
|
watchOutput(id, re, cb) {
|
|
1651
1684
|
const entry = this.find(id);
|
|
1652
|
-
if (!entry) {
|
|
1685
|
+
if (!entry || entry.exited || entry.retired) {
|
|
1653
1686
|
cb(null);
|
|
1654
1687
|
return () => { };
|
|
1655
1688
|
}
|
|
@@ -1658,10 +1691,7 @@ export class TerminalManager {
|
|
|
1658
1691
|
const watch = { re: own, buf: "", cb };
|
|
1659
1692
|
entry.watches.push(watch);
|
|
1660
1693
|
return () => {
|
|
1661
|
-
|
|
1662
|
-
if (!cur)
|
|
1663
|
-
return;
|
|
1664
|
-
cur.watches = cur.watches.filter((w) => w !== watch);
|
|
1694
|
+
entry.watches = entry.watches.filter((w) => w !== watch);
|
|
1665
1695
|
};
|
|
1666
1696
|
}
|
|
1667
1697
|
/** Emit a terminal failure (bad cwd, spawn error) and mark the terminal dead. */
|
|
@@ -1687,12 +1717,12 @@ export class TerminalManager {
|
|
|
1687
1717
|
this.appendOutput(entry, marker);
|
|
1688
1718
|
this.emit({ type: "terminal_output", terminalId: id, data: marker });
|
|
1689
1719
|
entry.exited = true;
|
|
1720
|
+
entry.exitCode = exitCode;
|
|
1690
1721
|
// 终端退出 → 未命中的输出观察器以 null 回调(宿主可据此通知「终端已关闭」)。
|
|
1691
1722
|
const pendingWatches = entry.watches;
|
|
1692
1723
|
entry.watches = [];
|
|
1693
1724
|
for (const w of pendingWatches)
|
|
1694
1725
|
w.cb(null);
|
|
1695
|
-
entry.exitCode = exitCode;
|
|
1696
1726
|
this.terms.delete(id);
|
|
1697
1727
|
// 进程已退出,立即释放底层的 PTY 句柄(Windows ConPTY / HPCON / sockets 等),
|
|
1698
1728
|
// 避免已退出的终端长期占用 ConPTY 与 MSYS2 控制台资源(issue #269)。
|
|
@@ -1730,17 +1760,28 @@ export class TerminalManager {
|
|
|
1730
1760
|
// PTY already gone — nothing to do.
|
|
1731
1761
|
}
|
|
1732
1762
|
}
|
|
1763
|
+
/** Retire callbacks against this exact generation without faking native exit. */
|
|
1764
|
+
retireTaskEntry(entry, shutdown = false) {
|
|
1765
|
+
if (entry.retired)
|
|
1766
|
+
return;
|
|
1767
|
+
this.disarmIdleWatch(entry);
|
|
1768
|
+
this.flushPending(entry);
|
|
1769
|
+
this.killNative(entry, shutdown);
|
|
1770
|
+
entry.retired = true;
|
|
1771
|
+
entry.sentinelPending = false;
|
|
1772
|
+
const watches = entry.watches;
|
|
1773
|
+
entry.watches = [];
|
|
1774
|
+
for (const wake of entry.waiters)
|
|
1775
|
+
wake();
|
|
1776
|
+
entry.waiters.clear();
|
|
1777
|
+
for (const watch of watches)
|
|
1778
|
+
watch.cb(null);
|
|
1779
|
+
}
|
|
1733
1780
|
/** Kill one terminal (tab closed), including an exited terminal's retained history. */
|
|
1734
1781
|
kill(id) {
|
|
1735
1782
|
const entry = this.terms.get(id);
|
|
1736
1783
|
if (entry) {
|
|
1737
|
-
this.
|
|
1738
|
-
const killedWatches = entry.watches;
|
|
1739
|
-
entry.watches = [];
|
|
1740
|
-
for (const w of killedWatches)
|
|
1741
|
-
w.cb(null);
|
|
1742
|
-
this.flushPending(entry);
|
|
1743
|
-
this.killNative(entry);
|
|
1784
|
+
this.retireTaskEntry(entry);
|
|
1744
1785
|
this.terms.delete(id);
|
|
1745
1786
|
this.emit({ type: "terminal_exit", terminalId: id, exitCode: null });
|
|
1746
1787
|
this.emitList();
|
|
@@ -1804,7 +1845,6 @@ export class TerminalManager {
|
|
|
1804
1845
|
const t = setTimeout(() => {
|
|
1805
1846
|
if (entry.exited)
|
|
1806
1847
|
return;
|
|
1807
|
-
entry.exited = true;
|
|
1808
1848
|
try {
|
|
1809
1849
|
entry.pty.kill();
|
|
1810
1850
|
}
|
|
@@ -1831,18 +1871,7 @@ export class TerminalManager {
|
|
|
1831
1871
|
killAll(opts) {
|
|
1832
1872
|
const shutdown = opts?.shutdown === true;
|
|
1833
1873
|
for (const entry of this.terms.values()) {
|
|
1834
|
-
this.
|
|
1835
|
-
if (entry.exited)
|
|
1836
|
-
continue;
|
|
1837
|
-
this.killNative(entry, shutdown);
|
|
1838
|
-
}
|
|
1839
|
-
for (const entry of this.terms.values()) {
|
|
1840
|
-
for (const wake of entry.waiters)
|
|
1841
|
-
wake();
|
|
1842
|
-
entry.waiters.clear();
|
|
1843
|
-
for (const w of entry.watches)
|
|
1844
|
-
w.cb(null);
|
|
1845
|
-
entry.watches = [];
|
|
1874
|
+
this.retireTaskEntry(entry, shutdown);
|
|
1846
1875
|
}
|
|
1847
1876
|
for (const entry of this.history.values()) {
|
|
1848
1877
|
this.killNative(entry, shutdown);
|
|
@@ -1873,15 +1902,45 @@ function lastSentinel(collected, nonce) {
|
|
|
1873
1902
|
* ② 命令回显:第一次出现的命令首行(及其之前的提示符)整段丢弃——它总在真实输出之前。
|
|
1874
1903
|
* 最后一个本次哨兵之后的内容是 shell 新提示符,整段截掉。
|
|
1875
1904
|
*/
|
|
1876
|
-
export function cleanBashOutput(raw, nonce, command = "") {
|
|
1905
|
+
export function cleanBashOutput(raw, nonce, command = "", injectedLine) {
|
|
1877
1906
|
const fmt = `[pi-exit-${nonce}:%s]`;
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1907
|
+
const rawLines = stripAnsi(raw).replace(/\r\n/g, "\n").split("\n");
|
|
1908
|
+
// ConPTY wraps a single physical input line at screen columns, including
|
|
1909
|
+
// inside the nonce or printf's final argument. Rejoin only exact fragments
|
|
1910
|
+
// of this invocation's generated input, never a generic control-looking line.
|
|
1911
|
+
if (command) {
|
|
1912
|
+
const injected = injectedLine ?? buildTerminalBashLine(command, undefined, nonce);
|
|
1913
|
+
for (let i = 0; i < rawLines.length; i++) {
|
|
1914
|
+
const start = rawLines[i].indexOf("eval $'");
|
|
1915
|
+
if (start < 0)
|
|
1916
|
+
continue;
|
|
1917
|
+
let matched = 0;
|
|
1918
|
+
let end = i;
|
|
1919
|
+
for (; end < rawLines.length; end++) {
|
|
1920
|
+
let fragment = end === i ? rawLines[end].slice(start) : rawLines[end];
|
|
1921
|
+
// Preserve a real space at the wrap boundary; trim screen padding only
|
|
1922
|
+
// when the untrimmed fragment cannot belong to the injected command.
|
|
1923
|
+
if (!injected.startsWith(fragment, matched))
|
|
1924
|
+
fragment = fragment.trimEnd();
|
|
1925
|
+
if (!fragment || !injected.startsWith(fragment, matched))
|
|
1926
|
+
break;
|
|
1927
|
+
matched += fragment.length;
|
|
1928
|
+
if (matched === injected.length) {
|
|
1929
|
+
rawLines.splice(i, end - i + 1, rawLines[i].slice(0, start) + injected);
|
|
1930
|
+
break;
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
}
|
|
1934
|
+
}
|
|
1935
|
+
// The complete eval echo includes the printf format and is removed as one
|
|
1936
|
+
// physical line. Capture a preceding two-line prompt before removing it.
|
|
1937
|
+
const echoAt = rawLines.findIndex((line) => line.includes(fmt));
|
|
1938
|
+
const preceding = echoAt > 0 ? rawLines[echoAt - 1].trim() : "";
|
|
1939
|
+
const echoedPrompt = /^[A-Za-z0-9._-]+@[A-Za-z0-9._-]+ /.test(preceding) ? preceding : "";
|
|
1940
|
+
let lines = rawLines.filter((line, index) => !line.includes(fmt) && !/^\s*\[pi-term-exit:-?\d+\]\s*$/.test(line) && !(echoedPrompt && index === echoAt - 1));
|
|
1882
1941
|
const anchor = (command.split("\n")[0] ?? "").trim().slice(0, 80);
|
|
1883
1942
|
// 命令回显前那一行提示符(如 `user@host MINGW64 /cwd`):收尾时用它识别「哨兵前残留的新提示符」。
|
|
1884
|
-
let promptLine =
|
|
1943
|
+
let promptLine = echoedPrompt;
|
|
1885
1944
|
// 锚点找不到(横向滚动只回显尾部 / 回显缺失)时的回落:首个非空行若呈
|
|
1886
1945
|
// 提示符形状(`user@host … $ ` / `[user@host dir]$ `),按提示符+回显行剥掉,
|
|
1887
1946
|
// 否则命令回显与提示符会整行留在返回给模型的输出里。
|
|
@@ -2031,6 +2090,8 @@ export function makeTerminalBashTool(terminals, opts) {
|
|
|
2031
2090
|
parameters: BASH_PARAMETERS,
|
|
2032
2091
|
execute: async (_id, p, signal) => {
|
|
2033
2092
|
const lang = opts.lang?.() ?? "en";
|
|
2093
|
+
if (signal?.aborted)
|
|
2094
|
+
throw new Error("Command aborted");
|
|
2034
2095
|
// 语法不完整的命令(续行符结尾 / 未闭合引号 / 未闭合括号组):交互 shell 会停在续行提示符
|
|
2035
2096
|
// (PS2)零执行,且无法注入退出码哨兵——没有任何办法得知它何时结束。直接拒绝,不建终端、
|
|
2036
2097
|
// 不注入,避免空等 60 秒后回报「仍在后台运行」这种与事实相反的状态(#571)。
|
|
@@ -2064,6 +2125,9 @@ export function makeTerminalBashTool(terminals, opts) {
|
|
|
2064
2125
|
// 也不计入终端数量上限。
|
|
2065
2126
|
const termId = persist ? PERSIST_ID : `ai-bash-${++oneShotBashSeq}`;
|
|
2066
2127
|
const title = persist ? "AI bash" : `AI bash ${oneShotBashSeq}`;
|
|
2128
|
+
if (terminals.isSentinelPending?.(termId)) {
|
|
2129
|
+
throw new Error(`Terminal ${termId} is busy. Use terminal({action:'wait', terminalId:'${termId}'}) or action:'read', 'input', 'key' for the current task.`);
|
|
2130
|
+
}
|
|
2067
2131
|
if (terminals.create(termId, opts.cwd, 120, 40, opts.cwd, title, {
|
|
2068
2132
|
forceBash: true,
|
|
2069
2133
|
agentBash: true,
|
|
@@ -2109,24 +2173,85 @@ export function makeTerminalBashTool(terminals, opts) {
|
|
|
2109
2173
|
const limiterNote = stripped
|
|
2110
2174
|
? pick(lang, `\n[注:检测到你带了「${limiterSegment}」这类限输出/过滤管道——已在终端里直跑底层命令(实时可见 + 真实退出码),只按参数返回片段。${limiterTailZh} 后续直接用 bash(command, tail=N) 参数限输出。]`, `\n[Note: detected a trailing output-limiting pipe "${limiterSegment}" — ran the underlying command directly in the terminal (live output + real exit code) and trimmed only the returned slice. ${limiterTailEn} Next time use the bash(command, tail=N) parameter to limit output.]`, "terminals.bash.limiter.note", { limiterSegment, limiterTailZh, limiterTailEn })
|
|
2111
2175
|
: "";
|
|
2176
|
+
const nonce = newSentinelNonce();
|
|
2177
|
+
const injectedLine = buildTerminalBashLine(runCommand, tailFile, nonce);
|
|
2178
|
+
const cleanCollected = (raw) => cleanBashOutput(raw, nonce, runCommand, injectedLine);
|
|
2179
|
+
let finished = false;
|
|
2180
|
+
let background = false;
|
|
2181
|
+
let exitCode = null;
|
|
2182
|
+
let failure;
|
|
2183
|
+
let unwatch = () => { };
|
|
2184
|
+
let timeout;
|
|
2185
|
+
const finish = (code) => {
|
|
2186
|
+
if (finished)
|
|
2187
|
+
return;
|
|
2188
|
+
finished = true;
|
|
2189
|
+
exitCode = code;
|
|
2190
|
+
if (timeout)
|
|
2191
|
+
clearTimeout(timeout);
|
|
2192
|
+
unwatch();
|
|
2193
|
+
signal?.removeEventListener("abort", onSignalAbort);
|
|
2194
|
+
ac.signal.removeEventListener("abort", onAbort);
|
|
2195
|
+
opts.kills.delete(ac);
|
|
2196
|
+
terminals.setSentinelPending(termId, false, nonce);
|
|
2197
|
+
if (background)
|
|
2198
|
+
opts.notifyBackgroundDone({ terminalId: termId, command: runCommand, exitCode: code });
|
|
2199
|
+
if (!failure && code !== null && !terminals.bashTaskState?.(termId).exited)
|
|
2200
|
+
closeOneShot();
|
|
2201
|
+
};
|
|
2202
|
+
const cancel = (error) => {
|
|
2203
|
+
if (finished)
|
|
2204
|
+
return;
|
|
2205
|
+
failure = error;
|
|
2206
|
+
// Destroy this task's shell rather than leave an unknown foreground reader
|
|
2207
|
+
// alive after Ctrl+C. Completion removes all callbacks before reuse.
|
|
2208
|
+
try {
|
|
2209
|
+
terminals.kill?.(termId);
|
|
2210
|
+
}
|
|
2211
|
+
finally {
|
|
2212
|
+
finish(null);
|
|
2213
|
+
}
|
|
2214
|
+
};
|
|
2215
|
+
const onAbort = () => cancel(new Error("Command aborted"));
|
|
2216
|
+
const onSignalAbort = () => ac.abort();
|
|
2217
|
+
terminals.setSentinelPending(termId, true, nonce);
|
|
2218
|
+
unwatch =
|
|
2219
|
+
terminals.watchOutput?.(termId, sentinelReFor(nonce), (m) => {
|
|
2220
|
+
finish(m ? Number(m[1]) : terminals.bashTaskState(termId).exitCode);
|
|
2221
|
+
}) ?? (() => { });
|
|
2222
|
+
if (!finished) {
|
|
2223
|
+
ac.signal.addEventListener("abort", onAbort, { once: true });
|
|
2224
|
+
signal?.addEventListener("abort", onSignalAbort, { once: true });
|
|
2225
|
+
}
|
|
2226
|
+
if (!finished && deadline !== null) {
|
|
2227
|
+
const checkDeadline = () => {
|
|
2228
|
+
if (finished)
|
|
2229
|
+
return;
|
|
2230
|
+
if (Date.now() >= deadline)
|
|
2231
|
+
cancel(new Error(`Command timed out after ${p.timeout}s`));
|
|
2232
|
+
else {
|
|
2233
|
+
timeout = setTimeout(checkDeadline, armDelay(deadline, Date.now()));
|
|
2234
|
+
timeout.unref?.();
|
|
2235
|
+
}
|
|
2236
|
+
};
|
|
2237
|
+
checkDeadline();
|
|
2238
|
+
}
|
|
2112
2239
|
try {
|
|
2113
2240
|
let collected = "";
|
|
2114
2241
|
let cursor = start;
|
|
2115
2242
|
let lastDataAt = Date.now();
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
if (
|
|
2121
|
-
|
|
2243
|
+
if (signal?.aborted)
|
|
2244
|
+
onSignalAbort();
|
|
2245
|
+
if (failure)
|
|
2246
|
+
throw failure;
|
|
2247
|
+
if (!finished) {
|
|
2248
|
+
const inputErr = terminals.inputChecked(termId, injectedLine + "\r");
|
|
2249
|
+
if (inputErr)
|
|
2250
|
+
throw new Error(inputErr);
|
|
2251
|
+
}
|
|
2122
2252
|
for (;;) {
|
|
2123
|
-
if (
|
|
2124
|
-
|
|
2125
|
-
terminals.setSentinelPending(termId, false);
|
|
2126
|
-
terminals.inputChecked(termId, "\x03");
|
|
2127
|
-
closeOneShot();
|
|
2128
|
-
throw new Error(pick(lang, "命令已中止", "Command aborted", "terminals.bash.aborted"));
|
|
2129
|
-
}
|
|
2253
|
+
if (failure)
|
|
2254
|
+
throw failure;
|
|
2130
2255
|
await sleep(60);
|
|
2131
2256
|
const read = terminals.read(termId, cursor);
|
|
2132
2257
|
if (read?.data) {
|
|
@@ -2140,58 +2265,53 @@ export function makeTerminalBashTool(terminals, opts) {
|
|
|
2140
2265
|
collected = collected.slice(collected.length - BASH_COLLECT_MAX / 2);
|
|
2141
2266
|
}
|
|
2142
2267
|
}
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2268
|
+
// Also scan the collected slice: adapters may deliver buffered output
|
|
2269
|
+
// without invoking live watchers. Both paths use the same nonce.
|
|
2270
|
+
const marker = lastSentinel(collected, nonce);
|
|
2271
|
+
if (!finished && marker)
|
|
2272
|
+
finish(Number(marker[1]));
|
|
2273
|
+
if (failure)
|
|
2274
|
+
throw failure;
|
|
2275
|
+
if (finished) {
|
|
2276
|
+
if (exitCode === null)
|
|
2277
|
+
throw new Error("Terminal closed before command completion (exit code unknown)");
|
|
2278
|
+
const text = applyHeadTail(cleanCollected(collected), p.head, effectiveTail, lang);
|
|
2148
2279
|
return {
|
|
2149
2280
|
content: [
|
|
2150
2281
|
{
|
|
2151
2282
|
type: "text",
|
|
2152
|
-
text: `${text}${text ? "\n" : ""}${limiterNote}[exit:${
|
|
2283
|
+
text: `${text}${text ? "\n" : ""}${limiterNote}[exit:${exitCode}]`,
|
|
2153
2284
|
},
|
|
2154
2285
|
],
|
|
2155
|
-
details: { exitCode
|
|
2286
|
+
details: { exitCode, output: text },
|
|
2156
2287
|
};
|
|
2157
2288
|
}
|
|
2158
|
-
if (deadline !== null && Date.now() > deadline) {
|
|
2159
|
-
terminals.setSentinelPending(termId, false);
|
|
2160
|
-
terminals.inputChecked(termId, "\x03");
|
|
2161
|
-
closeOneShot();
|
|
2162
|
-
const timeoutPartial = truncateMiddle(stripAnsi(collected), 4000);
|
|
2163
|
-
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, timeout: p.timeout, timeoutPartial, sentinelNote: "" }));
|
|
2164
|
-
}
|
|
2165
2289
|
// 静默解阻(仅持久终端):转后台 + 注册完成观察器,立即把控制权还给模型。
|
|
2166
2290
|
if (persist && idleMs > 0 && Date.now() - lastDataAt >= idleMs) {
|
|
2167
|
-
|
|
2291
|
+
background = true;
|
|
2292
|
+
return backgroundResult(terminals, opts, runCommand, applyHeadTail(cleanCollected(collected), p.head, effectiveTail, lang), Math.round((Date.now() - lastDataAt) / 1000), lang, nonce, termId, persist, "idle");
|
|
2168
2293
|
}
|
|
2169
2294
|
// 总时长解阻(持久与一次性终端):前台运行达到上限,转入后台继续执行,避免卡死。
|
|
2170
2295
|
if (maxForegroundMs > 0 && Date.now() - startTime >= maxForegroundMs) {
|
|
2171
|
-
|
|
2296
|
+
background = true;
|
|
2297
|
+
return backgroundResult(terminals, opts, runCommand, applyHeadTail(cleanCollected(collected), p.head, effectiveTail, lang), Math.round((Date.now() - startTime) / 1000), lang, nonce, termId, persist, "elapsed");
|
|
2172
2298
|
}
|
|
2173
2299
|
}
|
|
2174
2300
|
}
|
|
2301
|
+
catch (error) {
|
|
2302
|
+
cancel(error instanceof Error ? error : new Error(String(error)));
|
|
2303
|
+
throw error;
|
|
2304
|
+
}
|
|
2175
2305
|
finally {
|
|
2176
|
-
|
|
2306
|
+
if (!background && !finished)
|
|
2307
|
+
finish(null);
|
|
2177
2308
|
}
|
|
2178
2309
|
},
|
|
2179
2310
|
});
|
|
2180
2311
|
}
|
|
2181
2312
|
/** 静默 / 总时长解阻路径:注册完成观察器后立即返回「仍在后台运行」。 */
|
|
2182
2313
|
function backgroundResult(terminals, opts, command, partialText, durationSeconds, lang, nonce, termId = "ai-bash", persist = true, reason = "idle") {
|
|
2183
|
-
|
|
2184
|
-
// 后台命令最终结束(或终端被关)→ 清除待决标记,terminal_wait 不再适用。
|
|
2185
|
-
terminals.setSentinelPending(termId, false);
|
|
2186
|
-
opts.notifyBackgroundDone({
|
|
2187
|
-
terminalId: termId,
|
|
2188
|
-
command,
|
|
2189
|
-
exitCode: m ? Number(m[1]) : null,
|
|
2190
|
-
});
|
|
2191
|
-
if (!persist) {
|
|
2192
|
-
void terminals.inputChecked(termId, "exit\r");
|
|
2193
|
-
}
|
|
2194
|
-
});
|
|
2314
|
+
// The task controller retains completion, cancellation and deadline ownership.
|
|
2195
2315
|
// partialText 已在调用方做过 cleanBashOutput + applyTail。
|
|
2196
2316
|
const partial = truncateMiddle(partialText, 6000);
|
|
2197
2317
|
// 空输出占位按语言预渲染(issue #91 v2:vars 只收干净标识)。
|
|
@@ -2220,12 +2340,12 @@ function backgroundResult(terminals, opts, command, partialText, durationSeconds
|
|
|
2220
2340
|
`Partial output:\n${partialEn}\n`;
|
|
2221
2341
|
}
|
|
2222
2342
|
if (persist) {
|
|
2223
|
-
descZh += `要重新阻塞等它结束就用
|
|
2224
|
-
descEn += `To block until it finishes, use
|
|
2343
|
+
descZh += `要重新阻塞等它结束就用 terminal(action='wait', terminalId='${termId}')(无需反复轮询);需要交互用 terminal(action='input'/'key', terminalId='${termId}')(Ctrl+C 可终止)。`;
|
|
2344
|
+
descEn += `To block until it finishes, use terminal(action='wait', terminalId='${termId}') (no polling needed); use terminal(action='input'/'key', terminalId='${termId}') to interact (Ctrl+C aborts).`;
|
|
2225
2345
|
}
|
|
2226
2346
|
else {
|
|
2227
|
-
descZh += `命令完成后该终端将自动退出并发送通知;如需查看输出可用
|
|
2228
|
-
descEn += `When completed, this terminal will exit automatically and notify; to inspect output, use
|
|
2347
|
+
descZh += `命令完成后该终端将自动退出并发送通知;如需查看输出可用 terminal(action='read', terminalId='${termId}')。`;
|
|
2348
|
+
descEn += `When completed, this terminal will exit automatically and notify; to inspect output, use terminal(action='read', terminalId='${termId}').`;
|
|
2229
2349
|
}
|
|
2230
2350
|
if (reason === "elapsed") {
|
|
2231
2351
|
return {
|
|
@@ -2261,18 +2381,10 @@ function backgroundResult(terminals, opts, command, partialText, durationSeconds
|
|
|
2261
2381
|
}
|
|
2262
2382
|
/** Agent 持久终端工具名(唯一登记见 tool-manager.ts;此处 re-export 保兼容)。 */
|
|
2263
2383
|
export { TERMINAL_TOOL_NAMES } from "./tool-manager.js";
|
|
2264
|
-
/**
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
export
|
|
2268
|
-
- The program is interactive or TUI-based (REPLs, vim/htop, y/n installers, anything waiting on stdin): prefer bash({persist:true}), which runs it in the persistent 'ai-bash' terminal and returns immediately; then drive it with terminal_input / terminal_key / terminal_read on terminalId='ai-bash'.
|
|
2269
|
-
- You start a long-running server or watcher and want to watch its output (terminal_read with waitMs), send keys later (e.g. Ctrl+c via terminal_key), or block until a backgrounded command finishes without polling (terminal_wait).
|
|
2270
|
-
- The user asks you to work in the visible terminal panel.
|
|
2271
|
-
Liveness watchdog: terminals you touched are monitored — if one goes silent while you are working (default 15s), a system reminder prompts you to check it (terminal_read), answer its input prompt, or close it (terminal_close) if no longer needed.`;
|
|
2272
|
-
/** Build the agent-facing persistent terminal tools for one conversation. */
|
|
2273
|
-
export function makePersistentTerminalTools(terminals, cwd,
|
|
2274
|
-
/** per-call 返回文本的服务端语言(默认英文);工具 definition 为纯英文。 */
|
|
2275
|
-
lang, options) {
|
|
2384
|
+
/** Guidance for choosing the persistent terminal over ordinary bash calls. */
|
|
2385
|
+
export const TERMINAL_TOOLS_GUIDANCE = `Use terminal(action) for interactive programs, REPLs, TUIs, persistent servers, or work in the visible terminal panel. Prefer bash for ordinary commands. Use create/list to select a terminal, input/key to drive it, and close when finished. read supports incremental cursors, output waiting, head/tail, and literal search. wait blocks for a tracked bash command's exit marker; commands submitted through input/key have no such marker, so observe them with read(waitMs). bash({persist:true}) uses terminalId='ai-bash' and may wait before returning. read/wait are read-only; other actions are write operations. When a liveness reminder arrives, read the terminal, answer its prompt, or close it.`;
|
|
2386
|
+
/** Build the single agent-facing persistent terminal tool for one conversation. */
|
|
2387
|
+
export function makePersistentTerminalTools(terminals, cwd, lang, options) {
|
|
2276
2388
|
const getLang = lang ?? (() => "en");
|
|
2277
2389
|
const result = (text, details = {}) => ({ content: [{ type: "text", text }], details });
|
|
2278
2390
|
const failIf = (error) => {
|
|
@@ -2305,257 +2417,249 @@ lang, options) {
|
|
|
2305
2417
|
};
|
|
2306
2418
|
return [
|
|
2307
2419
|
defineTool({
|
|
2308
|
-
name: "
|
|
2309
|
-
label: "
|
|
2310
|
-
description: "
|
|
2311
|
-
promptSnippet: "drive interactive programs or
|
|
2420
|
+
name: "terminal",
|
|
2421
|
+
label: "Terminal",
|
|
2422
|
+
description: "Manage persistent interactive PTYs. Actions: create/list/close/input/key/read/wait. terminalId is required except for list; input requires data and key requires key. read returns incremental output and cursor, with optional waiting and head/tail/search filters. wait blocks for a tracked bash command's completion marker or timeout; input/key commands have no completion marker. read/wait are read-only; all other actions are write operations.",
|
|
2423
|
+
promptSnippet: "drive interactive programs or inspect persistent terminal output",
|
|
2312
2424
|
promptGuidelines: [
|
|
2313
|
-
"
|
|
2425
|
+
"Prefer bash for ordinary commands. Use read(waitMs) for output from input/key; use wait only for tracked bash commands. Retain the returned cursor for incremental reads.",
|
|
2314
2426
|
],
|
|
2315
2427
|
parameters: Type.Object({
|
|
2316
|
-
|
|
2317
|
-
|
|
2428
|
+
action: Type.Union([
|
|
2429
|
+
Type.Literal("create"),
|
|
2430
|
+
Type.Literal("list"),
|
|
2431
|
+
Type.Literal("close"),
|
|
2432
|
+
Type.Literal("input"),
|
|
2433
|
+
Type.Literal("key"),
|
|
2434
|
+
Type.Literal("read"),
|
|
2435
|
+
Type.Literal("wait"),
|
|
2436
|
+
]),
|
|
2437
|
+
terminalId: Type.Optional(Type.String({ minLength: 1, description: "Required except for list" })),
|
|
2438
|
+
cwd: Type.Optional(Type.String({ description: "Workspace-relative directory for create" })),
|
|
2318
2439
|
cols: Type.Optional(Type.Integer({ minimum: 2, maximum: 500 })),
|
|
2319
2440
|
rows: Type.Optional(Type.Integer({ minimum: 2, maximum: 200 })),
|
|
2441
|
+
data: Type.Optional(Type.String({ description: "Required for input; include newline to submit" })),
|
|
2442
|
+
key: Type.Optional(Type.String({ description: "Required for key, e.g. Enter or c" })),
|
|
2443
|
+
modifiers: Type.Optional(Type.Object({
|
|
2444
|
+
ctrl: Type.Optional(Type.Boolean()),
|
|
2445
|
+
alt: Type.Optional(Type.Boolean()),
|
|
2446
|
+
shift: Type.Optional(Type.Boolean()),
|
|
2447
|
+
})),
|
|
2448
|
+
cursor: Type.Optional(Type.Integer({ minimum: 0, description: "Absolute output offset; pass returned cursor on next read" })),
|
|
2449
|
+
maxBytes: Type.Optional(Type.Integer({ minimum: 1, maximum: 100000 })),
|
|
2450
|
+
waitMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 120000 })),
|
|
2451
|
+
maxWaitMs: Type.Optional(Type.Integer({ minimum: 100, maximum: 600000 })),
|
|
2452
|
+
head: Type.Optional(Type.Integer({ minimum: 1, description: "Read: first N matching lines" })),
|
|
2453
|
+
tail: Type.Optional(Type.Integer({ minimum: 1, description: "Read: last N matching lines; exclusive with head" })),
|
|
2454
|
+
search: Type.Optional(Type.String({ description: "Read: literal, case-sensitive line filter after stripping ANSI" })),
|
|
2320
2455
|
}),
|
|
2321
|
-
execute: async (_id,
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
if (
|
|
2328
|
-
throw new Error(
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
"
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2456
|
+
execute: async (_id, args, signal) => {
|
|
2457
|
+
signal?.throwIfAborted();
|
|
2458
|
+
if (!["create", "list", "close", "input", "key", "read", "wait"].includes(args.action))
|
|
2459
|
+
throw new Error("Unknown terminal action");
|
|
2460
|
+
if (args.action !== "list" && (typeof args.terminalId !== "string" || !args.terminalId.trim()))
|
|
2461
|
+
throw new Error("terminalId is required for " + args.action);
|
|
2462
|
+
if (args.action === "input" && typeof args.data !== "string")
|
|
2463
|
+
throw new Error("data is required for input");
|
|
2464
|
+
if (args.action === "key" && (typeof args.key !== "string" || !args.key))
|
|
2465
|
+
throw new Error("key is required for key");
|
|
2466
|
+
if (args.action === "read" && args.head !== undefined && args.tail !== undefined)
|
|
2467
|
+
throw new Error("head and tail are mutually exclusive");
|
|
2468
|
+
const p = { ...args, terminalId: args.terminalId ?? "", data: args.data ?? "", key: args.key ?? "" };
|
|
2469
|
+
switch (p.action) {
|
|
2470
|
+
case "create": {
|
|
2471
|
+
const lang = getLang();
|
|
2472
|
+
const safeCols = Math.max(2, Math.min(500, Math.floor(p.cols ?? 120)));
|
|
2473
|
+
const safeRows = Math.max(2, Math.min(200, Math.floor(p.rows ?? 40)));
|
|
2474
|
+
const info = terminals.create(p.terminalId, p.cwd ?? cwd, safeCols, safeRows, cwd, p.terminalId);
|
|
2475
|
+
const infoJson = JSON.stringify(info);
|
|
2476
|
+
if (!info)
|
|
2477
|
+
throw new Error(pick(lang, `创建终端失败:${p.terminalId}`, `Failed to create terminal: ${p.terminalId}`, "terminals.create.failed", { "p.terminalId": p.terminalId }));
|
|
2478
|
+
// AI 创建 → 启动活力检测纪元(静默提醒只针对 agent 触碰过的终端)。
|
|
2479
|
+
terminals.noteAgentActivity(p.terminalId);
|
|
2480
|
+
return result(pick(lang, `终端已创建:${infoJson}`, `Terminal created: ${infoJson}`, "terminals.create.done", {
|
|
2481
|
+
infoJson,
|
|
2482
|
+
}), info);
|
|
2483
|
+
}
|
|
2484
|
+
case "list": {
|
|
2485
|
+
const list = terminals.list();
|
|
2486
|
+
return result(JSON.stringify(list), list);
|
|
2487
|
+
}
|
|
2488
|
+
case "close": {
|
|
2489
|
+
const lang = getLang();
|
|
2490
|
+
if (!terminals.has(p.terminalId))
|
|
2491
|
+
throw new Error(pick(lang, `终端不存在:${p.terminalId}`, `Terminal not found: ${p.terminalId}`, "terminals.close.not.found", { "p.terminalId": p.terminalId }));
|
|
2492
|
+
terminals.kill(p.terminalId);
|
|
2493
|
+
return result(pick(lang, `终端已关闭:${p.terminalId}`, `Terminal closed: ${p.terminalId}`, "terminals.close.done", {
|
|
2494
|
+
"p.terminalId": p.terminalId,
|
|
2495
|
+
}));
|
|
2496
|
+
}
|
|
2497
|
+
case "input": {
|
|
2498
|
+
const lang = getLang();
|
|
2499
|
+
const prevPending = getPending(p.terminalId);
|
|
2500
|
+
const parsed = parseTerminalLineStream(prevPending, p.data);
|
|
2501
|
+
if (options?.checkSafety && parsed.completedLines.length > 0) {
|
|
2502
|
+
for (const line of parsed.completedLines) {
|
|
2503
|
+
const cleanCmd = stripAnsi(line).trim();
|
|
2504
|
+
if (!cleanCmd)
|
|
2505
|
+
continue;
|
|
2506
|
+
const safety = await options.checkSafety(cleanCmd, {
|
|
2507
|
+
terminalId: p.terminalId,
|
|
2508
|
+
toolCallId: _id,
|
|
2509
|
+
toolName: "terminal",
|
|
2510
|
+
action: "input",
|
|
2511
|
+
});
|
|
2512
|
+
signal?.throwIfAborted();
|
|
2513
|
+
if (safety.blocked) {
|
|
2514
|
+
// 发现阻断:若终端此前已留有未提交字符,发送 \x03 取消当前行
|
|
2515
|
+
if (prevPending) {
|
|
2516
|
+
try {
|
|
2517
|
+
terminals.inputChecked(p.terminalId, "\x03");
|
|
2518
|
+
}
|
|
2519
|
+
catch {
|
|
2520
|
+
// ignore
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
clearPending(p.terminalId);
|
|
2524
|
+
const reason = pick(lang, safety.reason ?? "", safety.reasonEn ?? safety.reason ?? "");
|
|
2525
|
+
const reasonSuffix = reason ? (lang === "zh" ? ` 原因:${reason}` : ` Reason: ${reason}`) : "";
|
|
2526
|
+
throw new Error(safety.userDenied
|
|
2527
|
+
? pick(lang, `【操作被用户拒绝】${reasonSuffix}`, `[Operation denied by user]${reasonSuffix}`, "terminals.operation.denied", { reasonSuffix })
|
|
2528
|
+
: pick(lang, `【终端输入命令被安全规则阻断】${reasonSuffix}`, `[Terminal command blocked by safety rule]${reasonSuffix}`, "terminals.command.blocked", { reasonSuffix }));
|
|
2381
2529
|
}
|
|
2382
|
-
|
|
2383
|
-
//
|
|
2530
|
+
if (safety.editedCommand !== undefined) {
|
|
2531
|
+
// 用户通过审批改写了命令
|
|
2532
|
+
if (prevPending) {
|
|
2533
|
+
try {
|
|
2534
|
+
terminals.inputChecked(p.terminalId, "\x03");
|
|
2535
|
+
}
|
|
2536
|
+
catch {
|
|
2537
|
+
// ignore
|
|
2538
|
+
}
|
|
2539
|
+
}
|
|
2540
|
+
clearPending(p.terminalId);
|
|
2541
|
+
failIf(terminals.inputChecked(p.terminalId, safety.editedCommand + "\r"));
|
|
2542
|
+
terminals.noteAgentActivity(p.terminalId);
|
|
2543
|
+
return result(pick(lang, `已发送改写后的命令到 ${p.terminalId}:${safety.editedCommand}`, `Sent edited command to ${p.terminalId}: ${safety.editedCommand}`, "terminals.input.edited_sent", { command: safety.editedCommand, "p.terminalId": p.terminalId }));
|
|
2384
2544
|
}
|
|
2385
2545
|
}
|
|
2386
|
-
clearPending(p.terminalId);
|
|
2387
|
-
const reason = pick(lang, safety.reason ?? "", safety.reasonEn ?? safety.reason ?? "");
|
|
2388
|
-
const reasonSuffix = reason ? (lang === "zh" ? ` 原因:${reason}` : ` Reason: ${reason}`) : "";
|
|
2389
|
-
throw new Error(safety.userDenied
|
|
2390
|
-
? pick(lang, `【操作被用户拒绝】${reasonSuffix}`, `[Operation denied by user]${reasonSuffix}`, "terminals.operation.denied", { reasonSuffix })
|
|
2391
|
-
: pick(lang, `【终端输入命令被安全规则阻断】${reasonSuffix}`, `[Terminal command blocked by safety rule]${reasonSuffix}`, "terminals.command.blocked", { reasonSuffix }));
|
|
2392
2546
|
}
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2547
|
+
failIf(terminals.inputChecked(p.terminalId, p.data));
|
|
2548
|
+
setPending(p.terminalId, parsed.remainingPending);
|
|
2549
|
+
// AI 发了输入 = 在等结果,重开一个静默纪元。
|
|
2550
|
+
terminals.noteAgentActivity(p.terminalId);
|
|
2551
|
+
return result(pick(lang, `已发送 ${p.data.length} 个字符到 ${p.terminalId}`, `Sent ${p.data.length} chars to ${p.terminalId}`, "terminals.input.sent", { "p.data.length": p.data.length, "p.terminalId": p.terminalId }));
|
|
2552
|
+
}
|
|
2553
|
+
case "key": {
|
|
2554
|
+
const lang = getLang();
|
|
2555
|
+
const encoded = encodeTerminalKey(p.key, p.modifiers);
|
|
2556
|
+
if ("error" in encoded)
|
|
2557
|
+
throw new Error(encoded.error);
|
|
2558
|
+
const isEnter = encoded.data.includes("\r") || encoded.data.includes("\n");
|
|
2559
|
+
if (isEnter) {
|
|
2560
|
+
const pending = getPending(p.terminalId);
|
|
2561
|
+
const cleanCmd = stripAnsi(pending).trim();
|
|
2562
|
+
if (options?.checkSafety && cleanCmd) {
|
|
2563
|
+
const safety = await options.checkSafety(cleanCmd, {
|
|
2564
|
+
terminalId: p.terminalId,
|
|
2565
|
+
toolCallId: _id,
|
|
2566
|
+
toolName: "terminal",
|
|
2567
|
+
action: "key",
|
|
2568
|
+
});
|
|
2569
|
+
signal?.throwIfAborted();
|
|
2570
|
+
if (safety.blocked) {
|
|
2571
|
+
// 阻断 Enter 提交:发送 \x03 冲刷取消终端屏幕残留的脏命令
|
|
2572
|
+
try {
|
|
2573
|
+
terminals.inputChecked(p.terminalId, "\x03");
|
|
2574
|
+
}
|
|
2575
|
+
catch {
|
|
2576
|
+
// ignore
|
|
2577
|
+
}
|
|
2578
|
+
clearPending(p.terminalId);
|
|
2579
|
+
const reason = pick(lang, safety.reason ?? "", safety.reasonEn ?? safety.reason ?? "");
|
|
2580
|
+
const reasonSuffix = reason ? (lang === "zh" ? ` 原因:${reason}` : ` Reason: ${reason}`) : "";
|
|
2581
|
+
throw new Error(safety.userDenied
|
|
2582
|
+
? pick(lang, `【操作被用户拒绝】${reasonSuffix}`, `[Operation denied by user]${reasonSuffix}`, "terminals.operation.denied", { reasonSuffix })
|
|
2583
|
+
: pick(lang, `【终端输入命令被安全规则阻断】${reasonSuffix}`, `[Terminal command blocked by safety rule]${reasonSuffix}`, "terminals.command.blocked", { reasonSuffix }));
|
|
2398
2584
|
}
|
|
2399
|
-
|
|
2400
|
-
//
|
|
2585
|
+
if (safety.editedCommand !== undefined) {
|
|
2586
|
+
// 用户在审批弹窗中改写了命令:先取消原行,再提交改写后的命令
|
|
2587
|
+
try {
|
|
2588
|
+
terminals.inputChecked(p.terminalId, "\x03");
|
|
2589
|
+
}
|
|
2590
|
+
catch {
|
|
2591
|
+
// ignore
|
|
2592
|
+
}
|
|
2593
|
+
clearPending(p.terminalId);
|
|
2594
|
+
failIf(terminals.inputChecked(p.terminalId, safety.editedCommand + "\r"));
|
|
2595
|
+
terminals.noteAgentActivity(p.terminalId);
|
|
2596
|
+
return result(pick(lang, `已发送改写后的命令到 ${p.terminalId}:${safety.editedCommand}`, `Sent edited command to ${p.terminalId}: ${safety.editedCommand}`, "terminals.key.edited_sent", { command: safety.editedCommand, "p.terminalId": p.terminalId }));
|
|
2401
2597
|
}
|
|
2402
2598
|
}
|
|
2599
|
+
// 提交回车成功
|
|
2600
|
+
failIf(terminals.inputChecked(p.terminalId, encoded.data));
|
|
2403
2601
|
clearPending(p.terminalId);
|
|
2404
|
-
failIf(terminals.inputChecked(p.terminalId, safety.editedCommand + "\r"));
|
|
2405
2602
|
terminals.noteAgentActivity(p.terminalId);
|
|
2406
|
-
return result(pick(lang,
|
|
2603
|
+
return result(pick(lang, `已发送按键 ${p.key} 到 ${p.terminalId}`, `Sent key ${p.key} to ${p.terminalId}`, "terminals.key.sent", { "p.key": p.key, "p.terminalId": p.terminalId }));
|
|
2407
2604
|
}
|
|
2605
|
+
// 非回车按键:若为退格或清除键,更新 pending 缓冲
|
|
2606
|
+
const prev = getPending(p.terminalId);
|
|
2607
|
+
const parsed = parseTerminalLineStream(prev, encoded.data);
|
|
2608
|
+
failIf(terminals.inputChecked(p.terminalId, encoded.data));
|
|
2609
|
+
setPending(p.terminalId, parsed.remainingPending);
|
|
2610
|
+
terminals.noteAgentActivity(p.terminalId);
|
|
2611
|
+
return result(pick(lang, `已发送按键 ${p.key} 到 ${p.terminalId}`, `Sent key ${p.key} to ${p.terminalId}`, "terminals.key.sent", { "p.key": p.key, "p.terminalId": p.terminalId }));
|
|
2408
2612
|
}
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
|
|
2426
|
-
|
|
2427
|
-
|
|
2428
|
-
|
|
2429
|
-
|
|
2430
|
-
|
|
2431
|
-
}),
|
|
2432
|
-
execute: async (_id, p) => {
|
|
2433
|
-
const lang = getLang();
|
|
2434
|
-
const encoded = encodeTerminalKey(p.key, p.modifiers);
|
|
2435
|
-
if ("error" in encoded)
|
|
2436
|
-
throw new Error(encoded.error);
|
|
2437
|
-
const isEnter = encoded.data.includes("\r") || encoded.data.includes("\n");
|
|
2438
|
-
if (isEnter) {
|
|
2439
|
-
const pending = getPending(p.terminalId);
|
|
2440
|
-
const cleanCmd = stripAnsi(pending).trim();
|
|
2441
|
-
if (options?.checkSafety && cleanCmd) {
|
|
2442
|
-
const safety = await options.checkSafety(cleanCmd, {
|
|
2443
|
-
terminalId: p.terminalId,
|
|
2444
|
-
toolCallId: _id,
|
|
2445
|
-
toolName: "terminal_key",
|
|
2446
|
-
});
|
|
2447
|
-
if (safety.blocked) {
|
|
2448
|
-
// 阻断 Enter 提交:发送 \x03 冲刷取消终端屏幕残留的脏命令
|
|
2449
|
-
try {
|
|
2450
|
-
terminals.inputChecked(p.terminalId, "\x03");
|
|
2451
|
-
}
|
|
2452
|
-
catch {
|
|
2453
|
-
// ignore
|
|
2454
|
-
}
|
|
2455
|
-
clearPending(p.terminalId);
|
|
2456
|
-
const reason = pick(lang, safety.reason ?? "", safety.reasonEn ?? safety.reason ?? "");
|
|
2457
|
-
const reasonSuffix = reason ? (lang === "zh" ? ` 原因:${reason}` : ` Reason: ${reason}`) : "";
|
|
2458
|
-
throw new Error(safety.userDenied
|
|
2459
|
-
? pick(lang, `【操作被用户拒绝】${reasonSuffix}`, `[Operation denied by user]${reasonSuffix}`, "terminals.operation.denied", { reasonSuffix })
|
|
2460
|
-
: pick(lang, `【终端输入命令被安全规则阻断】${reasonSuffix}`, `[Terminal command blocked by safety rule]${reasonSuffix}`, "terminals.command.blocked", { reasonSuffix }));
|
|
2613
|
+
case "read": {
|
|
2614
|
+
const lang = getLang();
|
|
2615
|
+
const cursor = Math.max(0, Math.floor(p.cursor ?? 0));
|
|
2616
|
+
const waitMs = p.waitMs !== undefined ? Math.max(0, Math.min(120_000, Math.floor(p.waitMs))) : undefined;
|
|
2617
|
+
const maxBytes = Math.max(1, Math.min(100_000, Math.floor(p.maxBytes ?? 20000)));
|
|
2618
|
+
if (waitMs)
|
|
2619
|
+
await terminals.waitForOutput(p.terminalId, cursor, waitMs, signal);
|
|
2620
|
+
const read = terminals.read(p.terminalId, cursor, maxBytes);
|
|
2621
|
+
if (!read)
|
|
2622
|
+
throw new Error(pick(lang, `终端不存在:${p.terminalId}`, `Terminal not found: ${p.terminalId}`, "terminals.read.not.found", { "p.terminalId": p.terminalId }));
|
|
2623
|
+
if (p.head !== undefined || p.tail !== undefined || p.search !== undefined) {
|
|
2624
|
+
let lines = stripAnsi(read.data).split("\n");
|
|
2625
|
+
if (lines.at(-1) === "")
|
|
2626
|
+
lines.pop();
|
|
2627
|
+
if (p.search !== undefined)
|
|
2628
|
+
lines = lines.filter((line) => line.includes(p.search));
|
|
2629
|
+
if (p.head !== undefined)
|
|
2630
|
+
lines = lines.slice(0, p.head);
|
|
2631
|
+
if (p.tail !== undefined)
|
|
2632
|
+
lines = lines.slice(-p.tail);
|
|
2633
|
+
const filtered = { ...read, data: lines.join("\n") };
|
|
2634
|
+
return result(JSON.stringify(filtered), filtered);
|
|
2461
2635
|
}
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2468
|
-
|
|
2469
|
-
|
|
2470
|
-
|
|
2471
|
-
|
|
2472
|
-
|
|
2473
|
-
|
|
2636
|
+
return result(JSON.stringify(read), read);
|
|
2637
|
+
}
|
|
2638
|
+
case "wait": {
|
|
2639
|
+
const lang = getLang();
|
|
2640
|
+
if (!terminals.has(p.terminalId)) {
|
|
2641
|
+
throw new Error(pick(lang, `终端不存在:${p.terminalId}(可能已被关闭或会话重置,请先 terminal(action='create'))`, `Terminal not found: ${p.terminalId} (it may have been closed or the session was reset — run terminal(action='create') first)`, "terminals.wait.not.found", { "p.terminalId": p.terminalId }));
|
|
2642
|
+
}
|
|
2643
|
+
// 没有带哨兵的待决命令:shell 空闲在提示符,或该终端的命令是经
|
|
2644
|
+
// terminal(action='input') 手动发的(无完成标记)——等哨兵永远等不到,直接
|
|
2645
|
+
// 说明并引导改用 terminal(action='read'),避免 AI 无限重试。(显式传 cursor
|
|
2646
|
+
// 的调用是有目的的追溯查询,不拦。)
|
|
2647
|
+
if (p.cursor === undefined && !terminals.isSentinelPending(p.terminalId)) {
|
|
2648
|
+
const why = pick(lang, `终端 ${p.terminalId} 当前没有正在等待完成的 bash 工具命令(shell 空闲,或该命令是通过 terminal(action='input') 发出的、没有完成标记)。terminal(action='wait') 不适用;要观察输出请用 terminal(action='read', terminalId="${p.terminalId}", waitMs=…)。`, `Terminal ${p.terminalId} has no pending bash-tool command to wait for (the shell is idle, or the command was sent via terminal(action='input') and has no completion marker). terminal(action='wait') does not apply; use terminal(action='read', terminalId="${p.terminalId}", waitMs=…) to observe output.`, "terminals.wait.no.pending", { "p.terminalId": p.terminalId });
|
|
2649
|
+
return result(JSON.stringify({ applicable: false, reason: why }), { applicable: false });
|
|
2474
2650
|
}
|
|
2651
|
+
const cursor = p.cursor ?? terminals.endCursor(p.terminalId) ?? 0;
|
|
2652
|
+
const maxWait = Math.max(100, Math.min(600_000, Math.floor(p.maxWaitMs ?? 300_000)));
|
|
2653
|
+
const wait = await terminals.waitForCompletion(p.terminalId, maxWait, signal, cursor);
|
|
2654
|
+
const read = terminals.read(p.terminalId, cursor, 20_000);
|
|
2655
|
+
const outputTail = read?.data ? stripAnsi(read.data).slice(-4000) : "";
|
|
2656
|
+
return result(JSON.stringify({ ...wait, outputTail }), {
|
|
2657
|
+
...wait,
|
|
2658
|
+
outputTail,
|
|
2659
|
+
});
|
|
2475
2660
|
}
|
|
2476
|
-
// 提交回车成功
|
|
2477
|
-
failIf(terminals.inputChecked(p.terminalId, encoded.data));
|
|
2478
|
-
clearPending(p.terminalId);
|
|
2479
|
-
terminals.noteAgentActivity(p.terminalId);
|
|
2480
|
-
return result(pick(lang, `已发送按键 ${p.key} 到 ${p.terminalId}`, `Sent key ${p.key} to ${p.terminalId}`, "terminals.key.sent", { "p.key": p.key, "p.terminalId": p.terminalId }));
|
|
2481
2661
|
}
|
|
2482
|
-
|
|
2483
|
-
const prev = getPending(p.terminalId);
|
|
2484
|
-
const parsed = parseTerminalLineStream(prev, encoded.data);
|
|
2485
|
-
failIf(terminals.inputChecked(p.terminalId, encoded.data));
|
|
2486
|
-
setPending(p.terminalId, parsed.remainingPending);
|
|
2487
|
-
terminals.noteAgentActivity(p.terminalId);
|
|
2488
|
-
return result(pick(lang, `已发送按键 ${p.key} 到 ${p.terminalId}`, `Sent key ${p.key} to ${p.terminalId}`, "terminals.key.sent", { "p.key": p.key, "p.terminalId": p.terminalId }));
|
|
2489
|
-
},
|
|
2490
|
-
}),
|
|
2491
|
-
defineTool({
|
|
2492
|
-
name: "terminal_read",
|
|
2493
|
-
label: "Read terminal output",
|
|
2494
|
-
description: "Read incremental output from a persistent PTY. " +
|
|
2495
|
-
"Keep the returned cursor and pass it on the next read; " +
|
|
2496
|
-
"optionally wait for new output or process exit. " +
|
|
2497
|
-
"commandPending=true means a bash-tool command has not reported its exit code yet " +
|
|
2498
|
-
"(manual terminal_input commands are not tracked).",
|
|
2499
|
-
parameters: Type.Object({
|
|
2500
|
-
terminalId: Type.String(),
|
|
2501
|
-
cursor: Type.Optional(Type.Integer({ minimum: 0 })),
|
|
2502
|
-
maxBytes: Type.Optional(Type.Integer({ minimum: 1, maximum: 100000 })),
|
|
2503
|
-
waitMs: Type.Optional(Type.Integer({ minimum: 0, maximum: 120000 })),
|
|
2504
|
-
}),
|
|
2505
|
-
execute: async (_id, p, signal) => {
|
|
2506
|
-
const lang = getLang();
|
|
2507
|
-
const cursor = Math.max(0, Math.floor(p.cursor ?? 0));
|
|
2508
|
-
const waitMs = p.waitMs !== undefined ? Math.max(0, Math.min(120_000, Math.floor(p.waitMs))) : undefined;
|
|
2509
|
-
const maxBytes = Math.max(1, Math.min(100_000, Math.floor(p.maxBytes ?? 20000)));
|
|
2510
|
-
if (waitMs)
|
|
2511
|
-
await terminals.waitForOutput(p.terminalId, cursor, waitMs, signal);
|
|
2512
|
-
const read = terminals.read(p.terminalId, cursor, maxBytes);
|
|
2513
|
-
if (!read)
|
|
2514
|
-
throw new Error(pick(lang, `终端不存在:${p.terminalId}`, `Terminal not found: ${p.terminalId}`, "terminals.read.not.found", { "p.terminalId": p.terminalId }));
|
|
2515
|
-
return result(JSON.stringify(read), read);
|
|
2516
|
-
},
|
|
2517
|
-
}),
|
|
2518
|
-
defineTool({
|
|
2519
|
-
name: "terminal_wait",
|
|
2520
|
-
label: "Wait for terminal command",
|
|
2521
|
-
description: "Block until a bash-tool command finishes (exit marker) or timeout — no polling. " +
|
|
2522
|
-
"Returns {finished, exitCode} plus output produced meanwhile; finished=false = still running (call again). " +
|
|
2523
|
-
"terminal_input commands have no completion marker — use terminal_read(waitMs=…) for those.",
|
|
2524
|
-
promptSnippet: "avoid polling: wait for a long bash command to finish",
|
|
2525
|
-
parameters: Type.Object({
|
|
2526
|
-
terminalId: Type.String(),
|
|
2527
|
-
cursor: Type.Optional(Type.Integer({
|
|
2528
|
-
minimum: 0,
|
|
2529
|
-
description: "Ignore exit markers before this absolute offset (default: now)",
|
|
2530
|
-
})),
|
|
2531
|
-
maxWaitMs: Type.Optional(Type.Integer({
|
|
2532
|
-
minimum: 100,
|
|
2533
|
-
maximum: 600000,
|
|
2534
|
-
description: "Max wait in ms (default 300000)",
|
|
2535
|
-
})),
|
|
2536
|
-
}),
|
|
2537
|
-
execute: async (_id, p, signal) => {
|
|
2538
|
-
const lang = getLang();
|
|
2539
|
-
if (!terminals.has(p.terminalId)) {
|
|
2540
|
-
throw new Error(pick(lang, `终端不存在:${p.terminalId}(可能已被关闭或会话重置,请先 terminal_create)`, `Terminal not found: ${p.terminalId} (it may have been closed or the session was reset — run terminal_create first)`, "terminals.wait.not.found", { "p.terminalId": p.terminalId }));
|
|
2541
|
-
}
|
|
2542
|
-
// 没有带哨兵的待决命令:shell 空闲在提示符,或该终端的命令是经
|
|
2543
|
-
// terminal_input 手动发的(无完成标记)——等哨兵永远等不到,直接
|
|
2544
|
-
// 说明并引导改用 terminal_read,避免 AI 无限重试。(显式传 cursor
|
|
2545
|
-
// 的调用是有目的的追溯查询,不拦。)
|
|
2546
|
-
if (p.cursor === undefined && !terminals.isSentinelPending(p.terminalId)) {
|
|
2547
|
-
const why = pick(lang, `终端 ${p.terminalId} 当前没有正在等待完成的 bash 工具命令(shell 空闲,或该命令是通过 terminal_input 发出的、没有完成标记)。terminal_wait 不适用;要观察输出请用 terminal_read(terminalId="${p.terminalId}", waitMs=…)。`, `Terminal ${p.terminalId} has no pending bash-tool command to wait for (the shell is idle, or the command was sent via terminal_input and has no completion marker). terminal_wait does not apply; use terminal_read(terminalId="${p.terminalId}", waitMs=…) to observe output.`, "terminals.wait.no.pending", { "p.terminalId": p.terminalId });
|
|
2548
|
-
return result(JSON.stringify({ applicable: false, reason: why }), { applicable: false });
|
|
2549
|
-
}
|
|
2550
|
-
const cursor = p.cursor ?? terminals.endCursor(p.terminalId) ?? 0;
|
|
2551
|
-
const maxWait = Math.max(100, Math.min(600_000, Math.floor(p.maxWaitMs ?? 300_000)));
|
|
2552
|
-
const wait = await terminals.waitForCompletion(p.terminalId, maxWait, signal, cursor);
|
|
2553
|
-
const read = terminals.read(p.terminalId, cursor, 20_000);
|
|
2554
|
-
const outputTail = read?.data ? stripAnsi(read.data).slice(-4000) : "";
|
|
2555
|
-
return result(JSON.stringify({ ...wait, outputTail }), {
|
|
2556
|
-
...wait,
|
|
2557
|
-
outputTail,
|
|
2558
|
-
});
|
|
2662
|
+
throw new Error("Unknown terminal action");
|
|
2559
2663
|
},
|
|
2560
2664
|
}),
|
|
2561
2665
|
];
|