// A LOOKOUT RUN — `pnpm ops lookout-run {"id"}` (lane/lookout slice 2): a // saved lookout's recent recordings read by the local model and grouped into // video ideas, as a `lookout-run` job on `draft:local`. // // WHAT IS READ IS THE PLAN'S `read` LIST, computed IN THE JOB at its turn // (planLookout, controller/lookoutPlan.ts) — the one enumeration the dry run // shows, never a second one that could disagree with it — and each recording // is chunked as the plan counted it (`chunksOf(cueLines(cues))`). // // stage 3, read one call per chunk (READ_SYSTEM, lib/lookoutRead.ts); every // quote located in the chunk by code or dropped; the chunk's // items appended to the video's reading notes // (lib/readingNotes-server.ts, its one writer) AFTER EVERY // CALL. A video whose notes are fresh and complete is not read // again; one whose notes are fresh and partial (a cancelled or // interrupted run) is read from the chunks it lacks. So a run // stopped anywhere continues, on its next start, where it // stopped, and re-reads nothing already judged. // stage 4, group the window's items as numbered lines, at most GROUP_CHARS a // call, date order; more than one call → one merge call over // the candidates; the lookout's `prompt` steers this only. // stage 5, check lib/lookoutRead.ts checkIdeas: ids that exist, at least two // moments, a story key, caveats from the voice. // The run is written whole once, when it ends however it ends // (lib/lookoutStore.ts writeLookoutRun): `done`, `partial` (cancelled, the // per-run call cap, a chunk that failed) or `failed` (the model kept failing). // A cancelled run groups nothing: its notes are kept for the next run. After // the cap, a render held past LOOKOUT_RENDER_WAIT_MAX_MS ("held for a render": // the wait holds the one-at-a-time draft:local queue) or a failure, the later // recordings' notes are still LOADED, so what is already read is grouped, and // no reading call is made past it. A failed grouping call leaves the run // `partial`. A reading-notes write that fails (the channel renamed or deleted // under the run) ends it `failed` with why, keeping what was written: the job // record names ONE channel (the registry has no multi-channel declaration), // so rename and delete do not see a lookout run's channels as busy. // // THE MACHINE: every model call goes through the generation route's ollama // config, whose fetch waits for the GPU (transcription first; gpuArbiter.ts) // and is recorded in the job's model log (CallSlot, controller/jobModelLog.ts); // render mode is read before every call and a held one is waited out with one // log line (render mode does not hold `draft:local` by itself); the job // refuses to start under LOOKOUT_MIN_FREE_MB of MemAvailable; the model is // unloaded when the job ends; no call is made with an aborted signal. The run // makes no other network request. // // LOCAL ONLY in this build: a lookout routed to `code` or `api` is refused // unless the run names a local model (no `answers`, no API spend yet). import path from "node:path"; import { readFile, stat } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { getSettings } from "../lib/settings"; import type { GenerationSettings } from "../lib/generationSettings"; import { lookoutById, type LookoutItem } from "../lib/lookoutSettings"; import { assertLookoutVerdictsReadable, newLookoutRunId, writeLookoutRun, type LookoutRun, } from "../lib/lookoutStore"; import { CHUNK_CHARS, GROUP_SCHEMA, GROUP_SYSTEM, MERGE_SCHEMA, MERGE_SYSTEM, READING_PROMPT_VERSION, READ_SCHEMA, READ_SYSTEM, applyMerges, checkIdeas, checkReading, groupBatches, groupPrompt, ideasOf, mergeLine, readPrompt, type GroupItem, type RawIdea, } from "../lib/lookoutRead"; import { loadReadingNotes, newReadingNotes, sameReadingProvenance, writeReadingNotes, withReadingChunk, type ReadingNotes, type ReadingProvenance, } from "../lib/readingNotes-server"; import { chunksOf } from "../lib/report/draft/tasks/sweep-pipeline"; import { CallSlot } from "../lib/llm/callLog-server"; import { providerOf, structuredAnswer, unloadOllama, type LlmConfig } from "../lib/llm"; import { DRAFT_LOCAL_QUEUE } from "../lib/queueKeys"; import { describeRenderPriority, readRenderPriority, renderPriorityFile } from "../lib/renderPriority.mjs"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { getRegistry } from "../jobs/registry"; import { CUES_JSON_FILENAME } from "../lib/videoStatus"; import { cueLines, cuesOfDoc, planLookout, type LookoutPlanOptions } from "./lookoutPlan"; import { modelLogged } from "./jobModelLog"; import { readMemAvailableMb } from "./persistVideos"; import { LOCAL_DRAFT_MIN_FREE_MB, llmConfigOf } from "./reportDraft"; export const LOOKOUT_RUN_JOB_KIND = "lookout-run"; export const LOOKOUT_RUN_RESULT_MARKER = "@@lookout-run "; export const LOOKOUT_TASK = "lookout" as const; /** Reading calls one run may make; past it the run ends `partial` with what it has. */ export const LOOKOUT_MAX_CALLS = 400; /** The job does not start with less MemAvailable than this (MiB) — it refuses; the report-draft floor (reportDraft.ts) is the same number but waits. LOCAL_MODEL_MIN_FREE_MB moves only that one. */ export const LOOKOUT_MIN_FREE_MB = LOCAL_DRAFT_MIN_FREE_MB; /** This many failed calls in a row end the run `failed`. */ export const LOOKOUT_MAX_FAILED_IN_A_ROW = 3; /** Render mode is looked at again this often while it holds. */ export const LOOKOUT_RENDER_POLL_MS = 15_000; /** A run waits for render mode at most this long in all, then ends partial ("held for a render"). */ export const LOOKOUT_RENDER_WAIT_MAX_MS = 10 * 60_000; export class LookoutRunRefusal extends Error {} /** One model call: the generation route's structured answer, or a test's stub. */ export type LookoutAsk = (o: { system: string; user: string; schema: object; phase: "reading" | "grouping"; label: string; slot: CallSlot; signal: AbortSignal; }) => Promise; export type LookoutRunDeps = { ask: LookoutAsk; /** Why render mode holds the machine now, or null (default: its state file). */ renderHeld?: () => string | null; sleep?: (ms: number, signal: AbortSignal) => Promise; renderPollMs?: number; /** The longest a run waits for render mode in all (default LOOKOUT_RENDER_WAIT_MAX_MS). */ renderWaitMaxMs?: number; now?: () => Date; }; export type LookoutRunOptions = Pick & { model: string; maxCalls?: number; signal: AbortSignal; onLog: (line: string) => void; onProgress?: (done: number, total: number) => void; }; export type LookoutRunOutcome = { run: LookoutRun; file: string }; /** Render mode, as the heavy slot's gate reads it: why it holds, or null. */ export function renderModeHeld(): string | null { try { const s = readRenderPriority(renderPriorityFile(process.env, { root: process.cwd() })); return s.held && s.state ? describeRenderPriority(s.state) : null; } catch { return null; // an unreadable state file holds nothing (queue-lock's rule) } } function abortableSleep(ms: number, signal: AbortSignal): Promise { return new Promise((resolve) => { if (signal.aborted) return resolve(); const t = setTimeout(done, ms); function done() { clearTimeout(t); signal.removeEventListener("abort", done); resolve(); } signal.addEventListener("abort", done, { once: true }); }); } type Cued = { cues: ReturnType; size: number; mtimeMs: number }; async function readCues(dir: string): Promise { const file = path.join(dir, CUES_JSON_FILENAME); try { const st = await stat(file); const doc = JSON.parse(await readFile(file, "utf8")) as Record; return { cues: cuesOfDoc(doc), size: st.size, mtimeMs: st.mtimeMs }; } catch { return null; } } /** * One lookout run, start to end: plan, read, group, check, write the run. * Never throws for a model failure, a cancel or the cap — those end the run * `partial` or `failed`, and it is written; a refusal (damaged verdicts, a * lookout with no channels) throws before anything is read. */ export async function runLookout(paths: Paths, item: LookoutItem, o: LookoutRunOptions, deps: LookoutRunDeps): Promise { const now = deps.now ?? (() => new Date()); const startedAt = now(); const runId = newLookoutRunId(startedAt); const { signal, onLog, model } = o; const maxCalls = o.maxCalls ?? LOOKOUT_MAX_CALLS; await assertLookoutVerdictsReadable(paths, item.id); const plan = await planLookout(paths, item, { days: o.days, maxVideos: o.maxVideos, until: o.until, now: startedAt }); for (const r of plan.refused) onLog(`not read: ${r.channel} — ${r.reason}`); onLog( `lookout ${item.id}: ${plan.window.from} to ${plan.window.to} (${plan.window.timeZone}), ` + `${plan.read.length} recording(s) to read, ${plan.estimate.readCalls} chunk(s), on ${model}`, ); let readCalls = 0; let groupCalls = 0; let groupFailed = 0; let seconds = 0; let failedInRow = 0; let stopped: LookoutRun["stopped"]; let failure: string | null = null; const dropped: Record = {}; const count = (k: string, n = 1) => { if (n) dropped[k] = (dropped[k] ?? 0) + n; }; const reading = { videos: plan.read.length, videosComplete: 0, chunks: 0, chunksRead: 0, chunksReused: 0, chunksFailed: 0, items: 0, readCalls: 0, groupCalls: 0, groupCallsFailed: 0, renderWaitSeconds: 0 }; const sleep = deps.sleep ?? abortableSleep; const renderHeld = deps.renderHeld ?? renderModeHeld; const renderWaitMax = deps.renderWaitMaxMs ?? LOOKOUT_RENDER_WAIT_MAX_MS; const progressTotal = Math.max(1, plan.estimate.readCalls); let renderWaited = 0; // Before every call: not cancelled; render mode waited out with one line — // at most LOOKOUT_RENDER_WAIT_MAX_MS in all for the run, since the wait // holds the one-at-a-time draft:local queue. Past it the run ends partial, // "held for a render"; its notes are kept and the next run resumes. const mayCall = async (): Promise => { if (signal.aborted || stopped === "render") return false; let why = renderHeld(); if (why) { onLog(`render mode holds the machine (${why}) — waiting before the next model call`); const t0 = now().getTime(); const waited = () => renderWaited + (now().getTime() - t0); while (why && !signal.aborted) { if (waited() >= renderWaitMax) { renderWaited = waited(); stopped = "render"; onLog(`held for a render for ${Math.round(renderWaited / 60_000)} min — the run ends here; the next run resumes from the notes`); return false; } await sleep(Math.min(deps.renderPollMs ?? LOOKOUT_RENDER_POLL_MS, Math.max(1, renderWaitMax - waited())), signal); why = renderHeld(); } renderWaited = waited(); if (!signal.aborted) onLog("render mode is off — reading again"); } return !signal.aborted; }; const call = async (phase: "reading" | "grouping", label: string, system: string, user: string, schema: object, slot: CallSlot): Promise => { const t0 = Date.now(); try { const answer = await deps.ask({ system, user, schema, phase, label, slot, signal }); seconds += (Date.now() - t0) / 1000; failedInRow = 0; return answer; } catch (err) { seconds += (Date.now() - t0) / 1000; if (signal.aborted) return null; failedInRow++; onLog(`${label}: the model call failed — ${(err as Error).message}`); if (failedInRow >= LOOKOUT_MAX_FAILED_IN_A_ROW) { stopped = "failed"; failure ??= `the model failed ${LOOKOUT_MAX_FAILED_IN_A_ROW} times in a row`; } return null; } }; // ─── Stage 3: read ─── // Every recording's notes are LOADED, even after the run has stopped reading // (the cap, a render, a failure): what is already read is grouped. Only a // cancel stops the loop. const notesOf = new Map(); for (const r of plan.read) { if (signal.aborted) break; const key = `${r.channel}/${r.video}`; const dir = path.join(paths.channelsDir, r.channel, "data", r.video); const cued = await readCues(dir); if (!cued) { onLog(`${key}: transcript.cues.json is not readable now — not read`); count("unreadableCues"); continue; } const chunks = chunksOf(cueLines(cued.cues), CHUNK_CHARS); if (chunks.length !== r.chunks) onLog(`${key}: ${chunks.length} chunk(s) now, ${r.chunks} when planned (its transcript changed)`); reading.chunks += chunks.length; const prov: ReadingProvenance = { model, promptVersion: READING_PROMPT_VERSION, chunkChars: CHUNK_CHARS, cues: { size: cued.size, mtimeMs: cued.mtimeMs } }; const loaded = await loadReadingNotes(dir, prov); if (loaded.state === "damaged") { onLog(`${key}: its reading-notes.json is damaged — what is whole in it is kept, this model's reading is read again and written over`); count("damagedNotes"); } const had = loaded.notes; let notes: ReadingNotes; if (had && had.chunkCount === chunks.length && sameReadingProvenance(had.provenance, prov)) { notes = had; reading.chunksReused += had.chunks.length; if (had.chunks.length && !had.complete && !stopped) onLog(`${key}: resuming its reading notes at ${had.chunks.length} of ${chunks.length} chunk(s)`); } else { if (had) onLog(`${key}: its reading notes are stale (another transcript) — read again`); notes = newReadingNotes(prov, chunks.length, now()); } if (notes.chunks.length) notesOf.set(key, notes); if (notes.complete) { reading.videosComplete++; continue; } if (stopped) continue; const done = new Set(notes.chunks.map((c) => c.index)); for (let i = 0; i < chunks.length; i++) { if (done.has(i)) continue; if (readCalls >= maxCalls) { stopped ??= "cap"; break; } if (!(await mayCall())) break; const slot = new CallSlot(); const label = `${key} part ${i + 1}/${chunks.length}`; const answer = await call("reading", label, READ_SYSTEM, readPrompt({ title: r.title, airDate: r.airDate }, chunks[i]!, i, chunks.length), READ_SCHEMA, slot); readCalls++; o.onProgress?.(readCalls, progressTotal); if (answer === null) { if (!signal.aborted) reading.chunksFailed++; if (stopped || signal.aborted) break; continue; } const checked = checkReading(answer, chunks[i]!, cued.cues, i); for (const d of checked.dropped) count(`quote:${d.reason}`); const fates = [ ...checked.chunk.items.map((it) => ({ outcome: "kept" as const, why: `located at ${it.start}s`, text: it.quote })), ...checked.dropped.map((d) => ({ outcome: "dropped" as const, why: d.reason, text: d.quote })), ]; if (fates.length) slot.decide(checked.chunk.items.length ? "kept" : "dropped", `${checked.chunk.items.length} of ${fates.length} item(s) kept`, fates); else slot.decide("n/a", "nothing in this part"); const next = withReadingChunk(notes, checked.chunk, now()); // After every call: a run stopped anywhere keeps what it read. A write // that fails (the channel renamed or deleted under the run) ends the run // failed, with why, and what was written before it stays. try { await writeReadingNotes(dir, next); } catch (err) { stopped = "failed"; failure = `${key}: the reading notes could not be written — ${(err as Error).message}`; onLog(failure); break; } notes = next; notesOf.set(key, notes); reading.chunksRead++; } if (notes.complete) reading.videosComplete++; } if (signal.aborted) stopped = "cancelled"; // ─── Stage 4: group ─── const items = new Map(); for (const r of plan.read) { const notes = notesOf.get(`${r.channel}/${r.video}`); if (!notes) continue; for (const c of notes.chunks) { for (const it of c.items) { const id = `i${items.size + 1}`; items.set(id, { ...it, id, channel: r.channel, video: r.video, recordId: r.id, platform: r.platform, url: r.url, title: r.title, date: r.airDate }); } } } reading.items = items.size; let raw: RawIdea[] = []; if (stopped === "cancelled") { onLog("cancelled — the reading notes so far are kept; the next run continues from them"); } else if (stopped === "failed") { onLog(`${failure ?? "the run failed"} — nothing grouped`); } else if (items.size < 2) { onLog(`${items.size} located moment(s): too few for a story — nothing to group`); } else { const batches = groupBatches([...items.values()]); const candidates = new Map(); const datesOf = new Map(); const going = () => !signal.aborted && stopped !== "failed"; for (let b = 0; b < batches.length && going(); b++) { if (!(await mayCall())) break; const slot = new CallSlot(); const batch = batches[b]!; const answer = await call("grouping", `group ${b + 1}/${batches.length}`, GROUP_SYSTEM, groupPrompt(batch, { prompt: item.prompt, from: plan.window.from, to: plan.window.to }), GROUP_SCHEMA, slot); groupCalls++; if (answer === null) { if (!signal.aborted) groupFailed++; continue; } const got = ideasOf(answer); slot.decide(got.length ? "kept" : "n/a", `${got.length} candidate idea(s)`); for (const idea of got) { const id = `c${candidates.size + 1}`; candidates.set(id, idea); datesOf.set(id, [...new Set(batch.map((x) => x.date))]); } } if (signal.aborted) stopped = "cancelled"; raw = [...candidates.values()]; if (going() && batches.length > 1 && candidates.size > 1 && (await mayCall())) { const slot = new CallSlot(); const lines = [...candidates].map(([id, idea]) => mergeLine(id, idea, datesOf.get(id) ?? [])); const answer = await call("grouping", "merge the groups", MERGE_SYSTEM, `Candidates:\n${lines.join("\n").slice(0, 12_000)}`, MERGE_SCHEMA, slot); groupCalls++; if (answer !== null) { const m = applyMerges(candidates, answer); slot.decide(m.merged ? "kept" : "n/a", `${m.merged} merge(s)`); raw = m.ideas; } else if (!signal.aborted) { groupFailed++; } } if (signal.aborted) stopped = "cancelled"; if (stopped === "cancelled") raw = []; } // ─── Stage 5: check ─── const checked = checkIdeas(raw, items, { siteOrigin: item.siteOrigin }); count("idea:inventedItemId", checked.dropped.inventedItemIds); count("idea:oneMoment", checked.dropped.oneMoment); count("idea:noCitation", checked.dropped.noCitation); count("idea:sameStory", checked.dropped.sameStory); reading.readCalls = readCalls; reading.groupCalls = groupCalls; reading.groupCallsFailed = groupFailed; reading.renderWaitSeconds = Math.round(renderWaited / 1000); // A failed reading or grouping call leaves the run partial, never done. const status: LookoutRun["status"] = stopped === "failed" ? "failed" : stopped || reading.chunksFailed || groupFailed ? "partial" : "done"; const note = stopped === "cap" ? `stopped at the per-run cap of ${maxCalls} reading calls; the next run continues from the notes` : stopped === "cancelled" ? "cancelled; the next run continues from the reading notes" : stopped === "render" ? `held for a render (${Math.round(renderWaited / 60_000)} min waited); the next run continues from the reading notes` : stopped === "failed" ? (failure ?? "failed") : groupFailed ? `${groupFailed} grouping call(s) failed: the ideas are from the rest` : null; const run: LookoutRun = { version: 1, lookoutId: item.id, runId, startedAt: startedAt.toISOString(), endedAt: now().toISOString(), status, window: { from: plan.window.from, to: plan.window.to, days: plan.window.days, timeZone: plan.window.timeZone }, model, calls: readCalls + groupCalls, seconds: Math.round(seconds * 10) / 10, selection: plan, ideas: checked.ideas, dropped, ...(stopped ? { stopped } : {}), reading, ...(note ? { note } : {}), }; const file = await writeLookoutRun(paths, run); onLog( `lookout ${item.id}: ${status}${stopped ? ` (${stopped})` : ""} — ${reading.chunksRead} chunk(s) read, ${reading.chunksReused} reused, ` + `${reading.chunksFailed} failed, ${items.size} moment(s), ${checked.ideas.length} idea(s), ${run.calls} call(s), ${run.seconds}s`, ); return { run, file }; } // ─── The job ─── // Which lookout each live job is of (the registry record has no field for // it); per process, on globalThis (Next may load a module twice). const JOBS_KEY = Symbol.for("archilyzer.lookoutRun.jobs"); function jobsOf(): Map { const g = globalThis as unknown as Record | undefined>; return (g[JOBS_KEY] ??= new Map()); } const ENQUEUEING_KEY = Symbol.for("archilyzer.lookoutRun.enqueueing"); function enqueueingOf(): Set { const g = globalThis as unknown as Record | undefined>; return (g[ENQUEUEING_KEY] ??= new Set()); } /** The queued or running lookout-run jobs of a lookout: `{jobId, status}`. */ export function lookoutRunJobs(id: string): { jobId: string; status: string }[] { const mine = jobsOf(); const live = getRegistry() .list() .filter((j) => j.kind === LOOKOUT_RUN_JOB_KIND && mine.has(j.id) && (j.status === "queued" || j.status === "running")); // An ended job is forgotten here as it is in the registry. const ids = new Set(live.map((j) => j.id)); for (const jobId of [...mine.keys()]) if (!ids.has(jobId)) mine.delete(jobId); return live.filter((j) => mine.get(j.id) === id).map((j) => ({ jobId: j.id, status: j.status })); } /** Cancel a lookout's queued or running run; the job ids cancelled. */ export function cancelLookoutRuns(id: string): string[] { const out: string[] = []; for (const j of lookoutRunJobs(id)) if (getRegistry().cancel(j.jobId)) out.push(j.jobId); return out; } /** The model a run reads with: the asked one, else the `lookout` route's — local only in this build. */ export function lookoutModel(gen: GenerationSettings, asked?: string): string { const route = gen.routes[LOOKOUT_TASK]; const model = asked ?? (route === "local" ? gen.models.local : null); if (!model) { throw new LookoutRunRefusal( `lookout is routed to ${route === "code" ? "Claude Code" : "the API"} (settings.generation.routes.lookout) — this build reads on the local model only: route it to local, or name a local "model"`, ); } if (providerOf(model) !== "local") throw new LookoutRunRefusal(`"${model}" is not a local model — this build reads a lookout on the local model only`); return model; } export type LookoutRunBody = { id: string; model?: string; days?: number; maxVideos?: number; until?: string; maxCalls?: number }; export type LookoutRunJobDeps = { paths: Paths; settings?: () => ReturnType; /** The run's model calls (default: structuredAnswer on the generation route's ollama, through the GPU arbiter). */ ask?: (llm: LlmConfig, model: string) => LookoutAsk; memAvailableMb?: () => Promise; renderHeld?: () => string | null; unload?: (model: string) => Promise; now?: () => Date; }; /** The run's calls on the generation route: structuredAnswer, recorded in the model log with the call's slot. */ export const structuredAsk = (llm: LlmConfig, model: string): LookoutAsk => (q) => structuredAnswer({ llm, model, system: q.system, user: q.user, schema: q.schema, signal: q.signal, call: { phase: q.phase, label: q.label, slot: q.slot } }); export type LookoutRunEnqueued = { result: StreamActionResult; model: string } | { result: StreamActionResult & { ok: false } }; /** * A lookout run as a `lookout-run` job. Refused before any job: lookouts off * (`settings.lookouts.enabled`), an unknown id, a route this build does not * read on, a run of the same lookout already queued or running, a damaged * verdicts.json. At the job's turn: the lookout read from settings again, * MemAvailable under the floor refused. */ export async function enqueueLookoutRun(body: LookoutRunBody, deps: LookoutRunJobDeps): Promise { const refuse = (error: string) => ({ result: { ok: false as const, error } }); const settings = deps.settings ?? getSettings; const s = settings(); if (!s.lookouts.enabled) { return refuse('lookouts are off (settings.lookouts.enabled) — a dry run ("dryRun": true) still lists what a lookout would read'); } const item = lookoutById(s.lookouts, body.id); if (!item) return refuse(`no lookout "${body.id}" — settings.lookouts.items names ${s.lookouts.items.map((i) => i.id).join(", ") || "none"}`); let model: string; try { model = lookoutModel(s.generation, body.model); await assertLookoutVerdictsReadable(deps.paths, item.id); } catch (e) { return refuse((e as Error).message); } const busy = lookoutRunJobs(item.id); if (busy.length) return refuse(`a run of lookout "${item.id}" is already ${busy[0]!.status} (job ${busy[0]!.jobId})`); // Two asks at once: the second is refused while the first is being queued. const enqueueing = enqueueingOf(); if (enqueueing.has(item.id)) return refuse(`a run of lookout "${item.id}" is being queued`); enqueueing.add(item.id); const paths = deps.paths; let result: StreamActionResult; try { result = await runManagedFunction({ kind: LOOKOUT_RUN_JOB_KIND, queueKey: DRAFT_LOCAL_QUEUE, paths, fn: modelLogged({ paths, task: LOOKOUT_TASK, model }, async (onLog, signal, setProgress) => { const now = settings(); const at = lookoutById(now.lookouts, item.id); if (!now.lookouts.enabled) throw new Error("lookouts were turned off (settings.lookouts.enabled) while this run waited"); if (!at) throw new Error(`lookout "${item.id}" is no longer in settings.lookouts.items`); const mb = await (deps.memAvailableMb ?? readMemAvailableMb)(); if (mb !== null && mb < LOOKOUT_MIN_FREE_MB) { throw new Error(`refused: ${mb} MB available is under the ${LOOKOUT_MIN_FREE_MB} MB a lookout run starts with — run it when the machine is quieter`); } const g = now.generation; const llm = llmConfigOf(g, paths, { onLog, signal }); let out: LookoutRunOutcome | null = null; try { out = await runLookout( paths, at, { model, ...(body.days !== undefined ? { days: body.days } : {}), ...(body.maxVideos !== undefined ? { maxVideos: body.maxVideos } : {}), ...(body.until !== undefined ? { until: body.until } : {}), ...(body.maxCalls !== undefined ? { maxCalls: body.maxCalls } : {}), signal, onLog, onProgress: (done, total) => setProgress({ metric: "calls", initial: 0, target: Math.max(total, done), current: done }), }, { ask: (deps.ask ?? structuredAsk)(llm, model), ...(deps.renderHeld ? { renderHeld: deps.renderHeld } : {}), ...(deps.now ? { now: deps.now } : {}) }, ); } finally { await (deps.unload ?? ((m: string) => unloadOllama({ baseUrl: g.ollamaUrl || paths.ollamaUrl }, m)))(model).then( () => onLog(`unloaded ${model} from ollama`), (e) => onLog(`ollama unload failed: ${(e as Error).message}`), ); } const r = out.run; onLog( `${LOOKOUT_RUN_RESULT_MARKER}${JSON.stringify({ id: r.lookoutId, runId: r.runId, status: r.status, ...(r.stopped ? { stopped: r.stopped } : {}), window: r.window, model: r.model, calls: r.calls, seconds: r.seconds, reading: r.reading, ideas: r.ideas.length, dropped: r.dropped, file: out.file, })}`, ); if (r.stopped === "cancelled" || signal.aborted) throw new Error("cancelled"); if (r.status === "failed") throw new Error("the model kept failing — the run is written as failed"); }), }); if (result.ok) jobsOf().set(result.jobId, item.id); } finally { enqueueing.delete(item.id); } if (!result.ok) return { result }; return { result, model }; }