// A research run's tools (release 27 S3b): the archive.org reads, and one // ACQUISITION tool per editor action a run may ask for. Every tool reaches // the editor through the injected `editor.run(action, args)` — the ops // actions, on the editor's own queues at each platform's pace — and nothing // else: no fetch, no yt-dlp, no gallery-dl here. // // An acquisition tool records a Proposal (its action, args, reason and // evidence) in the run's ledger, asks decideAcquisition, and then: // enqueue → editor.run; the proposal is `enqueued` with its job id (or // `failed`, with the editor's words); // approval → the proposal stays `proposed`, with why it waits; // refuse → the proposal is `rejected`, with the standing rule it broke. // The model is told which in one line. `runApprovedProposal` is what the // operator's yes runs (S11), through the same rules but past the autonomy. import type { AgentTool } from "../agentTool"; import { addSpent, decideAcquisition, NOTHING_SPENT, spendOf, standingRuleRefusal, type AcquisitionAction, type AcquisitionEstimate, type Autonomy, type Proposal, type ResearchLimits, type Spent, } from "./decide"; // The editor, as a research run sees it: one ops action, its JSON answer. // A refusal is thrown (the editor's sentence as the message). export type ResearchEditor = { run(action: string, args: Record): Promise>; }; export type ResearchLedger = { proposals: Proposal[]; spent: Spent; }; export type ResearchToolsContext = { editor: ResearchEditor; autonomy: Autonomy; limits: ResearchLimits; // The run's proposals and spend; the tools append and update in place. ledger: ResearchLedger; // Called after every change to the ledger (S11 writes proposals.json). onChange?: (ledger: ResearchLedger) => void | Promise; // Proposal ids (default p01, p02, … after the ledger's). nextId?: () => string; }; export function newLedger(): ResearchLedger { return { proposals: [], spent: { ...NOTHING_SPENT } }; } // ─── each action's editor call ─── type ActionSpec = { action: AcquisitionAction; // The ops action it runs. editorAction: string; description: string; // The action's own arguments (JSON schema properties) and which are needed. properties: Record; required: string[]; // The ops body from the tool's arguments. body(args: Record): Record; }; const str = { type: "string" }; const bool = { type: "boolean" }; const strList = { type: "array", items: { type: "string" } }; const pick = (args: Record, keys: readonly string[]) => Object.fromEntries(keys.filter((k) => args[k] !== undefined).map((k) => [k, args[k]])); export const ACTION_SPECS: Record = { "import-archive-org": { action: "import-archive-org", editorAction: "import-archive-org", description: "Import archive.org media into an existing channel, on archive.org's queue, paced: one item ({slug, item, files? | match?}) or several ({slug, items}). dryRun lists what it would get.", properties: { slug: str, item: str, items: { type: "array", items: {} }, files: strList, match: str, dryRun: bool, }, required: ["slug"], body: (a) => pick(a, ["slug", "item", "items", "files", "match", "dryRun"]), }, "import-video": { action: "import-video", editorAction: "import-video", description: "Import one video by its URL into an existing channel, on its platform's queue.", properties: { slug: str, url: str }, required: ["slug", "url"], body: (a) => pick(a, ["slug", "url"]), }, "create-channel": { action: "create-channel", editorAction: "create-channel", description: "Create a channel (on NO site — the operator adds it to one): fields {name, handling: youtube|transcribe, url, platform?, sourceKind?, postFetcher?, socialHandle?}. fetchPlaylist / fetchPostsNow start its first fetch.", properties: { slug: str, fields: { type: "object" }, fetchPlaylist: bool, fetchPostsNow: bool, }, required: ["fields"], body: (a) => pick(a, ["slug", "fields", "fetchPlaylist", "fetchPostsNow"]), }, "fetch-posts": { action: "fetch-posts", editorAction: "fetch-posts", description: "Fetch a social channel's posts on its platform's queue: new posts; full (re-walk the timeline) or older (walk back, to floor YYYY-MM-DD) are post walks.", properties: { slug: str, full: bool, older: bool, floor: str, from: str, limit: { type: "integer" } }, required: ["slug"], body: (a) => pick(a, ["slug", "full", "older", "floor", "from", "limit"]), }, "capture-posts": { action: "capture-posts", editorAction: "capture-posts", description: "Capture archived posts of a social channel: a screenshot and the attached media of each id; thread: an X reply also shot with the post it answers above it (shot-thread.png, the replied-to author blurred unless verified); X keeps each author's avatar (posts-media/_avatars/) and each post's context (the post it quotes, the post it answers) in its capture.json; avatarsOnly: only the avatars, one page per author; contextOnly: only the context, one page per post.", properties: { slug: str, ids: strList, shots: bool, media: bool, articles: bool, thread: bool, avatarsOnly: bool, contextOnly: bool }, required: ["slug", "ids"], body: (a) => pick(a, ["slug", "ids", "shots", "media", "articles", "thread", "avatarsOnly", "contextOnly"]), }, "import-post": { action: "import-post", editorAction: "import-post", description: "Import ONE post by its URL (an X status or a Bluesky post) into that platform's posts channel.", properties: { slug: str, url: str }, required: ["slug", "url"], body: (a) => pick(a, ["slug", "url"]), }, "transcribe-one": { action: "transcribe-one", editorAction: "transcribe-one", description: "Transcribe one held video of a channel on the transcription queue.", properties: { slug: str, id: str }, required: ["slug", "id"], body: (a) => pick(a, ["slug", "id"]), }, "priority-bump": { action: "priority-bump", editorAction: "channel-priority", description: "Raise a channel to the normal tier (optionally for one operation: sync, transcription, download, digest, backfill), so its queued work runs.", properties: { slug: str, operation: str }, required: ["slug"], body: (a) => ({ slugs: [a.slug], tier: "normal", ...(a.operation !== undefined ? { operation: a.operation } : {}) }), }, "persist-videos": { action: "persist-videos", editorAction: "persist-videos", description: "Save specific held videos' source media to the saved-video store: items [{slug, id}].", properties: { items: { type: "array", items: { type: "object" } }, format: str }, required: ["items"], body: (a) => pick(a, ["items", "format"]), }, }; const ESTIMATE_SCHEMA = { type: "object", description: "What it will cost, as far as you know: items, gb, transcribeHours.", properties: { items: { type: "number" }, gb: { type: "number" }, transcribeHours: { type: "number" } }, }; const jobIdOf = (answer: Record): string | undefined => { if (typeof answer.jobId === "string") return answer.jobId; const ids = answer.jobIds; return Array.isArray(ids) && typeof ids[0] === "string" ? (ids as string[]).join(",") : undefined; }; function nextIdFor(ledger: ResearchLedger): () => string { return () => { const n = ledger.proposals.reduce((m, p) => Math.max(m, Number(/^p(\d+)$/.exec(p.id)?.[1] ?? 0)), 0) + 1; return `p${String(n).padStart(2, "0")}`; }; } // Run a proposal's editor action and record the outcome on it. async function enqueue(ctx: Pick, p: Proposal): Promise { const spec = ACTION_SPECS[p.action]; try { const answer = await ctx.editor.run(spec.editorAction, spec.body(p.args)); const jobId = jobIdOf(answer); p.status = jobId ? "enqueued" : "done"; if (jobId) p.jobId = jobId; else p.doneAt = new Date().toISOString(); if (p.action === "create-channel" && typeof answer.slug === "string") p.channel = answer.slug; delete p.note; ctx.ledger.spent = addSpent(ctx.ledger.spent, spendOf(p)); } catch (e) { p.status = "failed"; p.note = `the editor refused: ${(e as Error).message}`; } } function describe(p: Proposal): string { switch (p.status) { case "enqueued": return `${p.id} ${p.action}: enqueued as job ${p.jobId} — it runs on the editor's queue; follow it, do not repeat it.`; case "done": return `${p.id} ${p.action}: done.`; case "proposed": return `${p.id} ${p.action}: proposed — waits for the operator's approval (${p.note}).`; case "rejected": return `${p.id} ${p.action}: refused — ${p.note}. Do not ask again.`; case "failed": return `${p.id} ${p.action}: failed — ${p.note}.`; default: return `${p.id} ${p.action}: ${p.status}.`; } } export function acquisitionTools(ctx: ResearchToolsContext): AgentTool[] { const nextId = ctx.nextId ?? nextIdFor(ctx.ledger); return Object.values(ACTION_SPECS).map((spec) => ({ name: spec.action, description: `${spec.description} Every acquisition is checked against the run's autonomy and limits first; give the reason and the evidence links.`, inputSchema: { type: "object", properties: { ...spec.properties, reason: { type: "string", description: "Why this acquisition is needed for the report." }, evidence: { type: "array", items: { type: "string" }, description: "Links that show why (search results, item pages, posts)." }, estimate: ESTIMATE_SCHEMA, }, required: [...spec.required, "reason"], additionalProperties: false, }, run: async (input: Record) => { const { reason, evidence, estimate, ...rest } = (input ?? {}) as Record; const missing = spec.required.filter((k) => rest[k] === undefined || rest[k] === ""); if (missing.length) throw new Error(`${spec.action} needs ${missing.join(", ")}`); const p: Proposal = { id: nextId(), action: spec.action, args: rest, reason: typeof reason === "string" ? reason.trim() : "", evidence: Array.isArray(evidence) ? evidence.filter((e): e is string => typeof e === "string") : [], ...(estimate && typeof estimate === "object" ? { estimate: estimate as AcquisitionEstimate } : {}), status: "proposed", }; if (!p.reason) throw new Error(`${spec.action} needs a reason`); const d = decideAcquisition(p, ctx.autonomy, ctx.limits, ctx.ledger.spent); ctx.ledger.proposals.push(p); if (d.decision === "refuse") { p.status = "rejected"; p.note = d.reason; } else if (d.decision === "approval") { p.note = d.reason; } else { await enqueue(ctx, p); } await ctx.onChange?.(ctx.ledger); if (p.status === "failed") throw new Error(describe(p)); return describe(p); }, })); } // What the operator's yes runs: the proposal's action through the editor, // past the run's autonomy and caps (the operator decided) — never past a // standing rule. export async function runApprovedProposal( ctx: Pick, id: string, ): Promise { const p = ctx.ledger.proposals.find((x) => x.id === id); if (!p) throw new Error(`no proposal ${id}`); if (p.status !== "proposed" && p.status !== "approved") throw new Error(`${id} is ${p.status}, not waiting for approval`); const broken = standingRuleRefusal(p); if (broken) { p.status = "rejected"; p.note = broken; } else { p.status = "approved"; await enqueue(ctx, p); } await ctx.onChange?.(ctx.ledger); return p; } export function rejectProposal(ledger: ResearchLedger, id: string, why = "the operator said no"): Proposal { const p = ledger.proposals.find((x) => x.id === id); if (!p) throw new Error(`no proposal ${id}`); if (p.status !== "proposed" && p.status !== "approved") throw new Error(`${id} is ${p.status}, not waiting for approval`); p.status = "rejected"; p.note = why; return p; } // ─── the archive.org reads ─── export function archiveReadTools(ctx: Pick): AgentTool[] { return [ { name: "archive-search", description: "Search archive.org (its advanced search syntax: words, title:(…), creator:(…), collection:…, date:[a TO b]); identifiers and titles. Read only, paced by the editor.", inputSchema: { type: "object", properties: { query: str, limit: { type: "integer", description: "How many items (default 50, at most 500)." } }, required: ["query"], additionalProperties: false, }, run: async (input: { query?: unknown; limit?: unknown }) => { const a = await ctx.editor.run("archive-search", { query: String(input?.query ?? ""), ...(typeof input?.limit === "number" ? { limit: input.limit } : {}), }); const items = (a.items as { identifier: string; title?: string }[] | undefined) ?? []; return ( `${a.found ?? items.length} item(s) found` + (items.length ? `:\n${items.map((i) => `- ${i.identifier}${i.title ? ` — ${i.title}` : ""} https://archive.org/details/${i.identifier}`).join("\n")}` : ".") ); }, }, { name: "archive-item", description: "One archive.org item's files: name, format, size, length, which are media, and whether archive.org restricts it. Read only, paced by the editor.", inputSchema: { type: "object", properties: { item: { type: "string", description: "The item's identifier." } }, required: ["item"], additionalProperties: false, }, run: async (input: { item?: unknown }) => { const a = await ctx.editor.run("archive-item", { item: String(input?.item ?? "") }); return JSON.stringify(a.item ?? a, null, 1); }, }, ]; }