SPB Git

Repository Public

job.ts 26.6 KB 332 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SP Wallet8 * File             : services/research-runner/src/job.ts9 * Module           : services10 * Repository       : https://git.spboucher.ai/sp-wallet11 * Project Website  : https://wallet.spboucher.ai12 * Created          : 2026-11-1113 * Last Modified    : 2026-11-1114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development      : dev@spboucher.ai24 * Support          : support@spboucher.ai25 * Security/Admin   : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License          : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243// One research job, from a claimed job to a result: prepare the job directory, launch the coding agent under the OS44// sandbox, enforce the owner's budgets from outside, collect the submission.45//46//   <jobsRoot>/<id>/ro/   read-only for the agent: lab/ (laboratory code), data/ (candles), JOB.json, CLAUDE.md47//   <jobsRoot>/<id>/rw/   read-write: work/ (cwd; work/submission/ is what is handed in), ledger/, tmp/, home/48//   <stateRoot>/<id>/     the runner's own: ledger.jsonl (append-only copy), profile.sb — outside the agent's reach49//50// The agent's environment holds no secret: PATH, HOME and TMPDIR inside rw/, the laboratory's paths, and the address of the51// job's model gateway with a placeholder key. Nothing of the runner's own environment is inherited.52import { spawn, type ChildProcess } from 'node:child_process';53import { createHash, randomBytes } from 'node:crypto';54import { chmodSync, closeSync, constants, cpSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, realpathSync, rmSync, writeFileSync } from 'node:fs';55import path from 'node:path';56import { MAX_LEDGER_BYTES, MAX_LOG_LINE, SUBMISSION_FILES, type RunnerJob, type RunnerResult, type RunnerUsage, type SubmissionFileName } from '@spw/core/research-job';57import { SANDBOX_EXEC, sandboxProfile } from '@spw/core/research-sandbox';58import { jobBrief, kickoffPrompt } from './brief.ts';59import type { RunnerConfig } from './config.ts';60import { ModelGateway } from './gateway.ts';61import { LedgerTail } from './ledger.ts';6263export interface JobHooks {64  log(stream: 'out' | 'err' | 'sys', text: string): void;65  /** the agent process started */66  running(): void;67  /** the owner asked to cancel (learned from the API when log lines are pushed) */68  cancelRequested(): boolean;69}70export const sandboxAvailable = (): boolean => process.platform === 'darwin' && existsSync(SANDBOX_EXEC);7172export interface JobPaths { job: string; ro: string; rw: string; work: string; submission: string; ledger: string; state: string; ledgerCopy: string; profile: string }73export function jobPaths(cfg: Pick<RunnerConfig, 'jobsRoot' | 'stateRoot'>, id: string): JobPaths {74  if (!/^[0-9a-f-]{36}$/.test(id)) throw new Error('bad job id');75  const job = path.join(cfg.jobsRoot, id), rw = path.join(job, 'rw'), state = path.join(cfg.stateRoot, id);76  return { job, ro: path.join(job, 'ro'), rw, work: path.join(rw, 'work'), submission: path.join(rw, 'work', 'submission'), ledger: path.join(rw, 'ledger', 'trials.jsonl'),77    state, ledgerCopy: path.join(state, 'ledger.jsonl'), profile: path.join(state, 'profile.sb') };78}7980const sh = (cmd: string, args: string[], o: { cwd?: string; input?: Buffer } = {}): Promise<{ code: number | null; out: Buffer; err: string }> => new Promise((resolve) => {81  const ch = spawn(cmd, args, { cwd: o.cwd, stdio: ['pipe', 'pipe', 'pipe'], env: { PATH: '/usr/bin:/bin:/opt/homebrew/bin:/usr/local/bin' } });82  const out: Buffer[] = []; let err = '';83  ch.stdout.on('data', (c: Buffer) => out.push(c)); ch.stderr.on('data', (c: Buffer) => { err = (err + c).slice(-2000); });84  ch.on('error', (e) => resolve({ code: null, out: Buffer.concat(out), err: e.message }));85  ch.on('close', (code) => resolve({ code, out: Buffer.concat(out), err }));86  ch.stdin.on('error', () => {}); ch.stdin.end(o.input);87});8889const LAB_PARTS = ['src', 'schema', 'strategies', 'README.md', 'pyproject.toml', 'uv.lock'];90/** Put the laboratory at the pinned commit into `dest`. Returns the commit that was used (null: an unpinned copy of the directory). */91export async function installLab(cfg: Pick<RunnerConfig, 'labDir' | 'labPin'>, commit: string | null, dest: string): Promise<string | null> {92  mkdirSync(dest, { recursive: true });93  if (cfg.labPin === 'worktree') {94    if (commit) throw new Error(`this job is pinned to laboratory commit ${commit}, but this runner copies its working tree (SPW_RUNNER_LAB_PIN=worktree): refusing`);95    for (const part of LAB_PARTS) if (existsSync(path.join(cfg.labDir, part))) cpSync(path.join(cfg.labDir, part), path.join(dest, part), { recursive: true, filter: (src) => !/(__pycache__|\.pytest_cache)/.test(src) });96    return null;97  }98  const git = (args: string[]) => sh('git', ['-C', cfg.labDir, ...args]);99  const prefix = (await git(['rev-parse', '--show-prefix'])).out.toString().trim();100  const head = await git(['rev-parse', commit ?? 'HEAD']);101  if (head.code !== 0) throw new Error(`the laboratory checkout does not have commit ${commit ?? 'HEAD'}: ${head.err.trim().slice(0, 160)}`);102  const sha = head.out.toString().trim();103  // the prepared virtualenv was built from the checkout's uv.lock: a job pinned to a commit with other dependencies must not run on it104  const lock = await git(['show', `${sha}:${prefix}uv.lock`]);105  if (lock.code !== 0 || createHash('sha256').update(lock.out).digest('hex') !== createHash('sha256').update(readFileSync(path.join(cfg.labDir, 'uv.lock'))).digest('hex'))106    throw new Error(`the laboratory environment of this runner was not built for commit ${sha.slice(0, 12)} (uv.lock differs): run uv sync on that commit first`);107  const tar = await git(['archive', '--format=tar', `${sha}:${prefix.replace(/\/$/, '') || '.'}`, ...LAB_PARTS]);108  if (tar.code !== 0) throw new Error(`git archive failed: ${tar.err.trim().slice(0, 160)}`);109  const x = await sh('tar', ['-x', '-C', dest], { input: tar.out });110  if (x.code !== 0) throw new Error(`could not unpack the laboratory: ${x.err.trim().slice(0, 160)}`);111  return sha;112}113114/** every symbolic link met while resolving `p` (a venv's python → a versioned alias → the real interpreter): the sandbox must115 *  let the process read each link itself, not only the final target */116export function symlinksOnPath(p: string): string[] {117  const out: string[] = []; let todo = path.resolve(p).split(path.sep).filter(Boolean), cur: string = path.sep, hops = 0;118  while (todo.length) {119    const next = path.join(cur, todo.shift()!);120    let st; try { st = lstatSync(next); } catch { break; }121    if (st.isSymbolicLink() && hops++ < 40) { out.push(next); const target = path.resolve(cur, readlinkSync(next)); todo = [...target.split(path.sep).filter(Boolean), ...todo]; cur = path.sep; }122    else cur = next;123  }124  return out;125}126/** read-only toolchain paths the sandbox must allow: the virtualenv, the real interpreter behind it, the agent's program */127export function toolchain(cfg: Pick<RunnerConfig, 'python' | 'readable' | 'agent'>): string[] {128  const up = (p: string, n: number): string => { let x = p; for (let i = 0; i < n; i++) x = path.dirname(x); return x; };129  const out = new Set<string>(cfg.readable.map((p) => realpathSync(p)));130  out.add(realpathSync(up(cfg.python, 2)));                              // <venv>131  out.add(up(realpathSync(cfg.python), 2));                              // the interpreter's installation132  for (const l of symlinksOnPath(cfg.python)) out.add(l);133  const bin = cfg.agent.kind === 'claude' ? cfg.agent.bin : cfg.agent.argv[0];134  if (bin && existsSync(bin)) { out.add(up(realpathSync(bin), 2)); for (const l of symlinksOnPath(bin)) out.add(l); }135  return [...out];136}137138const setTree = (root: string, dirMode: number, fileMode: number): void => {139  const walk = (p: string): void => { const st = lstatSync(p); if (st.isSymbolicLink()) return;140    if (st.isDirectory()) { chmodSync(p, 0o700); for (const e of readdirSync(p)) walk(path.join(p, e)); chmodSync(p, dirMode); } else chmodSync(p, fileMode); };141  if (existsSync(root)) walk(root);142};143/** bytes and entries under a directory (no symlink is followed) */144export function diskUsage(root: string, maxEntries = 200_000): { bytes: number; entries: number } {145  let bytes = 0, entries = 0;146  const walk = (p: string): void => { let st; try { st = lstatSync(p); } catch { return; }147    entries += 1; if (entries > maxEntries) return;148    if (st.isDirectory()) { let list: string[] = []; try { list = readdirSync(p); } catch { /* unreadable: counted as empty */ } for (const e of list) walk(path.join(p, e)); } else bytes += st.blocks ? st.blocks * 512 : st.size; };149  walk(root);150  return { bytes, entries };151}152153/** Read the submission directory with the runner's own privileges — so every file is opened without following links, must be154 *  a regular file with ONE link (a hard link to a file elsewhere is refused), within its size limit, and one of the expected names. */155export function collectSubmission(dir: string): { path: SubmissionFileName; b64: string }[] {156  let st; try { st = lstatSync(dir); } catch { throw new Error('no submission directory'); }157  if (!st.isDirectory()) throw new Error('submission is not a directory');158  const names = readdirSync(dir).sort(), files: { path: SubmissionFileName; b64: string }[] = [];159  for (const name of names) if (!(name in SUBMISSION_FILES)) throw new Error(`unexpected file in the submission: ${JSON.stringify(name.slice(0, 60))} (only ${Object.keys(SUBMISSION_FILES).join(', ')})`);160  for (const [name, spec] of Object.entries(SUBMISSION_FILES) as [SubmissionFileName, { max: number; required: boolean }][]) {161    if (!names.includes(name)) { if (spec.required) throw new Error(`the submission has no ${name}`); continue; }162    let fd: number;163    try { fd = openSync(path.join(dir, name), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } catch { throw new Error(`${name} cannot be opened as a regular file (a link?)`); }164    try {165      const f = fstatSync(fd);166      if (!f.isFile()) throw new Error(`${name} is not a regular file`);167      if (f.nlink !== 1) throw new Error(`${name} has ${f.nlink} hard links: refused`);168      if (f.size > spec.max) throw new Error(`${name} is ${f.size} bytes (limit ${spec.max})`);169      if (f.size === 0) throw new Error(`${name} is empty`);170      const buf = Buffer.alloc(f.size); let got = 0;171      while (got < f.size) { const n = readSync(fd, buf, got, f.size - got, got); if (n <= 0) break; got += n; }172      files.push({ path: name, b64: buf.subarray(0, got).toString('base64') });173    } finally { closeSync(fd); }174  }175  return files;176}177178/** One line of the Claude Code `stream-json` output → a line of the job log (and the cost the CLI reports at the end). */179export function describeStreamEvent(line: string): { text: string | null; costUsd: number | null } {180  let ev: any;181  try { ev = JSON.parse(line); } catch { return { text: line, costUsd: null }; }182  if (!ev || typeof ev !== 'object') return { text: line, costUsd: null };183  const clip = (s: unknown, n = 400): string => String(s ?? '').replace(/\s+/g, ' ').slice(0, n);184  if (ev.type === 'system') return { text: ev.subtype === 'init' ? `agent started (model ${clip(ev.model, 60)}, tools ${clip((ev.tools ?? []).join(','), 200)})` : null, costUsd: null };185  if (ev.type === 'assistant' && Array.isArray(ev.message?.content)) {186    const parts: string[] = [];187    for (const c of ev.message.content) {188      if (c?.type === 'text' && c.text) parts.push(`agent: ${clip(c.text, 1200)}`);189      else if (c?.type === 'tool_use') parts.push(`tool ${clip(c.name, 30)}: ${clip(c.input?.command ?? c.input?.file_path ?? c.input?.pattern ?? JSON.stringify(c.input ?? {}), 500)}`);190    }191    return { text: parts.length ? parts.join('\n') : null, costUsd: null };192  }193  if (ev.type === 'user' && Array.isArray(ev.message?.content)) {194    const parts: string[] = [];195    for (const c of ev.message.content) if (c?.type === 'tool_result') parts.push(`  → ${c.is_error ? 'ERROR ' : ''}${clip(typeof c.content === 'string' ? c.content : (c.content ?? []).map((x: any) => x?.text ?? '').join(' '), 500)}`);196    return { text: parts.length ? parts.join('\n') : null, costUsd: null };197  }198  if (ev.type === 'result') { const cost = typeof ev.total_cost_usd === 'number' && Number.isFinite(ev.total_cost_usd) ? ev.total_cost_usd : null;199    return { text: `agent finished: ${clip(ev.subtype, 40)}${ev.is_error ? ' (error)' : ''}, ${Number(ev.num_turns ?? 0)} turns${cost === null ? '' : `, ${cost.toFixed(4)} USD reported by the CLI`}`, costUsd: cost }; }200  return { text: null, costUsd: null };201}202203export function agentArgv(cfg: RunnerConfig, job: RunnerJob, p: JobPaths): string[] {204  const prompt = kickoffPrompt(job, { ro: p.ro, work: p.work, python: cfg.python });205  if (cfg.agent.kind === 'command') return cfg.agent.argv.map((a) => a.replaceAll('{work}', p.work).replaceAll('{ro}', p.ro).replaceAll('{prompt}', prompt));206  // Claude Code, headless (`claude --help`, 2.1.x):207  //   -p / --output-format stream-json --verbose   non-interactive, one JSON event per line208  //   --bare                    no hooks, plugins, auto-memory, CLAUDE.md discovery, and NO keychain / OAuth read: the only209  //                             credential it would accept is ANTHROPIC_API_KEY — here a placeholder for the job's gateway210  //   --tools / --allowedTools  the built-in tools that exist for this run, all pre-approved; nothing else can be approved:211  //   --permission-mode dontAsk + --permission-prompts none   anything that would prompt is denied (unattended)212  //   --strict-mcp-config (no MCP server), --disable-slash-commands, --no-session-persistence213  //   --max-budget-usd          the CLI's own spend cap (a convenience: the runner's gateway and clock are the enforcement)214  const tools = job.tools.join(',');215  return [cfg.agent.bin, '-p', prompt, '--bare', '--output-format', 'stream-json', '--verbose', '--append-system-prompt-file', path.join(p.ro, 'CLAUDE.md'),216    '--tools', tools, '--allowedTools', tools, '--disallowedTools', 'WebFetch,WebSearch', '--permission-mode', 'dontAsk', '--permission-prompts', 'none',217    '--strict-mcp-config', '--disable-slash-commands', '--no-session-persistence', '--max-budget-usd', String(job.budgets.maxModelUsd),218    ...(cfg.agent.model ? ['--model', cfg.agent.model] : [])];219}220221export async function runJob(job: RunnerJob, cfg: RunnerConfig, hooks: JobHooks): Promise<RunnerResult> {222  const p = jobPaths(cfg, job.id), t0 = Date.now();223  const usage: RunnerUsage = { wallMs: 0, trials: 0, diskMb: 0, modelTokens: 0, modelRequests: 0, modelUsd: null, ledgerTampered: false, sandbox: 'none', agent: cfg.agent.kind === 'claude' ? 'claude-code' : 'command', labCommit: null, exitCode: null, signal: null };224  const sys = (t: string): void => hooks.log('sys', t);225  let gateway: ModelGateway | null = null, ledger: LedgerTail | null = null;226  const ledgerText = (): string => { try { return readFileSync(p.ledgerCopy, 'utf8').slice(0, MAX_LEDGER_BYTES); } catch { return ''; } };227  const finish = (r: { outcome: 'failed' | 'cancelled' | 'over_budget'; reason: string }): RunnerResult => {228    usage.wallMs = Date.now() - t0; if (ledger) { ledger.sync(); usage.trials = ledger.lines; usage.ledgerTampered = ledger.tampered; }229    sys(`job ${r.outcome}: ${r.reason}`);230    return { outcome: r.outcome, usage, reason: r.reason.slice(0, 600), ledger: ledgerText() };231  };232  try {233    // ---- preparing234    const confined = sandboxAvailable();235    if (!confined && cfg.sandbox === 'required') return finish({ outcome: 'failed', reason: 'this runner has no OS sandbox (sandbox-exec) and is configured to require one: the job was not started' });236    usage.sandbox = confined ? 'sandbox-exec' : 'none';237    if (existsSync(p.job)) return finish({ outcome: 'failed', reason: 'a job directory with this id already exists on the runner' });238    for (const d of [cfg.jobsRoot, cfg.stateRoot, p.state, p.ro, p.work, p.submission, path.join(p.work, 'candidates'), path.dirname(p.ledger), path.join(p.rw, 'tmp'), path.join(p.rw, 'home')]) mkdirSync(d, { recursive: true, mode: 0o700 });239    const real = { job: realpathSync(p.job), ro: realpathSync(p.ro), rw: realpathSync(p.rw), lab: realpathSync(cfg.labDir) };240    // the job directory is never inside the laboratory checkout (an application checkout), nor the reverse241    if (real.job.startsWith(real.lab + path.sep) || real.lab.startsWith(real.job + path.sep) || real.job.startsWith(path.dirname(real.lab) + path.sep)) return finish({ outcome: 'failed', reason: 'the jobs directory is inside an application checkout: refusing to run' });242    usage.labCommit = await installLab(cfg, job.labCommit, path.join(p.ro, 'lab'));243    sys(`laboratory ${usage.labCommit ? `at commit ${usage.labCommit.slice(0, 12)}` : 'copied from the working tree (unpinned)'}`);244    const dataDir = path.join(real.ro, 'data'), tools = toolchain(cfg);245    const baseEnv: Record<string, string> = { PATH: `${path.dirname(cfg.python)}:/usr/bin:/bin`, HOME: path.join(real.rw, 'home'), TMPDIR: path.join(real.rw, 'tmp'), LANG: 'en_US.UTF-8',246      // shells write here-documents to temporary files: bash under TMPDIR, zsh under TMPPREFIX (default /tmp/zsh, outside the job)247      SHELL: '/bin/bash', TMPPREFIX: path.join(real.rw, 'tmp', 'zsh'),248      PYTHONPATH: path.join(real.ro, 'lab', 'src'), PYTHONDONTWRITEBYTECODE: '1', PYTHONUNBUFFERED: '1', JOBLIB_MULTIPROCESSING: '0', MPLCONFIGDIR: path.join(real.rw, 'tmp'), UV_OFFLINE: '1' };249    const confine = (profile: string | null, argv: string[]): string[] => (profile ? [SANDBOX_EXEC, '-f', profile, ...argv] : argv);250    if (job.data.kind === 'spot') {251      for (const f of job.data.files) { const dir = path.join(dataDir, job.data.source); mkdirSync(dir, { recursive: true }); writeFileSync(path.join(dir, `${f.symbol}_${job.data.interval}.csv`), f.csv); }252    } else {253      // perpetual data arrive as one bundle; the laboratory's importer (offline, sandboxed, no network at all) writes the store254      const bundle = path.join(real.rw, 'tmp', 'bundle.json'); writeFileSync(bundle, JSON.stringify(job.data.bundle));255      const prep = path.join(p.state, 'prepare.sb');256      if (confined) writeFileSync(prep, sandboxProfile({ writable: [real.job], readable: tools, localPorts: [] }), { mode: 0o600 });257      const argv = confine(confined ? prep : null, [cfg.python, '-m', 'spq.data.hl_import', '--input', bundle, '--out', dataDir]);258      const r = await new Promise<{ code: number | null; err: string }>((resolve) => { const ch = spawn(argv[0]!, argv.slice(1), { cwd: real.rw, env: baseEnv, stdio: ['ignore', 'ignore', 'pipe'] }); let err = '';259        ch.stderr.on('data', (c: Buffer) => { err = (err + c).slice(-1000); }); ch.on('error', (e) => resolve({ code: null, err: e.message })); ch.on('close', (code) => resolve({ code, err })); });260      rmSync(bundle, { force: true });261      if (r.code !== 0) return finish({ outcome: 'failed', reason: `the data of the job could not be imported: ${r.err.trim().split('\n').pop()?.slice(0, 200) ?? ''}` });262    }263    writeFileSync(path.join(p.ro, 'JOB.json'), JSON.stringify({ kind: job.kind, symbols: job.universe, interval: job.interval, capital_usd: job.capitalUsd, data_dir: dataDir, source: job.data.kind === 'spot' ? job.data.source : null, name: job.strategyName, version: job.strategyVersion }, null, 1));264    writeFileSync(path.join(p.ro, 'CLAUDE.md'), jobBrief(job, { ro: real.ro, work: path.join(real.rw, 'work'), python: cfg.python }));265    setTree(p.ro, 0o555, 0o444);266267    // ---- running268    ledger = new LedgerTail(p.ledger, p.ledgerCopy, MAX_LEDGER_BYTES);269    const jobKey = `job-${randomBytes(24).toString('hex')}`;270    gateway = new ModelGateway({ upstream: cfg.model.upstream, credential: cfg.model.credential, jobKey, maxTokens: job.budgets.maxModelTokens, onLog: sys });271    const port = await gateway.start();272    if (confined) writeFileSync(p.profile, sandboxProfile({ writable: [real.rw], readable: [real.ro, ...tools], localPorts: [port] }), { mode: 0o600 });273    const env: Record<string, string> = { ...baseEnv, SPQ_JOB_FILE: path.join(real.ro, 'JOB.json'), SPQ_JOB_LEDGER: path.join(real.rw, 'ledger', 'trials.jsonl'), SPQ_DATA_DIR: dataDir,274      // the model API as the agent sees it: the job's gateway on loopback and a placeholder key (the real credential stays in the runner)275      ANTHROPIC_BASE_URL: `http://127.0.0.1:${port}`, ANTHROPIC_API_KEY: jobKey, CLAUDE_CONFIG_DIR: path.join(real.rw, 'home', '.claude'), CLAUDE_CODE_TMPDIR: path.join(real.rw, 'tmp'),276      CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1', DISABLE_AUTOUPDATER: '1', DISABLE_TELEMETRY: '1', DISABLE_ERROR_REPORTING: '1', NO_COLOR: '1',277      SPW_JOB_ID: job.id, SPW_JOB_RO: real.ro, SPW_JOB_WORK: path.join(real.rw, 'work'), SPW_JOB_GATEWAY_PORT: String(port) };278    if (cfg.agent.kind === 'claude') env.PATH = `${path.dirname(cfg.python)}:${path.dirname(cfg.agent.bin)}:/usr/bin:/bin`;279    const rp = { ...p, ro: real.ro, rw: real.rw, work: path.join(real.rw, 'work') };280    const argv = confine(confined ? p.profile : null, agentArgv(cfg, job, rp));281    sys(`starting the agent (${usage.agent}) ${confined ? 'under sandbox-exec' : 'WITHOUT an OS sandbox'}; budgets: ${job.budgets.wallSeconds} s, ${job.budgets.maxTrials} trials, ${job.budgets.maxDiskMb} MB, ${job.budgets.maxModelTokens} tokens, ${job.budgets.maxModelUsd} USD`);282    const child: ChildProcess = spawn(argv[0]!, argv.slice(1), { cwd: rp.work, env, stdio: ['ignore', 'pipe', 'pipe'], detached: true });283    hooks.running();284    const st: { stop: { outcome: 'cancelled' | 'over_budget'; reason: string } | null; costUsd: number | null; startError: string | null } = { stop: null, costUsd: null, startError: null };285    const killAll = (): void => { try { if (child.pid) process.kill(-child.pid, 'SIGKILL'); } catch { try { child.kill('SIGKILL'); } catch { /* gone */ } } };286    const lines = (stream: 'out' | 'err') => { let carry = ''; return (c: Buffer): void => { const parts = (carry + c.toString('utf8')).split('\n'); carry = (parts.pop() ?? '').slice(0, 1_000_000);287      for (const raw of parts) { if (!raw.trim()) continue;288        if (stream === 'out' && cfg.agent.kind === 'claude') { const d = describeStreamEvent(raw); if (d.costUsd !== null) st.costUsd = d.costUsd; if (d.text) for (const l of d.text.split('\n')) hooks.log('out', l.slice(0, MAX_LOG_LINE)); }289        else hooks.log(stream, raw.slice(0, MAX_LOG_LINE)); } }; };290    child.stdout!.on('data', lines('out')); child.stderr!.on('data', lines('err'));291    let tick = 0;292    const check = (): void => {293      if (st.stop) return;294      tick += 1; ledger!.sync();295      const over = (reason: string): void => { st.stop = { outcome: 'over_budget', reason }; killAll(); };296      if (hooks.cancelRequested()) { st.stop = { outcome: 'cancelled', reason: 'cancelled by the owner' }; killAll(); return; }297      if (Date.now() - t0 > job.budgets.wallSeconds * 1000) return over(`wall time over ${job.budgets.wallSeconds} s`);298      if (ledger!.lines > job.budgets.maxTrials) return over(`${ledger!.lines} trials, budget ${job.budgets.maxTrials}`);299      if (gateway!.usage.exhausted) return over(`${gateway!.usage.total} model tokens, budget ${job.budgets.maxModelTokens}`);300      if (st.costUsd !== null && st.costUsd > job.budgets.maxModelUsd) return over(`${st.costUsd.toFixed(2)} USD reported by the CLI, budget ${job.budgets.maxModelUsd}`);301      if (tick % 4 === 0) { const d = diskUsage(p.rw); usage.diskMb = Math.round(d.bytes / 1024 / 1024 * 10) / 10;302        if (d.bytes > job.budgets.maxDiskMb * 1024 * 1024 || d.entries > 200_000) return over(`${usage.diskMb} MB on disk (${d.entries} entries), budget ${job.budgets.maxDiskMb} MB`); }303    };304    const timer = setInterval(check, cfg.tickMs);305    const exit = await new Promise<{ code: number | null; signal: string | null }>((resolve) => {306      child.on('error', (e) => { st.startError = e.message; resolve({ code: null, signal: null }); });307      child.on('close', (code, signal) => resolve({ code, signal }));308    });309    clearInterval(timer);310    killAll();                                                          // whatever the agent left running in its process group311    check();                                                            // a last look at the budgets with the final ledger312    usage.exitCode = exit.code; usage.signal = exit.signal; usage.modelUsd = st.costUsd;313    usage.modelTokens = gateway.usage.total; usage.modelRequests = gateway.usage.requests;314    usage.diskMb = Math.round(diskUsage(p.rw).bytes / 1024 / 1024 * 10) / 10;315    if (st.stop) return finish(st.stop);316    if (st.startError) return finish({ outcome: 'failed', reason: `the agent could not be started: ${st.startError.slice(0, 200)}` });317    if (exit.code !== 0) return finish({ outcome: 'failed', reason: `the agent exited ${exit.signal ? `on signal ${exit.signal}` : `with code ${exit.code}`} without a submission` });318319    // ---- collecting (the agent's processes are dead; the files are read without following any link)320    let files;321    try { files = collectSubmission(p.submission); } catch (e) { return finish({ outcome: 'failed', reason: `malformed submission: ${(e as Error).message}` }); }322    ledger.sync(); usage.trials = ledger.lines; usage.ledgerTampered = ledger.tampered; usage.wallMs = Date.now() - t0;323    sys(`submission collected: ${files.map((f) => f.path).join(', ')}; ${usage.trials} trials${usage.ledgerTampered ? ' (the agent\'s ledger file was rewritten: every line counted)' : ''}`);324    return { outcome: 'submission', usage, archive: { v: 1, files, ledger: ledgerText() } };325  } catch (e) {326    return finish({ outcome: 'failed', reason: `runner error: ${(e as Error).message.slice(0, 300)}` });327  } finally {328    await gateway?.stop().catch(() => {});329    if (!cfg.keepJobs) { try { setTree(p.ro, 0o700, 0o600); rmSync(p.job, { recursive: true, force: true }); } catch { /* left for the operator */ } }330  }331}332
Files main
Menu

Theme