import { spawn } from 'node:child_process'; import { existsSync } from 'node:fs'; import { delimiter, join } from 'node:path'; import { z } from 'zod'; import { requestUserChoice } from '../../askBridge.js'; import { getWorkingDir } from '../../bootstrap/workingDir.js'; import { classifyCommand } from '../../irreversible/rules.js'; import { mustSettleBackgroundTasks } from '../../runtime/invocationPolicy.js'; import type { Tool, ToolCallContext, ToolResult } from '../../types.js'; import { toToolParameters } from '../../utils/zodToJson.js'; import { checkForbidden, sanitizedChildEnv } from '../bash/bash.js'; import { killTree } from '../shared/killTree.js'; import { startBackgroundTask } from '../tasks/backgroundTaskService.js'; import { processExecutionMetadata } from '../tasks/processEvidence.js'; import { DEFAULT_MAX_RESULT_SIZE_CHARS } from '../types.js'; import { permanentDeleteReason } from '../shared/permanentDeleteGuard.js'; import { ToolOutputStore } from '../shared/toolOutputStore.js'; const MAX_TIMEOUT_MS = 600_000; function findPowerShell(): string | undefined { if (process.platform !== 'win32') return undefined; const explicit = process.env.MINIMAL_AGENT_POWERSHELL_PATH; if (explicit && existsSync(explicit)) return explicit; for (const name of ['pwsh.exe', 'powershell.exe']) { for (const dir of (process.env.PATH ?? '').split(delimiter)) { const path = join(dir, name); if (existsSync(path)) return path; } } const system = join( process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe', ); return existsSync(system) ? system : undefined; } const inputSchema = z.object({ command: z.string().min(1), timeout: z.number().int().positive().max(MAX_TIMEOUT_MS).optional(), description: z.string().optional(), run_in_background: z.boolean().optional(), }); type PowerShellInput = z.infer; function invocation(command: string): string[] { return [ '-NoLogo', '-NoProfile', '-NonInteractive', '-Command', `$OutputEncoding=[Console]::OutputEncoding=[Text.UTF8Encoding]::new(); ${command}`, ]; } async function approved( command: string, signal?: AbortSignal, cwd = getWorkingDir(), ): Promise { const permanentDelete = permanentDeleteReason(command, 'powershell'); if (permanentDelete) return { ok: false, error: `永久删除检查拒绝执行:${permanentDelete}\n命令:${command}\n\n` + '请立即调用 Trash(action="move") 将目标移入系统回收站。' + '不要创建替代文件、不要换写法重试,也不要把删除目标改成其他路径。', recovery: 'change-input', }; const forbidden = checkForbidden(command); if (forbidden) return { ok: false, error: `安全检查拒绝执行:${forbidden}\n命令:${command}`, }; const irreversible = classifyCommand(command, cwd); if (!irreversible) return undefined; const [answer] = await requestUserChoice( [ { question: `这条命令不可逆:${irreversible.why}。\n\n命令:${command}\n\n确认执行吗?`, header: '不可逆操作', options: [ { label: '取消,不执行 (推荐)', description: '放弃并改用可回滚做法' }, { label: '我已确认后果,执行', description: '继续执行不可逆操作' }, ], }, ], signal, ); return answer?.selected?.length === 1 && answer.selected[0] === '我已确认后果,执行' ? undefined : { ok: false, error: `已拒绝执行不可逆 PowerShell 命令:${command}` }; } async function call( input: PowerShellInput, signal?: AbortSignal, context?: ToolCallContext, ): Promise { if (signal?.aborted) return { ok: false, error: 'aborted' }; const executable = findPowerShell(); if (!executable) return { ok: false, error: '当前宿主没有可用的 PowerShell' }; const refusal = await approved(input.command, signal, context?.cwd ?? getWorkingDir()); if (refusal) return refusal; if (signal?.aborted) return { ok: false, error: 'aborted' }; const args = invocation(input.command); const cwd = context?.cwd ?? getWorkingDir(); // 同 bash.ts:'wait' 策略的宿主没有空闲唤醒者,分离出去等于回合结束就被杀。 const settleBackground = mustSettleBackgroundTasks( context?.executionServices?.invocationPolicy, ); const backgroundDegraded = Boolean(input.run_in_background) && settleBackground; if (input.run_in_background && !settleBackground) { try { const task = await startBackgroundTask( { command: input.command, executable, args, cwd, env: sanitizedChildEnv(), sessionId: context?.sessionId, workspaceId: context?.workspaceId, shellKind: 'powershell', deliveryId: context?.deliveryId, request: context?.backgroundRequest ?? context?.currentUserInput, }, context?.sessionState?.backgroundTasks, ); return { ok: true, content: `PowerShell 后台任务已启动。task_id=${task.id.replace(/^proc_/, '')}\nprocess_id=${task.id}\nlog=${task.logPath}`, metadata: processExecutionMetadata({ shell: 'powershell', mode: 'background', command: input.command, status: 'started', taskId: task.id, }), }; } catch (error) { return { ok: false, error: `PowerShell 后台任务启动失败:${(error as Error).message}`, }; } } return await new Promise((resolvePromise) => { const child = spawn(executable, args, { cwd, env: sanitizedChildEnv(), windowsHide: true, detached: false, stdio: ['ignore', 'pipe', 'pipe'], }); let finished = false; const store = new ToolOutputStore({ workspaceId: context?.workspaceId, sessionId: context?.sessionId, }); const finish = async ( status: 'completed' | 'failed' | 'stopped', code: number | null, prefix = '', ) => { if (finished) return; finished = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); const output = await store.finish(); const reference = output.path ? `\n[完整输出: ${output.path}; bytes=${output.bytes}; sha256=${output.sha256}; complete=${output.complete}]` : ''; const degradedNote = backgroundDegraded ? `[本阶段必须在返回前结清委派工作,已按前台执行(超时上限 ${input.timeout ?? 120_000}ms),不是后台任务;没有 task_id 可查]\n` : ''; let text = `${degradedNote}${prefix}${output.stdout ? `\n${output.stdout.trimEnd()}\n\n` : ''}${output.stderr ? `\n${output.stderr.trimEnd()}\n\n` : ''}[exit code: ${code ?? 'killed'}]`; if (text.length + reference.length > DEFAULT_MAX_RESULT_SIZE_CHARS) { const suffix = `\n... (输出预览已截断)${reference}`; text = text.slice( 0, Math.max(0, DEFAULT_MAX_RESULT_SIZE_CHARS - suffix.length), ) + suffix; } else text += reference; const metadata = processExecutionMetadata({ shell: 'powershell', mode: 'foreground', command: input.command, status, exitCode: code, }); resolvePromise( status === 'completed' ? { ok: true, content: text, metadata } : { ok: false, error: text, metadata }, ); }; const abort = () => { killTree(child); void finish('stopped', null, 'PowerShell 命令被中断\n'); }; const timeout = input.timeout ?? 120_000; const timer = setTimeout(() => { killTree(child); void finish('failed', null, `PowerShell 命令超时(${timeout}ms)\n`); }, timeout); signal?.addEventListener('abort', abort, { once: true }); child.stdout?.setEncoding('utf8'); child.stderr?.setEncoding('utf8'); child.stdout?.on('data', (chunk) => { if (!store.append('stdout', chunk)) { child.stdout?.pause(); store.onDrain(() => child.stdout?.resume()); } }); child.stderr?.on('data', (chunk) => { if (!store.append('stderr', chunk)) { child.stderr?.pause(); store.onDrain(() => child.stderr?.resume()); } }); child.once('error', (error) => { void finish('failed', null, `PowerShell 启动失败:${error.message}\n`); }); child.once('close', (code) => { void finish(code === 0 ? 'completed' : 'failed', code); }); if (signal?.aborted) abort(); }); } export const powerShellTool: Tool = { name: 'PowerShell', description: `Executes native PowerShell on Windows. Use for Windows-specific administration and scripts; use run_in_background for long builds, tests, or servers, then TaskOutput/TaskStop. Non-interactive: inherited stdin is closed (EOF); there is no PTY or follow-up input channel. Supply input through explicit pipes/redirection or non-interactive flags. # Safety - two levels, from strict to lenient ## 1. Blocked outright (fails before execution - do NOT retry with variants) Catastrophic commands (no legitimate use): \`rm -rf /\`-class deletions of root/$HOME/system directories, \`mkfs\`, \`format X:\`, \`dd\` to raw devices, shutdown/reboot, fork bombs, pipe-to-shell from network (\`curl ... | sh\`), \`chmod 777 /\`, full-disk \`del /s\` / \`rmdir /s\`, \`diskpart\`. Permanent deletion (bypasses the Recycle Bin - use the Trash tool instead): \`Remove-Item\`, \`Clear-RecycleBin\`, \`del\` / \`erase\` / \`rd\` / \`rmdir\` / \`rm\` / \`ri\`, and \`.Delete()\` method calls - all fail before execution. 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 try other deletion spellings - they are blocked the same way. If a permanent deletion is truly required, ask the user to run it themselves. ## 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 they are automatically cancelled. - Git discard/rewrite: reset --hard, path checkout, restore, forced checkout/switch, commit --amend, bypassing hooks/signing, push --force-with-lease. Reflog does not reliably recover uncommitted edits; repair requests do not authorize discarding others' work. - \`git push --force\` / \`-f\` / \`+refspec\`, \`git push --delete \` - \`git filter-branch\` / \`git filter-repo\`, \`git reflog expire --expire=now\` / \`git gc --prune=now\` - \`shred -u\` / \`shred --remove\` - SQL data destruction: \`DROP DATABASE\`, \`DROP TABLE\`, \`TRUNCATE TABLE\``, inputSchema, parameters: toToolParameters(inputSchema), isReadOnly: false, isConcurrencySafe: false, maxResultSizeChars: DEFAULT_MAX_RESULT_SIZE_CHARS, interruptBehavior: () => 'block', resolveAvailability: () => { const executable = findPowerShell(); return { available: Boolean(executable), signature: executable ?? 'unavailable', }; }, call: (input, signal) => call(input, signal), callWithContext: (input, signal, context) => call(input, signal, context), };