archivo del paquete→ .shtukbase/packages/harness/lib/harness.ts
lib/harness.ts
284 líneas, 15.7 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // The shared part of the harness packages: an agent page (`/agents/<x>.md`) becomes one non-interactive run of a
- // coding-agent CLI. A harness package (harness-claude, harness-codex …) is a thin adapter: it says how to build the
- // command line; everything else is here — reading the agent, the prompt, the time limit, the run journal (package
- // runs), the log file, the dry run. Bun only, no dependencies. The working directory is the project root.
- import { spawnSync } from 'node:child_process';
- import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
- import { delimiter, isAbsolute, join, relative, resolve } from 'node:path';
- import { readPage } from '../../collections/checks/lib/pages.ts';
- import { AGENT_TYPES, Project, count, map, text } from '../../agents/lib/factlib.ts';
- import { args, create, now, slug, update } from '../../agents/lib/write.ts';
- /** What the agent may do with files: read only, or read and write inside the project. */
- export type Access = 'read' | 'write';
- /** One run, resolved from the agent page and the command line. Paths are absolute. */
- export type Spec = {
- root: string;
- agent: string; // project path of the agent page
- harness: string;
- model: string; // the agent's model, or the adapter's default
- effort: string; // '' when not given
- cwd: string; // the working folder, inside the project
- access: Access;
- network: boolean;
- prompt: string; // the full text the agent gets
- minutes: number; // time limit
- tmp: string; // a scratch folder for this run (inside .shtukbase), removed after the run
- };
- /** The command an adapter builds. `stdin` is fed to the process; `files` are written before the run. */
- export type Command = {
- exe: string;
- args: string[];
- env?: Record<string, string>;
- unset?: string[];
- stdin?: string;
- files?: { path: string; text: string }[];
- notes?: string[]; // what the harness cannot enforce, said honestly
- };
- export type Adapter = {
- id: string; // the value of `runtime` on an agent page: claude, codex, opencode, dsh, hermes
- pkg: string; // the package id: harness-<id>
- bin: string; // the executable looked up on PATH
- title: string;
- defaultModel: string;
- install: string; // one line: how to get the CLI
- build(s: Spec): Command;
- };
- /** The harness names the packages know; `runtime` (or `harness`) on an agent page names one of them. */
- export const KNOWN = ['claude', 'codex', 'opencode', 'dsh', 'hermes'];
- /** Other spellings of the same harness. */
- const ALIAS: Record<string, string> = { 'claude-code': 'claude', deepseek: 'dsh', 'deepseek-harness': 'dsh', 'opencode-go': 'opencode', 'hermes-agent': 'hermes' };
- /** The harness an agent page names: `harness`, else `runtime`, lower case, aliases resolved; '' when none. */
- export function harnessOf(fm: Record<string, any>): string {
- const h = text(fm.harness || fm.runtime).toLowerCase();
- return ALIAS[h] ?? h;
- }
- /** The package that runs a harness, and its installed folder in the project. */
- export function harnessPkg(root: string, harness: string): { pkg: string; dir: string; installed: boolean } {
- const pkg = `harness-${harness}`;
- const dir = join(root, '.shtukbase', 'packages', pkg);
- return { pkg, dir, installed: existsSync(join(dir, 'actions', 'ask.ts')) };
- }
- /** Full path of an executable found on PATH, or null. */
- export function which(bin: string, path = process.env.PATH ?? ''): string | null {
- for (const d of path.split(delimiter).filter(Boolean)) {
- const f = join(d, bin);
- try {
- if (statSync(f).isFile()) return f;
- } catch { /* not here */ }
- }
- return null;
- }
- /** A project path (`/a/b`) → an absolute path inside the project, or null when it leaves the project. */
- export function inside(root: string, p: string): string | null {
- const abs = resolve(root, p.replace(/^\/+/, ''));
- const rel = relative(root, abs);
- return rel.startsWith('..') || isAbsolute(rel) ? null : abs;
- }
- /** Problems of an agent page for a harness run: [] when it can run. Used by `ask` and by the check HRN-R01. */
- export function agentProblems(root: string, fm: Record<string, any>): { what: string; fix: string; code: string }[] {
- const out: { what: string; fix: string; code: string }[] = [];
- if (!text(fm.model)) out.push({ what: 'no model set (model)', fix: 'write model: the model of the harness', code: 'no-model' });
- const acc = text(fm.access);
- if (!acc) out.push({ what: 'no access set (access)', fix: 'write access: read or write', code: 'no-access' });
- else if (acc !== 'read' && acc !== 'write') out.push({ what: `access "${acc}" is unknown`, fix: 'set access: read or write', code: 'bad-access' });
- if (fm.network !== undefined && fm.network !== null && typeof fm.network !== 'boolean' && !['true', 'false'].includes(text(fm.network)))
- out.push({ what: `network: "${text(fm.network)}" is not true/false`, fix: 'set network: false or true', code: 'bad-network' });
- const wd = text(fm.workdir);
- if (wd) {
- const abs = inside(root, wd);
- if (!abs) out.push({ what: `the working folder ${wd} is outside the project`, fix: 'workdir is a folder inside the project, a path from the root', code: 'workdir-outside' });
- else if (!existsSync(abs) || !statSync(abs).isDirectory()) out.push({ what: `the working folder ${wd} does not exist`, fix: 'create the folder or fix workdir', code: 'no-workdir' });
- }
- const ins = text(fm.instructions);
- if (ins) {
- const abs = inside(root, ins);
- if (!abs || !existsSync(abs)) out.push({ what: `the instruction file ${ins} is not in the project`, fix: 'fix instructions or remove the field (then the instruction is the page body)', code: 'no-instructions' });
- }
- if (fm.limits?.minutes !== undefined && count(fm.limits.minutes) === null)
- out.push({ what: `limits.minutes: "${text(fm.limits.minutes)}" is not a whole number`, fix: 'set limits: {minutes: 10}', code: 'bad-minutes' });
- return out;
- }
- function fail(msg: string, code = 2): never {
- console.error(msg);
- process.exit(code);
- }
- /** Single quotes for a shell, when a word needs them. */
- export function shq(s: string): string {
- return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
- }
- /** Reads the agent page and the task into a run spec. Exits 2 on a problem. */
- export function specOf(root: string, agentPath: string, task: string, adapter: Adapter | null, minutes?: unknown): Spec {
- const page = '/' + agentPath.replace(/^\/+/, '').replace(/(\.md)?$/, '.md');
- const file = inside(root, page);
- if (!file || !existsSync(file)) fail(`no agent page ${page}`);
- const { fm, body } = readPage(file);
- if (!AGENT_TYPES.includes(text(fm.type))) fail(`${page}: type "${text(fm.type) || '—'}" is not an agent (${AGENT_TYPES.join(', ')})`);
- const harness = harnessOf(fm);
- if (!harness) fail(`${page}: no harness named — write runtime: ${KNOWN.join(' | ')}`);
- if (adapter && harness !== adapter.id) fail(`${page}: the agent is on the harness "${harness}", but this is the package ${adapter.pkg}; run: shtuk run harness-${harness} ask --agent ${page}`);
- const probs = agentProblems(root, fm);
- if (probs.length) fail(probs.map((p) => `${page}: ${p.what} → ${p.fix}`).join('\n'));
- const ins = text(fm.instructions);
- const instructions = (ins ? readFileSync(inside(root, ins)!, 'utf8') : body).trim();
- const full = [instructions, task.trim()].filter(Boolean).join('\n\n---\n\n');
- if (!full) fail(`${page}: nothing to tell the agent — neither a page body nor --prompt`);
- const net = fm.network === true || text(fm.network) === 'true';
- const lim = count(minutes) ?? count(map(fm.limits)?.minutes) ?? 10;
- return {
- root, agent: page, harness, model: text(fm.model) || adapter?.defaultModel || '', effort: text(fm.effort),
- cwd: inside(root, text(fm.workdir) || '/')!, access: text(fm.access) as Access, network: net, prompt: full, minutes: lim,
- tmp: join(root, '.shtukbase', 'tmp', `run-${process.pid}-${Date.now()}`),
- };
- }
- /** The command line as one shell line, the prompt shortened. */
- export function commandLine(s: Spec, c: Command): string {
- const short = (w: string) => (w === s.prompt ? `<prompt: ${s.prompt.length} characters>` : shq(w));
- const env = Object.entries(c.env ?? {}).map(([k, v]) => `${k}=${shq(v.length > 200 ? v.slice(0, 200) + '…' : v)}`);
- const unset = (c.unset ?? []).map((k) => `-u ${k}`);
- const head = env.length || unset.length ? ['env', ...unset, ...env] : [];
- return [...head, c.exe, ...c.args.map(short)].join(' ') + (c.stdin !== undefined ? ` < <prompt: ${c.stdin.length} characters>` : '');
- }
- const MAXBUF = 64 * 1024 * 1024;
- /** Text without terminal colour codes. */
- export function plain(s: string): string {
- return s.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '');
- }
- /** Runs the command in the spec's folder with its time limit. */
- export function execute(s: Spec, c: Command): { code: number; out: string; err: string; seconds: number; timedOut: boolean; missing: boolean } {
- const exe = c.exe.includes('/') ? c.exe : which(c.exe);
- if (!exe) return { code: 127, out: '', err: `${c.exe} not found in PATH`, seconds: 0, timedOut: false, missing: true };
- mkdirSync(s.tmp, { recursive: true });
- for (const f of c.files ?? []) writeFileSync(f.path, f.text);
- const env: Record<string, string | undefined> = { ...process.env, ...(c.env ?? {}) };
- for (const k of c.unset ?? []) delete env[k];
- const t0 = Date.now();
- const r = spawnSync(exe, c.args, {
- cwd: s.cwd, env, input: c.stdin ?? '', encoding: 'utf8', timeout: s.minutes * 60_000, maxBuffer: MAXBUF, killSignal: 'SIGTERM',
- });
- rmSync(s.tmp, { recursive: true, force: true });
- const timedOut = (r.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT';
- return {
- code: timedOut ? 124 : r.status ?? 1, out: r.stdout ?? '', err: (r.stderr ?? '') + (r.error && !timedOut ? `\n${r.error.message}` : ''),
- seconds: Math.round((Date.now() - t0) / 100) / 10, timedOut, missing: false,
- };
- }
- /** Who started the run, written on the run page. */
- export type Origin = { automation?: string; action?: string; woke?: string; slot?: string; title?: string };
- /** The folder of the run journal (`/runs` unless the project put it elsewhere). */
- export function runsFolder(root: string): string {
- return new Project(root).coll('RUN') ?? '/runs';
- }
- /** Runs the spec and writes it to the run journal: a run page (running → done/failed) and a log file next to the
- * journal. Prints the run page and the agent's answer. Returns the exit code. */
- export function runLogged(s: Spec, c: Command, o: Origin): number {
- const coll = runsFolder(s.root);
- const started = now();
- const title = o.title || `${s.harness}: ${s.agent.replace(/^\/agents\//, '').replace(/\.md$/, '')}`;
- const name = `${started.slice(0, 10)}-${started.slice(11, 19).replaceAll(':', '')}-${slug(title)}`;
- const page = create(s.root, coll, name, {
- type: 'Run', title, agent: s.agent, action: o.action, automation: o.automation, woke: o.woke || 'hand', slot: o.slot,
- harness: s.harness, model: s.model, started, status: 'running',
- }, '');
- const file = join(s.root, page.replace(/^\/+/, ''));
- const log = `${coll.replace(/\/+$/, '')}/logs/${page.split('/').pop()!.replace(/\.md$/, '')}.log`;
- const r = execute(s, c);
- mkdirSync(join(s.root, log.replace(/^\/+/, ''), '..'), { recursive: true });
- writeFileSync(join(s.root, log.replace(/^\/+/, '')), [
- `# ${title}`, `command: ${commandLine(s, c)}`, `cwd: ${relative(s.root, s.cwd) || '.'}`, `exit: ${r.code}${r.timedOut ? ' (time limit)' : ''}`,
- `seconds: ${r.seconds}`, '', '## prompt', s.prompt, '', '## stdout', r.out, '', '## stderr', r.err, '',
- ].join('\n'));
- r.out = plain(r.out);
- r.err = plain(r.err);
- const answer = r.out.trim().split('\n').filter(Boolean).pop()?.slice(0, 200) ?? '';
- const ok = r.code === 0;
- const why = r.missing ? `${c.exe} not found in PATH`
- : r.timedOut ? `did not finish in ${s.minutes} min`
- : `exit code ${r.code}: ${(r.err.trim().split('\n').filter(Boolean).pop() ?? '').slice(0, 200)}`;
- update(file, {
- status: ok ? 'done' : 'failed', ended: now(), seconds: r.seconds,
- evidence: ok ? [log, ...(answer ? [`answer: ${answer}`] : [])] : undefined,
- message: ok ? undefined : why,
- }, ok ? undefined : `Log: ${log}`);
- console.log(`run: ${page} (${ok ? 'done' : 'failed'}, ${r.seconds} s)`);
- if (r.out.trim()) console.log(r.out.trim());
- if (!ok) console.error(why);
- return ok ? 0 : r.code || 1;
- }
- /** `ask --agent /agents/x.md [--prompt text | --prompt-file f] [--dry-run] [--minutes N] [--automation …] [--action …]
- * [--woke clock] [--slot ISO] [--title …]` for one adapter. Returns the exit code. */
- export function ask(adapter: Adapter | null, argv: string[], root = process.cwd()): number {
- const a = args(argv);
- const agent = typeof a.agent === 'string' ? a.agent : fail('--agent /agents/<name>.md is required');
- let task = typeof a.prompt === 'string' ? a.prompt : '';
- if (typeof a['prompt-file'] === 'string') {
- const f = resolve(root, a['prompt-file']);
- if (!existsSync(f)) fail(`no file ${a['prompt-file']}`);
- task = [task, readFileSync(f, 'utf8')].filter((x) => x.trim()).join('\n\n');
- }
- if (!adapter) {
- // the generic `harness ask`: find the adapter the agent names and run its package
- const file = inside(root, '/' + agent.replace(/^\/+/, '').replace(/(\.md)?$/, '.md'));
- if (!file || !existsSync(file)) fail(`no agent page ${agent}`);
- const h = harnessOf(readPage(file).fm);
- const hp = harnessPkg(root, h);
- if (!h) fail(`${agent}: no harness named — write runtime: ${KNOWN.join(' | ')}`);
- if (!hp.installed) fail(`${agent}: harness "${h}", but the package ${hp.pkg} is not in the project — shtuk install …/${hp.pkg}`);
- const r = spawnSync(process.execPath, [join(hp.dir, 'actions', 'ask.ts'), ...argv], { cwd: root, stdio: 'inherit' });
- return r.status ?? 1;
- }
- const s = specOf(root, agent, task, adapter, a.minutes);
- const c = adapter.build(s);
- if (a['dry-run']) {
- console.log(`harness: ${adapter.id} (${adapter.title}), model: ${s.model}, access: ${s.access}, network: ${s.network ? 'yes' : 'no'}, limit: ${s.minutes} min`);
- console.log(`folder: ${relative(root, s.cwd) || '.'}`);
- console.log(`command: ${commandLine(s, c)}`);
- for (const f of c.files ?? []) console.log(`file for the time of the run: ${relative(root, f.path)}\n${f.text.trimEnd()}`);
- for (const n of c.notes ?? []) console.log(`attention: ${n}`);
- console.log(`--- prompt ---\n${s.prompt}`);
- console.log(which(c.exe) ? 'dry run: nothing was run' : `dry run: nothing was run; ${c.exe} not found in PATH`);
- return 0;
- }
- return runLogged(s, c, {
- automation: typeof a.automation === 'string' ? a.automation : undefined,
- action: typeof a.action === 'string' ? a.action : undefined,
- woke: typeof a.woke === 'string' ? a.woke : undefined,
- slot: typeof a.slot === 'string' ? a.slot : undefined,
- title: typeof a.title === 'string' ? a.title : undefined,
- });
- }
- /** The sensor of a harness package: is the CLI on PATH and does it answer `--version`. Never fails the check: a
- * missing CLI is a warning line (agents on it will not run), exit 0. */
- export function sensor(adapter: Adapter): void {
- const exe = which(adapter.bin);
- if (!exe) {
- console.log(`warning: ${adapter.bin} not found in PATH — agents on the harness ${adapter.id} will not run; install: ${adapter.install}`);
- return;
- }
- const r = spawnSync(exe, ['--version'], { encoding: 'utf8', timeout: 20_000, stdio: ['ignore', 'pipe', 'pipe'] });
- const line = `${r.stdout ?? ''}\n${r.stderr ?? ''}`.split('\n').map((l) => l.trim()).find((l) => /\d+\.\d+/.test(l));
- if (r.error || r.status !== 0 || !line)
- console.log(`warning: ${adapter.bin} --version did not answer (${r.error ? r.error.message : `code ${r.status}`}) — check the installation: ${adapter.install}`);
- else console.log(`${adapter.bin}: ${line}`);
- }