/** * ============================================================ * src/tools/bash.ts —— Bash 工具(万能命令兜底) * ------------------------------------------------------------ * 对应 kakadeai 主仓库的 BashTool。 * 这是 minimal-agent 的"瑞士军刀" —— 当 Read/Edit/Write/Glob/Grep * 搞不定时(rm 文件、chmod、git、npm/curl、跑测试...),就用它。 * * 设计原则(重要): * * 1. 优先用专用工具,Bash 只做兜底 * - 读文件 → Read(不要 cat/head/tail) * - 写文件 → Write(不要 echo > / cat <nul & ` 强制 UTF-8 输出(根治乱码)。 // ③ description 运行时声明实际 shell(见下),模型按真实语法写命令。 // 可用 MINIMAL_AGENT_BASH_PATH 显式指定(绿色版 U 盘机器上 Git 安装位置不可预知)。 function detectWindowsBash(): string | null { if (process.platform !== 'win32') return null; const explicit = process.env.MINIMAL_AGENT_BASH_PATH; if (explicit && existsSync(explicit)) return explicit; const pf = process.env.ProgramFiles ?? 'C:\\Program Files'; const pf86 = process.env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)'; const local = process.env.LOCALAPPDATA ?? ''; const candidates = [ join(pf, 'Git', 'bin', 'bash.exe'), join(pf, 'Git', 'usr', 'bin', 'bash.exe'), join(pf86, 'Git', 'bin', 'bash.exe'), local ? join(local, 'Programs', 'Git', 'bin', 'bash.exe') : '', ].filter(Boolean); for (const c of candidates) { if (existsSync(c)) return c; } // PATH 兜底扫描(跳过 System32 的 WSL bash) for (const dir of (process.env.PATH ?? '').split(';')) { if (!dir || /\\system32\\?/i.test(dir)) continue; const p = join(dir, 'bash.exe'); if (existsSync(p)) return p; } return null; } const WIN_BASH = detectWindowsBash(); /** * 本工具这一刻**真正**把命令交给谁执行。 * * 单一出处:description(告诉模型该写哪种语法)与 permanentDeleteGuard(按哪套动词 * 匹配删除命令)必须看同一个判断,否则就会出现「description 说这是 cmd、守卫却按 * bash 匹配」这种两头对不上的裂缝 —— del / rd 会因此直接穿过全部三层防护。 */ function effectiveShellKind(): ShellKind { return process.platform === 'win32' && !WIN_BASH ? 'cmd' : 'bash'; } /** * 每台机器不同、只能运行时探测的 shell 方言警告(K1 事故修复的核心内容)。 * 单一出处:完整 description(下方)和 toolPromptGuides.ts 的压缩 override * 都调这个函数,不允许各自抄一份文案——否则「压缩省 token」的那份会在 * 无 Git Bash 的机器上悄悄丢掉这条警告,模型照抄 POSIX 语法必挂 * (`mkdir -p` 在 cmd.exe 下不生成中间目录、`$VAR`/`export` 不存在)。 */ export function bashShellNotice(): string { if (process.platform !== 'win32') return 'Commands run via /bin/sh -c (POSIX shell), not a login shell. For Bash-specific syntax invoke bash explicitly. Each call starts in the workspace; cd and shell variables do not persist.'; return WIN_BASH ? `# Shell (this machine) Commands run in a real bash (Git Bash at ${WIN_BASH}). POSIX syntax works: \`mkdir -p\`, \`$VAR\`, \`$(...)\`, \`&&\`, \`[ -f x ]\` are all fine. Note the working directory is a Windows path — both \`D:\\path\` and \`/d/path\` forms work in this bash.` : `# Shell (this machine) — IMPORTANT No bash found on this Windows machine: commands run in cmd.exe (UTF-8 enforced). POSIX syntax does NOT work here: - NO \`mkdir -p\` — cmd's \`mkdir a\\b\\c\` creates intermediate directories by default; better: the Write tool auto-creates parent directories - NO \`$VAR\` / \`$(...)\` / \`[ -f x ]\` / \`export\` — use \`%VAR%\`, \`if exist\`, \`set\` - Use \`dir\` / \`copy\` / \`del\` / \`type\` instead of \`ls\` / \`cp\` / \`rm\` / \`cat\` \`&&\` and \`;\`-style chaining: \`&&\` works in cmd; \`;\` does not (use \`&\`).`; } /** * G1:stdout / stderr 即时缓冲上限(各自)。命令狂输出(如 cat 大文件 / yes)时, * 在最终统一截断之前先把内存封顶,防 OOM。取最终展示截断阈值的 2 倍 —— 正常输出不受影响, * 超大输出也只占有限内存(最终仍按 DEFAULT_MAX_RESULT_SIZE_CHARS 截断展示)。 */ const MAX_STREAM_BUFFER_CHARS = DEFAULT_MAX_RESULT_SIZE_CHARS * 2; /** * 灾难性命令黑名单。 * 命中任意一条就直接拒绝执行 —— 这层是"防猪队友"而不是真沙盒。 * * 选词依据(每条注释解释为啥要拦): * - 历史上"误删生产/格盘/锁机"的真实事故都对应一类模式 * - 工程协作里这些命令几乎不会被合法用到(如要用,肯定是用户在终端自己手敲) * * 工具仅是"模型可调用的能力",模型规规矩矩地写代码、跑测试时永远不会触到这些。 */ const FORBIDDEN_PATTERNS: Array<{ pattern: RegExp; reason: string }> = [ // ---- rm -rf / 及变体 ---- // 经典:"rm -rf /"、"rm -rf /*"、"rm -fr /usr"、"rm -rf $HOME"、"rm -rf ~" // 也覆盖 sudo rm -rf / { pattern: /\brm\s+(?:-[a-zA-Z]*[rRf][a-zA-Z]*\s+)+(?:\/+\*?|\$HOME|~)(?:\s|$)/, reason: '禁止递归删除根目录或家目录(rm -rf / 类)', }, // 拦截 "rm -rf <绝对路径>" 中目标是关键系统目录的情况(防误伤其它正常 rm -rf ./tmp) { pattern: /\brm\s+(?:-[a-zA-Z]*[rRf][a-zA-Z]*\s+)+(?:\/etc|\/usr|\/bin|\/sbin|\/var|\/boot|\/lib|\/System|\/Windows|\/Users|\/home)(?:\/|\s|$)/, reason: '禁止递归删除系统关键目录', }, // ---- 格盘 / 改写裸设备 ---- { pattern: /\bmkfs(?:\.[a-z0-9]+)?\b/i, reason: '禁止格式化文件系统(mkfs)', }, { // 末尾不能用 \b:盘符 "C:" 后是非 word char,\b 匹配不到。 // 改成"盘符后跟空白/反斜杠/结尾"。 pattern: /\bformat\s+[A-Za-z]:(?=\s|\\|$)/i, reason: '禁止 Windows 格盘命令(format X:)', }, { pattern: /\bdd\s+[^|;&]*\bof=\/dev\/(?:sd[a-z]|nvme|disk|hd[a-z]|mmcblk)/i, reason: '禁止 dd 写入裸磁盘设备', }, { pattern: />\s*\/dev\/(?:sd[a-z]|nvme|disk|hd[a-z]|mmcblk)/i, reason: '禁止重定向到裸磁盘设备', }, // ---- 关机 / 重启 ---- // 只匹配「命令位置」的关机词:串首 / 换行 / ; & | ` ( { / $( / sudo·doas·exec·nohup / systemctl 之后。 // 事故(2026-07-02):此前 /\b(?:shutdown|…)\b/ 对整段命令裸词扫描(注释也算), // ppt.yaml stage_export 的 bash 注释「硬门 halt」被误杀 → 整步执行前被拒 → // onError:halt → 确定性死端(resume 原样命令原样再拒,永久卡死)。 // "halt" 是工作流引擎自身词汇(onError: halt),注释/echo 文案里出现属正常写作。 // 已知窄化(防猪队友层可接受):env/timeout 等间接调用不再拦;注释里 ASCII "; halt" 仍会误伤 // (workflows 全库有 bashBlacklist.sweep.test.ts 兜底扫描)。 { pattern: /(?:^|[\n;&|`({]|\$\(|\b(?:sudo|doas|exec|nohup)\s+|\bsystemctl\s+)\s*(?:shutdown|reboot|halt|poweroff)\b/i, reason: '禁止关机/重启命令', }, { pattern: /\binit\s+[06]\b/, reason: '禁止 init 0/6(关机/重启)', }, // ---- Fork bomb ---- { pattern: /:\s*\(\s*\)\s*\{\s*:\s*\|\s*:\s*&\s*\}\s*;\s*:/, reason: '禁止 fork bomb', }, // ---- 管道到 shell(典型恶意安装脚本模式) ---- // curl ... | sh / wget ... | bash:POSIX shell 把管道内容整体当脚本执行,不管有没有 // 参数,网络内容变代码天然危险,无条件拦。 { pattern: /\b(?:curl|wget|fetch)\b[^|;&]*\|\s*(?:sh|bash|zsh|dash)\b/i, reason: '禁止从网络管道到 shell 解释器(curl ... | sh 模式)', }, // curl ... | python / node 等脚本解释器:只有**裸调用**(后面没有 -c/-e/-m/脚本文件参数, // 管道内容本身就是被执行的程序,如 curl get-pip.py | python 这类经典安装器)才是同类风险。 // 事故教训:旧正则无条件拦所有 curl|python,连 `curl ... | python3 -c "import // sys,json;print(json.load(sys.stdin)['token'])"` 这种从 curl 响应里提取字段的常见写法 // 也一并误杀——此时管道内容只是喂给本地可见代码的 stdin 数据,不是被当程序执行,拦这个 // 纯属把无害的数据处理当成"下载执行",与 agent 能力优先的原则冲突。 // 判据是"管道内容会不会变成被执行的程序":裸调用(无参数)和显式 `-`(python/node/perl/ // ruby 都认这个写法为"从 stdin 读程序")等价危险,都拦;带 -c/-e/-m/脚本文件名则只是数据,放行。 { pattern: /\b(?:curl|wget|fetch)\b[^|;&]*\|\s*(?:python3?|perl|ruby|node)\s*-?\s*(?:[;&|\n]|$)/i, reason: '禁止从网络管道到脚本解释器裸执行(curl ... | python 模式)', }, // ---- chmod 整盘 777 ---- { pattern: /\bchmod\s+(?:-R\s+)?[0-7]*7[0-7]*\s+\/(?:\s|$)/, reason: '禁止对根目录 chmod 777', }, // ---- Windows 系统级删除 ---- { pattern: /\b(?:del|erase)\s+\/[sS][^|;&]*[A-Za-z]:\\?\s*$/, reason: '禁止 Windows 全盘删除(del /s 根目录)', }, { pattern: /\brmdir\s+\/[sS][^|;&]*[A-Za-z]:\\?\s*$/, reason: '禁止 Windows 全盘 rmdir', }, { pattern: /\bdiskpart\b/i, reason: '禁止 diskpart', }, ]; /** * 检查命令是否命中黑名单。 * 返回命中的原因字符串,否则返回 null。 */ export function checkForbidden(command: string): string | null { for (const { pattern, reason } of FORBIDDEN_PATTERNS) { if (pattern.test(command)) return reason; } return null; } /** * 子进程环境变量:从 process.env 复制后**剥离 agent 自己的密钥** * (`MINIMAL_AGENT_*` / `TAVILY_*`)。 * * 动机(安全):main.tsx 启动时会把 saved config 里的 key 注入 process.env。 * 若原样把 process.env 透传给 Bash 子进程,模型只要跑 `echo $MINIMAL_AGENT_API_KEY` * 就能把 key(绿色版里是卖家预置的)读进 tool result、回传 LLM、甚至打到 -p stdout。 * 这些 env 是 agent 自身配置,子进程命令并不需要 —— 直接删掉,最小化泄露面。 * 其余变量(PATH / HOME / 用户自己 export 的)照常透传。 * * 导出供测试断言。 */ export function sanitizedChildEnv( base: NodeJS.ProcessEnv = process.env, ): NodeJS.ProcessEnv { const env = sanitizeCredentialEnv(base); for (const key of Object.keys(env)) { if (key.startsWith('MINIMAL_AGENT_') || key.startsWith('TAVILY_')) { delete env[key]; } } // 保证子进程里的 Python 用 UTF-8 解码(PEP 540 UTF-8 Mode)。否则中文 Windows 上 // locale.getpreferredencoding() = cp936/GBK,`subprocess.run(text=True)` / `open()` // 默认就用 GBK 解码子进程的 UTF-8 输出 → 撞非法字节必崩(曾致 ppt 工作流 build_probe // `UnicodeDecodeError: 'gbk' codec can't decode byte 0xa8` 直接 halt 整条工作流)。 // 这是 Bash 工具「保证 UTF-8 世界」既有立场(cmd 回落已 chcp 65001)的加性延伸: // 一处覆盖所有 bash 步 spawn 的 python(内联 heredoc + 技能脚本),现在与将来。 // 跨平台安全:类 Unix 本就 UTF-8 → no-op;顺带治 POSIX/C locale(ASCII) 同类坑。 env.PYTHONUTF8 = '1'; env.PYTHONIOENCODING = 'utf-8'; return env; } // ---------------- 1. Zod 输入 schema ---------------- const inputSchema = z.object({ command: z .string() .min(1, '必须提供 command') .describe('要执行的 shell 命令;方言以当前工具说明为准'), timeout: z .number() .int() .positive() .max(MAX_TIMEOUT_MS) .optional() .describe(`超时(毫秒),最多 ${MAX_TIMEOUT_MS}(${MAX_TIMEOUT_MS / 60_000} 分钟);不填默认 ${DEFAULT_TIMEOUT_MS}`), description: z .string() .optional() .describe('用一句话主动语态描述命令做什么(5-10 词),如 "List files in current directory"'), run_in_background: z.boolean().optional().describe('长时间构建、测试或开发服务器设为 true;用 TaskOutput 获取增量输出、TaskStop 停止'), }); type BashInput = z.infer; // ---------------- 2. JSON Schema(由 Zod 自动派生) ---------------- const parameters = toToolParameters(inputSchema); // ---------------- 3. Description(给 LLM 看的工具说明) ---------------- // // 提炼自 kakadeai/tools/BashTool/prompt.ts 的 getSimplePrompt()。 // 核心逻辑: // - 先点明"专用工具优先"的原则,把每类操作映射到对应工具 // - 再列 Bash 自身的使用规范(绝对路径 / 不 cd / 超时 / 多命令并行...) // - 最后强调安全黑名单(让模型知道哪些命令会被拒,避免反复试) const shellNotice = bashShellNotice(); const description = `Executes a given bash command and returns its output. Each call starts in the current workspace. A cd or shell variable change affects only that call; shell state and profile loading are not preserved. Non-interactive: inherited stdin is closed (EOF), with no PTY or follow-up input channel. Use explicit pipes/redirection or a command's non-interactive flags when it needs input. IMPORTANT: Avoid using this tool to run \`find\`, \`grep\`, \`cat\`, \`head\`, \`tail\`, \`sed\`, \`awk\`, or \`echo\` commands, unless explicitly instructed or after you have verified that a dedicated tool cannot accomplish your task. Instead, use the appropriate dedicated tool as this will provide a much better experience for the user: - File search: Use Glob (NOT find or ls) - Content search: Use Grep (NOT grep or rg) - Read files: Use Read (NOT cat/head/tail) - Edit files: Use Edit (NOT sed/awk) - Write files: Use Write (NOT echo >/cat <>>\` — optionally \`|detail=low\` (cheap overview) and \`|maxLongSide=960\`. The image is attached for you to see and the line is stripped from the output. Up to ${MAX_ATTACH_IMAGES} per call; the file must live under the working directory or the system temp directory. # Exit code semantics Some commands return non-zero exit codes for informational (non-error) reasons. Bash recognizes these and reports them as success (ok=true) — do NOT retry just because exit code is 1: - \`grep\` / \`rg\` exit 1 → no match found (not an error) - \`find\` exit 1 → some directories inaccessible (non-fatal, partial results still returned) - \`diff\` / \`cmp\` exit 1 → files differ (informational, not an error) - \`test\` / \`[\` exit 1 → condition is false (the answer to a question, not a failure) Only exit codes ≥ 2 from these commands indicate a real failure. For all other commands, non-zero exit codes are treated as failures normally. # Safety - three levels, from strict to lenient ## 1. Blocked outright (fails before execution - do NOT retry with variants) Catastrophic commands (no legitimate use): - \`rm -rf /\` and variants targeting root, $HOME, ~, or system directories (/etc, /usr, /bin, /Windows, /Users, /home, ...) - Filesystem destruction: \`mkfs\`, \`format X:\`, \`dd of=/dev/sdX\`, redirects to raw block devices - Power management: \`shutdown\`, \`reboot\`, \`halt\`, \`poweroff\`, \`init 0/6\` - Fork bombs - Pipe-to-shell from network: \`curl ... | sh\`, \`wget ... | bash\`, etc. - \`chmod 777 /\`, Windows full-disk \`del /s\` / \`rmdir /s\`, \`diskpart\` Permanent deletion (bypasses the OS Trash / Recycle Bin - use the Trash tool instead): - \`rm\`, \`unlink\`, \`rmdir\` (any shell-level file/dir deletion, any target) - \`find ... -delete\` - \`git clean -f\` / \`git clean --force\` (\`-n\` / \`--dry-run\` is fine) To delete files or directories use the **Trash** tool (\`action: "move"\` - recoverable); to clean Git untracked files use Trash with \`action: "git-clean"\`. Do NOT work around this by switching to \`find -delete\`, Python \`os.remove\`, Node \`fs.rm\`, or other shell variants - they are blocked the same way. If a permanent deletion is truly required, ask the user to run it themselves in their terminal. ## 2. Requires user confirmation (irreversible) These have legitimate uses but destroy the last copy - execution pauses and asks the user to confirm. In non-interactive contexts (sub-agents, cron, batch mode) they are automatically cancelled. - Discard/rewrite operations: \`git reset --hard\`, path \`git checkout\`, \`git restore\`, forced checkout/switch, \`git commit --amend\`, bypassing hooks/signing. - \`git push --force-with-lease\` still rewrites remote history; lease checking is not authorization. - \`git push --force\` / \`-f\`, and \`git push origin +branch\` (+refspec = force push) - \`git push --delete \` / \`git push :\` (deleting remote branches) - \`git filter-branch\` / \`git filter-repo\` (rewriting history) - \`git reflog expire --expire=now\` / \`git gc --prune=now\` (destroying reflog) - \`shred -u\` / \`shred --remove\` (overwrite and delete - unrecoverable) - SQL data destruction: \`DROP DATABASE\`, \`DROP TABLE\`, \`TRUNCATE TABLE\` ## 3. Warning only (command still runs) These execute normally; a \`⚠️ 警告:\` line is prepended to the output as a reminder. They are NOT blocked. - \`git branch -D\`, \`git stash drop\` / \`git stash clear\` (local, recoverable via reflog in most cases) - \`DELETE FROM ...\` (SQL row deletion; DROP/TRUNCATE are in level 2) - \`kubectl delete\`, \`terraform destroy\` Regular Git operations (commit, add, status, log, diff, pull, fetch, checkout , merge, rebase, etc.) run without extra restrictions.${shellNotice ? `\n\n${shellNotice}` : ''}`; // ---------------- 4. call() —— 真正干活 ---------------- async function call(input: BashInput, signal?: AbortSignal, context?: ToolCallContext): Promise { if (signal?.aborted) return { ok: false, error: 'aborted' }; const command = input.command; const timeoutMs = Math.min(input.timeout ?? DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS); // 4a. 安全黑名单(命中即拒) const forbiddenReason = checkForbidden(command); if (forbiddenReason) { return { ok: false, error: `安全检查拒绝执行:${forbiddenReason}\n命令:${command}`, recovery: 'user-action', }; } // 传**实际执行命令的 shell**,不是工具名:win32 上找不到 Git Bash 时下面走的是 // cmd.exe(见 WIN_BASH 探测),description 也会告诉模型「这里是 cmd」,模型于是写 // del / rd —— 按 'bash' 匹配的话这两个词一个都拦不住(黑名单与 irreversible 规则表 // 同样只认 POSIX 形态),等于三层全空。 const permanentDelete = permanentDeleteReason(command, effectiveShellKind()); if (permanentDelete) return { ok: false, error: `永久删除检查拒绝执行:${permanentDelete}\n命令:${command}\n\n` + '请立即调用 Trash(action="move") 将目标移入系统回收站。' + '不要创建替代文件、不要换写法重试,也不要把删除目标改成其他路径。', recovery: 'change-input', }; // 4a-1. 不可逆动作闸门:毁掉「最后一份副本」的命令要**停下来问人**。 // // 与上面黑名单的分工:黑名单是「灾难且无正当用途」→ 直接拒;这里是 // 「不可逆但有正当用途」(force push / 删库 / 毁 reflog)→ 问一句。 // 判据与规则表都在内核 `src/irreversible/rules.ts`,与 ComputerUse 共用。 // // ★ 选项顺序不能改:askBridge 在**没有交互宿主**时(`-p`、cron、子 agent) // 自动选第一项。所以第一项必须是「取消」——无人可问时 fail-closed。 const irreversible = classifyCommand(command, context?.cwd ?? getWorkingDir()); if (irreversible) { const [answer] = await requestUserChoice( [ { question: `这条命令不可逆:${irreversible.why}。\n\n命令:${command}\n\n确认执行吗?`, header: '不可逆操作', options: [ { label: '取消,不执行 (推荐)', description: '放弃这一步,请 AI 换个可回滚的做法' }, { label: '我已确认后果,执行', description: '我清楚这一步做完找不回来' }, ], }, ], signal, ); const approved = answer?.selected?.length === 1 && answer.selected[0] === '我已确认后果,执行'; if (!approved) { return { ok: false, // 明确要求模型**停下**而不是改写命令绕过去。没有这句,模型收到拒绝后 // 极可能把 `--force` 换成 `-f`、把 `push --force` 换成 `push origin +main` // 再试一次 —— 那既绕过了闸门,也不是用户想要的。 error: `已被用户/策略拒绝执行(不可逆操作:${irreversible.why})。\n` + `命令:${command}\n\n` + `请**不要**改写命令重试(换 -f、换 +refspec、拆成多条都算绕过)。` + `改用可回滚的做法,或直接把这一步交还给用户手动执行。`, }; } } // 4a-2. 破坏性命令告警扫描(仅警告,不阻塞) // 命中后把警告挂到结果输出顶部,让模型/用户看见苗头。 const destructiveWarning = scanDestructiveCommand(command); if (signal?.aborted) return { ok: false, error: 'aborted' }; // 'wait' 策略下不许分离:这些宿主(工作流步骤、子任务、-p)没有空闲唤醒者, // 回合一结束 backgroundTaskService 的 exit 钩子就把进程杀了,产物静默丢失。 // 契约本身已经向模型声明了「宿主会等待其完成」,所以退化为前台正是那句话的实现。 const settleBackground = mustSettleBackgroundTasks( context?.executionServices?.invocationPolicy, ); const backgroundDegraded = Boolean(input.run_in_background) && settleBackground; if (input.run_in_background && !settleBackground) { try { const cwd = context?.cwd ?? getWorkingDir(); const task = await startBackgroundTask( WIN_BASH ? { command, executable: WIN_BASH, args: ['-c', command], cwd, env: sanitizedChildEnv(), sessionId: context?.sessionId, workspaceId: context?.workspaceId, shellKind: 'bash' as const, deliveryId: context?.deliveryId, request: context?.backgroundRequest ?? context?.currentUserInput } : { command: process.platform === 'win32' ? `chcp 65001 >nul & ${command}` : command, cwd, env: sanitizedChildEnv(), shell: true, sessionId: context?.sessionId, workspaceId: context?.workspaceId, shellKind: 'bash' as const, deliveryId: context?.deliveryId, request: context?.backgroundRequest ?? context?.currentUserInput, }, context?.sessionState?.backgroundTasks, ); return { ok: true, content: `${destructiveWarning ? `⚠️ 警告: ${destructiveWarning}\n` : ''}后台任务已启动。task_id=${task.id.replace(/^proc_/,'')}\nprocess_id=${task.id}\nlog=${task.logPath}\n使用 TaskOutput 增量读取输出,TaskStop 停止进程。`, metadata: processExecutionMetadata({ shell: 'bash', mode: 'background', command, status: 'started', taskId: task.id }), }; } catch (error) { return { ok: false, error: `后台命令启动失败:${(error as Error).message}` }; } } // 4b. spawn —— 平台分派(见 0b 探测注释): // Unix: /bin/sh -c (shell:true) // Windows + Git Bash: bash.exe -c (POSIX 语法成立) // Windows 无 bash: cmd.exe,命令前缀 chcp 65001 强制 UTF-8 输出 let stdout = ''; let stderr = ''; const outputStore = new ToolOutputStore({ workspaceId: context?.workspaceId, sessionId: context?.sessionId, }); let exitCode: number | null = null; let timedOut = false; let killedBySignal = false; // 用 AbortController 把外部 signal + 我们自己的 timeout 合并成一个 const ac = new AbortController(); const onAbort = () => ac.abort(); signal?.addEventListener('abort', onAbort, { once: true }); if (signal?.aborted) ac.abort(); const timer = setTimeout(() => { timedOut = true; ac.abort(); }, timeoutMs); try { await new Promise((resolveP, rejectP) => { const spawnOpts = { cwd: context?.cwd ?? getWorkingDir(), env: sanitizedChildEnv(), windowsHide: true, // This tool has no interactive input channel: readers must observe EOF. stdio: ['ignore', 'pipe', 'pipe'] as ['ignore', 'pipe', 'pipe'], // POSIX:detached 自成进程组,中断时 killTree 的 kill(-pid) 才能掀整组;win32 不 detached(taskkill /T 掀树)。 detached: process.platform !== 'win32', }; const child = WIN_BASH ? spawn(WIN_BASH, ['-c', command], spawnOpts) : spawn( process.platform === 'win32' ? `chcp 65001 >nul & ${command}` : command, { ...spawnOpts, shell: true }, ); // 中断/超时收尾:杀**整棵进程树**(不是只杀直接 shell)。否则 win32 上 shell 被杀后,在飞的 // 孙进程(bun test / 构建 / 起服务…)变孤儿继续跑、还占着 stdout 管道让 'close' 永不触发 —— // 表现为「点了停止、agent 停了、活儿还在后台跑」的"停不下来"(与 2026-07-02 生图事故同源)。 // 不再把 signal 交给 spawn 自己 kill(那只杀直接子进程,还会抢在 killTree 前把 shell 杀掉、 // 让 taskkill /T 够不到已成孤儿的孙进程);改由这里统一 killTree + 立即 resolve,不空等 'close'。 const onKill = () => { killedBySignal = true; killTree(child, 'SIGKILL'); child.stdout?.destroy(); child.stderr?.destroy(); resolveP(); }; if (ac.signal.aborted) onKill(); else ac.signal.addEventListener('abort', onKill, { once: true }); child.stdout?.setEncoding('utf8'); child.stderr?.setEncoding('utf8'); child.stdout?.on('data', (chunk) => { if (!outputStore.append('stdout', chunk)) { child.stdout?.pause(); outputStore.onDrain(() => child.stdout?.resume()); } }); child.stderr?.on('data', (chunk) => { if (!outputStore.append('stderr', chunk)) { child.stderr?.pause(); outputStore.onDrain(() => child.stderr?.resume()); } }); child.on('error', (e) => { ac.signal.removeEventListener('abort', onKill); rejectP(e); }); child.on('close', (code, sig) => { ac.signal.removeEventListener('abort', onKill); exitCode = code; if (sig) killedBySignal = true; resolveP(); }); }); } catch (e) { return { ok: false, error: `执行命令失败:${(e as Error).message}\n命令:${command}`, metadata: processExecutionMetadata({ shell: 'bash', mode: 'foreground', command, status: 'failed', exitCode: null }), }; } finally { clearTimeout(timer); signal?.removeEventListener('abort', onAbort); } const storedOutput = await outputStore.finish(); stdout = storedOutput.stdout; stderr = storedOutput.stderr; // 4b-2. ATTACH_IMAGE sentinel:脚本可以打一行 `<<>>` 让模型亲眼看图。 // 协议行**从 content 剥掉**(那是给宿主看的,不是给模型读的噪声);被拒的条目 // 如实写进输出(静默丢弃会让脚本作者以为图发出去了,无从 debug)。 // `ToolResult` 的成功与失败分支都能带 visionImages,所以脚本**不必**为了 // 附图而假装成功——非零退出码照样能把图带给模型。 const attach = extractAttachImageDirectives(stdout); stdout = attach.text; const { images: visionImages, rejections: attachRejections } = await resolveAttachImages(attach.directives); // 4c. 拼输出 const parts: string[] = []; if (backgroundDegraded) { parts.push( `[本阶段必须在返回前结清委派工作,已按前台执行(超时上限 ${timeoutMs}ms),不是后台任务;没有 task_id 可查]`, ); } if (stdout) parts.push(`\n${stdout.replace(/\s+$/, '')}\n`); if (stderr) parts.push(`\n${stderr.replace(/\s+$/, '')}\n`); if (visionImages.length > 0) { parts.push(`[已附加 ${visionImages.length} 张图片供你查看]`); } if (attachRejections.length > 0) { parts.push( `[附图被拒绝]\n${attachRejections.map((r) => `- ${r}`).join('\n')}`, ); } if (parts.length === 0) parts.push(''); if (timedOut) { parts.push(`\n[超时 ${timeoutMs}ms 后被中断]`); } else if (killedBySignal && !timedOut) { parts.push(`\n[被信号中断]`); } parts.push(`\n[exit code: ${exitCode === null ? 'killed' : exitCode}]`); const outputReference = storedOutput.path ? `\n[完整输出: ${storedOutput.path}; bytes=${storedOutput.bytes}; sha256=${storedOutput.sha256}; complete=${storedOutput.complete}]` : ''; let combinedOutput = parts.join('\n'); // 4d. 大小兜底 if (combinedOutput.length + outputReference.length > DEFAULT_MAX_RESULT_SIZE_CHARS) { const suffix = `\n\n... (输出超过 ${DEFAULT_MAX_RESULT_SIZE_CHARS} 字符,预览已截断)${outputReference}`; combinedOutput = safeSlice(combinedOutput, 0, Math.max(0, DEFAULT_MAX_RESULT_SIZE_CHARS - suffix.length)) + suffix; } else combinedOutput += outputReference; // 4e. 中断 / 超时仍然算硬失败 // 失败也带上已解析的附图:脚本挂掉前截的那张诊断图正是最该看的。 if (timedOut || killedBySignal) { return { ok: false, error: combinedOutput, metadata: processExecutionMetadata({ shell: 'bash', mode: 'foreground', command, status: 'failed', exitCode }), ...(visionImages.length > 0 ? { visionImages } : {}), }; } // 4f. 语义化退出码判定 // 交给 semantics 模块:grep/rg/find/diff/test 有"信息性退出码", // 其它命令用默认语义(exitCode !== 0 即错)。 // destructiveWarning 命中时把告警贴在输出头部,模型/用户都能看见。 const semantic = interpretCommandResult( command, exitCode ?? 0, stdout, stderr, ); const finalContent = destructiveWarning ? `⚠️ 警告: ${destructiveWarning}\n\n${combinedOutput}` : combinedOutput; if (semantic.isError) { return { ok: false, error: `命令失败 (exit ${exitCode}): ${stderr || stdout || semantic.message || ''}`.trim() + `\n\n${finalContent}`, metadata: processExecutionMetadata({ shell: 'bash', mode: 'foreground', command, status: 'failed', exitCode }), ...(visionImages.length > 0 ? { visionImages } : {}), }; } return { ok: true, content: finalContent, metadata: processExecutionMetadata({ shell: 'bash', mode: 'foreground', command, status: 'completed', exitCode }), ...(visionImages.length > 0 ? { visionImages } : {}), }; } // ---------------- 5. 导出 ---------------- export const bashTool: Tool = { name: 'Bash', description, inputSchema, parameters, isReadOnly: false, isConcurrencySafe: false, // 默认按"会改状态"算;保守不并发 maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, interruptBehavior: () => 'block', call: (input, signal) => call(input, signal), callWithContext: (input, signal, context) => call(input, signal, context), };