// `report-draft {"task": "cast-assign", "project", "handles"?, "model"?, "maxUsd"?, "answers"?}` — a character // proposed for each post author of a umtool video project (characters C3), as an editor job, asked ONLY on request: // umtool's `cast assign

--model` (and the Voices page's "Ask the model too") starts it through the ops API after // its own rule has proposed; `pnpm ops report-draft` does the same. // // project the video project's directory (absolute; it must hold a video.manifest.json) // handles the authors to ask about (umtool sends the ones its rule proposed for); none: every post author // answers the `code` route: a Claude Code session's answer (`{authors: [{handle, character, voice, speed?, // direction?}]}`), checked exactly as a model's — no model is called // // Out: `/narration/cast-assign.json` — the checked answers only; nothing is applied and the project's // characters file is never written here (umtool's one writer lays them over its proposed rows). Routed by // settings.generation.routes["cast-assign"] (local by default: `draft:local`, ollama through the GPU arbiter, // unloaded when the job ends) or the API (`draft:api`: the narration cap, the daily cap, the ledger's task // `cast-assign`). The log ends `@@report-draft {article: "", iteration: 0, task: "cast-assign", project, status, // summary, usd, cast: {at, answered, refused, file}}`. import { modelLogged } from "./jobModelLog"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { DRAFT_API_QUEUE, DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { getSettings } from "../lib/settings"; import { capFor } from "../lib/generationSettings"; import { providerOf, unloadOllama } from "../lib/llm"; import { usageOf } from "../lib/report/draft/tasks/run"; import { CAST_ASSIGN_TASK, CAST_CODE_MODEL, loadCastProject, planCastAssign, runCastAssign, type CastAssignOutcome, type CastAssignPlan, } from "../lib/report/draft/tasks/castAssign"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import { projectDirOf } from "./clipsSuggest"; import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, modelFor, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft"; export { CAST_ASSIGN_TASK, CAST_CODE_MODEL }; type Refused = { result: StreamActionResult & { ok: false } }; /** The plan, nothing written: what one ask would send (a session answers it on the `code` route). */ export async function planCastAssignJob(body: ReportDraftBody, deps: Pick): Promise { const gen = (deps.settings ?? getSettings)().generation; const dir = projectDirOf(body.project ?? "", deps.paths); const route = gen.routes[CAST_ASSIGN_TASK]; const model = body.model ?? (route === "code" ? CAST_CODE_MODEL : modelFor(gen, CAST_ASSIGN_TASK)); return planCastAssign({ project: dir, model, ...(body.handles ? { handles: body.handles } : {}) }, { llm: llmConfigOf(gen, deps.paths) }); } export async function enqueueCastAssign(body: ReportDraftBody, deps: ReportDraftDeps): Promise { const refuse = (error: string): Refused => ({ result: { ok: false as const, error } }); const paths = deps.paths; const gen = (deps.settings ?? getSettings)().generation; let dir: string; let model: string; try { dir = projectDirOf(body.project ?? "", paths); model = body.answers !== undefined ? CAST_CODE_MODEL : modelFor(gen, CAST_ASSIGN_TASK, body.model); // Refused at the ask, not at the job's turn: no manifest. await loadCastProject(dir); } catch (e) { return refuse((e as Error).message); } const provider = model === CAST_CODE_MODEL ? "code" : providerOf(model); let maxUsd: number | undefined; if (provider === "api") { try { maxUsd = capFor(gen.caps, "narration", body.maxUsd); } catch (e) { return refuse((e as Error).message); } const refusal = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), gen.caps.daily); if (refusal) return refuse(refusal); } const result = await runManagedFunction({ kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, fn: modelLogged({ paths, task: "cast-assign" }, async (onLog, signal, setProgress, ctx) => { const g = (deps.settings ?? getSettings)().generation; if (provider === "api") { const late = dailyCapRefusal(await dayUsage(paths.generationUsageFile, utcDay(deps.now?.())), g.caps.daily); if (late) throw new Error(late); } onLog( `cast-assign in ${dir} on ${model} (` + (provider === "api" ? `the Claude API, cap $${maxUsd}` : provider === "local" ? "the local model, through the GPU arbiter: it waits for a transcription" : "a Claude Code session's answer") + ")", ); setProgress?.({ metric: "turns", initial: 0, target: 1, current: 0 }); let out: CastAssignOutcome | null = null; try { out = await runCastAssign( { project: dir, model, ...(body.handles ? { handles: body.handles } : {}), ...(maxUsd !== undefined ? { maxUsd } : {}), ...(body.answers !== undefined ? { answers: body.answers } : {}), }, { llm: llmConfigOf(g, paths, provider === "local" ? { onLog, signal } : undefined), log: onLog, signal, ...(deps.now ? { now: deps.now } : {}), }, ); } finally { if (provider === "local") { await unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, model).then( () => onLog(`unloaded ${model} from ollama`), (e) => onLog(`ollama unload failed: ${(e as Error).message}`), ); } } setProgress?.({ metric: "turns", initial: 0, target: 1, current: 1 }); if (provider === "api") { const at = deps.now?.() ?? new Date(); const rows: GenerationUsageRow[] = Object.entries(out.byModel) .filter(([, t]) => t.calls > 0) .map(([m, t]) => { const u = usageOf(t); return { at: at.toISOString(), day: utcDay(at), jobId: ctx.jobId, article: "", iteration: 0, task: CAST_ASSIGN_TASK, 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).catch((e) => onLog(`usage not recorded: ${(e as Error).message}`)); } const d = out.doc; onLog( `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: "", iteration: 0, task: CAST_ASSIGN_TASK, project: dir, status: out.status, summary: out.summary, usd: out.usd, cast: { at: d?.at ?? null, answered: d?.answers.length ?? 0, refused: d?.refused.length ?? 0, file: out.file }, })}`, ); if (out.status === "cancelled" || signal.aborted) throw new Error("cancelled"); if (out.status === "failed") throw new Error(out.summary); }), }); if (!result.ok) return { result }; return { result, iteration: 0 }; }