// THE MODEL's PROPOSALS, umtool's half (characters C3; `umtool cast assign

--model`, the Voices page's "Ask the // model too"): OPTIONAL, asked only on request. The rule has proposed already (cast-assign.mjs assignPlan); the // EDITOR's `report-draft` task `cast-assign` (routed by settings.generation, local by default) is asked about the // authors the RULE proposed for, and writes its checked answers to `/narration/cast-assign.json` -- never // the characters file. Here each answer is laid over its rule row field by field (cast-assign.mjs // mergeModelProposal: a stock voice, a speed in bounds, one plain line); a row whose answer is missing or fails // stays the rule's. The caller writes the rows through the one writer (castStore.mjs). // // Plain ESM: the CLI runs it under bare node. import { readFile } from "node:fs/promises"; import path from "node:path"; import { mergeModelProposal } from "umtool-report-to-video/cast-assign"; export const CAST_ASSIGN_TASK = "cast-assign"; /** The editor task's answers file (common lib/report/draft/tasks/castAssign.ts CAST_ASSIGN_FILE). */ export const CAST_ASSIGN_FILE = "narration/cast-assign.json"; /** How often the editor's job is asked about. */ const POLL_MS = 2000; /** How long a job is followed before giving up (the job keeps running in the editor). */ const FOLLOW_MS = 30 * 60 * 1000; const RESULT_MARKER = "@@report-draft "; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); /** * How the task is routed, for the button and the report (settings.generation as the editor's policy says it): * `{ route, model, why }` -- `why` set when this page cannot start it (routed to Claude Code, or no route). */ export function castAssignRouteOf(generation) { if (!isObj(generation) || !isObj(generation.routes)) return { route: null, model: null, why: "the editor's policy was not read" }; const route = generation.routes[CAST_ASSIGN_TASK] ?? null; if (route === "code") return { route, model: null, why: "routed to Claude Code: a session answers it (pnpm ops report-draft with \"answers\")" }; const model = route === "api" ? generation.models?.api : route === "local" ? generation.models?.local : null; return { route, model: typeof model === "string" ? model : null, why: route ? null : "the editor's policy routes no cast-assign (an older editor)" }; } /** One call to the editor's ops API: `{ ok, body }` or `{ ok: false, error }`. Never throws. */ async function editorCall(cfg, method, route, body) { try { const res = await fetch(`${cfg.url}${route}`, { method, headers: { ...(cfg.token ? { authorization: `Bearer ${cfg.token}` } : {}), "content-type": "application/json" }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), }); const json = await res.json().catch(() => ({})); if (!res.ok || json?.ok === false) return { ok: false, error: String(json?.error ?? `HTTP ${res.status}`) }; return { ok: true, body: json }; } catch (err) { return { ok: false, error: `the editor at ${cfg.url} did not answer: ${err?.message ?? err}` }; } } /** * ASK THE EDITOR (the default `ask`): one `report-draft` job, task cast-assign, for these handles, followed to its * end; its answers file read. `{ answers: [{handle, character?, voice?, speed?, direction?}], model, summary }`. * Throws in a sentence when the editor refuses, the job fails, or no answers file is left. */ export async function askEditorCastAssign(project, handles, { env = process.env, emit = () => {} } = {}) { const { editorConfig } = await import("./fetchWindows.mjs"); const cfg = editorConfig(env); const started = await editorCall(cfg, "POST", "/api/ops/report-draft", { task: CAST_ASSIGN_TASK, project: project.dir, handles }); if (!started.ok) throw new Error(`the editor refused the ask: ${started.error}`); const jobId = String(started.body?.jobId ?? ""); if (!jobId) throw new Error("the editor started no job"); emit(`the editor's job ${jobId} (cast-assign)`); const until = Date.now() + FOLLOW_MS; let job = null; let tail = []; let said = ""; while (Date.now() < until) { const r = await editorCall(cfg, "GET", `/api/ops/job/${encodeURIComponent(jobId)}?tail=200`); if (r.ok) { job = r.body.job ?? {}; tail = Array.isArray(r.body.tail) ? r.body.tail.map(String) : []; if (job.status !== said) emit(`job ${jobId}: ${(said = String(job.status))}`); if (["done", "failed", "cancelled"].includes(job.status)) break; } await sleep(POLL_MS); } if (!job || !["done", "failed", "cancelled"].includes(job.status)) throw new Error(`the editor's job ${jobId} did not end in time (it may still be running: pnpm ops job ${jobId})`); const markerLine = [...tail].reverse().find((l) => l.includes(RESULT_MARKER)); let marker = null; try { marker = markerLine ? JSON.parse(markerLine.slice(markerLine.indexOf(RESULT_MARKER) + RESULT_MARKER.length)) : null; } catch { marker = null; } if (job.status !== "done") throw new Error(`the editor's job ${jobId} ended ${job.status}: ${marker?.summary ?? tail.filter((l) => !l.includes(RESULT_MARKER)).slice(-2).join(" | ")}`); let doc; try { doc = JSON.parse(await readFile(path.join(project.dir, ...CAST_ASSIGN_FILE.split("/")), "utf8")); } catch (e) { throw new Error(`the job ended but ${CAST_ASSIGN_FILE} cannot be read: ${e instanceof Error ? e.message : e}`); } return { answers: Array.isArray(doc?.answers) ? doc.answers : [], model: typeof doc?.model === "string" ? doc.model : null, summary: marker?.summary ?? null, jobId }; } /** * THE MODEL's PROPOSALS laid over the rule's (see the head): `plan` is assignPlan's. Returns `{ proposals, replaced, * report }` -- `proposals` the new rows (the rule's, each with the model's valid fields over it), `replaced` the held * RULE rows the model improved (to be written in their place), `report` `{ asked, kept, model, summary, refused?, * error? }`. The model asked about nothing (no rule row) is never called. A failed ask leaves every row the rule's. * * @param {{ id: string, dir: string }} project * @param {Record} manifest * @param {{ authors: any[], proposals: any[] }} plan * @param {{ ask?: (project: any, handles: string[], o?: any) => Promise<{ answers: any[], model: string | null, summary?: string | null }>, emit?: (s: string) => void }} [o] */ export async function modelProposals(project, manifest, plan, { ask = undefined, emit = () => {} } = {}) { // Only the RULE's rows: a person's (`by: "person"`, changed by hand) is never re-sent or overwritten; an author an // anonymous character or an anonymous proposal covers is never sent to a model at all (their name, bio and words). const targets = plan.authors.filter((a) => (a.state === "propose" || (a.state === "proposed" && a.proposal?.by === "rule")) && a.proposal?.anonymous !== true); if (!targets.length) return { proposals: plan.proposals, replaced: [], report: { asked: 0, kept: 0, model: null, summary: "no rule proposal to ask the model about" } }; const handles = targets.map((a) => a.handle); let r; try { r = await (ask ?? askEditorCastAssign)(project, handles, { emit }); } catch (e) { const error = e instanceof Error ? e.message : String(e); return { proposals: plan.proposals, replaced: [], report: { asked: handles.length, kept: 0, model: null, error, summary: `the model was not heard (${error}): the rule's proposals stand` } }; } const byHandle = new Map((Array.isArray(r?.answers) ? r.answers : []).filter((a) => isObj(a) && typeof a.handle === "string").map((a) => [a.handle.toLowerCase(), a])); const refused = []; let kept = 0; const lay = (rule) => { const h = rule.handles?.[0]; const a = byHandle.get(h); if (!a) { refused.push(`@${h}: not answered`); return rule; } const m = mergeModelProposal(rule, a, { model: r.model }); for (const why of m.refused) refused.push(`@${h}: ${why}`); if (m.kept.length) kept += 1; return m.proposal; }; const proposals = plan.proposals.map(lay); const replaced = targets.filter((a) => a.state === "proposed").map((a) => lay(a.proposal)).filter((x, i) => x !== targets.filter((t) => t.state === "proposed")[i].proposal); return { proposals, replaced, report: { asked: handles.length, kept, model: r.model ?? null, ...(refused.length ? { refused } : {}), summary: `${kept} of ${handles.length} proposal(s) took the model's answer${refused.length ? `; ${refused.length} field(s) refused or unanswered (the rule's kept there)` : ""}${r.model ? ` (${r.model})` : ""}` }, }; }