import { agentToken } from "@/lib/annotations/agentAuth.mjs"; import { editorUrl, EDITOR_GET_TIMEOUT_MS, EDITOR_POST_TIMEOUT_MS } from "@/lib/articles/generation"; import { CaseError } from "./case-stage-files"; // --------------------------------------------------------------------------- // THE EDITOR, AS THE CASE STAGES ASK IT (release 38 lane C). Every fetch, // capture, transcription and channel goes through the editor's ops door -- // never yt-dlp, a worker or the Wayback Machine by hand: the editor paces each // site, holds the cookies and the queues, and records who asked. // // Unlike askEditor (lib/articles/generation.ts) a refusal comes back as an // ANSWER with the editor's body, because the body is the point: a Wayback 403 // is `{refusal: "excluded"}`, and the capture table says so rather than // failing. Only "the editor could not be asked" throws. // --------------------------------------------------------------------------- export type EditorAnswer = { ok: boolean; status: number; body: Record }; export async function editorCall(route: string, init: { method?: "GET" | "POST"; body?: unknown } = {}): Promise { const token = agentToken(); if (!token) throw new CaseError("WORKER_TOKEN is not set for umtool, so the editor cannot be asked", 503); const method = init.method ?? "GET"; let res: Response; try { res = await fetch(`${editorUrl()}${route}`, { method, headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}), cache: "no-store", signal: AbortSignal.timeout(method === "GET" ? EDITOR_GET_TIMEOUT_MS : EDITOR_POST_TIMEOUT_MS), }); } catch (e) { throw new CaseError(`the editor at ${editorUrl()} did not answer: ${(e as Error).message}`, 502); } const body = ((await res.json().catch(() => null)) ?? {}) as Record; if (res.status === 503) throw new CaseError("the editor's ops surface is off (it has no WORKER_TOKEN)", 503); if (res.status === 401) throw new CaseError("the editor refused umtool's WORKER_TOKEN", 502); return { ok: res.ok && body.ok !== false, status: res.status, body }; } /** The editor's words for a refusal. */ export const refusalText = (a: EditorAnswer) => String(a.body.error ?? `the editor answered HTTP ${a.status}`); /** POST and expect a job id back; a refusal throws with the editor's words. */ export async function startJob(route: string, body: unknown): Promise { const a = await editorCall(route, { method: "POST", body }); const id = typeof a.body.jobId === "string" ? a.body.jobId : null; if (!a.ok || !id) throw new CaseError(`the editor refused it: ${refusalText(a)}`, a.status >= 400 ? a.status : 400); return id; } export type JobState = { status: string; done: boolean; tail: string[] }; export const isJobId = (id: string) => /^[A-Za-z0-9_-]{1,80}$/.test(id); /** Where a job is, and its last lines. */ export async function jobState(jobId: string, tail = 80): Promise { if (!isJobId(jobId)) throw new CaseError(`"${jobId}" is not a job id`, 400); const a = await editorCall(`/api/ops/job/${jobId}?tail=${tail}`); if (!a.ok) throw new CaseError(`the editor has no job ${jobId}: ${refusalText(a)}`, a.status === 404 ? 404 : 502); const status = String((a.body.job as { status?: string } | undefined)?.status ?? "unknown"); const lines = Array.isArray(a.body.tail) ? a.body.tail.map(String) : []; return { status, done: status === "done" || status === "failed" || status === "cancelled", tail: lines }; } /** The JSON after `marker` on the last line that has it, or null. */ export function resultLine(tail: string[], marker: string): T | null { const line = [...tail].reverse().find((l) => l.includes(marker)); if (!line) return null; try { return JSON.parse(line.slice(line.indexOf(marker) + marker.length)) as T; } catch { return null; } }