// `report-draft` — a generation over an article's iteration, as an editor job // (release 27, S6; D6). `pnpm ops report-draft` → POST /api/ops/report-draft → // here. // // task sweep | revise-report | revise-video | research, or a media // draft: narrate | cut | onscreen | teaser | flips | threads | // youtube | social (a STEP on a done iteration, MEDIA_STEP_TASKS) // article the article id (an article in the making is fine for a sweep) // iteration a revision's parent; the iteration a narration voices; for a // sweep, the research run it CONTINUES (S11: its question, and its // channels widened by what it acquired, are the defaults); else none // model default: settings.generation.models[route] for the task's route // extractorModel an API sweep's extractor (default: // settings.generation.models.extractor): a Claude model id the // price table knows (release 28 F2) // question / channels / from / to a sweep's // seed a NEW sweep's starting report: cited markdown in the /sweep // shape (umtool's research board, R2), kept as the iteration's // seed.md; the agent's report starts from it and the sweep // verifies and extends it. API models only (the local pipeline // writes its report from scratch) // feedback a revision's // copyOf run iteration N again on another model (same kind and inputs) // maxUsd the job's cap (default by task; never above caps.max) // source / build the corpus (default: the newest build holding the channels) // cards / force a narration's (force: a continuation over a research // run that still waits, with what is done so far) // entries a media draft's (cut, onscreen, teaser, flips, threads, // youtube, social; narrate too): only these entry ids; `force` re-drafts // a field that is a draft already (release 28) // autonomy a research run's: propose | limits | auto (default: // settings.generation.research.autonomy; the limits are the // settings') // ids a sweep restricted to these recordings (umtool R4; kept in its // scope): an enumeration shows only them, a read of another is // refused // // task "refresh" (umtool R4, ./reportRefresh.ts): re-fetch, see what changed, // update — `iteration` (default: the current report's), `model`, // `extractorModel`, `maxUsd`; `fetch: false` skips the fetch and the build; // `dryRun: true` answers the plan and writes nothing; `ids` (umtool R6: what a // triage flagged) — the update reads these recordings, whatever else changed. // // task "triage" (umtool R6, ./reportTriage.ts): the cheap pass — `article` is // its OWNER (the schedule it is for), `question`, `channels`, `terms` // (`regex`), `topics`, `threshold`, `since`, `ids`, `windows`, // `maxCandidates`, `model` (default settings.generation.triage's). A run of // reports/.triage//; the answer's `iteration` is the run's number. // A sweep's `triage` ("/") names the triage it escalates (kept in // its scope; its trace's first line after the start is the triage's tiers). // // The iteration is created `queued` before the job, and the job's id set on it; // the job runs the S5 task in process. Its queue is the model's provider's: // `draft:api` (network, never the GPU lane or the heavy slot) or `draft:local` // (every ollama call through the GPU arbiter; ollama unloaded when the job // ends). An API job is held to its cap and to the DAILY cap: a job that would // start past the day's total is refused, at the ask and again at its turn. // Every finished API job appends its usage rows to the ledger. // // The corpus tools come in from the caller (`deps.corpusTools`): they are the // MCP's, and common cannot import the mcp package. import { modelLogged } from "./jobModelLog"; import os from "node:os"; import { projectsRootFrom } from "../lib/projectsRoot.mjs"; import { originOfHandle } from "../lib/remoteArchives"; import { isRemoteOnlyChannel } from "../lib/channelConfig"; import path from "node:path"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import type { JobProgress } from "../jobs/registry"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getPaths, type Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; import { GENERATION_TASKS, capFor, isStepTask, type GenerationSettings, type GenerationTask } from "../lib/generationSettings"; import { PROJECT_URL } from "../lib/project"; import { PRICES, isLocalOnly, localOnlyJobRefusal, providerOf, unloadOllama, type LlmConfig } from "../lib/llm"; import { readMemAvailableMb } from "./persistVideos"; import { webTools } from "../lib/web/tools"; import { copyIteration, createIteration, lineageSource, readIteration, readIterationFile, reportSourceOf, updateIteration, writeIterationFile, type Iteration, } from "../lib/report/iterations"; import { diskPostChannelOf } from "../lib/report/convert-server"; import { readAllPosts } from "../lib/posts-server"; import { isXTrendingChannel } from "../lib/xTrending/config"; import { runTask, type TaskDeps, type TaskInput, type TaskResult, pickCorpusBuild, siteOriginOf } from "../lib/report/draft/tasks/index"; import { corpusCuesOf } from "../lib/report/draft/tasks/corpusCues"; import { loadDeckChecks, type DeckChecks } from "../lib/report/draft/tasks/deckChecks"; import type { CorpusToolsLike } from "../lib/report/draft/tasks/types"; import { verifyReportQuotes } from "../bin/reports-check"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import { AUTONOMIES, type Autonomy, type ResearchLimits } from "../lib/report/draft/research/decide"; import type { ResearchEditor } from "../lib/report/draft/research/tools"; import type { JobOf } from "../lib/report/draft/research/state"; import type { EditorChannel } from "../lib/report/draft/tasks/types"; import { listChannelConfigs } from "./channels"; import { continuationOf, markContinued } from "./researchRuns"; import { gpuGatedFetch } from "./gpuArbiter"; export const REPORT_DRAFT_JOB_KIND = "report-draft"; export const REPORT_DRAFT_RESULT_MARKER = "@@report-draft "; export const REPORT_DRAFT_BODY_KEYS = [ "task", "article", "iteration", "model", "extractorModel", "feedback", "question", "channels", "from", "to", "copyOf", "maxUsd", "source", "build", "cards", "entries", "force", "autonomy", "seed", "ids", "fetch", "dryRun", "terms", "regex", "topics", "threshold", "windows", "since", "maxCandidates", "triage", // release 29 M8: a `verdicts` job's claims (default: every unruled one). "claims", // release 36 lane D: a `clips-suggest` job's project directory, the // proposals it labels, the note it answers, a session's answers. "project", "proposals", "note", "answers", // release 38 lane E: a `video-assist` job's request and scope (it shares // "project", "note" and "answers" with clips-suggest). "request", "scope", // characters C3: a `cast-assign` job's authors (it shares "project" and "answers"). "handles", ] as const; // A seed's size: a board of a few hundred quotes, with room. export const SEED_MAX_CHARS = 200_000; export class ReportDraftInputError extends Error {} // A refresh (umtool R4) is a report-draft task with no route of its own: its // update runs on the sweep route's model. export const REFRESH_TASK = "refresh" as const; // A triage (umtool R6) neither: it runs on settings.generation.triage's model. export const TRIAGE_DRAFT_TASK = "triage" as const; export type ReportDraftTask = GenerationTask | typeof REFRESH_TASK | typeof TRIAGE_DRAFT_TASK; export type ReportDraftBody = { task: ReportDraftTask; article: string; iteration?: number; model?: string; extractorModel?: string; feedback?: string; question?: string; channels?: string[]; from?: string; to?: string; copyOf?: number; maxUsd?: number; source?: string; build?: string; cards?: string[]; entries?: string[]; force?: boolean; autonomy?: Autonomy; seed?: string; ids?: string[]; fetch?: boolean; dryRun?: boolean; // A triage's (umtool R6). terms?: string; regex?: boolean; topics?: string[]; threshold?: { strong: number; weak: number }; windows?: Record; since?: string; maxCandidates?: number; // A sweep's: the triage it escalates ("/"). triage?: { owner: string; k: number }; // A verdicts job's (release 29 M8): the claims to propose for. claims?: string[]; // A clips-suggest job's (release 36 lane D, ./clipsSuggest.ts): the // reactions project's directory, only these proposals, the note an Ask // answers, a Claude Code session's answers (the `code` route). project?: string; proposals?: string[]; note?: string; answers?: unknown; // A video-assist job's (release 38 lane E, ./videoAssist.ts): what to // change, in words, and what it may touch (look | clips | fx | all). request?: string; scope?: string; // A cast-assign job's (characters C3, ./castAssign.ts): the post authors to propose a character for. handles?: string[]; }; // A Claude model the price table knows: one of its ids, or a dated id of one // (`claude-haiku-4-5-20251001`). export function isKnownApiModel(model: string): boolean { return model.startsWith("claude-") && Object.keys(PRICES).some((p) => model === p || model.startsWith(`${p}-`)); } // `frames` is routed by settings.generation like every task, but it is the // frame scan's (`pnpm ops frame-scan`), never a report-draft. // Neither a frame scan nor a lookout run is a report-draft job: each is its own // kind (frame-scan, lookout-run). const TASKS: readonly ReportDraftTask[] = [...GENERATION_TASKS.filter((t) => t !== "frames" && t !== "lookout"), REFRESH_TASK, TRIAGE_DRAFT_TASK]; const ymd = /^\d{4}-\d{2}-\d{2}$/; function fail(msg: string): never { throw new ReportDraftInputError(msg); } // The body, judged without touching the disk. export function parseReportDraftBody(b: Record): ReportDraftBody { const task = b.task; if (typeof task !== "string" || !TASKS.includes(task as ReportDraftTask)) fail(`"task" is one of ${TASKS.join(", ")}`); const article = b.article; // A clips-suggest job (release 36 lane D) and a video-assist job (release 38 // lane E) are on a umtool project, not an article. // A propose-groups job (lane L4, ./proposeGroups.ts) is on a video project too. const groups = task === "propose-groups"; // A cast-assign job (characters C3, ./castAssign.ts) is on a video project too. const castJob = task === "cast-assign"; const onProject = task === "clips-suggest" || task === "video-assist" || groups || castJob; const assist = task === "video-assist"; if (onProject) { if (article !== undefined && article !== null && article !== "") { fail(assist || groups || castJob ? `a ${task} job names its "project" (the video project's directory), not an article` : 'a clips-suggest job names its "project" (the reactions project\'s directory), not an article'); } } else if (typeof article !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(article)) fail('"article" is an article id (a lowercase slug)'); const int = (k: string) => { const v = b[k]; if (v === undefined || v === null) return undefined; if (typeof v !== "number" || !Number.isInteger(v) || v < 1) fail(`"${k}" is an iteration number (1, 2, …)`); return v as number; }; const text = (k: string) => { const v = b[k]; if (v === undefined || v === null) return undefined; if (typeof v !== "string" || !v.trim()) fail(`"${k}" is text`); return (v as string).trim(); }; const list = (k: string) => { const v = b[k]; if (v === undefined || v === null) return undefined; const arr = typeof v === "string" ? v.split(",") : v; if (!Array.isArray(arr) || !arr.every((x) => typeof x === "string" && x.trim())) fail(`"${k}" is a list of names`); return (arr as string[]).map((x) => x.trim()); }; const out: ReportDraftBody = { task: task as ReportDraftTask, article: onProject ? "" : (article as string) }; const set = (k: K, v: ReportDraftBody[K] | undefined) => { if (v !== undefined) out[k] = v; }; set("iteration", int("iteration")); set("copyOf", int("copyOf")); set("model", text("model")); const extractor = text("extractorModel"); if (extractor !== undefined) { if (!isKnownApiModel(extractor)) { fail(`"extractorModel" is a Claude model id (${Object.keys(PRICES).filter((m) => m.startsWith("claude-")).join(", ")}): an API sweep's extractor runs on the API`); } if (task !== "sweep" && task !== REFRESH_TASK) fail('"extractorModel" is a sweep\'s (the extractor an API sweep reads batches with)'); out.extractorModel = extractor; } set("feedback", text("feedback")); set("question", text("question")); set("channels", list("channels")); set("cards", list("cards")); set("entries", list("entries")); set("source", text("source")); set("build", text("build")); for (const k of ["from", "to"] as const) { const v = text(k); if (v !== undefined && !ymd.test(v)) fail(`"${k}" is a YYYY-MM-DD date`); set(k, v); } if (b.maxUsd !== undefined && b.maxUsd !== null) { if (typeof b.maxUsd !== "number" || !(b.maxUsd > 0)) fail('"maxUsd" is a positive number of dollars'); out.maxUsd = b.maxUsd; } if (b.force !== undefined) { if (typeof b.force !== "boolean") fail('"force" is true or false'); out.force = b.force; } if (b.autonomy !== undefined && b.autonomy !== null) { if (!(AUTONOMIES as readonly unknown[]).includes(b.autonomy)) fail(`"autonomy" is one of ${AUTONOMIES.join(", ")}`); if (out.task !== "research") fail('"autonomy" is a research run\'s'); out.autonomy = b.autonomy as Autonomy; } if (b.seed !== undefined && b.seed !== null) { if (typeof b.seed !== "string" || !b.seed.trim()) fail('"seed" is markdown text'); if (b.seed.length > SEED_MAX_CHARS) fail(`"seed" is at most ${SEED_MAX_CHARS} characters`); if (out.task !== "sweep" || out.iteration !== undefined || out.copyOf !== undefined) fail('"seed" starts a new sweep: no "iteration", no "copyOf"'); out.seed = b.seed; } for (const k of ["fetch", "dryRun"] as const) { if (b[k] === undefined || b[k] === null) continue; if (typeof b[k] !== "boolean") fail(`"${k}" is true or false`); if (out.task !== REFRESH_TASK && !(k === "dryRun" && onProject)) fail(`"${k}" is a refresh's`); out[k] = b[k] as boolean; } const ids = list("ids"); if (ids !== undefined) { if (out.task !== "sweep" && out.task !== REFRESH_TASK && out.task !== TRIAGE_DRAFT_TASK) fail('"ids" is a sweep\'s (the recordings it is restricted to), a refresh\'s or a triage\'s'); if (!ids.length) fail('"ids" names at least one recording'); if (ids.length > 2000) fail('"ids" is at most 2,000 recordings'); out.ids = [...new Set(ids)]; } // A triage's own keys (umtool R6). const triageKeys = ["terms", "regex", "topics", "threshold", "windows", "since", "maxCandidates"] as const; const given = triageKeys.filter((k) => b[k] !== undefined && b[k] !== null); if (given.length && out.task !== TRIAGE_DRAFT_TASK) fail(`${given.map((k) => `"${k}"`).join(", ")} ${given.length === 1 ? "is" : "are"} a triage's`); if (out.task === TRIAGE_DRAFT_TASK) { set("terms", text("terms")); if (b.regex !== undefined && b.regex !== null) { if (typeof b.regex !== "boolean") fail('"regex" is true or false'); out.regex = b.regex; } set("topics", list("topics")); if (b.threshold !== undefined && b.threshold !== null) { const t = b.threshold as Record; const ok = (v: unknown) => v === undefined || (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 50); if (!t || typeof t !== "object" || Array.isArray(t) || !ok(t.strong) || !ok(t.weak)) fail('"threshold" is {"strong": n, "weak": n}: whole numbers 0–50 (0: that rule off)'); out.threshold = { strong: (t.strong as number | undefined) ?? 1, weak: (t.weak as number | undefined) ?? 3 }; } const since = text("since"); if (since !== undefined && !ymd.test(since)) fail('"since" is a YYYY-MM-DD date'); set("since", since); if (b.maxCandidates !== undefined && b.maxCandidates !== null) { if (typeof b.maxCandidates !== "number" || !Number.isInteger(b.maxCandidates) || b.maxCandidates < 1 || b.maxCandidates > 500) fail('"maxCandidates" is a whole number, 1–500'); out.maxCandidates = b.maxCandidates; } if (b.windows !== undefined && b.windows !== null) { const w = b.windows as Record; if (!w || typeof w !== "object" || Array.isArray(w)) fail('"windows" is {"": [{"start": s, "end": s}, …]}'); const outW: Record = {}; for (const [id, list] of Object.entries(w)) { if (!Array.isArray(list) || !list.every((x) => x && typeof x === "object" && typeof (x as { start?: unknown }).start === "number" && typeof (x as { end?: unknown }).end === "number" && (x as { end: number }).end >= (x as { start: number }).start)) { fail(`"windows.${id}" is a list of {"start", "end"} in seconds, end ≥ start`); } outW[id] = (list as { start: number; end: number }[]).map((x) => ({ start: x.start, end: x.end })); } out.windows = outW; } const extra = (["feedback", "copyOf", "seed", "cards", "entries", "force", "autonomy", "iteration", "extractorModel"] as const).filter((k) => out[k] !== undefined); if (extra.length) fail(`a triage takes no ${extra.join(", ")}`); if (!out.question) fail("a triage needs its question"); if (!out.channels?.length) fail("a triage needs its channels"); } if (b.triage !== undefined && b.triage !== null) { if (out.task !== "sweep") fail('"triage" is a sweep\'s: the triage it escalates ("/")'); const m = typeof b.triage === "string" ? /^([a-z0-9][a-z0-9-]{0,63})\/([1-9]\d{0,6})$/.exec(b.triage) : null; if (!m) fail('"triage" names a triage run: "/"'); out.triage = { owner: m![1]!, k: Number(m![2]) }; } // Verdict proposals (release 29 M8): the article's current report, no iteration. const claims = list("claims"); if (claims !== undefined) { if (out.task !== "verdicts") fail('"claims" is a verdicts job\'s (the claims to propose for)'); if (!claims.every((c) => /^[A-Za-z0-9._:-]{1,64}$/.test(c))) fail('"claims" is a list of claim ids'); out.claims = [...new Set(claims)]; } if (out.task === "verdicts") { const extra = (["iteration", "copyOf", "feedback", "question", "channels", "from", "to", "seed", "cards", "entries", "force", "autonomy", "ids", "source", "build"] as const).filter((k) => out[k] !== undefined); if (extra.length) fail(`a verdicts job reads the article's current report: it takes no ${extra.join(", ")}`); } // The clip finder's AI pass (release 36 lane D): a project, not an article. const clipsKeys = ["project", "proposals", "note", "answers"] as const; const clipsGiven = clipsKeys.filter((k) => b[k] !== undefined && b[k] !== null); if (clipsGiven.length && !onProject) fail(`${clipsGiven.map((k) => `"${k}"`).join(", ")} ${clipsGiven.length === 1 ? "is" : "are"} a clips-suggest job's`); // The video assistant's (release 38 lane E). const assistGiven = (["request", "scope"] as const).filter((k) => b[k] !== undefined && b[k] !== null && !(groups && k === "request")); if (assistGiven.length && !assist) fail(`${assistGiven.map((k) => `"${k}"`).join(", ")} ${assistGiven.length === 1 ? "is" : "are"} a video-assist job's`); if (b.handles !== undefined && b.handles !== null && !castJob) fail('"handles" is a cast-assign job\'s'); if (castJob) { // A character proposed for each post author of a video project (characters C3): the project, the handles to ask // about (none: every post author), a session's answer on the code route. const project = b.project; if (typeof project !== "string" || !project.startsWith("/") || project.length > 1024) fail('"project" is the video project\'s absolute directory'); out.project = project as string; for (const k of ["proposals", "note", "request", "scope"] as const) if (b[k] !== undefined && b[k] !== null) fail(`a cast-assign job takes no "${k}"`); const handles = list("handles"); if (handles !== undefined) { const hs = [...new Set(handles.map((h) => h.trim().replace(/^@+/, "").toLowerCase()))]; if (!hs.length || hs.length > 300 || !hs.every((h) => /^[a-z0-9_.-]{1,64}$/.test(h))) fail('"handles" is a list of post authors\' handles (at most 300)'); out.handles = hs; } if (b.answers !== undefined && b.answers !== null) { if (typeof b.answers !== "object" || Array.isArray(b.answers)) fail('"answers" is a session\'s answer: {"authors": [{"handle", "character", "voice", "speed", "direction"}]}'); if (JSON.stringify(b.answers).length > 100_000) fail('"answers" is at most 100,000 characters'); out.answers = b.answers; } if (out.answers !== undefined && out.model) fail('"answers" are a Claude Code session\'s: no "model"'); if (out.dryRun && out.answers !== undefined) fail('"dryRun" plans the ask: no "answers"'); const extra = (["iteration", "copyOf", "feedback", "question", "channels", "from", "to", "seed", "cards", "entries", "force", "autonomy", "ids", "source", "build", "claims"] as const).filter((k) => out[k] !== undefined); if (extra.length) fail(`a cast-assign job reads its project: it takes no ${extra.join(", ")}`); } else if (groups) { // Claim groups proposed for a video project's cut (lane L4): the project, // optional words for the ask, a session's answer on the code route. const project = b.project; if (typeof project !== "string" || !project.startsWith("/") || project.length > 1024) fail('"project" is the video project\'s absolute directory'); out.project = project as string; if (b.proposals !== undefined && b.proposals !== null) fail('"proposals" is a clips-suggest job\'s'); if (b.note !== undefined && b.note !== null) fail('a propose-groups job takes no "note": give its words as "request"'); if (b.request !== undefined && b.request !== null) { if (typeof b.request !== "string") fail('"request" is words for the ask'); if (b.request.length > 2000) fail('"request" is at most 2,000 characters'); const r = b.request.replace(/\s+/g, " ").trim(); if (r) out.request = r; } if (b.answers !== undefined && b.answers !== null) { if (typeof b.answers !== "object" || Array.isArray(b.answers)) fail('"answers" is a session\'s answer: {"groups": [{"section", "claim", "ids", "why"}]}'); if (JSON.stringify(b.answers).length > 200_000) fail('"answers" is at most 200,000 characters'); out.answers = b.answers; } if (out.answers !== undefined && out.model) fail('"answers" are a Claude Code session\'s: no "model"'); if (out.dryRun && out.answers !== undefined) fail('"dryRun" plans the ask: no "answers"'); const extra = (["iteration", "copyOf", "feedback", "question", "channels", "from", "to", "seed", "cards", "entries", "force", "autonomy", "ids", "source", "build", "claims"] as const).filter((k) => out[k] !== undefined); if (extra.length) fail(`a propose-groups job reads its project: it takes no ${extra.join(", ")}`); } else if (assist) { const project = b.project; if (typeof project !== "string" || !project.startsWith("/") || project.length > 1024) fail('"project" is the video project\'s absolute directory'); out.project = project as string; if (b.proposals !== undefined && b.proposals !== null) fail('"proposals" is a clips-suggest job\'s'); if (b.request !== undefined && b.request !== null) { if (typeof b.request !== "string" || !b.request.trim()) fail('"request" is what to change, in words'); if (b.request.length > 2000) fail('"request" is at most 2,000 characters'); out.request = b.request.replace(/\s+/g, " ").trim(); } if (b.scope !== undefined && b.scope !== null) { if (!["look", "clips", "fx", "all"].includes(String(b.scope))) fail('"scope" is look, clips, fx or all'); out.scope = String(b.scope); } if (b.note !== undefined && b.note !== null) { if (typeof b.note !== "string" || !/^n_[a-z0-9]{4,32}$/.test(b.note)) fail('"note" is a note id (n_…)'); out.note = b.note; } if (b.answers !== undefined && b.answers !== null) { if (typeof b.answers !== "object" || Array.isArray(b.answers)) fail('"answers" is a session\'s answer: {"ops": [{"op", "id", "key", "value"}], "reply"}'); if (JSON.stringify(b.answers).length > 100_000) fail('"answers" is at most 100,000 characters'); out.answers = b.answers; } if (!out.request && !out.note) fail('a video-assist job needs its "request" (what to change), or the "note" whose text is one'); if (out.request && out.note) fail('give "request" or "note", not both: a note\'s text is its request'); if (out.answers !== undefined && out.model) fail('"answers" are a Claude Code session\'s: no "model"'); if (out.dryRun && out.answers !== undefined) fail('"dryRun" plans the ask: no "answers"'); const extra = (["iteration", "copyOf", "feedback", "question", "channels", "from", "to", "seed", "cards", "entries", "force", "autonomy", "ids", "source", "build", "claims"] as const).filter((k) => out[k] !== undefined); if (extra.length) fail(`a video-assist job reads its project: it takes no ${extra.join(", ")}`); } else if (onProject) { const project = b.project; if (typeof project !== "string" || !project.startsWith("/") || project.length > 1024) fail('"project" is the reactions project\'s absolute directory'); out.project = project as string; const proposals = list("proposals"); if (proposals !== undefined) { if (!proposals.length || !proposals.every((p) => /^[A-Za-z0-9._:-]{1,64}$/.test(p))) fail('"proposals" is a list of proposal ids'); out.proposals = [...new Set(proposals)]; } if (b.note !== undefined && b.note !== null) { if (typeof b.note !== "string" || !/^n_[a-z0-9]{4,32}$/.test(b.note)) fail('"note" is a note id (n_…)'); out.note = b.note; } if (b.answers !== undefined && b.answers !== null) { if (typeof b.answers !== "object" || Array.isArray(b.answers)) fail('"answers" is a session\'s answer: {"items": [{"id", "label", "why", "score"}]}'); if (JSON.stringify(b.answers).length > 200_000) fail('"answers" is at most 200,000 characters'); out.answers = b.answers; } if (out.note && (out.answers !== undefined || out.proposals)) fail('an Ask ("note") takes no "answers" or "proposals"'); if (out.answers !== undefined && out.model) fail('"answers" are a Claude Code session\'s: no "model"'); if (out.dryRun && (out.note || out.answers !== undefined)) fail('"dryRun" plans a labels pass: no "note" or "answers"'); const extra = (["iteration", "copyOf", "feedback", "question", "channels", "from", "to", "seed", "cards", "entries", "force", "autonomy", "ids", "source", "build", "claims"] as const).filter((k) => out[k] !== undefined); if (extra.length) fail(`a clips-suggest job reads its project: it takes no ${extra.join(", ")}`); } if (out.task === REFRESH_TASK) { const extra = (["question", "channels", "from", "to", "feedback", "copyOf", "seed", "cards", "entries", "force", "autonomy"] as const).filter((k) => out[k] !== undefined); if (extra.length) fail(`a refresh takes its question and scope from the iteration it refreshes — not ${extra.join(", ")}`); } if (out.source && !/^(local|remote|hub):\S+/.test(out.source)) fail('"source" is a corpus handle: local:, remote: or hub:'); if (out.source && out.build) fail('give "source" or "build", not both'); // What each task needs. // A sweep with "iteration" continues that research run (its question and // widened channels are the defaults). if (out.task === "sweep" && out.copyOf === undefined && out.iteration === undefined) { if (!out.question) fail("a sweep needs its question"); if (!out.channels?.length) fail("a sweep needs its channels"); } if (out.task === "research" && out.copyOf === undefined) { if (!out.question) fail("a research run needs its question"); if (out.iteration !== undefined) fail('a research run starts from its question: it takes no "iteration"'); } if ((out.task === "revise-report" || out.task === "revise-video") && out.copyOf === undefined) { if (out.iteration === undefined) fail(`a ${out.task} names the iteration it revises ("iteration")`); if (!out.feedback) fail(`a ${out.task} needs feedback: say what to change`); } // A media draft (narrate, cut, …) is a step on the iteration it names. if (out.task === "narrate" && out.iteration === undefined) fail('a narration names the iteration it voices ("iteration")'); if (out.task === "narrate" && out.copyOf !== undefined) fail("a narration is a step, not an iteration: it has no copy"); if (isStepTask(out.task) && out.iteration === undefined) fail(`a ${out.task} draft names the iteration it drafts on ("iteration")`); if (isStepTask(out.task) && out.copyOf !== undefined) fail(`a ${out.task} draft is a step, not an iteration: it has no copy`); if (out.entries && !isStepTask(out.task)) fail('"entries" is a media draft\'s (narrate, cut, onscreen, teaser, flips, threads, youtube, social)'); return out; } // A step task (narrate, cut, …) has no iteration of its own, so no kind; its // cap is a narration's. function kindOf(task: GenerationTask): Iteration["kind"] { if (isStepTask(task)) throw new ReportDraftInputError(`a ${task} draft is a step: it makes no iteration`); return task === "revise-report" || task === "revise-video" || task === "research" ? task : "sweep"; } const capOf = (task: GenerationTask): "sweep" | "revision" | "narration" => isStepTask(task) || task === "clips-suggest" || task === "video-assist" || task === "propose-groups" || task === "cast-assign" ? "narration" : task === "revise-report" || task === "revise-video" || task === "verdicts" ? "revision" : "sweep"; export function expandHome(p: string): string { return p === "~" ? os.homedir() : p.startsWith("~/") ? path.join(os.homedir(), p.slice(2)) : p; } export function projectsRootOf(gen: GenerationSettings): string { return projectsRootFrom(gen.projectsRoot); } // LOCAL ONLY (lib/llm/localOnly.ts): the refusal for a report-draft job on a // local-only instance, or null — at the ask, so the job is refused with a // sentence. It is not the guarantee: the Claude API client, the ollama client // and the digest's CLI lane refuse at their own last point before any I/O. export function localOnlyRefusalOf(body: ReportDraftBody, gen: GenerationSettings, env?: Record): string | null { if (!isLocalOnly(env)) return null; const task = body.task; const route = task === REFRESH_TASK ? gen.routes.sweep : task === TRIAGE_DRAFT_TASK ? null : (gen.routes[task as GenerationTask] ?? null); const models: string[] = []; if (body.model) models.push(body.model); else if (task === TRIAGE_DRAFT_TASK) models.push(gen.triage.model === "local" ? gen.models.local : gen.models.extractor); else if (route === "api") models.push(gen.models.api); else if (route === "local" && task !== "verdicts") models.push(gen.models.local); if (body.extractorModel) models.push(body.extractorModel); return localOnlyJobRefusal( { models, answers: body.answers !== undefined && body.answers !== null, route: body.model ? null : route }, (m) => providerOf(m) === "local", env, ); } /** A `draft:local` report-draft job waits for this much MemAvailable (MiB) before it starts; a lookout run refuses below the same number. */ export const LOCAL_DRAFT_MIN_FREE_MB = 3072; /** How often a job under the floor reads MemAvailable again, and how long it waits in all before it fails. */ export const LOCAL_DRAFT_MEMORY_POLL_MS = 15_000; export const LOCAL_DRAFT_MEMORY_WAIT_MS = 10 * 60_000; /** The floor a report-draft job on a local model starts with: LOCAL_MODEL_MIN_FREE_MB (MiB; 0 = none), else LOCAL_DRAFT_MIN_FREE_MB. */ export function localDraftFloorMb(env: Record = process.env): number { const v = (env.LOCAL_MODEL_MIN_FREE_MB ?? "").trim(); return /^\d+$/.test(v) ? Number(v) : LOCAL_DRAFT_MIN_FREE_MB; } // The model a task runs on: the asked one, else the route's. export function modelFor(gen: GenerationSettings, task: GenerationTask, asked?: string): string { if (asked) return asked; const route = gen.routes[task]; if (route === "code") { fail(`${task} is routed to Claude Code (settings.generation.routes) — name a model to run it here, or route it to api or local`); } return route === "api" ? gen.models.api : gen.models.local; } // The LLM config a job runs on. A base URL that is not Anthropic's is never // sent the environment's key: only the configured file's. export function llmConfigOf(gen: GenerationSettings, paths: Pick, local?: { onLog: (l: string) => void; signal?: AbortSignal }): LlmConfig { return { anthropic: { apiKeyFile: gen.apiKeyFile, cacheTtl: gen.cacheTtl, ...(gen.anthropicBaseUrl ? { baseUrl: gen.anthropicBaseUrl, env: {} } : {}), }, ollama: { baseUrl: gen.ollamaUrl || paths.ollamaUrl, ...(local ? { fetch: gpuGatedFetch(fetch, local) } : {}), }, }; } export type ReportDraftDeps = { paths: Paths; // A refresh's editor (umtool R4): its ops actions in process — sync, // fetch-posts, refresh-report, transcribe-bucket, publish (the editor's // route passes itself). Without it a refresh is refused. refreshEditor?: ResearchEditor; // A refresh's polling and waits (the tests shorten them). refreshTiming?: { pollMs?: number; waitMs?: number; sleep?: (ms: number, signal?: AbortSignal) => Promise }; // The MCP's corpus tools over a source handle (mcp/src/callTool.ts). corpusTools: (source: string) => Promise }>; settings?: () => { generation: GenerationSettings }; now?: () => Date; // A research run's editor: its ops actions, in process (the editor's route // passes itself). Without it a research run is refused. researchEditor?: ResearchEditor; // An editor job's state (default: the registry and the .jobs sidecars). jobOf?: JobOf; // MemAvailable in MiB, or null when unknown (default: /proc/meminfo) — the // local-model floor (LOCAL_DRAFT_MIN_FREE_MB). memAvailableMb?: () => Promise; // The floor's wait (default LOCAL_DRAFT_MEMORY_POLL_MS / _WAIT_MS; tests shorten them). memoryWait?: { pollMs?: number; maxWaitMs?: number }; // R4.1: why transcription would not run now, or null (default: the worker // pool — paused, or no worker enabled). A refresh's fetch skips // transcribe-bucket under a hold rather than wait on it. transcriptionHeld?: () => Promise; }; // The editor's channels, as a research run lists them. export async function editorChannelsOf(paths: Pick): Promise { // A remote-only channel (demo epic D1) is no channel of the editor's own — // it holds an archive's clip windows — so a research run never lists it, or // imports into it. // Nor is an X trending library (lane x-trending): private, so a research // run never lists it, reads it or imports into it. return (await listChannelConfigs(paths as Paths)).filter(({ config }) => !isRemoteOnlyChannel(config) && !isXTrendingChannel(config)).map(({ slug, config }) => { const c = config as Record; const s = (k: string) => (typeof c[k] === "string" && c[k] ? (c[k] as string) : undefined); const kind = s("sourceKind") ?? (s("postFetcher") ? "posts" : s("handling")); return { slug, ...(s("name") ? { name: s("name") } : {}), ...(s("platform") ? { platform: s("platform") } : {}), ...(kind ? { kind } : {}), ...(s("url") ? { url: s("url") } : {}) }; }); } // The channels a revision or narration reads: its report's citations'. async function channelsOfReport(article: string, n: number, paths: Paths): Promise { const from = await reportSourceOf(article, n, paths).catch(() => null); const text = from === null ? null : await readIterationFile(article, from, "report.json", paths); if (!text) return []; const cites = (JSON.parse(text) as { citations?: Record }).citations ?? {}; return [...new Set(Object.values(cites).map((c) => c.channel).filter((c): c is string => !!c))]; } // The origin a run over a named corpus cites on (demo epic D1 item 3): a // published archive's own origin — its moments are its pages — unless // settings.generation.citationOrigin is set, which overrides; a hub (whose // members each have their own) or a local dir, the citation origin or the // project's site, as before. export function citationOriginFor(source: string, gen: Pick): string { return gen.citationOrigin || originOfHandle(source) || PROJECT_URL; } // The corpus and the origin the run cites on. `inherited`: the corpus the // iteration's lineage read (lineageSource) — a revision, a media draft or a // refresh of a sweep over an archive reads that archive, not a local build. export async function resolveCorpus( body: Pick, channels: string[], paths: Pick, gen: GenerationSettings, inherited?: string | null, ): Promise<{ source: string; origin: string; build?: string }> { const fallback = gen.citationOrigin || PROJECT_URL; const named = body.source ?? (body.build ? undefined : (inherited ?? undefined)); if (named) return { source: named, origin: citationOriginFor(named, gen) }; const b = await pickCorpusBuild(channels, { exportBuildsDir: paths.exportBuildsDir, ...(body.build ? { want: body.build } : {}) }); return { source: `local:${b.dir}`, origin: (await siteOriginOf(b.build, paths.sitesDir)) ?? fallback, build: b.build }; } // A triage's answer names its run (`iteration` is the run's number). export type ReportDraftEnqueued = { result: StreamActionResult; iteration: number; warnings?: string[]; triage?: { owner: string; k: number } }; export async function enqueueReportDraft(raw: Record, deps: ReportDraftDeps): Promise { const paths = deps.paths; const gen = (deps.settings ?? getSettings)().generation; let body: ReportDraftBody; try { body = parseReportDraftBody(raw); } catch (e) { return { result: { ok: false, error: (e as Error).message } }; } const refuse = (error: string) => ({ result: { ok: false as const, error } }); const localOnly = localOnlyRefusalOf(body, gen); if (localOnly) return refuse(localOnly); if (body.task === TRIAGE_DRAFT_TASK) { try { const { enqueueTriage } = await import("./reportTriage"); return await enqueueTriage(body, deps); } catch (e) { return refuse((e as Error).message); } } if (body.task === "verdicts") { try { const { enqueueVerdictProposals } = await import("./reportVerdicts"); return await enqueueVerdictProposals(body, deps); } catch (e) { return refuse((e as Error).message); } } if (body.task === "clips-suggest") { if (body.dryRun) return refuse('a clips-suggest plan is planClipsSuggestJob\'s ("dryRun": true at the ops route)'); try { const { enqueueClipsSuggest } = await import("./clipsSuggest"); return await enqueueClipsSuggest(body, deps); } catch (e) { return refuse((e as Error).message); } } if (body.task === "propose-groups") { if (body.dryRun) return refuse('a propose-groups plan is planProposeGroupsJob\'s ("dryRun": true at the ops route)'); try { const { enqueueProposeGroups } = await import("./proposeGroups"); return await enqueueProposeGroups(body, deps); } catch (e) { return refuse((e as Error).message); } } if (body.task === "cast-assign") { if (body.dryRun) return refuse('a cast-assign plan is planCastAssignJob\'s ("dryRun": true at the ops route)'); try { const { enqueueCastAssign } = await import("./castAssign"); return await enqueueCastAssign(body, deps); } catch (e) { return refuse((e as Error).message); } } if (body.task === "video-assist") { if (body.dryRun) return refuse('a video-assist plan is planVideoAssistJob\'s ("dryRun": true at the ops route)'); try { const { enqueueVideoAssist } = await import("./videoAssist"); return await enqueueVideoAssist(body, deps); } catch (e) { return refuse((e as Error).message); } } if (body.task === REFRESH_TASK) { if (body.dryRun) return refuse('a refresh\'s plan is planRefresh\'s ("dryRun": true at the ops route)'); try { const { enqueueRefresh } = await import("./reportRefresh"); return await enqueueRefresh(body, deps); } catch (e) { return refuse((e as Error).message); } } try { // The model, and from it the lane; the copy's source tells a copy's kind. const src = body.copyOf !== undefined ? await readIteration(body.article, body.copyOf, paths) : null; if (body.copyOf !== undefined) { if (!src) return refuse(`"${body.article}" has no iteration i${body.copyOf} to copy`); if (src.kind !== kindOf(body.task)) return refuse(`i${body.copyOf} is a ${src.kind} iteration, not a ${body.task}`); } if (body.task === "research" && !deps.researchEditor) { return refuse("a research run runs in the editor (its reads and acquisitions are the editor's actions)"); } // A sweep continuing a research run: its question and widened scope. const cont = body.task === "sweep" && body.copyOf === undefined && body.iteration !== undefined ? await continuationOf(body.article, body.iteration, { paths, ...(deps.jobOf ? { jobOf: deps.jobOf } : {}), ...(body.force ? { force: true } : {}), ...(body.question ? { question: body.question } : {}), ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}), }) : null; const warnings: string[] = []; // A continuation of a research run over an archive reads that archive // (the run inherits it: lineageSource), so no local build is asked for. if (cont && !body.source && !(await lineageSource(body.article, cont.research.n, paths).catch(() => null))) { // The sweep reads a composed build: one must hold the widened channels // (a channel on no site is in none until the operator puts it on one // and builds it), and an acquisition after the build is not in it. const b = await pickCorpusBuild(cont.channels, { exportBuildsDir: paths.exportBuildsDir, ...(body.build ? { want: body.build } : {}) }); if (cont.lastAcquired !== null && b.mtimeMs < cont.lastAcquired) { warnings.push(`the build ${b.build} predates the run's last acquisition (${new Date(cont.lastAcquired).toISOString()}): rebuild it to read what was acquired`); } } const model = modelFor(gen, body.task, body.model); const provider = providerOf(model); if (body.seed && provider !== "api") { return refuse(`a seeded sweep runs the agent on a Claude model, not ${model}: the local pipeline writes its report from scratch`); } if (body.extractorModel && provider === "local") { warnings.push(`extractorModel ${body.extractorModel} is unused: a sweep on a local model runs the pipeline, which has no extractor`); } let maxUsd: number | undefined; if (provider === "api") { maxUsd = capFor(gen.caps, capOf(body.task), body.maxUsd); const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); if (refusal) return refuse(refusal); } // The iteration: a new one (or a copy), queued; a step's is the one named. let n: number; if (isStepTask(body.task)) { const it = await readIteration(body.article, body.iteration!, paths); if (!it) return refuse(`"${body.article}" has no iteration i${body.iteration}`); const what = body.task === "narrate" ? "a narration" : `a ${body.task} draft`; if (it.status !== "done") return refuse(`"${body.article}" i${it.n} is ${it.status}: ${what} runs over a done iteration`); n = it.n; } else if (src) { n = (await copyIteration(body.article, src.n, { model }, paths)).n; } else if (cont) { n = ( await createIteration( body.article, { kind: "sweep", model, parent: cont.research.n, question: cont.question, scope: { channels: cont.channels, ...(body.source ? { source: body.source } : {}), ...(cont.from ? { from: cont.from } : {}), ...(cont.to ? { to: cont.to } : {}), ...(body.ids ? { ids: body.ids } : {}) }, }, paths, ) ).n; } else { n = ( await createIteration( body.article, { kind: kindOf(body.task), model, ...(body.task === "sweep" || body.task === "research" ? { question: body.question, scope: { ...(body.source ? { source: body.source } : {}), ...(body.channels ? { channels: body.channels } : {}), ...(body.from ? { from: body.from } : {}), ...(body.to ? { to: body.to } : {}), ...(body.ids ? { ids: body.ids } : {}), ...(body.triage ? { triage: body.triage } : {}) } } : { parent: body.iteration!, feedback: body.feedback }), }, paths, ) ).n; // A seeded sweep's starting report, beside the iteration (the task reads it). if (body.seed) await writeIterationFile(body.article, n, "seed.md", body.seed, paths); } const result = await runManagedFunction({ kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "api" ? DRAFT_API_QUEUE : DRAFT_LOCAL_QUEUE, paths, fn: modelLogged({ paths, task: "report-draft" }, (onLog, signal, setProgress, ctx) => runReportDraft({ body, model, maxUsd, n, jobId: ctx.jobId, onLog, signal, setProgress }, deps)), }); if (!result.ok) { if (!isStepTask(body.task)) await updateIteration(body.article, n, { status: "failed", error: result.error }, paths).catch(() => {}); return { result }; } if (!isStepTask(body.task)) await updateIteration(body.article, n, { jobId: result.jobId }, paths).catch(() => {}); if (cont) await markContinued(body.article, cont.research.n, n, paths).catch(() => {}); // A job cancelled (or refused) before it ran leaves its iteration queued: end it. void result.done.then(async (d) => { if (isStepTask(body.task)) return; const it = await readIteration(body.article, n, paths).catch(() => null); if (it?.status === "queued") { await updateIteration(body.article, n, { status: d.status === "cancelled" ? "cancelled" : "failed", error: `the job ended ${d.status} before it ran` }, paths).catch(() => {}); } }); return { result, iteration: n, ...(warnings.length ? { warnings } : {}) }; } catch (e) { return refuse((e as Error).message); } } async function runReportDraft( o: { body: ReportDraftBody; model: string; maxUsd?: number; n: number; jobId: string; onLog: (l: string) => void; signal: AbortSignal; setProgress?: (snap: JobProgress) => void; }, deps: ReportDraftDeps, ): Promise { const { body, model, n, onLog, signal } = o; const paths = deps.paths; const gen = (deps.settings ?? getSettings)().generation; const provider = providerOf(model); onLog(`${body.task} of ${body.article} i${n} on ${model} (${provider === "api" ? `the Claude API, cap $${o.maxUsd}` : "the local model"})`); if (provider === "local") { // The memory floor (demo epic D5), at the job's turn: a local model's run // beside a machine already short of memory is what OOM-killed ollama in // D0. Under it the job WAITS — MemAvailable read again every pollMs, one // log line when it starts waiting and one when it goes on — and fails with // the sentence only after maxWaitMs. A cancel ends the wait at once. const floor = localDraftFloorMb(); const readMb = deps.memAvailableMb ?? readMemAvailableMb; const { pollMs = LOCAL_DRAFT_MEMORY_POLL_MS, maxWaitMs = LOCAL_DRAFT_MEMORY_WAIT_MS } = deps.memoryWait ?? {}; let mb = floor > 0 ? await readMb() : null; if (mb !== null && mb < floor) { const started = Date.now(); const minutes = maxWaitMs >= 60_000 ? `${Math.round(maxWaitMs / 60_000)} min` : `${Math.round(maxWaitMs / 1000)} s`; onLog(`waiting for memory — ${mb} MB available, the floor is ${floor} MB (LOCAL_MODEL_MIN_FREE_MB); waits up to ${minutes}`); while (mb !== null && mb < floor) { if (Date.now() - started >= maxWaitMs) { const refusal = `refused: ${mb} MB available is under the ${floor} MB a local model's run starts with, after waiting ${minutes} — run it when the machine is quieter`; if (!isStepTask(body.task)) await updateIteration(body.article, n, { status: "failed", error: refusal }, paths).catch(() => {}); throw new Error(refusal); } await new Promise((resolve, reject) => { if (signal.aborted) return reject(new Error("cancelled while waiting for memory")); const onAbort = () => { clearTimeout(t); reject(new Error("cancelled while waiting for memory")); }; const t = setTimeout(() => { signal.removeEventListener("abort", onAbort); resolve(); }, pollMs); signal.addEventListener("abort", onAbort, { once: true }); }); mb = await readMb(); } onLog(`memory: ${mb ?? "unknown"} MB available — going on`); } } if (provider === "api") { // Again at the job's turn: jobs ahead in the queue may have spent the day. const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); if (refusal) { if (!isStepTask(body.task)) await updateIteration(body.article, n, { status: "failed", error: refusal }, paths).catch(() => {}); throw new Error(refusal); } } const it = (await readIteration(body.article, n, paths))!; const channels = body.task === "sweep" || body.task === "research" ? (it.scope?.channels ?? []) : await channelsOfReport(body.article, isStepTask(body.task) ? n : (it.parent ?? n), paths); let corpus: (CorpusToolsLike & { close(): Promise }) | null = null; let result: TaskResult | null = null; try { const where = await resolveCorpus(body, channels, paths, gen, await lineageSource(body.article, n, paths).catch(() => null)); onLog(`corpus ${where.source}${where.build ? ` (build ${where.build})` : ""}; links on ${where.origin}`); corpus = await deps.corpusTools(where.source); const disk = paths.channelsDir; const posts = new Map>>(); const postText = (ch: string, id: string) => { let p = posts.get(ch); if (!p) { p = readAllPosts(path.join(disk, ch)).then((all) => new Map(all.map((x) => [x.id, x.text])), () => new Map()); posts.set(ch, p); } return p.then((m) => m.get(id) ?? null); }; let deck: Promise | undefined; const taskDeps: TaskDeps = { llm: llmConfigOf(gen, paths, provider === "local" ? { onLog, signal } : undefined), corpus, web: webTools({ ...(gen.web.searchUrl ? { searchUrl: gen.web.searchUrl } : {}) }), cuesOf: corpusCuesOf(corpus), postTextOf: postText, postChannelOf: diskPostChannelOf(disk), // The corpus on disk adds what the build cannot say: an en-orig track // whose words differ. Only a drift counts; a record the disk does not // hold is the build's to answer. verifyReport: async (report) => (await verifyReportQuotes(report, { paths }).catch(() => [])) .filter((r) => r.status === "drift" || r.status === "en-orig-drift") .map((r) => ({ citation: r.citation, status: r.status, ...(r.message ? { message: r.message } : {}) })), paths, log: onLog, // The task's count as the job's progress (release 28 F3): turns, cards // or entries, the runner's own `current` (nothing on disk re-counts it). progress: (p) => o.setProgress?.({ metric: p.metric, initial: 0, target: Math.max(p.total ?? p.current, p.current), current: p.current }), // The build's validators, from this checkout's umtool (loaded once, when // a media task first asks). deckChecks: () => (deck ??= loadDeckChecks(paths.monorepoRoot || getPaths().monorepoRoot)), signal, ...(deps.now ? { now: deps.now } : {}), ...(body.task === "research" && deps.researchEditor ? { editor: deps.researchEditor, editorChannels: () => editorChannelsOf(paths) } : {}), }; const projectsRoot = projectsRootOf(gen); // A local run costs nothing: it has no dollar cap. const cap = provider === "api" ? o.maxUsd! : Number.POSITIVE_INFINITY; const extractor = body.extractorModel ?? gen.models.extractor; let input: TaskInput; switch (body.task) { case "refresh": case "triage": case "verdicts": case "frames": case "clips-suggest": case "video-assist": case "propose-groups": case "cast-assign": case "lookout": // A refresh, a triage, verdict proposals, a frame scan, the clip finder's labels and the video assistant are their own jobs (./reportRefresh.ts, ./reportTriage.ts, ./reportVerdicts.ts, ./frameScan.ts, ./clipsSuggest.ts, ./videoAssist.ts), never this one. throw new Error(`a ${body.task} runs as its own job`); case "sweep": input = provider === "api" ? { task: "sweep-agent", article: body.article, n, extractorModel: extractor, origin: where.origin, maxUsd: cap } : { task: "sweep-pipeline", article: body.article, n, origin: where.origin, claimForm: gen.localSweep.claimForm, readAloud: gen.localSweep.readAloud }; break; case "revise-report": input = { task: "revise-report", article: body.article, n, origin: where.origin, maxUsd: cap }; break; case "revise-video": input = { task: "revise-video", article: body.article, n, origin: where.origin, maxUsd: cap, projectsRoot }; break; case "research": { const r = gen.research; const was = (it as { research?: { autonomy?: Autonomy } }).research?.autonomy; const limits: ResearchLimits = { maxItemsPerRun: r.maxItemsPerRun, maxGbPerRun: r.maxGbPerRun, maxTranscribeHours: r.maxTranscribeHours, newChannelsNeedApproval: r.newChannelsNeedApproval, postWalksNeedApproval: r.postWalksNeedApproval, }; input = { task: "research", article: body.article, n, origin: where.origin, maxUsd: cap, autonomy: body.autonomy ?? was ?? r.autonomy, limits }; break; } case "narrate": case "cut": case "onscreen": case "teaser": case "flips": case "threads": case "youtube": case "social": { // A media draft: a step on the done iteration n (./tasks/media.ts). const step = { article: body.article, n, model, projectsRoot, ...(o.maxUsd ? { maxUsd: o.maxUsd } : {}), jobId: o.jobId, ...(body.entries ? { entries: body.entries } : {}), ...(body.force ? { force: true } : {}), }; input = body.task === "narrate" ? { task: "narrate", ...step, ...(body.cards ? { cards: body.cards } : {}) } : body.task === "cut" ? { task: "cut", ...step, maxClips: gen.cut.maxClips } : { task: body.task, ...step }; break; } } result = await runTask(input, taskDeps); } catch (e) { if (!isStepTask(body.task)) { const cur = await readIteration(body.article, n, paths).catch(() => null); if (cur && (cur.status === "queued" || cur.status === "running")) { await updateIteration(body.article, n, { status: signal.aborted ? "cancelled" : "failed", error: (e as Error).message }, paths).catch(() => {}); } } throw e; } finally { await corpus?.close().catch(() => {}); if (provider === "local") { // Free the card for transcription and TTS, however the job ended. await unloadOllama({ baseUrl: gen.ollamaUrl || paths.ollamaUrl }, model).then( () => onLog(`unloaded ${model} from ollama`), (e) => onLog(`ollama unload failed: ${(e as Error).message}`), ); } if (provider === "api" && result) { await recordUsage(body, n, model, o.jobId, paths, deps.now?.() ?? new Date()).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); } } onLog(`${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: body.article, iteration: n, task: body.task, status: result.status, summary: result.summary, usd: result.usd, minutes: result.minutes })}`); if (result.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (result.status === "failed") throw new Error(result.summary); } // The job's spend, per model, from the iteration's usage (a step — a // narration, any media draft: the step's cost, on its model). async function recordUsage(body: ReportDraftBody, n: number, model: string, jobId: string, paths: Paths, now: Date) { const it = await readIteration(body.article, n, paths); if (!it) return; const day = utcDay(now); const base = { at: now.toISOString(), day, jobId, article: body.article, iteration: n, task: body.task }; let rows: GenerationUsageRow[]; if (isStepTask(body.task)) { const step = [...it.steps].reverse().find((s) => s.task === body.task && s.jobId === jobId); rows = step?.cost ? [{ ...base, model, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: step.cost }] : []; } else { rows = Object.entries(it.usage) .filter(([m, u]) => providerOf(m) === "api" && (u.usd > 0 || (u.calls ?? 0) > 0)) .map(([m, u]) => ({ ...base, model: m, inputTokens: u.inputTokens, outputTokens: u.outputTokens, cacheReadTokens: u.cacheReadTokens ?? 0, cacheWriteTokens: u.cacheWriteTokens ?? 0, usd: Math.round(u.usd * 10_000) / 10_000, })); } await appendGenerationUsage(paths.generationUsageFile, rows); }