// `report-draft {"task": "clips-suggest", "project", "model"?, "maxUsd"?, // "proposals"?, "note"?, "answers"?, "dryRun"?}` — the clip finder's optional // AI pass (release 36 lane D) as an editor job. umtool's clip editor starts it // (Suggest, Ask the assistant) through `editorCall`; `pnpm ops report-draft` // and the MCP's `generate` do the same. // // project the reactions project's directory (absolute; it must hold a // reactions.json, and it is never inside the corpus) // labels (no `note`) → `/clip-suggestions.json` (lib/clips/suggest.mjs) // note an Ask: that note's reply is posted to umtool's notes as the // agent's (`POST /api/notes?project=`, Bearer // WORKER_TOKEN), with at most one proposal the operator applies // answers the `code` route: a Claude Code session's labels (the answer // a model would give, `{items: [{id, label, why, score}]}`), read // and written exactly as a model's — no model is called // dryRun (the ops route) the plan: how many proposals, calls, the // estimate, and the request a session answers; nothing written // // Routed by settings.generation.routes["clips-suggest"] like every task // (`modelFor`: a task routed to `code` needs a named model, or `answers`). // The lane is the model's provider's: `draft:local` (every ollama call // through the GPU arbiter; ollama unloaded when the job ends) or `draft:api` // (metered: the narration cap — a small media draft — and the daily cap, its // usage in the ledger as task `clips-suggest`). The log ends `@@report-draft // {article: "", iteration: 0, task: "clips-suggest", kind, project, status, // summary, usd, suggestions | ask}`. import { modelLogged } from "./jobModelLog"; import path from "node:path"; 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 { diskCuesOf } from "../lib/report/convert-server"; import { usageOf } from "../lib/report/draft/tasks/run"; import { CLIPS_SUGGEST_TASK, CODE_MODEL, ClipsSuggestRefusal, loadAsk, loadClipsProject, planClipsSuggest, runClipsAsk, runClipsSuggest, type ClipsAskOutcome, type ClipsSuggestOutcome, type SuggestPlan, } from "../lib/report/draft/tasks/clipsSuggest"; import type { AskProposal } from "../lib/clips/suggest.mjs"; import { getWorkerToken } from "../lib/workerToken"; import { umtoolUrl } from "../lib/umtoolUrl"; import { appendGenerationUsage, dailyCapRefusal, dayUsage, utcDay, type GenerationUsageRow } from "./generationUsage"; import { REPORT_DRAFT_JOB_KIND, REPORT_DRAFT_RESULT_MARKER, llmConfigOf, modelFor, type ReportDraftBody, type ReportDraftDeps, type ReportDraftEnqueued } from "./reportDraft"; export { CLIPS_SUGGEST_TASK, CODE_MODEL }; /** Where umtool is, for an Ask's reply: `UMTOOL_URL` (lane A's reader, common/lib/umtoolUrl.ts); null when unset. */ export const umtoolOrigin = (env: Readonly> = process.env): string | null => umtoolUrl(env); export type ClipsSuggestJobDeps = ReportDraftDeps & { // An Ask's reply, posted (default: umtool's /api/notes over HTTP). postReply?: (r: { project: string; note: string; text: string; proposal: AskProposal | null }) => Promise; umtoolUrl?: string | null; workerToken?: string; }; /** The project directory a body names, checked: absolute, normalised, never inside the corpus. */ export function projectDirOf(raw: string, paths: { transcriptsDir: string }): string { if (!path.isAbsolute(raw)) throw new ClipsSuggestRefusal('"project" is the reactions project\'s absolute directory'); const dir = path.resolve(raw); if (dir !== raw.replace(/\/+$/, "")) throw new ClipsSuggestRefusal('"project" is a plain absolute path (no "..", no "//")'); const corpus = path.resolve(paths.transcriptsDir); if (dir === corpus || dir.startsWith(`${corpus}${path.sep}`)) throw new ClipsSuggestRefusal('"project" is a umtool project, never inside the corpus'); return dir; } /** POST the reply to umtool's notes as the agent's. */ export async function postReplyToUmtool( r: { project: string; note: string; text: string; proposal: AskProposal | null }, o: { umtoolUrl: string; workerToken: string; fetch?: typeof fetch }, ): Promise { const f = o.fetch ?? fetch; const res = await f(`${o.umtoolUrl}/api/notes?project=${encodeURIComponent(r.project)}`, { method: "POST", headers: { authorization: `Bearer ${o.workerToken}`, "content-type": "application/json" }, body: JSON.stringify({ op: { op: "reply", id: r.note, text: r.text, ...(r.proposal ? { proposal: r.proposal } : {}) } }), }); if (!res.ok) { const j = (await res.json().catch(() => ({}))) as { error?: string }; throw new Error(`umtool refused the reply (${res.status}): ${j.error ?? res.statusText}`); } } type Refused = { result: StreamActionResult & { ok: false } }; /** The model a job runs on: the session's answers are `claude-code`'s; else the asked one, else the route's. */ function modelOfBody(body: ReportDraftBody, gen: ReturnType["generation"]): string { if (body.answers !== undefined) return CODE_MODEL; return modelFor(gen, CLIPS_SUGGEST_TASK, body.model); } /** `dryRun`: the plan, nothing written (the ops route answers `{ ok, plan }`). */ export async function planClipsSuggestJob(body: ReportDraftBody, deps: Pick): Promise { const gen = (deps.settings ?? getSettings)().generation; const dir = projectDirOf(body.project ?? "", deps.paths); // A plan for a task routed to Claude Code is the request a session answers. const route = gen.routes[CLIPS_SUGGEST_TASK]; const model = body.model ?? (route === "code" ? CODE_MODEL : modelFor(gen, CLIPS_SUGGEST_TASK)); return planClipsSuggest({ project: dir, model, ...(body.proposals?.length ? { proposals: body.proposals } : {}) }, { cuesOf: diskCuesOf(deps.paths.channelsDir) }); } export async function enqueueClipsSuggest(body: ReportDraftBody, deps: ClipsSuggestJobDeps): 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 = modelOfBody(body, gen); // Refused at the ask, not at the job's turn: no reactions.json, no note. await loadClipsProject(dir, {}); if (body.note) await loadAsk(dir, body.note); } catch (e) { return refuse((e as Error).message); } const ask = !!body.note; const umtool = deps.umtoolUrl === undefined ? umtoolOrigin() : deps.umtoolUrl; const token = deps.workerToken ?? getWorkerToken(); if (ask && !deps.postReply) { if (!umtool) return refuse("UMTOOL_URL is not set on the editor: the assistant's reply is posted to umtool's notes"); if (!token) return refuse("WORKER_TOKEN is not set on the editor: umtool takes the assistant's reply with it"); } const provider = model === 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 postReply = deps.postReply ?? ((r: { project: string; note: string; text: string; proposal: AskProposal | null }) => postReplyToUmtool(r, { umtoolUrl: umtool!, workerToken: token })); const result = await runManagedFunction({ kind: REPORT_DRAFT_JOB_KIND, queueKey: provider === "local" ? DRAFT_LOCAL_QUEUE : DRAFT_API_QUEUE, paths, fn: modelLogged({ paths, task: "clips-suggest" }, 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( `clips-suggest ${ask ? `ask ${body.note}` : "labels"} in ${dir} on ${model} (` + (provider === "api" ? `the Claude API, cap $${maxUsd}` : provider === "local" ? "the local model, through the GPU arbiter" : "a Claude Code session's answers") + ")", ); const taskDeps = { llm: llmConfigOf(g, paths, provider === "local" ? { onLog, signal } : undefined), cuesOf: diskCuesOf(paths.channelsDir), log: onLog, progress: (done: number, total: number) => setProgress?.({ metric: "entries", initial: 0, target: Math.max(total, done), current: done }), signal, ...(deps.now ? { now: deps.now } : {}), }; let out: ClipsSuggestOutcome | ClipsAskOutcome | null = null; try { out = ask ? await runClipsAsk( { project: dir, model, note: body.note!, ...(maxUsd !== undefined ? { maxUsd } : {}) }, { ...taskDeps, postReply: (r) => postReply({ project: dir, ...r }) }, ) : await runClipsSuggest( { project: dir, model, ...(body.proposals?.length ? { proposals: body.proposals } : {}), ...(maxUsd !== undefined ? { maxUsd } : {}), ...(body.answers !== undefined ? { answers: body.answers } : {}), }, taskDeps, ); } 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}`), ); } } 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: CLIPS_SUGGEST_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 detail = "labelled" in out ? { kind: "labels", suggestions: { labelled: out.labelled, refused: out.refused.length, failed: out.failed.reduce((n, f) => n + f.ids.length, 0), file: out.file } } : { kind: "ask", ask: { note: out.note, clip: out.clip, proposal: out.proposal, dropped: out.dropped } }; onLog( `${REPORT_DRAFT_RESULT_MARKER}${JSON.stringify({ article: "", iteration: 0, task: CLIPS_SUGGEST_TASK, project: dir, status: out.status, summary: out.summary, usd: out.usd, ...detail })}`, ); 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 }; }