// The life of one task over an iteration (release 27, S5): mark it running, // meter its spend, keep its turns, and record how it ended — done, failed or // cancelled — with the minutes, the cost per model, the ops and the checks. // // A task's own failure (no report, nothing verified, the model refused) is a // `failed` iteration and a result, never a throw; a cancel (the job's signal) // is `cancelled`. What throws is a call that cannot start: no such iteration, // or one that is not this task's to run. import { CancelledError, Meter, type ModelTally } from "../../../llm"; import { currentJobContext } from "../../../jobContext"; import { ModelLogWriter, modelLogFilesIn, processScrub, runWithModelLog } from "../../../llm/callLog-server"; import { addIterationUsage, appendIterationTurns, iterationDir, readIteration, recordIterationStep, updateIteration, type Iteration, type IterationCheck, type IterationPatch, } from "../../iterations"; import { ArticleRegistryError } from "../../registry"; import type { IterationCoverage } from "../../iterations"; import { NO_TRACE, openTrace, type RunTracer, type TraceInput } from "./trace"; import { readTriageFile } from "../triage/store"; import { getPaths } from "../../../paths"; import type { StorePaths, TaskDeps, TaskProgress, TaskResult, TaskStatus } from "./types"; export class TaskInputError extends Error {} // What a task body hands back when it ends on its own. export type TaskOutcome = { status: Exclude; summary: string; patch?: IterationPatch; }; export type TaskHandle = { article: string; n: number; iteration: Iteration; meter: Meter; deps: TaskDeps; paths: StorePaths | undefined; log(line: string): void; // Progress for the job (deps.progress); a listener never stops the task. progress(p: TaskProgress): void; // Turns for turns.jsonl (an agent's transcript, a pipeline's events). turns(entries: readonly unknown[]): void; check(c: IterationCheck): void; checks: IterationCheck[]; // The run's trace (trace.jsonl, ./trace.ts) when the task keeps one, else a // no-op. Never throws, never waits. trace(e: TraceInput): void; // The iteration's coverage, read when the run ends (whatever ended it). setCoverage(read: () => IterationCoverage): void; }; export function usageOf(t: ModelTally) { return { usd: t.usd, inputTokens: t.input, outputTokens: t.output, cacheReadTokens: t.cacheRead, cacheWriteTokens: t.cacheWrite, calls: t.calls, }; } const isCancel = (err: unknown, signal?: AbortSignal) => err instanceof CancelledError || (err as Error)?.name === "AbortError" || !!signal?.aborted; const round2 = (v: number) => Math.round(v * 100) / 100; // Run `body` as iteration `n` of `article`. `step` set: the task is a STEP on // a done iteration (narration) — recorded in its `steps`, its status left as // it is. Else the iteration itself is the task's: it must be queued (or // running, a resumed job) and is marked running, then ended. export async function runOnIteration( o: { article: string; n: number; deps: TaskDeps; maxUsd?: number; kinds?: readonly Iteration["kind"][]; step?: { task: string; model: string; jobId?: string }; // Keep a trace (trace.jsonl): the run's start and end are written here, // the task writes the rest through `h.trace` (umtool R3). // `model` defaults to the iteration's. trace?: { task: string; model?: string; extractor?: string }; }, body: (h: TaskHandle) => Promise, ): Promise { const { article, n, deps } = o; const paths = deps.paths; const now = deps.now ?? (() => new Date()); const it = await readIteration(article, n, paths); if (!it) throw new TaskInputError(`"${article}" has no iteration i${n}`); if (o.kinds && !o.kinds.includes(it.kind)) { throw new TaskInputError(`"${article}" i${n} is a ${it.kind} iteration, not ${o.kinds.join(" or ")}`); } if (o.step) { if (it.status !== "done") throw new TaskInputError(`"${article}" i${n} is ${it.status}: a ${o.step.task} step runs over a done iteration`); } else if (it.status !== "queued" && it.status !== "running") { throw new TaskInputError(`"${article}" i${n} is ${it.status}: only a queued iteration is run`); } const started = now(); const meter = new Meter({ maxUsd: o.maxUsd }); const turns: unknown[] = []; const checks: IterationCheck[] = []; const log = (line: string) => { try { deps.log?.(line); } catch { // a listener never stops the task } }; const record = async (status: TaskStatus | "running", detail?: string) => { const at = now(); const minutes = round2((at.getTime() - started.getTime()) / 60_000); if (o.step) { await recordIterationStep( article, n, { task: o.step.task, model: o.step.model, status, startedAt: started.toISOString(), ...(status === "running" ? {} : { endedAt: at.toISOString(), minutes, cost: Math.round(meter.usd * 10_000) / 10_000 }), ...(o.step.jobId ? { jobId: o.step.jobId } : {}), ...(detail ? { detail: detail.slice(0, 500) } : {}), }, paths, at, ); } return minutes; }; if (o.step) await record("running"); else await updateIteration(article, n, { status: "running", error: undefined }, paths, started); // The trace: opened after the iteration is running (so its first line is // never older than the status a page reads beside it). const tracer: RunTracer = o.trace ? await openTrace({ article, n, paths, now, log }).catch(() => NO_TRACE) : NO_TRACE; if (o.trace) { tracer.emit({ t: "run", phase: "start", task: o.trace.task, model: o.trace.model || it.model, ...(o.trace.extractor ? { extractor: o.trace.extractor } : {}), ...(it.jobId ? { jobId: it.jobId } : {}) }); // A sweep a triage escalated (umtool R6): the triage's tiers first. const tri = it.scope?.triage; if (tri) { const f = await readTriageFile(tri.owner, tri.k, paths ?? getPaths()).catch(() => null); if (f) { tracer.emit({ t: "triage", owner: f.owner, k: f.k, candidates: (f.tier0?.candidates ?? []).map((c) => c.id), flagged: [...new Set((f.tier1?.flags ?? []).map((x) => x.id))], dismissed: f.tier1?.dismissed.length ?? 0, escalated: !!f.escalation?.escalate, ...(f.escalation ? { why: f.escalation.why } : {}), cost: f.cost, model: f.model, }); } } } // The model log (demo epic D3): every model call the body makes, on any // route, is recorded in the iteration's calls.jsonl under this run. const storePaths = paths ?? getPaths(); const modelLog = new ModelLogWriter({ files: modelLogFilesIn(iterationDir(storePaths, article, n)), task: o.step?.task ?? it.kind, // The running job's own id (an iteration's jobId is written after its job starts). ...((o.step?.jobId ?? currentJobContext()?.jobId ?? it.jobId) ? { jobId: o.step?.jobId ?? currentJobContext()?.jobId ?? it.jobId } : {}), model: o.step?.model ?? o.trace?.model ?? it.model, where: { article, iteration: n }, scrub: processScrub(Object.values(storePaths).filter((v): v is string => typeof v === "string")), now, log, }); await modelLog.start(); let coverageOf: (() => IterationCoverage) | null = null; const handle: TaskHandle = { article, n, iteration: o.step ? it : { ...it, status: "running" }, meter, deps, paths, log, progress: (p) => { try { deps.progress?.(p); } catch { // a listener never stops the task } }, turns: (entries) => turns.push(...entries), check: (c) => { const i = checks.findIndex((x) => x.name === c.name); if (i >= 0) checks[i] = c; else checks.push(c); }, checks, trace: (e) => { try { tracer.emit(e); } catch { // a trace never stops the task } }, setCoverage: (read) => { coverageOf = read; }, }; let status: TaskStatus; let summary: string; let patch: IterationPatch = {}; try { const out = await runWithModelLog(modelLog, () => body(handle)); status = deps.signal?.aborted ? "cancelled" : out.status; summary = deps.signal?.aborted ? "cancelled" : out.summary; patch = out.patch ?? {}; } catch (err) { if (err instanceof TaskInputError || err instanceof ArticleRegistryError) { // Not the model's doing: the iteration fails with the reason. status = deps.signal?.aborted ? "cancelled" : "failed"; summary = status === "cancelled" ? "cancelled" : (err as Error).message; } else if (isCancel(err, deps.signal)) { status = "cancelled"; summary = "cancelled"; } else { status = "failed"; summary = `${(err as Error)?.name ?? "Error"}: ${(err as Error)?.message ?? String(err)}`; } } await modelLog.flush(); // The record of the run, whatever happened: turns, spend, the ending. if (turns.length) await appendIterationTurns(article, n, turns, paths).catch((e) => log(`turns not kept: ${(e as Error).message}`)); const tallies = meter.summary().byModel; for (const [model, t] of Object.entries(tallies)) { if (!t.calls) continue; await addIterationUsage(article, n, model, usageOf(t), paths, now()); } const minutes = await record(status, summary); let coverage: IterationCoverage | undefined; try { coverage = coverageOf ? (coverageOf as () => IterationCoverage)() : undefined; } catch { coverage = undefined; } // The trace ends BEFORE the status does: a page that reads the iteration // ended finds the trace's end already written. if (o.trace) { const usd = Math.round(meter.usd * 10_000) / 10_000; tracer.emit({ t: "run", phase: "end", status, summary: summary.slice(0, 1000), usd, minutes: o.step ? minutes : round2((now().getTime() - started.getTime()) / 60_000), ...(coverage ? { coverage } : {}) }); await tracer.flush(); } if (!o.step) { await updateIteration( article, n, (cur) => ({ ...patch, ...(coverage ? { coverage } : {}), status, minutes: round2((now().getTime() - started.getTime()) / 60_000), ...(checks.length ? { checks: [...(cur.checks ?? []).filter((c) => !checks.some((x) => x.name === c.name)), ...checks] } : {}), ...(status === "done" ? { error: undefined } : { error: summary.slice(0, 1000) }), }), paths, now(), ); } else if (checks.length) { await updateIteration( article, n, (cur) => ({ checks: [...(cur.checks ?? []).filter((c) => !checks.some((x) => x.name === c.name)), ...checks] }), paths, now(), ); } log(`${status}: ${summary}`); return { article, n, status, summary, usd: Math.round(meter.usd * 10_000) / 10_000, minutes: o.step ? minutes : round2((now().getTime() - started.getTime()) / 60_000), }; }