// TASK research — find what the corpus lacks for a question and acquire it // through the editor (release 27 S11; the plan's "Research"). // // One agent run over an iteration of kind `research`, in the plan's phases: // discover the corpus first (the MCP's read tools), then the web and // archive.org (search, an item's file list — the editor's paced // read actions); // propose each acquisition is a tool call naming its editor action, its // args, the reason and the evidence links, and what it will cost; // acquire decideAcquisition judges it against the run's autonomy and // limits: an `enqueue` becomes an editor job at once (the editor's // queues, holds and pacing), an `approval` waits in proposals.json // for the operator, a standing rule refuses it; // wait the job ends; the run is resumable — research-approve and a // continuation refresh its acquisitions from their jobs' states // (research/state.ts), with no process waiting; // continue a `sweep` iteration over the widened scope, its parent this one // (`report-draft {task: "sweep", iteration: }`). // // The run's own record: proposals.json (written on every change) and the // iteration's `research` key ({autonomy, phase, notes}). A research iteration // has no report: its result is its acquisitions. import { providerOf, runAgent, type AgentTool } from "../../../llm"; import { iterationLabel, updateIteration } from "../../iterations"; import { UNATTENDED_RULE } from "../authoringRules"; import type { Autonomy, ResearchLimits } from "../research/decide"; import { acquisitionTools, archiveReadTools } from "../research/tools"; import { countProposals, newResearchState, phaseOf, readResearchState, writeResearchState, type ResearchRecord, type ResearchState, } from "../research/state"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; import type { EditorChannel, TaskDeps, TaskResult } from "./types"; // The corpus reads a research run makes: enough to know what is already // held, never whole transcripts in bulk (that is the sweep's). export const RESEARCH_READ_TOOLS = [ "list_channels", "search_transcripts", "enumerate_matches", "get_video_metadata", "channel_coverage", "get_post", ] as const; // The local model's smaller set: its prompt is capped at 8k tokens, the tool // schemas included. const LOCAL_READ_TOOLS = ["list_channels", "search_transcripts", "get_video_metadata"] as const; export const RESEARCH_NOTES_CHARS = 4000; export type ResearchInput = { article: string; n: number; // Default: the iteration's question, scope and model. question?: string; channels?: string[]; from?: string; to?: string; model?: string; // The article's citation origin (evidence links into the corpus). origin: string; maxUsd: number; autonomy: Autonomy; limits: ResearchLimits; web?: boolean; webSearchMaxUses?: number; maxTurns?: number; }; function autonomyLine(a: Autonomy, l: ResearchLimits): string { const caps = `${l.maxItemsPerRun} item(s), ${l.maxGbPerRun} GB and ${l.maxTranscribeHours} h of transcription`; switch (a) { case "propose": return "This run PROPOSES: every acquisition you ask for waits for the operator's yes or no. Ask for everything the report needs, each once, with its reason and evidence."; case "limits": return ( `This run acts WITHIN LIMITS: an acquisition into an existing channel runs at once while the run stays under ${caps} and its size is known` + `${l.newChannelsNeedApproval ? "; a new channel waits for the operator" : ""}${l.postWalksNeedApproval ? "; a walk over an account's post history waits" : ""}` + "; a priority change waits; anything past a cap waits." ); case "auto": return `This run is AUTONOMOUS: acquisitions run at once, through the editor, while the run stays under ${caps}; past a cap, or of unknown size, they wait for the operator.`; } } function systemPrompt(o: { autonomy: Autonomy; limits: ResearchLimits; origin: string; maxUsd: number; local: boolean }): string { return [ UNATTENDED_RULE, "", "You RESEARCH a question for a report from an archive of transcripts and posts. You do not write the report: you find what the archive lacks for a complete answer and ask the editor to acquire it. A sweep reads the widened archive afterwards.", "", "1. Discover. Search the archive first (search_transcripts, enumerate_matches, list_channels, get_video_metadata): what does it already hold on the question, and from whom? editor_channels lists every channel the editor archives (some are on no public site). Then look outside: web_search / web_fetch for where the missing material is, and archive-search / archive-item for archive.org items (a show's archive, a deleted stream someone saved) — read an item's file list before you propose it.", "2. Propose. For each acquisition the report needs for complete context, call its tool once: the editor action's own arguments, a `reason` (what the report gains), `evidence` (the links that show it: search results, item pages, posts) and an `estimate` (items; gb from the item's file sizes; transcribeHours from its lengths). An honest estimate matters: one of unknown size waits for approval.", " - import-archive-org / import-video: media into an EXISTING channel (prefer a whole archive.org item over one-by-one platform fetches; name the files or a match when only some are needed).", " - create-channel: a new channel, only when no existing one fits. It is always created on NO site: never pass `sites` — the operator puts it on one.", " - fetch-posts / capture-posts / import-post: posts — a channel's new posts, one post by its URL, screenshots of archived ones. A full or older walk is a post walk.", " - transcribe-one, persist-videos, priority-bump: transcription and keeping media for what is already held.", "3. The standing rules (refused in every mode): never a Twitch VOD URL (expired VODs are gone — look for the stream on archive.org or elsewhere); an X channel never goes on a site; nothing bypasses the editor's queues. The editor paces every platform and holds one that is rate-limited: do not repeat an acquisition, and do not fetch anything yourself.", `4. ${autonomyLine(o.autonomy, o.limits)}`, "", `Links into the archive are on ${o.origin}. This run's budget is about $${o.maxUsd === Number.POSITIVE_INFINITY ? "0 (a local model)" : o.maxUsd.toFixed(2)}.`, o.local ? "Be brief: your context is small. One search at a time." : "", "When you are done, stop calling tools and answer in a few lines: what the archive already holds on the question, what you asked for and why, and what is still missing.", ] .filter((l) => l !== "") .join("\n"); } function channelsTool(list: () => Promise): AgentTool { return { name: "editor_channels", description: "Every channel the editor archives (slug, name, platform, what it holds) — the channels an import goes into. Some are on no public site.", inputSchema: { type: "object", properties: {}, additionalProperties: false }, run: async () => { const all = await list(); if (!all.length) return "The editor archives no channels."; return all .map((c) => `- ${c.slug}${c.name ? ` — ${c.name}` : ""}${[c.platform, c.kind].filter(Boolean).length ? ` (${[c.platform, c.kind].filter(Boolean).join(", ")})` : ""}${c.url ? ` ${c.url}` : ""}`) .join("\n"); }, }; } export async function research(input: ResearchInput, deps: TaskDeps): Promise { return runOnIteration({ article: input.article, n: input.n, deps, maxUsd: input.maxUsd, kinds: ["research"] }, (h) => researchBody(h, input)); } async function researchBody(h: TaskHandle, input: ResearchInput): Promise { const { deps, iteration } = h; const editor = deps.editor; if (!editor) throw new TaskInputError("a research run needs the editor (its archive.org reads and acquisitions are editor actions)"); const question = (input.question ?? iteration.question ?? "").trim(); if (!question) throw new TaskInputError("a research run needs its question"); const channels = input.channels ?? iteration.scope?.channels ?? []; const from = input.from ?? iteration.scope?.from; const to = input.to ?? iteration.scope?.to; const model = input.model ?? iteration.model; const local = providerOf(model) === "local"; const origin = input.origin.replace(/\/+$/, ""); // Resumed (the job ran before): its proposals stand, with their autonomy. const state: ResearchState = (await readResearchState(h.article, h.n, h.paths)) ?? newResearchState(input.autonomy, input.limits); const save = () => writeResearchState(h.article, h.n, state, h.paths); await save(); const record = (patch: Partial): ResearchRecord => ({ autonomy: state.autonomy, phase: "discover", ...((iteration as { research?: ResearchRecord }).research ?? {}), ...patch, }); await updateIteration(h.article, h.n, { research: record({ phase: "discover" }) }, h.paths); h.log(`${iterationLabel(h.n)} research on ${model} (${state.autonomy}), corpus ${deps.corpus.source}`); const readNames: readonly string[] = local ? LOCAL_READ_TOOLS : RESEARCH_READ_TOOLS; const corpusTools = deps.corpus.tools.filter((t) => readNames.includes(t.name)); const web = input.web === false ? [] : (deps.web ?? []); const tools: AgentTool[] = [ ...corpusTools, ...(deps.editorChannels ? [channelsTool(deps.editorChannels)] : []), ...archiveReadTools({ editor }), ...acquisitionTools({ editor, autonomy: state.autonomy, limits: state.limits, ledger: state, onChange: async () => { await save(); }, }), ...web, ]; const scope = [ channels.length ? `The archive's channels on it so far: ${channels.join(", ")}.` : "No channel is named yet: find who and where.", from || to ? `The question is dated${from ? ` from ${from}` : ""}${to ? ` to ${to}` : ""}.` : "", ] .filter(Boolean) .join(" "); const onEvent = (e: Parameters[0]["onEvent"]>>[0]) => { if (e.type === "turn") { h.progress({ metric: "turns", current: e.turn + 1, total: input.maxTurns ?? 60 }); h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); } else if (e.type === "wrap-up") h.log(`budget: 85% spent (~$${e.usd.toFixed(2)}) — wrapping up`); else if (e.type === "note") h.log(e.text); }; const run = await runAgent({ llm: deps.llm, model, system: systemPrompt({ autonomy: state.autonomy, limits: state.limits, origin, maxUsd: input.maxUsd, local }), user: `Research this for a report: ${question}\n\n${scope}`, tools, meter: h.meter, maxUsd: input.maxUsd, maxTurns: input.maxTurns ?? 60, ...(!local && input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 5 } } : {}), signal: deps.signal, onEvent, }); h.turns(run.transcript); if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" }; const c = countProposals(state); const phase = phaseOf(state); const notes = run.text.trim().slice(0, RESEARCH_NOTES_CHARS); const parts = [ c.enqueued && `${c.enqueued} enqueued`, c.done && `${c.done} done`, c.proposed && `${c.proposed} waiting for approval`, c.rejected && `${c.rejected} refused`, c.failed && `${c.failed} failed`, ].filter(Boolean); h.log(`agent ended: ${run.stopReason}; ${state.proposals.length} acquisition(s)${parts.length ? `: ${parts.join(", ")}` : ""}`); return { status: "done", summary: `${state.proposals.length} acquisition(s)${parts.length ? ` (${parts.join(", ")})` : ""} — ${phase === "ready" ? "nothing pending: ready to continue" : "waiting"}` + `${run.stopReason === "end_turn" ? "" : ` (the agent stopped: ${run.stopReason})`} — ~$${h.meter.usd.toFixed(2)}`, patch: { research: record({ phase, ...(notes ? { notes } : {}) }) }, }; }