src/tools/program-tool.ts
4 KB - 查看原始文件
// Running programs without a shell (lab 04).
//
// The model sends a program name and an argument LIST, never a command string. We call
// execFile, which starts the program directly: there is no shell, so `;`, `|`, `&&`, `$(...)`,
// and globs have no special meaning. "ls; rm -rf ~" is just a strange file name to ls.
//
// What may run is decided by the policy (src/security/policy.ts), which matches the argument
// vector against allow / ask / deny rules before this code is ever reached.
import { execFile } from 'node:child_process';
import { mkdtempSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { z } from 'zod';
import { defineTool, type Tool } from './tool.ts';
import type { Workspace } from './workspace.ts';
const MAX_BUFFER = 1_000_000;
export interface ProgramToolOptions {
workspace: Workspace;
timeoutMs: number;
}
export function programTool({ workspace, timeoutMs }: ProgramToolOptions): Tool {
// HOME is an empty folder outside the workspace. If HOME were the workspace, a .gitconfig the
// model wrote there would become git's global config, and git runs programs named in it
// (core.fsmonitor, hooks, filters). Global and system git config are switched off as well.
let home: string | undefined;
const emptyHome = () => (home ??= mkdtempSync(path.join(os.tmpdir(), 'steward-home-')));
return defineTool({
name: 'run_program',
description:
'Runs one program in the workspace folder, without a shell. Give the program name and ' +
'its arguments as a list, for example {"program": "git", "args": ["log", "--oneline", ' +
'"-5"]}. Pipes, redirects, and ";" do not work. Some programs need the owner\'s approval.',
input: z.object({
program: z
.string()
.regex(/^[A-Za-z0-9._+-]+$/, 'a bare program name such as "git", not a path')
.describe('Program name, found on PATH'),
args: z.array(z.string().refine((a) => !a.includes('\0'), 'no NUL bytes')).default([]),
}),
argv: ({ program, args }) => [program, ...args],
summarize: ({ program, args }) => `run_program ${[program, ...args].join(' ')}`,
run: ({ program, args }, context) =>
new Promise<string>((resolve) => {
execFile(
program,
args,
{
cwd: workspace.root,
...(context.signal ? { signal: context.signal } : {}),
timeout: timeoutMs,
maxBuffer: MAX_BUFFER,
// A minimal environment: no API keys or tokens from the parent process.
env: {
PATH: process.env.PATH ?? '/usr/bin:/bin',
HOME: emptyHome(),
XDG_CONFIG_HOME: emptyHome(),
GIT_CONFIG_GLOBAL: '/dev/null',
GIT_CONFIG_NOSYSTEM: '1',
GIT_TERMINAL_PROMPT: '0',
LANG: 'C.UTF-8',
},
},
(error, stdout, stderr) => {
const parts: string[] = [];
if (error && 'killed' in error && error.killed) {
parts.push(`Stopped after ${timeoutMs} ms (timeout).`);
} else if (error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
// The program started but printed too much and was stopped. Keep what it printed
// (limitOutput cuts it down to tools.maxOutputChars).
const printed = [
stdout && `--- stdout ---\n${stdout}`,
stderr && `--- stderr ---\n${stderr}`,
];
resolve(
[`Stopped: the output passed ${MAX_BUFFER} bytes.`, ...printed]
.filter(Boolean)
.join('\n'),
);
return;
} else if (error?.code === 'ABORT_ERR') {
resolve(`Stopped: the turn was cancelled before ${program} finished.`);
return;
} else if (error && typeof error.code === 'string') {
// ENOENT and similar: the program could not be started at all.
resolve(`Could not start ${program}: ${error.code}`);
return;
}
const code = error ? (typeof error.code === 'number' ? error.code : 1) : 0;
parts.push(`exit code ${code}`);
if (stdout) parts.push(`--- stdout ---\n${stdout}`);
if (stderr) parts.push(`--- stderr ---\n${stderr}`);
resolve(parts.join('\n'));
},
);
}),
});
}