ShtukbaseStandard
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.

  1. // The shared part of the harness packages: an agent page (`/agents/<x>.md`) becomes one non-interactive run of a
  2. // coding-agent CLI. A harness package (harness-claude, harness-codex …) is a thin adapter: it says how to build the
  3. // command line; everything else is here — reading the agent, the prompt, the time limit, the run journal (package
  4. // runs), the log file, the dry run. Bun only, no dependencies. The working directory is the project root.
  5. import { spawnSync } from 'node:child_process';
  6. import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
  7. import { delimiter, isAbsolute, join, relative, resolve } from 'node:path';
  8. import { readPage } from '../../collections/checks/lib/pages.ts';
  9. import { AGENT_TYPES, Project, count, map, text } from '../../agents/lib/factlib.ts';
  10. import { args, create, now, slug, update } from '../../agents/lib/write.ts';
  11. /** What the agent may do with files: read only, or read and write inside the project. */
  12. export type Access = 'read' | 'write';
  13. /** One run, resolved from the agent page and the command line. Paths are absolute. */
  14. export type Spec = {
  15. root: string;
  16. agent: string; // project path of the agent page
  17. harness: string;
  18. model: string; // the agent's model, or the adapter's default
  19. effort: string; // '' when not given
  20. cwd: string; // the working folder, inside the project
  21. access: Access;
  22. network: boolean;
  23. prompt: string; // the full text the agent gets
  24. minutes: number; // time limit
  25. tmp: string; // a scratch folder for this run (inside .shtukbase), removed after the run
  26. };
  27. /** The command an adapter builds. `stdin` is fed to the process; `files` are written before the run. */
  28. export type Command = {
  29. exe: string;
  30. args: string[];
  31. env?: Record<string, string>;
  32. unset?: string[];
  33. stdin?: string;
  34. files?: { path: string; text: string }[];
  35. notes?: string[]; // what the harness cannot enforce, said honestly
  36. };
  37. export type Adapter = {
  38. id: string; // the value of `runtime` on an agent page: claude, codex, opencode, dsh, hermes
  39. pkg: string; // the package id: harness-<id>
  40. bin: string; // the executable looked up on PATH
  41. title: string;
  42. defaultModel: string;
  43. install: string; // one line: how to get the CLI
  44. build(s: Spec): Command;
  45. };
  46. /** The harness names the packages know; `runtime` (or `harness`) on an agent page names one of them. */
  47. export const KNOWN = ['claude', 'codex', 'opencode', 'dsh', 'hermes'];
  48. /** Other spellings of the same harness. */
  49. const ALIAS: Record<string, string> = { 'claude-code': 'claude', deepseek: 'dsh', 'deepseek-harness': 'dsh', 'opencode-go': 'opencode', 'hermes-agent': 'hermes' };
  50. /** The harness an agent page names: `harness`, else `runtime`, lower case, aliases resolved; '' when none. */
  51. export function harnessOf(fm: Record<string, any>): string {
  52. const h = text(fm.harness || fm.runtime).toLowerCase();
  53. return ALIAS[h] ?? h;
  54. }
  55. /** The package that runs a harness, and its installed folder in the project. */
  56. export function harnessPkg(root: string, harness: string): { pkg: string; dir: string; installed: boolean } {
  57. const pkg = `harness-${harness}`;
  58. const dir = join(root, '.shtukbase', 'packages', pkg);
  59. return { pkg, dir, installed: existsSync(join(dir, 'actions', 'ask.ts')) };
  60. }
  61. /** Full path of an executable found on PATH, or null. */
  62. export function which(bin: string, path = process.env.PATH ?? ''): string | null {
  63. for (const d of path.split(delimiter).filter(Boolean)) {
  64. const f = join(d, bin);
  65. try {
  66. if (statSync(f).isFile()) return f;
  67. } catch { /* not here */ }
  68. }
  69. return null;
  70. }
  71. /** A project path (`/a/b`) → an absolute path inside the project, or null when it leaves the project. */
  72. export function inside(root: string, p: string): string | null {
  73. const abs = resolve(root, p.replace(/^\/+/, ''));
  74. const rel = relative(root, abs);
  75. return rel.startsWith('..') || isAbsolute(rel) ? null : abs;
  76. }
  77. /** Problems of an agent page for a harness run: [] when it can run. Used by `ask` and by the check HRN-R01. */
  78. export function agentProblems(root: string, fm: Record<string, any>): { what: string; fix: string; code: string }[] {
  79. const out: { what: string; fix: string; code: string }[] = [];
  80. if (!text(fm.model)) out.push({ what: 'no model set (model)', fix: 'write model: the model of the harness', code: 'no-model' });
  81. const acc = text(fm.access);
  82. if (!acc) out.push({ what: 'no access set (access)', fix: 'write access: read or write', code: 'no-access' });
  83. else if (acc !== 'read' && acc !== 'write') out.push({ what: `access "${acc}" is unknown`, fix: 'set access: read or write', code: 'bad-access' });
  84. if (fm.network !== undefined && fm.network !== null && typeof fm.network !== 'boolean' && !['true', 'false'].includes(text(fm.network)))
  85. out.push({ what: `network: "${text(fm.network)}" is not true/false`, fix: 'set network: false or true', code: 'bad-network' });
  86. const wd = text(fm.workdir);
  87. if (wd) {
  88. const abs = inside(root, wd);
  89. 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' });
  90. 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' });
  91. }
  92. const ins = text(fm.instructions);
  93. if (ins) {
  94. const abs = inside(root, ins);
  95. 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' });
  96. }
  97. if (fm.limits?.minutes !== undefined && count(fm.limits.minutes) === null)
  98. out.push({ what: `limits.minutes: "${text(fm.limits.minutes)}" is not a whole number`, fix: 'set limits: {minutes: 10}', code: 'bad-minutes' });
  99. return out;
  100. }
  101. function fail(msg: string, code = 2): never {
  102. console.error(msg);
  103. process.exit(code);
  104. }
  105. /** Single quotes for a shell, when a word needs them. */
  106. export function shq(s: string): string {
  107. return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
  108. }
  109. /** Reads the agent page and the task into a run spec. Exits 2 on a problem. */
  110. export function specOf(root: string, agentPath: string, task: string, adapter: Adapter | null, minutes?: unknown): Spec {
  111. const page = '/' + agentPath.replace(/^\/+/, '').replace(/(\.md)?$/, '.md');
  112. const file = inside(root, page);
  113. if (!file || !existsSync(file)) fail(`no agent page ${page}`);
  114. const { fm, body } = readPage(file);
  115. if (!AGENT_TYPES.includes(text(fm.type))) fail(`${page}: type "${text(fm.type) || '—'}" is not an agent (${AGENT_TYPES.join(', ')})`);
  116. const harness = harnessOf(fm);
  117. if (!harness) fail(`${page}: no harness named — write runtime: ${KNOWN.join(' | ')}`);
  118. 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}`);
  119. const probs = agentProblems(root, fm);
  120. if (probs.length) fail(probs.map((p) => `${page}: ${p.what} → ${p.fix}`).join('\n'));
  121. const ins = text(fm.instructions);
  122. const instructions = (ins ? readFileSync(inside(root, ins)!, 'utf8') : body).trim();
  123. const full = [instructions, task.trim()].filter(Boolean).join('\n\n---\n\n');
  124. if (!full) fail(`${page}: nothing to tell the agent — neither a page body nor --prompt`);
  125. const net = fm.network === true || text(fm.network) === 'true';
  126. const lim = count(minutes) ?? count(map(fm.limits)?.minutes) ?? 10;
  127. return {
  128. root, agent: page, harness, model: text(fm.model) || adapter?.defaultModel || '', effort: text(fm.effort),
  129. cwd: inside(root, text(fm.workdir) || '/')!, access: text(fm.access) as Access, network: net, prompt: full, minutes: lim,
  130. tmp: join(root, '.shtukbase', 'tmp', `run-${process.pid}-${Date.now()}`),
  131. };
  132. }
  133. /** The command line as one shell line, the prompt shortened. */
  134. export function commandLine(s: Spec, c: Command): string {
  135. const short = (w: string) => (w === s.prompt ? `<prompt: ${s.prompt.length} characters>` : shq(w));
  136. const env = Object.entries(c.env ?? {}).map(([k, v]) => `${k}=${shq(v.length > 200 ? v.slice(0, 200) + '…' : v)}`);
  137. const unset = (c.unset ?? []).map((k) => `-u ${k}`);
  138. const head = env.length || unset.length ? ['env', ...unset, ...env] : [];
  139. return [...head, c.exe, ...c.args.map(short)].join(' ') + (c.stdin !== undefined ? ` < <prompt: ${c.stdin.length} characters>` : '');
  140. }
  141. const MAXBUF = 64 * 1024 * 1024;
  142. /** Text without terminal colour codes. */
  143. export function plain(s: string): string {
  144. return s.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '');
  145. }
  146. /** Runs the command in the spec's folder with its time limit. */
  147. export function execute(s: Spec, c: Command): { code: number; out: string; err: string; seconds: number; timedOut: boolean; missing: boolean } {
  148. const exe = c.exe.includes('/') ? c.exe : which(c.exe);
  149. if (!exe) return { code: 127, out: '', err: `${c.exe} not found in PATH`, seconds: 0, timedOut: false, missing: true };
  150. mkdirSync(s.tmp, { recursive: true });
  151. for (const f of c.files ?? []) writeFileSync(f.path, f.text);
  152. const env: Record<string, string | undefined> = { ...process.env, ...(c.env ?? {}) };
  153. for (const k of c.unset ?? []) delete env[k];
  154. const t0 = Date.now();
  155. const r = spawnSync(exe, c.args, {
  156. cwd: s.cwd, env, input: c.stdin ?? '', encoding: 'utf8', timeout: s.minutes * 60_000, maxBuffer: MAXBUF, killSignal: 'SIGTERM',
  157. });
  158. rmSync(s.tmp, { recursive: true, force: true });
  159. const timedOut = (r.error as NodeJS.ErrnoException | undefined)?.code === 'ETIMEDOUT';
  160. return {
  161. code: timedOut ? 124 : r.status ?? 1, out: r.stdout ?? '', err: (r.stderr ?? '') + (r.error && !timedOut ? `\n${r.error.message}` : ''),
  162. seconds: Math.round((Date.now() - t0) / 100) / 10, timedOut, missing: false,
  163. };
  164. }
  165. /** Who started the run, written on the run page. */
  166. export type Origin = { automation?: string; action?: string; woke?: string; slot?: string; title?: string };
  167. /** The folder of the run journal (`/runs` unless the project put it elsewhere). */
  168. export function runsFolder(root: string): string {
  169. return new Project(root).coll('RUN') ?? '/runs';
  170. }
  171. /** Runs the spec and writes it to the run journal: a run page (running → done/failed) and a log file next to the
  172. * journal. Prints the run page and the agent's answer. Returns the exit code. */
  173. export function runLogged(s: Spec, c: Command, o: Origin): number {
  174. const coll = runsFolder(s.root);
  175. const started = now();
  176. const title = o.title || `${s.harness}: ${s.agent.replace(/^\/agents\//, '').replace(/\.md$/, '')}`;
  177. const name = `${started.slice(0, 10)}-${started.slice(11, 19).replaceAll(':', '')}-${slug(title)}`;
  178. const page = create(s.root, coll, name, {
  179. type: 'Run', title, agent: s.agent, action: o.action, automation: o.automation, woke: o.woke || 'hand', slot: o.slot,
  180. harness: s.harness, model: s.model, started, status: 'running',
  181. }, '');
  182. const file = join(s.root, page.replace(/^\/+/, ''));
  183. const log = `${coll.replace(/\/+$/, '')}/logs/${page.split('/').pop()!.replace(/\.md$/, '')}.log`;
  184. const r = execute(s, c);
  185. mkdirSync(join(s.root, log.replace(/^\/+/, ''), '..'), { recursive: true });
  186. writeFileSync(join(s.root, log.replace(/^\/+/, '')), [
  187. `# ${title}`, `command: ${commandLine(s, c)}`, `cwd: ${relative(s.root, s.cwd) || '.'}`, `exit: ${r.code}${r.timedOut ? ' (time limit)' : ''}`,
  188. `seconds: ${r.seconds}`, '', '## prompt', s.prompt, '', '## stdout', r.out, '', '## stderr', r.err, '',
  189. ].join('\n'));
  190. r.out = plain(r.out);
  191. r.err = plain(r.err);
  192. const answer = r.out.trim().split('\n').filter(Boolean).pop()?.slice(0, 200) ?? '';
  193. const ok = r.code === 0;
  194. const why = r.missing ? `${c.exe} not found in PATH`
  195. : r.timedOut ? `did not finish in ${s.minutes} min`
  196. : `exit code ${r.code}: ${(r.err.trim().split('\n').filter(Boolean).pop() ?? '').slice(0, 200)}`;
  197. update(file, {
  198. status: ok ? 'done' : 'failed', ended: now(), seconds: r.seconds,
  199. evidence: ok ? [log, ...(answer ? [`answer: ${answer}`] : [])] : undefined,
  200. message: ok ? undefined : why,
  201. }, ok ? undefined : `Log: ${log}`);
  202. console.log(`run: ${page} (${ok ? 'done' : 'failed'}, ${r.seconds} s)`);
  203. if (r.out.trim()) console.log(r.out.trim());
  204. if (!ok) console.error(why);
  205. return ok ? 0 : r.code || 1;
  206. }
  207. /** `ask --agent /agents/x.md [--prompt text | --prompt-file f] [--dry-run] [--minutes N] [--automation …] [--action …]
  208. * [--woke clock] [--slot ISO] [--title …]` for one adapter. Returns the exit code. */
  209. export function ask(adapter: Adapter | null, argv: string[], root = process.cwd()): number {
  210. const a = args(argv);
  211. const agent = typeof a.agent === 'string' ? a.agent : fail('--agent /agents/<name>.md is required');
  212. let task = typeof a.prompt === 'string' ? a.prompt : '';
  213. if (typeof a['prompt-file'] === 'string') {
  214. const f = resolve(root, a['prompt-file']);
  215. if (!existsSync(f)) fail(`no file ${a['prompt-file']}`);
  216. task = [task, readFileSync(f, 'utf8')].filter((x) => x.trim()).join('\n\n');
  217. }
  218. if (!adapter) {
  219. // the generic `harness ask`: find the adapter the agent names and run its package
  220. const file = inside(root, '/' + agent.replace(/^\/+/, '').replace(/(\.md)?$/, '.md'));
  221. if (!file || !existsSync(file)) fail(`no agent page ${agent}`);
  222. const h = harnessOf(readPage(file).fm);
  223. const hp = harnessPkg(root, h);
  224. if (!h) fail(`${agent}: no harness named — write runtime: ${KNOWN.join(' | ')}`);
  225. if (!hp.installed) fail(`${agent}: harness "${h}", but the package ${hp.pkg} is not in the project — shtuk install …/${hp.pkg}`);
  226. const r = spawnSync(process.execPath, [join(hp.dir, 'actions', 'ask.ts'), ...argv], { cwd: root, stdio: 'inherit' });
  227. return r.status ?? 1;
  228. }
  229. const s = specOf(root, agent, task, adapter, a.minutes);
  230. const c = adapter.build(s);
  231. if (a['dry-run']) {
  232. console.log(`harness: ${adapter.id} (${adapter.title}), model: ${s.model}, access: ${s.access}, network: ${s.network ? 'yes' : 'no'}, limit: ${s.minutes} min`);
  233. console.log(`folder: ${relative(root, s.cwd) || '.'}`);
  234. console.log(`command: ${commandLine(s, c)}`);
  235. for (const f of c.files ?? []) console.log(`file for the time of the run: ${relative(root, f.path)}\n${f.text.trimEnd()}`);
  236. for (const n of c.notes ?? []) console.log(`attention: ${n}`);
  237. console.log(`--- prompt ---\n${s.prompt}`);
  238. console.log(which(c.exe) ? 'dry run: nothing was run' : `dry run: nothing was run; ${c.exe} not found in PATH`);
  239. return 0;
  240. }
  241. return runLogged(s, c, {
  242. automation: typeof a.automation === 'string' ? a.automation : undefined,
  243. action: typeof a.action === 'string' ? a.action : undefined,
  244. woke: typeof a.woke === 'string' ? a.woke : undefined,
  245. slot: typeof a.slot === 'string' ? a.slot : undefined,
  246. title: typeof a.title === 'string' ? a.title : undefined,
  247. });
  248. }
  249. /** The sensor of a harness package: is the CLI on PATH and does it answer `--version`. Never fails the check: a
  250. * missing CLI is a warning line (agents on it will not run), exit 0. */
  251. export function sensor(adapter: Adapter): void {
  252. const exe = which(adapter.bin);
  253. if (!exe) {
  254. console.log(`warning: ${adapter.bin} not found in PATH — agents on the harness ${adapter.id} will not run; install: ${adapter.install}`);
  255. return;
  256. }
  257. const r = spawnSync(exe, ['--version'], { encoding: 'utf8', timeout: 20_000, stdio: ['ignore', 'pipe', 'pipe'] });
  258. const line = `${r.stdout ?? ''}\n${r.stderr ?? ''}`.split('\n').map((l) => l.trim()).find((l) => /\d+\.\d+/.test(l));
  259. if (r.error || r.status !== 0 || !line)
  260. console.log(`warning: ${adapter.bin} --version did not answer (${r.error ? r.error.message : `code ${r.status}`}) — check the installation: ${adapter.install}`);
  261. else console.log(`${adapter.bin}: ${line}`);
  262. }