Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit fce0eac75f112b7b2bc9e233be9d19302ef419a1
parent 50b349567c7c99ad8bbe38f9a9384bfb47a1b767
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 10:51:32 -0400

common, mcp, editor: release 27 S3 — the corpus tools in process, and a paced web search and page reader

- mcp/src/callTool.ts: createCorpusTools({source}) — the MCP's own read tools
  over the SDK's in-memory transport against createServer, in the agent loop's
  AgentTool shape. `source` forced (an argument naming another is overwritten,
  and no schema shows it); a read-only allowlist (listing, search, enumerate,
  get_* corpus reads, coverage, sources, sweep_plan, ask_plan, and notes for
  list and read only); fetch_clip, enqueue, get_job and open_link are not in
  it. Exported as `yt-dlp-transcript-mcp/callTool`; the editor depends on the
  package.
- common/lib/web: one in-process pacer (one request at a time, 3 s gaps, a
  back-off on 429/503 with Retry-After), webSearch over DuckDuckGo's HTML page
  (endpoint injectable), webFetch (http(s) only, no private or loopback host by
  name, address or resolution, every redirect hop checked, text pages only,
  length-capped), and the agent tools web_search / web_fetch.
- editor: ops actions web-search and web-fetch (synchronous, read only), their
  ACTIONS rows and help, COMMANDS.md regenerated.
- testing/web/fakeWeb.mjs: a DuckDuckGo-shaped fake and pages, on loopback.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 2++
Acommon/lib/report/draft/agentTool.ts | 13+++++++++++++
Acommon/lib/web/fetchPage.ts | 217+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/web/pacer.ts | 150+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/web/search.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/web/tools.ts | 71+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/web/web.test.ts | 164+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/web/fakeWeb.d.mts | 17+++++++++++++++++
Acommon/testing/web/fakeWeb.mjs | 93+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/_corpusTools.test.ts | 26++++++++++++++++++++++++++
Aeditor/app/api/ops/_web.test.ts | 46++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/api/ops/_web.ts | 11+++++++++++
Aeditor/app/api/ops/web-fetch/route.ts | 28++++++++++++++++++++++++++++
Aeditor/app/api/ops/web-search/route.ts | 25+++++++++++++++++++++++++
Meditor/package.json | 3++-
Mmcp/package.json | 4++++
Amcp/src/callTool.test.ts | 108+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Amcp/src/callTool.ts | 187+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mpnpm-lock.yaml | 3+++
Mscripts/archilyzer-ops.mjs | 20++++++++++++++++++++
20 files changed, 1267 insertions(+), 1 deletion(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -129,6 +129,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | | | `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | | | `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` | +| `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -&gt; {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` | +| `web-fetch` | web-fetch reads one web page as plain text: {"url", "maxChars"?: 12000 (at most 60000)} -&gt; {page: {url, finalUrl, status, contentType, title?, text, truncated}}. http and https only; a private or loopback host (by name, by address, or by what its name resolves to, every redirect checked) is refused before any request, and so is a page that is not text (a PDF, an image). Read only, on the same web queue as web-search. | `pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'` | ### Usage, flags and environment diff --git a/common/lib/report/draft/agentTool.ts b/common/lib/report/draft/agentTool.ts @@ -0,0 +1,13 @@ +// The tool shape the agent loop runs (common/lib/llm, release 27 lane A): +// a name, a description, a JSON schema for its input, and `run`, whose text +// goes back to the model. A thrown error is the tool's error result. +// +// Declared here (and in mcp/src/callTool.ts) until S5 imports lane A's one +// definition; the two must stay this exact shape. + +export type AgentTool = { + name: string; + description: string; + inputSchema: Record<string, unknown>; + run(input: any, ctx: { signal?: AbortSignal }): Promise<string>; // eslint-disable-line @typescript-eslint/no-explicit-any +}; diff --git a/common/lib/web/fetchPage.ts b/common/lib/web/fetchPage.ts @@ -0,0 +1,217 @@ +// WEB FETCH — one web page as readable text, through the pacer (release 27 +// D7). Read only, and fenced: +// - http and https only; +// - never a private, loopback, link-local or unspecified host — by name +// (`localhost`, `*.local`, `*.internal`) or by address, the name resolved +// first so a public name pointing inside is refused too; every redirect hop +// is checked the same way (at most WEB_FETCH_MAX_REDIRECTS). A test opens +// the fence with `allowPrivate`; +// - text only (HTML, plain text, JSON, XML); a PDF, an image or a video is +// refused, not downloaded; +// - the body read up to WEB_FETCH_MAX_BYTES, the text cut at `maxChars`. +// +// A page is context for a model, never evidence: nothing here cites it. + +import { lookup } from "node:dns/promises"; +import { isIP } from "node:net"; +import { decodeEntities } from "../../social/htmlReader"; +import { webPacer, WebRequestError, type WebPacer } from "./pacer"; + +export const WEB_FETCH_DEFAULT_CHARS = 12_000; +export const WEB_FETCH_MAX_CHARS = 60_000; +export const WEB_FETCH_MAX_BYTES = 2_000_000; +export const WEB_FETCH_MAX_REDIRECTS = 5; + +export type WebPage = { + url: string; + // Where the last redirect landed. + finalUrl: string; + status: number; + contentType: string; + title?: string; + text: string; + truncated: boolean; +}; + +export type WebFetchOptions = { + maxChars?: number; + pacer?: WebPacer; + signal?: AbortSignal; + // Tests only: let a loopback fake server through the fence. + allowPrivate?: boolean; + // Name → addresses (default: the system resolver). + resolve?: (host: string) => Promise<string[]>; +}; + +// ─── the fence ─── + +function ipv4Private(ip: string): boolean { + const p = ip.split(".").map(Number); + if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true; + const [a, b] = p as [number, number, number, number]; + return ( + a === 0 || + a === 10 || + a === 127 || + (a === 100 && b >= 64 && b <= 127) || + (a === 169 && b === 254) || + (a === 172 && b >= 16 && b <= 31) || + (a === 192 && b === 168) || + (a === 192 && b === 0 && p[2] === 0) || + (a === 198 && (b === 18 || b === 19)) || + a >= 224 + ); +} + +function ipv6Private(ip: string): boolean { + const s = ip.toLowerCase().replace(/^\[|\]$/g, ""); + if (s === "::" || s === "::1") return true; + const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(s); + if (mapped) return ipv4Private(mapped[1]!); + return /^(fc|fd|fe[89ab])/.test(s) || s.startsWith("ff"); +} + +// An address no web fetch may reach. +export function isPrivateAddress(ip: string): boolean { + const v = isIP(ip.replace(/^\[|\]$/g, "")); + if (v === 4) return ipv4Private(ip); + if (v === 6) return ipv6Private(ip); + return true; +} + +const PRIVATE_NAME = /(^|\.)(localhost|local|internal|lan|home|localdomain)$/i; + +const defaultResolve = async (host: string) => (await lookup(host, { all: true, verbatim: true })).map((a) => a.address); + +// The reason `url` may not be fetched, or null. +export async function fetchRefusal( + url: string, + opts: Pick<WebFetchOptions, "allowPrivate" | "resolve"> = {}, +): Promise<string | null> { + let u: URL; + try { + u = new URL(url); + } catch { + return `"${url}" is not a URL`; + } + if (u.protocol !== "http:" && u.protocol !== "https:") return `only http and https pages are read (not ${u.protocol})`; + if (u.username || u.password) return "a URL with credentials in it is not read"; + if (opts.allowPrivate) return null; + const host = u.hostname.replace(/^\[|\]$/g, ""); + if (PRIVATE_NAME.test(host)) return `${host} is a private host`; + if (isIP(host)) return isPrivateAddress(host) ? `${host} is a private address` : null; + let addrs: string[]; + try { + addrs = await (opts.resolve ?? defaultResolve)(host); + } catch (e) { + return `${host} does not resolve (${(e as Error).message})`; + } + if (addrs.length === 0) return `${host} does not resolve`; + const inside = addrs.find(isPrivateAddress); + return inside ? `${host} resolves to a private address (${inside})` : null; +} + +// ─── the page as text ─── + +const TEXT_TYPES = /^(text\/|application\/(json|xml|xhtml\+xml|rss\+xml|atom\+xml|ld\+json))/i; + +export function htmlToReadableText(html: string): { title?: string; text: string } { + const titleM = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html); + const title = titleM ? decodeEntities(titleM[1]!.replace(/<[^>]+>/g, "")).replace(/\s+/g, " ").trim() : undefined; + let body = html + .replace(/<!--[\s\S]*?-->/g, " ") + .replace(/<(script|style|noscript|svg|template|iframe|head|title)\b[^>]*>[\s\S]*?<\/\1>/gi, " ") + .replace(/<(nav|footer)\b[^>]*>[\s\S]*?<\/\1>/gi, " "); + body = body + .replace(/<br\s*\/?>/gi, "\n") + .replace(/<\/(p|div|li|h[1-6]|blockquote|tr|section|article|header|pre|table|ul|ol|dd|dt)>/gi, "\n") + .replace(/<li\b[^>]*>/gi, "- ") + .replace(/<[^>]+>/g, " "); + const text = decodeEntities(body) + .replace(/ /g, " ") + .split("\n") + .map((l) => l.replace(/[ \t\r\f\v]+/g, " ").trim()) + .join("\n") + .replace(/\n{3,}/g, "\n\n") + .trim(); + return { ...(title ? { title } : {}), text }; +} + +async function readCapped(res: Response, maxBytes: number): Promise<string> { + if (!res.body) return ""; + const reader = res.body.getReader(); + const chunks: Uint8Array[] = []; + let n = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(value); + n += value.byteLength; + if (n >= maxBytes) { + await reader.cancel().catch(() => {}); + break; + } + } + return new TextDecoder("utf-8", { fatal: false }).decode(Buffer.concat(chunks).subarray(0, maxBytes)); +} + +export async function webFetch(url: string, opts: WebFetchOptions = {}): Promise<WebPage> { + const maxChars = Math.min(WEB_FETCH_MAX_CHARS, Math.max(200, Math.floor(opts.maxChars ?? WEB_FETCH_DEFAULT_CHARS))); + const pacer = opts.pacer ?? webPacer; + let at = url.trim(); + for (let hop = 0; ; hop++) { + const refusal = await fetchRefusal(at, opts); + if (refusal) throw new WebRequestError(refusal, null); + const step = await pacer.request( + at, + { + method: "GET", + redirect: "manual", + headers: { accept: "text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5" }, + ...(opts.signal ? { signal: opts.signal } : {}), + }, + async (res): Promise<{ redirect: string } | { page: WebPage }> => { + if (res.status >= 300 && res.status < 400 && res.headers.get("location")) { + await res.body?.cancel().catch(() => {}); + return { redirect: new URL(res.headers.get("location")!, at).toString() }; + } + if (!res.ok) { + await res.body?.cancel().catch(() => {}); + throw new WebRequestError(`${new URL(at).host} answered HTTP ${res.status}`, res.status); + } + const contentType = (res.headers.get("content-type") ?? "").split(";")[0]!.trim().toLowerCase(); + if (contentType && !TEXT_TYPES.test(contentType)) { + await res.body?.cancel().catch(() => {}); + throw new WebRequestError(`not a text page (${contentType}) — only pages are read here`, res.status); + } + const raw = await readCapped(res, WEB_FETCH_MAX_BYTES); + const html = /html|xml/.test(contentType) || (!contentType && /^\s*</.test(raw)); + const read = html ? htmlToReadableText(raw) : { text: raw.replace(/\r\n/g, "\n").trim() }; + const truncated = read.text.length > maxChars; + return { + page: { + url, + finalUrl: at, + status: res.status, + contentType: contentType || (html ? "text/html" : "text/plain"), + ...(read.title ? { title: read.title } : {}), + text: truncated ? read.text.slice(0, maxChars) : read.text, + truncated, + }, + }; + }, + ); + if ("page" in step) return step.page; + if (hop + 1 > WEB_FETCH_MAX_REDIRECTS) { + throw new WebRequestError(`more than ${WEB_FETCH_MAX_REDIRECTS} redirects from ${url}`, null); + } + at = step.redirect; + } +} + +export function formatPage(p: WebPage): string { + return ( + `${p.title ? `# ${p.title}\n` : ""}${p.finalUrl}\n\n${p.text}` + + (p.truncated ? `\n\n(cut at ${p.text.length} characters)` : "") + ); +} diff --git a/common/lib/web/pacer.ts b/common/lib/web/pacer.ts @@ -0,0 +1,150 @@ +// THE WEB PACER — every web request a generation run makes (search and page +// reads, release 27 D7) goes through ONE in-process queue: one request at a +// time, at least WEB_MIN_GAP_MS between one request's end and the next's +// start, a plain user agent, and a back-off on 429 / 503 (Retry-After when +// the server gives one, else doubling from WEB_BACKOFF_BASE_MS) before the +// request is tried again, at most WEB_MAX_ATTEMPTS times. Polite scraping: +// one stream, real gaps, back off when told. +// +// The editor's `web-search` / `web-fetch` actions and a job's agent tools +// share the process's pacer (`webPacer`), so two callers in one editor never +// make two streams. + +export const WEB_MIN_GAP_MS = 3_000; +export const WEB_BACKOFF_BASE_MS = 10_000; +export const WEB_BACKOFF_MAX_MS = 120_000; +export const WEB_MAX_ATTEMPTS = 3; +export const WEB_TIMEOUT_MS = 30_000; +export const WEB_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:128.0) Gecko/20100101 Firefox/128.0"; + +const BACK_OFF = new Set([429, 503]); + +export type WebPacerDeps = { + fetch?: (url: string, init: RequestInit) => Promise<Response>; + now?: () => number; + sleep?: (ms: number, signal?: AbortSignal) => Promise<void>; +}; + +export type WebPacerOpts = { + minGapMs?: number; + backoffBaseMs?: number; + backoffMaxMs?: number; + maxAttempts?: number; + timeoutMs?: number; +}; + +export class WebRequestError extends Error { + constructor( + message: string, + readonly status: number | null, + ) { + super(message); + this.name = "WebRequestError"; + } +} + +function defaultSleep(ms: number, signal?: AbortSignal): Promise<void> { + return new Promise((resolve, reject) => { + if (signal?.aborted) return reject(signal.reason ?? new Error("aborted")); + const t = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(t); + reject(signal?.reason ?? new Error("aborted")); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +function retryAfterMs(value: string | null, nowMs: number): number | null { + if (!value) return null; + const v = value.trim(); + if (/^\d+$/.test(v)) return Number(v) * 1000; + const at = Date.parse(v); + return Number.isFinite(at) ? Math.max(0, at - nowMs) : null; +} + +export class WebPacer { + private readonly deps: Required<WebPacerDeps>; + private readonly opts: Required<WebPacerOpts>; + private chain: Promise<unknown> = Promise.resolve(); + private lastDoneAt = -Infinity; + // Every attempt sent, with when it started (tests and logs). + readonly sent: { url: string; at: number }[] = []; + + constructor(deps: WebPacerDeps = {}, opts: WebPacerOpts = {}) { + this.deps = { + fetch: deps.fetch ?? ((url, init) => fetch(url, init)), + now: deps.now ?? (() => Date.now()), + sleep: deps.sleep ?? defaultSleep, + }; + this.opts = { + minGapMs: opts.minGapMs ?? WEB_MIN_GAP_MS, + backoffBaseMs: opts.backoffBaseMs ?? WEB_BACKOFF_BASE_MS, + backoffMaxMs: opts.backoffMaxMs ?? WEB_BACKOFF_MAX_MS, + maxAttempts: opts.maxAttempts ?? WEB_MAX_ATTEMPTS, + timeoutMs: opts.timeoutMs ?? WEB_TIMEOUT_MS, + }; + } + + // Run `fn` after every earlier request (and its gap) has finished. + private serial<T>(fn: () => Promise<T>): Promise<T> { + const run = this.chain.then(fn, fn); + this.chain = run.catch(() => {}); + return run; + } + + // One request through the queue. `read` consumes the response inside the + // queue's turn (so a body is read before the next request starts). A 429 + // or 503 backs off and retries; any other answer is handed to `read`. + request<T>( + url: string, + init: Omit<RequestInit, "signal"> & { signal?: AbortSignal }, + read: (res: Response) => Promise<T>, + ): Promise<T> { + return this.serial(async () => { + for (let attempt = 1; ; attempt++) { + const wait = this.lastDoneAt + this.opts.minGapMs - this.deps.now(); + if (wait > 0) await this.deps.sleep(wait, init.signal); + this.sent.push({ url, at: this.deps.now() }); + let res: Response; + try { + const timeout = AbortSignal.timeout(this.opts.timeoutMs); + res = await this.deps.fetch(url, { + ...init, + signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout, + headers: { "user-agent": WEB_USER_AGENT, "accept-language": "en", ...(init.headers as Record<string, string>) }, + }); + } catch (e) { + this.lastDoneAt = this.deps.now(); + if (init.signal?.aborted) throw e; + throw new WebRequestError(`${new URL(url).host} did not answer: ${(e as Error).message}`, null); + } + if (BACK_OFF.has(res.status)) { + await res.body?.cancel().catch(() => {}); + this.lastDoneAt = this.deps.now(); + if (attempt >= this.opts.maxAttempts) { + throw new WebRequestError( + `${new URL(url).host} answered HTTP ${res.status} ${attempt} times — backing off; try later`, + res.status, + ); + } + const told = retryAfterMs(res.headers.get("retry-after"), this.deps.now()); + const backoff = Math.min(this.opts.backoffMaxMs, told ?? this.opts.backoffBaseMs * 2 ** (attempt - 1)); + await this.deps.sleep(backoff, init.signal); + continue; + } + try { + return await read(res); + } finally { + this.lastDoneAt = this.deps.now(); + } + } + }); + } +} + +// The process's pacer: the editor's actions and every job's tools share it. +export const webPacer = new WebPacer(); diff --git a/common/lib/web/search.ts b/common/lib/web/search.ts @@ -0,0 +1,80 @@ +// WEB SEARCH — DuckDuckGo's HTML endpoint, read once per query through the +// pacer (release 27 D7: no service to run). Read only: titles, URLs and +// snippets. The endpoint is injectable (`searchUrl`) for tests and for the +// settings' web provider (S6). + +import { decodeEntities } from "../../social/htmlReader"; +import { webPacer, WebRequestError, type WebPacer } from "./pacer"; + +export const DUCKDUCKGO_HTML_URL = "https://html.duckduckgo.com/html/"; +export const WEB_SEARCH_DEFAULT_RESULTS = 6; +export const WEB_SEARCH_MAX_RESULTS = 20; + +export type WebSearchResult = { title: string; url: string; snippet: string }; + +export type WebSearchOptions = { + // How many results (default 6, at most 20). + n?: number; + searchUrl?: string; + pacer?: WebPacer; + signal?: AbortSignal; +}; + +const strip = (html: string) => decodeEntities(html.replace(/<[^>]+>/g, "")).replace(/\s+/g, " ").trim(); + +// A result link: DuckDuckGo wraps it in a redirect (`/l/?uddg=<url>`). +function unwrap(href: string): string { + const h = decodeEntities(href); + const m = /[?&]uddg=([^&]+)/.exec(h); + const url = m ? decodeURIComponent(m[1]!) : h.startsWith("//") ? `https:${h}` : h; + return url; +} + +// The results of one DuckDuckGo HTML page. +export function parseDuckDuckGoHtml(html: string, n = WEB_SEARCH_DEFAULT_RESULTS): WebSearchResult[] { + const out: WebSearchResult[] = []; + const anchor = /<a\b[^>]*class="[^"]*\bresult__a\b[^"]*"[^>]*>/g; + const starts = [...html.matchAll(anchor)]; + for (let i = 0; i < starts.length && out.length < n; i++) { + const tag = starts[i]![0]; + const from = starts[i]!.index! + tag.length; + const to = i + 1 < starts.length ? starts[i + 1]!.index! : html.length; + const chunk = html.slice(from, to); + const href = /\bhref="([^"]*)"/.exec(tag)?.[1]; + if (!href) continue; + const url = unwrap(href); + if (!/^https?:\/\//i.test(url)) continue; + // Ads go through DuckDuckGo's own y.js; they are not results. + if (/duckduckgo\.com\/y\.js/.test(url)) continue; + const title = strip(chunk.slice(0, chunk.indexOf("</a>") >= 0 ? chunk.indexOf("</a>") : chunk.length)); + const sn = /class="[^"]*\bresult__snippet\b[^"]*"[^>]*>([\s\S]*?)<\/(?:a|div|td)>/.exec(chunk); + out.push({ title, url, snippet: sn ? strip(sn[1]!) : "" }); + } + return out; +} + +export async function webSearch(query: string, opts: WebSearchOptions = {}): Promise<WebSearchResult[]> { + const q = query.trim(); + if (!q) throw new WebRequestError("web search needs a query", null); + const n = Math.min(WEB_SEARCH_MAX_RESULTS, Math.max(1, Math.floor(opts.n ?? WEB_SEARCH_DEFAULT_RESULTS))); + const pacer = opts.pacer ?? webPacer; + const url = opts.searchUrl ?? DUCKDUCKGO_HTML_URL; + return pacer.request( + url, + { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded", accept: "text/html" }, + body: new URLSearchParams({ q }).toString(), + ...(opts.signal ? { signal: opts.signal } : {}), + }, + async (res) => { + if (!res.ok) throw new WebRequestError(`the search answered HTTP ${res.status}`, res.status); + return parseDuckDuckGoHtml(await res.text(), n); + }, + ); +} + +export function formatSearchResults(results: readonly WebSearchResult[]): string { + if (results.length === 0) return "(no results)"; + return results.map((r) => `- ${r.title}\n ${r.url}${r.snippet ? `\n ${r.snippet}` : ""}`).join("\n"); +} diff --git a/common/lib/web/tools.ts b/common/lib/web/tools.ts @@ -0,0 +1,71 @@ +// The web as agent tools (release 27 D7): `web_search` and `web_fetch`, read +// only, through the process's pacer. For the local model; a Claude run uses +// the API's own server-side search and may take `web_fetch` from here. + +import type { AgentTool } from "../report/draft/agentTool"; +import type { WebPacer } from "./pacer"; +import { formatPage, webFetch, WEB_FETCH_DEFAULT_CHARS, WEB_FETCH_MAX_CHARS } from "./fetchPage"; +import { formatSearchResults, webSearch, WEB_SEARCH_DEFAULT_RESULTS, WEB_SEARCH_MAX_RESULTS } from "./search"; + +export type WebToolsOptions = { + pacer?: WebPacer; + // The search endpoint (default DuckDuckGo's HTML page). + searchUrl?: string; + // Tests only: let a loopback fake server through web_fetch's fence. + allowPrivate?: boolean; + resolve?: (host: string) => Promise<string[]>; +}; + +export function webTools(opts: WebToolsOptions = {}): AgentTool[] { + return [ + { + name: "web_search", + description: + "Search the web (DuckDuckGo): titles, URLs and snippets. Read only, paced (one request at a time, a few " + + "seconds apart). For context — a web page is never cited as what someone said.", + inputSchema: { + type: "object", + properties: { + query: { type: "string", description: "What to search for." }, + n: { type: "integer", description: `How many results (default ${WEB_SEARCH_DEFAULT_RESULTS}, at most ${WEB_SEARCH_MAX_RESULTS}).` }, + }, + required: ["query"], + additionalProperties: false, + }, + run: async (input: { query?: unknown; n?: unknown }, ctx) => + formatSearchResults( + await webSearch(String(input?.query ?? ""), { + ...(typeof input?.n === "number" ? { n: input.n } : {}), + ...(opts.searchUrl ? { searchUrl: opts.searchUrl } : {}), + ...(opts.pacer ? { pacer: opts.pacer } : {}), + ...(ctx?.signal ? { signal: ctx.signal } : {}), + }), + ), + }, + { + name: "web_fetch", + description: + "Read one web page (http or https, public hosts only) as plain text, cut to max_chars. Read only, paced. " + + "For context — a web page is never cited as what someone said.", + inputSchema: { + type: "object", + properties: { + url: { type: "string", description: "The page's URL." }, + max_chars: { type: "integer", description: `Characters of text (default ${WEB_FETCH_DEFAULT_CHARS}, at most ${WEB_FETCH_MAX_CHARS}).` }, + }, + required: ["url"], + additionalProperties: false, + }, + run: async (input: { url?: unknown; max_chars?: unknown }, ctx) => + formatPage( + await webFetch(String(input?.url ?? ""), { + ...(typeof input?.max_chars === "number" ? { maxChars: input.max_chars } : {}), + ...(opts.pacer ? { pacer: opts.pacer } : {}), + ...(opts.allowPrivate ? { allowPrivate: true } : {}), + ...(opts.resolve ? { resolve: opts.resolve } : {}), + ...(ctx?.signal ? { signal: ctx.signal } : {}), + }), + ), + }, + ]; +} diff --git a/common/lib/web/web.test.ts b/common/lib/web/web.test.ts @@ -0,0 +1,164 @@ +// The web module against a fake web on loopback: the pacer (one at a time, +// 3 s gaps, back-off), DuckDuckGo's HTML read, the page reader and its fence. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { startFakeWeb, type FakeWeb } from "../../testing/web/fakeWeb.mjs"; +import { WebPacer, WebRequestError, WEB_MIN_GAP_MS } from "./pacer"; +import { parseDuckDuckGoHtml, webSearch } from "./search"; +import { fetchRefusal, htmlToReadableText, isPrivateAddress, webFetch } from "./fetchPage"; +import { webTools } from "./tools"; + +let web: FakeWeb; +before(async () => { + web = await startFakeWeb({ + results: { + "second shop": [ + { title: "The second shop opens", url: "https://news.example/shop?id=1&x=2", snippet: "It opened in the <b>spring</b>." }, + { title: "Bakery & co", url: "https://bakery.example/", snippet: "" }, + { title: "Third", url: "https://third.example/", snippet: "three" }, + ], + }, + }); +}); +after(() => web.close()); + +// A pacer on a fake clock: sleeping advances it, and every sleep is recorded. +function clockPacer(opts: ConstructorParameters<typeof WebPacer>[1] = {}) { + let now = 1_000_000; + const sleeps: number[] = []; + const pacer = new WebPacer( + { + now: () => now, + sleep: async (ms) => { + sleeps.push(ms); + now += ms; + }, + }, + opts, + ); + return { pacer, sleeps, advance: (ms: number) => (now += ms) }; +} + +const page = (p: string, pacer: WebPacer) => webFetch(web.url(p), { pacer, allowPrivate: true }); + +test("pacer: one request at a time, at least 3 s between them", async () => { + const { pacer, sleeps } = clockPacer(); + assert.equal(WEB_MIN_GAP_MS, 3000); + let inFlight = 0; + let most = 0; + const pacerFetch = new WebPacer( + { + now: () => 0, + sleep: async () => {}, + fetch: async (url, init) => { + inFlight++; + most = Math.max(most, inFlight); + await new Promise((r) => setTimeout(r, 15)); + inFlight--; + return fetch(url, init); + }, + }, + {}, + ); + await Promise.all([page("/page/a", pacerFetch), page("/page/b", pacerFetch), page("/text", pacerFetch)]); + assert.equal(most, 1, "never two at once"); + // On the fake clock: the second and third each waited the full gap. + await Promise.all([page("/page/a", pacer), page("/page/b", pacer), page("/text", pacer)]); + assert.deepEqual(sleeps, [3000, 3000]); + assert.equal(pacer.sent.length, 3); + assert.ok(pacer.sent[1]!.at - pacer.sent[0]!.at >= 3000); + assert.ok(web.requests.every((r) => /Firefox/.test(r.ua ?? "")), "a plain user agent"); +}); + +test("pacer: a 429 backs off (Retry-After) and retries; a 503 that persists fails after three tries, backing off each time", async () => { + const { pacer, sleeps } = clockPacer(); + const p = await page("/busy", pacer); + assert.match(p.text, /second shop opened/); + assert.deepEqual(sleeps, [1000, 2000], "Retry-After: 1, then the rest of the 3 s gap"); + const down = clockPacer(); + await assert.rejects(page("/down", down.pacer), (e: Error) => e instanceof WebRequestError && /HTTP 503 3 times — backing off/.test(e.message)); + assert.deepEqual(down.sleeps, [10000, 20000]); +}); + +test("search: DuckDuckGo's HTML read — links unwrapped, ads skipped, snippets as text, n results", async () => { + const { pacer } = clockPacer(); + const r = await webSearch("second shop", { searchUrl: web.searchUrl, pacer, n: 2 }); + assert.deepEqual(r, [ + { title: "The second shop opens", url: "https://news.example/shop?id=1&x=2", snippet: "It opened in the spring." }, + { title: "Bakery & co", url: "https://bakery.example/", snippet: "" }, + ]); + assert.deepEqual(await webSearch("nothing here", { searchUrl: web.searchUrl, pacer }), []); + await assert.rejects(webSearch(" ", { searchUrl: web.searchUrl, pacer }), /needs a query/); + const posted = web.requests.filter((x) => x.path === "/html/"); + assert.equal(posted[0]!.method, "POST"); + assert.equal(new URLSearchParams(posted[0]!.body).get("q"), "second shop"); + assert.deepEqual(parseDuckDuckGoHtml("<html>no results</html>"), []); +}); + +test("fetch: a page as readable text — title, no script, style, nav or footer, entities decoded", async () => { + const { pacer } = clockPacer(); + const p = await page("/page/a", pacer); + assert.equal(p.title, "The bakery & the oven"); + assert.equal(p.contentType, "text/html"); + assert.match(p.text, /^The bakery\nThe second shop opened in the spring\.\n+It is a small place with a big oven\.\n- bread\n- pies/); + assert.doesNotMatch(p.text, /tracking|color:red|Home \| About|footer text/); + assert.equal(p.truncated, false); + const t = await page("/text", pacer); + assert.equal(t.text, "plain words\nsecond line"); + const long = await webFetch(web.url("/long"), { pacer, allowPrivate: true, maxChars: 500 }); + assert.equal(long.truncated, true); + assert.equal(long.text.length, 500); +}); + +test("fetch: redirects followed (each hop fenced), at most five; a PDF is refused, not read", async () => { + const { pacer } = clockPacer(); + const p = await page(`/redirect?to=${encodeURIComponent("/page/x")}`, pacer); + assert.equal(p.finalUrl, web.url("/page/x")); + assert.match(p.text, /The bakery/); + await assert.rejects(page("/loop", pacer), /more than 5 redirects/); + await assert.rejects(page("/pdf", pacer), /not a text page \(application\/pdf\)/); + await assert.rejects(page("/missing", pacer), /answered HTTP 404/); +}); + +test("the fence: http(s) only, no private or loopback host by name, address or resolution", async () => { + const pub = async () => ["93.184.216.34"]; + const inside = async () => ["10.1.2.3"]; + assert.match((await fetchRefusal("file:///etc/passwd"))!, /only http and https/); + assert.match((await fetchRefusal("ftp://example.com/x"))!, /only http and https/); + assert.match((await fetchRefusal("not a url"))!, /is not a URL/); + assert.match((await fetchRefusal("http://user:pw@example.com/"))!, /credentials/); + assert.match((await fetchRefusal("http://localhost:3001/api/ops/settings"))!, /private host/); + assert.match((await fetchRefusal("http://printer.local/"))!, /private host/); + assert.match((await fetchRefusal("http://127.0.0.1:3001/"))!, /private address/); + assert.match((await fetchRefusal("http://[::1]/"))!, /private address/); + assert.match((await fetchRefusal("http://169.254.169.254/latest/meta-data"))!, /private address/); + assert.match((await fetchRefusal("https://sneaky.example/", { resolve: inside }))!, /resolves to a private address \(10\.1\.2\.3\)/); + assert.equal(await fetchRefusal("https://example.com/", { resolve: pub }), null); + assert.equal(await fetchRefusal("http://127.0.0.1:9/", { allowPrivate: true }), null); + // The fake web is on loopback: without the test option, refused before any request. + const { pacer } = clockPacer(); + const before = web.requests.length; + await assert.rejects(webFetch(web.url("/page/a"), { pacer }), /private address/); + assert.equal(web.requests.length, before); + for (const ip of ["10.0.0.1", "172.16.0.1", "172.31.255.255", "192.168.1.1", "127.0.0.1", "0.0.0.0", "100.64.0.1", "fd00::1", "fe80::1", "::ffff:192.168.0.1"]) { + assert.equal(isPrivateAddress(ip), true, ip); + } + for (const ip of ["93.184.216.34", "8.8.8.8", "172.32.0.1", "2606:4700::1111"]) assert.equal(isPrivateAddress(ip), false, ip); +}); + +test("htmlToReadableText keeps paragraphs apart", () => { + assert.deepEqual(htmlToReadableText("<title>T</title><p>a</p><p>b&amp;c</p>"), { title: "T", text: "a\nb&c" }); +}); + +test("the agent tools: web_search and web_fetch, in the AgentTool shape", async () => { + const { pacer } = clockPacer(); + const tools = webTools({ pacer, searchUrl: web.searchUrl, allowPrivate: true }); + assert.deepEqual(tools.map((t) => t.name), ["web_search", "web_fetch"]); + const s = await tools[0]!.run({ query: "second shop", n: 1 }, {}); + assert.equal(s, "- The second shop opens\n https://news.example/shop?id=1&x=2\n It opened in the spring."); + const f = await tools[1]!.run({ url: web.url("/page/a"), max_chars: 300 }, {}); + assert.match(f, /^# The bakery & the oven\nhttp:\/\/127\.0\.0\.1:\d+\/page\/a\n\nThe bakery\n/); + // Without the test option the tool keeps the fence. + await assert.rejects(webTools({ pacer })[1]!.run({ url: web.url("/page/a") }, {}), /private address/); +}); diff --git a/common/testing/web/fakeWeb.d.mts b/common/testing/web/fakeWeb.d.mts @@ -0,0 +1,17 @@ +export type FakeSearchResult = { title: string; url: string; snippet?: string }; + +export function duckDuckGoHtml(results: FakeSearchResult[]): string; + +export type FakeWeb = { + base: string; + searchUrl: string; + url(path: string): string; + requests: { method: string; path: string; body: string; at: number; ua?: string }[]; + close(): Promise<void>; +}; + +export function startFakeWeb(opts?: { + results?: Record<string, FakeSearchResult[]>; + pages?: Record<string, string>; + busyTimes?: number; +}): Promise<FakeWeb>; diff --git a/common/testing/web/fakeWeb.mjs b/common/testing/web/fakeWeb.mjs @@ -0,0 +1,93 @@ +// A fake web for the generation tests (release 27 D7): a DuckDuckGo-shaped +// HTML search page and a few pages, on loopback. No test reaches the real web. +// +// const web = await startFakeWeb({ results: { oven: [{ title, url, snippet }] } }); +// web.searchUrl POST q=… here (the endpoint webSearch takes) +// web.url("/page/a") a page on the fake +// web.requests every request: { method, path, body, at } +// await web.close() +// +// Routes: +// POST /html/ results for the form's `q` (opts.results[q], else +// the `*` entry, else none), each link wrapped in +// DuckDuckGo's /l/?uddg= redirect, plus one ad +// GET /page/<name> opts.pages[name] as text/html (a default page) +// GET /text a plain-text page +// GET /long a page longer than any default cut +// GET /redirect?to=<u> 302 to <u> +// GET /loop 302 to itself +// GET /pdf application/pdf +// GET /busy 429 (Retry-After: 1) for the first opts.busyTimes +// requests (default 1), then a page +// GET /down 503 always + +import http from "node:http"; + +const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"); + +export function duckDuckGoHtml(results) { + const items = results + .map( + (r) => `<div class="result results_links web-result"><div class="links_main result__body"> +<h2 class="result__title"><a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=${encodeURIComponent(r.url)}&amp;rut=abc">${esc(r.title)}</a></h2> +<a class="result__snippet" href="//duckduckgo.com/l/?uddg=${encodeURIComponent(r.url)}">${r.snippet ?? ""}</a> +</div></div>`, + ) + .join("\n"); + const ad = `<div class="result result--ad"><a class="result__a" href="https://duckduckgo.com/y.js?ad_provider=x&amp;u3=1">An ad</a></div>`; + return `<!doctype html><html><head><title>results</title></head><body>${ad}\n${items}</body></html>`; +} + +const DEFAULT_PAGE = `<!doctype html><html><head><title>The bakery &amp; the oven</title> +<style>body{color:red}</style><script>var tracking = "do not read me";</script></head> +<body><nav>Home | About</nav><h1>The bakery</h1><p>The second shop opened in the spring.</p> +<p>It is a small place&nbsp;with a big oven.</p><ul><li>bread</li><li>pies</li></ul><footer>footer text</footer></body></html>`; + +export async function startFakeWeb(opts = {}) { + const requests = []; + let busy = opts.busyTimes ?? 1; + const server = http.createServer(async (req, res) => { + const chunks = []; + for await (const c of req) chunks.push(c); + const body = Buffer.concat(chunks).toString("utf8"); + const u = new URL(req.url ?? "/", "http://fake"); + requests.push({ method: req.method, path: u.pathname + u.search, body, at: Date.now(), ua: req.headers["user-agent"] }); + const send = (status, type, text, headers = {}) => { + res.writeHead(status, { "content-type": type, ...headers }); + res.end(text); + }; + if (u.pathname === "/html/" && req.method === "POST") { + const q = new URLSearchParams(body).get("q") ?? ""; + const results = (opts.results ?? {})[q] ?? (opts.results ?? {})["*"] ?? []; + return send(200, "text/html; charset=utf-8", duckDuckGoHtml(results)); + } + if (u.pathname.startsWith("/page/")) { + const name = decodeURIComponent(u.pathname.slice(6)); + return send(200, "text/html; charset=utf-8", (opts.pages ?? {})[name] ?? DEFAULT_PAGE); + } + if (u.pathname === "/text") return send(200, "text/plain", "plain words\r\nsecond line\n"); + if (u.pathname === "/long") return send(200, "text/html", `<p>${"word ".repeat(30000)}</p>`); + if (u.pathname === "/redirect") return send(302, "text/plain", "", { location: u.searchParams.get("to") ?? "/page/a" }); + if (u.pathname === "/loop") return send(302, "text/plain", "", { location: "/loop" }); + if (u.pathname === "/pdf") return send(200, "application/pdf", "%PDF-1.4"); + if (u.pathname === "/busy") { + if (busy > 0) { + busy--; + return send(429, "text/plain", "slow down", { "retry-after": "1" }); + } + return send(200, "text/html", DEFAULT_PAGE); + } + if (u.pathname === "/down") return send(503, "text/plain", "down"); + return send(404, "text/plain", "not found"); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const port = server.address().port; + const base = `http://127.0.0.1:${port}`; + return { + base, + searchUrl: `${base}/html/`, + url: (p) => `${base}${p}`, + requests, + close: () => new Promise((r) => server.close(() => r())), + }; +} diff --git a/editor/app/api/ops/_corpusTools.test.ts b/editor/app/api/ops/_corpusTools.test.ts @@ -0,0 +1,26 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool"; +import { writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/_corpusTools.test.ts" +// +// The MCP's corpus tools are importable from the editor (release 27 S3, D2): +// the package export resolves and the tools answer over a synthetic corpus. +// The generation jobs (S6) run them in this process. + +test("the editor imports the MCP's in-process corpus tools", async () => { + const dir = await writeDraftCorpus(await mkdtemp(path.join(os.tmpdir(), "editor-corpus-tools-"))); + const corpus = await createCorpusTools({ source: `local:${dir}` }); + try { + assert.ok(corpus.tools.some((t) => t.name === "search_transcripts")); + assert.match(await corpus.call("list_channels"), /synth-kitchen/); + } finally { + await corpus.close(); + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/editor/app/api/ops/_web.test.ts b/editor/app/api/ops/_web.test.ts @@ -0,0 +1,46 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { callPost, setupOpsCorpus } from "./_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/_web.test.ts" +// +// web-search and web-fetch (release 27 S3): the refusals answered before any +// request leaves the machine. The reads themselves are tested against a fake +// web in common/lib/web/web.test.ts. + +const corpus = await setupOpsCorpus(null); +type Post = Parameters<typeof callPost>[0]; +const route = async (name: string) => (await import(`./${name}/route`)).POST as Post; +test.after(() => corpus.cleanup()); + +test("web-search: the query is required, n a whole number, unknown keys refused", async () => { + const search = await route("web-search"); + const none = await callPost(search, {}); + assert.equal(none.status, 400); + assert.match(String(none.body.error), /"query" is required/); + const badN = await callPost(search, { query: "x", n: 0 }); + assert.equal(badN.status, 400); + assert.match(String(badN.body.error), /"n" must be a whole number above zero/); + const extra = await callPost(search, { query: "x", searchUrl: "http://127.0.0.1/" }); + assert.equal(extra.status, 400); + assert.match(String(extra.body.error), /unknown key\(s\): searchUrl/); +}); + +test("web-fetch: http(s) only, and never a private or loopback host — refused before any request", async () => { + const fetchRoute = await route("web-fetch"); + for (const [url, why] of [ + ["file:///etc/passwd", /only http and https/], + ["http://localhost:3001/api/ops/settings", /localhost is a private host/], + ["http://127.0.0.1:3001/", /127\.0\.0\.1 is a private address/], + ["http://169.254.169.254/latest/meta-data", /private address/], + ["http://[::1]:3001/", /private address/], + ] as const) { + const r = await callPost(fetchRoute, { url }); + assert.equal(r.status, 400, url); + assert.match(String(r.body.error), why, url); + } + const noUrl = await callPost(fetchRoute, {}); + assert.equal(noUrl.status, 400); + assert.match(String(noUrl.body.error), /"url" is required/); +}); diff --git a/editor/app/api/ops/_web.ts b/editor/app/api/ops/_web.ts @@ -0,0 +1,11 @@ +import { NextResponse } from "next/server"; +import { WebRequestError } from "yt-dlp-transcript-common/lib/web/pacer"; +import { opsFail } from "./_lib"; + +// A web read's failure as an ops answer: a request the fence or the input +// refuses before anything is sent is a 400; an answer from the far side (an +// HTTP error, a back-off that ran out, a page that is not text) is a 502. +export function webFailure(e: unknown): NextResponse { + if (e instanceof WebRequestError) return opsFail(e.message, e.status === null ? 400 : 502); + throw e; +} diff --git a/editor/app/api/ops/web-fetch/route.ts b/editor/app/api/ops/web-fetch/route.ts @@ -0,0 +1,28 @@ +import { NextResponse } from "next/server"; +import { webFetch } from "yt-dlp-transcript-common/lib/web/fetchPage"; +import { ops, optPositiveInt, reqString } from "../_lib"; +import { webFailure } from "../_web"; + +export const dynamic = "force-dynamic"; + +// POST { url, maxChars? } -> { ok: true, page: { url, finalUrl, status, +// contentType, title?, text, truncated } } +// +// One web page as readable text (release 27 D7), read only, through the +// process's web pacer (common/lib/web): http(s) only, never a private or +// loopback host (by name, address or what the name resolves to, every +// redirect hop checked), text pages only, the text cut at `maxChars` +// (default 12,000, at most 60,000). Nothing is written. A generation run's +// agent tool `web_fetch` is the same read. +export async function POST(request: Request) { + return ops(request, ["url", "maxChars"], async (body) => { + const url = reqString(body, "url"); + const maxChars = optPositiveInt(body, "maxChars"); + try { + const page = await webFetch(url, maxChars !== undefined ? { maxChars } : {}); + return NextResponse.json({ ok: true, page }); + } catch (e) { + return webFailure(e); + } + }); +} diff --git a/editor/app/api/ops/web-search/route.ts b/editor/app/api/ops/web-search/route.ts @@ -0,0 +1,25 @@ +import { NextResponse } from "next/server"; +import { webSearch } from "yt-dlp-transcript-common/lib/web/search"; +import { ops, optPositiveInt, reqString } from "../_lib"; +import { webFailure } from "../_web"; + +export const dynamic = "force-dynamic"; + +// POST { query, n? } -> { ok: true, query, results: [{ title, url, snippet }] } +// +// A web search (DuckDuckGo's HTML page, release 27 D7), read only, through +// the process's web pacer (common/lib/web): one request at a time, 3 s apart, +// backing off on a 429 or 503. `n` results (default 6, at most 20). Nothing +// is written. A generation run's agent tool `web_search` is the same read. +export async function POST(request: Request) { + return ops(request, ["query", "n"], async (body) => { + const query = reqString(body, "query"); + const n = optPositiveInt(body, "n"); + try { + const results = await webSearch(query, n !== undefined ? { n } : {}); + return NextResponse.json({ ok: true, query, results }); + } catch (e) { + return webFailure(e); + } + }); +} diff --git a/editor/package.json b/editor/package.json @@ -20,7 +20,8 @@ "next": "16.2.3", "react": "19.2.4", "react-dom": "19.2.4", - "yt-dlp-transcript-common": "workspace:*" + "yt-dlp-transcript-common": "workspace:*", + "yt-dlp-transcript-mcp": "workspace:*" }, "devDependencies": { "@playwright/test": "^1.59.1", diff --git a/mcp/package.json b/mcp/package.json @@ -3,6 +3,10 @@ "version": "0.1.0", "private": true, "type": "module", + "exports": { + "./package.json": "./package.json", + "./callTool": "./src/callTool.ts" + }, "description": "MCP server exposing a yt-dlp transcript archive (or a federated hub) to Claude Code and other MCP clients \u2014 reads the site's static JSON shards.", "bin": { "yt-dlp-transcript-mcp": "src/index.ts" diff --git a/mcp/src/callTool.test.ts b/mcp/src/callTool.test.ts @@ -0,0 +1,108 @@ +// The corpus tools in process, over the synthetic draft corpus read the way +// the MCP's --local reads a composed public dir. + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs"; +import { CORPUS_TOOL_NAMES, CorpusToolError, createCorpusTools, type CorpusTools } from "./callTool"; +import { fakeEditor } from "./editorOps.testkit"; + +let dir: string; +let corpus: CorpusTools; + +before(async () => { + dir = await writeDraftCorpus(await mkdtemp(path.join(os.tmpdir(), "mcp-calltool-"))); + corpus = await createCorpusTools({ source: `local:${dir}` }); +}); + +after(async () => { + await corpus.close(); + await rm(dir, { recursive: true, force: true }); +}); + +test("the allowlist: read-only corpus tools only — no fetch_clip, enqueue, get_job or open_link", () => { + const names = corpus.tools.map((t) => t.name); + assert.deepEqual([...names].sort(), [...CORPUS_TOOL_NAMES].sort()); + for (const n of ["fetch_clip", "enqueue", "get_job", "open_link"]) assert.ok(!names.includes(n), n); + for (const t of corpus.tools) { + assert.equal(typeof t.run, "function"); + assert.equal(typeof t.description, "string"); + const props = (t.inputSchema as { properties?: Record<string, unknown> }).properties ?? {}; + assert.ok(!("source" in props), `${t.name} shows no source`); + assert.ok(!((t.inputSchema as { required?: string[] }).required ?? []).includes("source")); + } +}); + +test("a call outside the allowlist is refused before the server sees it", async () => { + for (const n of ["fetch_clip", "enqueue", "get_job", "open_link", "nope"]) { + await assert.rejects(corpus.call(n, {}), (e: Error) => e instanceof CorpusToolError && /not one of this run's read-only corpus tools/.test(e.message)); + } +}); + +test("search and transcript reads over the draft corpus, through the same dispatch Claude Code uses", async () => { + const channels = await corpus.call("list_channels"); + assert.match(channels, /synth-kitchen/); + assert.match(channels, /synth-other/); + const hits = await corpus.call("search_transcripts", { query: "second shop" }); + assert.match(hits, /qa-long-03/); + const t = await corpus.tools.find((x) => x.name === "get_transcript")!.run({ video_id: "bread-day-01", channel: "synth-kitchen" }, {}); + assert.match(t, /I would never sell the bakery to a chain/); + // Every result names its corpus — the forced one. + assert.match(t, new RegExp(`\\(corpus: local:${dir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`)); +}); + +test("source is FORCED: an argument naming another corpus is overwritten", async () => { + const out = await corpus.call("list_channels", { source: "remote:https://elsewhere.example" }); + assert.match(out, /synth-kitchen/); + assert.match(out, /\(corpus: local:/); + assert.doesNotMatch(out, /elsewhere/); +}); + +test("a tool's own error comes back as a CorpusToolError with its words", async () => { + await assert.rejects( + corpus.call("get_transcript", { video_id: "no-such-video" }), + (e: Error) => e instanceof CorpusToolError && /no-such-video/.test(e.message), + ); +}); + +test("notes: list and read only; a reply is refused, and the schema offers neither reply nor its fields", async () => { + const notes = corpus.tools.find((t) => t.name === "notes")!; + const props = (notes.inputSchema as { properties: Record<string, { enum?: string[] }> }).properties; + assert.deepEqual(props.action!.enum, ["list", "read"]); + for (const k of ["note_id", "text", "resolve"]) assert.ok(!(k in props), k); + await assert.rejects(corpus.call("notes", { action: "reply", note_id: "n_1", text: "x" }), /list and read only/); + + // list goes through to umtool, as the MCP's notes does. + const editor = fakeEditor(() => ({ status: 200, body: { notes: [] } }), { UMTOOL_URL: "http://umtool.test" }); + const withNotes = await createCorpusTools({ source: `local:${dir}`, only: ["notes"], editorDeps: editor.deps }); + try { + await withNotes.call("notes", { action: "list" }).catch(() => ""); + assert.ok(editor.sent.length >= 1); + assert.ok(editor.sent.every((s) => s.method === "GET"), JSON.stringify(editor.sent)); + } finally { + await withNotes.close(); + } +}); + +test("only: a narrower set; a name outside the allowlist cannot be asked for", async () => { + const two = await createCorpusTools({ source: `local:${dir}`, only: ["search_transcripts", "get_transcript"] }); + try { + assert.deepEqual(two.tools.map((t) => t.name), ["search_transcripts", "get_transcript"]); + await assert.rejects(two.call("list_channels"), CorpusToolError); + } finally { + await two.close(); + } + await assert.rejects( + createCorpusTools({ source: `local:${dir}`, only: ["fetch_clip" as never] }), + /not a read-only corpus tool/, + ); +}); + +test("an aborted signal stops a call", async () => { + const ac = new AbortController(); + ac.abort(); + await assert.rejects(corpus.tools[0]!.run({}, { signal: ac.signal })); +}); diff --git a/mcp/src/callTool.ts b/mcp/src/callTool.ts @@ -0,0 +1,187 @@ +// THE CORPUS TOOLS IN PROCESS (release 27 S3, D2) — the MCP's own read tools +// for an agent a generation job runs, so it sees exactly what Claude Code +// sees, with no MCP process and no stdio. +// +// A Client and the server (createServer) linked over the SDK's in-memory +// transport: the tool handlers are module-private, and going through +// `tools/call` keeps the dispatch wrapper (the corpus note on every result, +// the error shapes) in the path. +// +// The rules, in code: +// - `source` is FORCED: every call reads the run's corpus. An argument naming +// another source is overwritten, and `source` is not in the schemas the +// agent sees. +// - A READ-ONLY allowlist (CORPUS_TOOL_NAMES): the listing, search, +// enumerate, get_* corpus reads, channel coverage, the sources, and the +// sweep and ask plans. `notes` is in it for `list` and `read` only (a +// reply writes in umtool). `fetch_clip` and `enqueue` cause work in the +// editor, `get_job` reads the editor's jobs and `open_link` reads OTHER +// corpora by URL: none of them is in it. +// +// The tools come in the agent loop's AgentTool shape (common/lib/llm, lane A +// of release 27); the type is declared here until S5 unifies the import. + +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import type { FetchClipDeps } from "./fetchClip"; +import { createServer, TOOLS } from "./server"; +import { SourceRegistry } from "./sourceRegistry"; +import type { ShardSource } from "./source"; +import type { SourceSpec } from "./sources"; + +export type AgentTool = { + name: string; + description: string; + inputSchema: Record<string, unknown>; + run(input: any, ctx: { signal?: AbortSignal }): Promise<string>; // eslint-disable-line @typescript-eslint/no-explicit-any +}; + +export const CORPUS_TOOL_NAMES = [ + "list_channels", + "list_tags", + "list_reports", + "get_report", + "search_transcripts", + "enumerate_matches", + "get_transcript", + "get_post", + "get_thread", + "get_transcripts", + "get_video_metadata", + "channel_coverage", + "notes", + "list_sources", + "resolve_source", + "sweep_plan", + "ask_plan", +] as const; + +export type CorpusToolName = (typeof CORPUS_TOOL_NAMES)[number]; + +// What `notes` may do in process. +export const NOTES_ACTIONS = ["list", "read"] as const; + +export class CorpusToolError extends Error {} + +export type CorpusTools = { + // The source handle every call reads. + source: string; + tools: AgentTool[]; + // Call one allowed tool; its text. A tool error is thrown as a + // CorpusToolError carrying the tool's own words. + call(name: string, args?: Record<string, unknown>): Promise<string>; + close(): Promise<void>; +}; + +export type CorpusToolsOptions = { + // The corpus: a handle (`local:<dir>`, `remote:<url>`, `hub:<url>`), a + // spec, or a built ShardSource (tests). + source: string | SourceSpec | ShardSource; + // Only these of CORPUS_TOOL_NAMES (default: all of them). + only?: readonly CorpusToolName[]; + // The editor and umtool the editor-backed reads (channel_coverage, notes) + // reach: env, fetch, clock. Default: the process's. + editorDeps?: Partial<FetchClipDeps>; +}; + +function specOf(handle: string): SourceSpec { + const m = /^(local|remote|hub):(.+)$/s.exec(handle.trim()); + if (!m) throw new Error(`createCorpusTools: "${handle}" is not a source handle (local:<dir>, remote:<url>, hub:<url>)`); + const rest = m[2]!.trim(); + if (m[1] === "local") return { kind: "local", dir: rest }; + if (m[1] === "remote") return { kind: "remote", url: rest.replace(/\/+$/, "") }; + const hash = rest.indexOf("#"); + if (hash < 0) return { kind: "hub", url: rest.replace(/\/+$/, "") }; + const sites = rest + .slice(hash + 1) + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + return { kind: "hub", url: rest.slice(0, hash).replace(/\/+$/, ""), ...(sites.length ? { sites } : {}) }; +} + +const isSource = (s: unknown): s is ShardSource => + typeof s === "object" && s !== null && typeof (s as ShardSource).listChannels === "function"; + +type JsonSchema = { properties?: Record<string, unknown>; required?: string[] } & Record<string, unknown>; + +// A tool's schema as the agent sees it: no `source`; `notes` list/read only. +function agentSchema(name: string, schema: unknown): Record<string, unknown> { + const s = structuredClone(schema) as JsonSchema; + if (s.properties) delete s.properties.source; + if (Array.isArray(s.required)) { + s.required = s.required.filter((r) => r !== "source"); + if (s.required.length === 0) delete s.required; + } + if (name === "notes" && s.properties) { + s.properties.action = { type: "string", enum: [...NOTES_ACTIONS], description: 'Default "list".' }; + for (const k of ["note_id", "text", "resolve"]) delete s.properties[k]; + } + return s; +} + +const NOTES_DESCRIPTION = + "The operator's notes in umtool on articles and report-video projects (read only here). action " + + '"list": every open note, grouped by target. action "read" with target (as list names it: ' + + '"sites/<site>/<report>" for an article, else a project id): each note with its anchor resolved ' + + "(status: open, resolved or all)."; + +export async function createCorpusTools(opts: CorpusToolsOptions): Promise<CorpusTools> { + let registry: SourceRegistry; + if (isSource(opts.source)) registry = SourceRegistry.forSource(opts.source); + else registry = new SourceRegistry(typeof opts.source === "string" ? specOf(opts.source) : opts.source); + const source = registry.defaultHandle; + const allowed = new Set<string>(opts.only ?? CORPUS_TOOL_NAMES); + for (const n of allowed) { + if (!(CORPUS_TOOL_NAMES as readonly string[]).includes(n)) { + throw new Error(`createCorpusTools: "${n}" is not a read-only corpus tool`); + } + } + + const server = createServer(registry, opts.editorDeps ? { fetchClipDeps: opts.editorDeps } : {}); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "archilyzer-generation", version: "0" }, { capabilities: {} }); + await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]); + + const call = async (name: string, args: Record<string, unknown> = {}, signal?: AbortSignal): Promise<string> => { + if (!allowed.has(name)) { + throw new CorpusToolError(`${name}: not one of this run's read-only corpus tools (${[...allowed].join(", ")})`); + } + const a: Record<string, unknown> = { ...(args ?? {}), source }; + if (name === "notes") { + const action = a.action ?? "list"; + if (!(NOTES_ACTIONS as readonly unknown[]).includes(action)) { + throw new CorpusToolError(`notes: ${NOTES_ACTIONS.join(" and ")} only here (a reply is the operator's)`); + } + a.action = action; + for (const k of ["note_id", "text", "resolve"]) delete a[k]; + } + signal?.throwIfAborted(); + const res = (await client.callTool({ name, arguments: a }, signal ? { signal } : undefined)) as { + content?: { type: string; text?: string }[]; + isError?: boolean; + }; + const text = (res.content ?? []) + .filter((c) => c.type === "text") + .map((c) => c.text ?? "") + .join("\n"); + if (res.isError) throw new CorpusToolError(text); + return text; + }; + + const tools: AgentTool[] = TOOLS.filter((t) => allowed.has(t.name)).map((t) => ({ + name: t.name, + description: t.name === "notes" ? NOTES_DESCRIPTION : (t.description ?? ""), + inputSchema: agentSchema(t.name, t.inputSchema), + run: (input: Record<string, unknown>, ctx: { signal?: AbortSignal }) => call(t.name, input, ctx?.signal), + })); + + return { + source, + tools, + call: (name, args) => call(name, args), + close: async () => { + await client.close(); + await server.close(); + }, + }; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml @@ -156,6 +156,9 @@ importers: yt-dlp-transcript-common: specifier: workspace:* version: link:../common + yt-dlp-transcript-mcp: + specifier: workspace:* + version: link:../mcp devDependencies: '@playwright/test': specifier: ^1.59.1 diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -95,6 +95,8 @@ // pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait // pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait // pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait +// pnpm ops web-search --json '{"query":"second shop opening","n":5}' +// pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}' // // --file reads the BODY from a JSON file, which is how a big one gets sent: a // four-thousand-id tag-videos body is written by a script, not typed by a model @@ -359,6 +361,11 @@ const ACTIONS = [ "delete-file", "do-not-clean", "cleanup", + // WEB READS (release 27 S3): a DuckDuckGo search ({query, n?}) and one + // page as text ({url, maxChars?}), read only, through the editor's one + // paced web queue. Synchronous; no job. + "web-search", + "web-fetch", ]; // The log line a transcribe job ends with: this marker, then the result as @@ -1079,6 +1086,19 @@ export function usage() { " (a local llama-server the editor starts and stops) and waits while a", " transcription holds it. With --wait the result is printed on stdout.", "", + 'web-search searches the web (DuckDuckGo\'s HTML page) and answers the', + ' results: {"query", "n"?: 6 (at most 20)} -> {results: [{title, url,', + ' snippet}]}. Read only, through the editor\'s one web queue: one request at', + " a time, 3 s apart, backing off on a 429 or 503. For context; a web page", + " is never cited as what someone said.", + "", + 'web-fetch reads one web page as plain text: {"url", "maxChars"?: 12000 (at', + ' most 60000)} -> {page: {url, finalUrl, status, contentType, title?, text,', + " truncated}}. http and https only; a private or loopback host (by name, by", + " address, or by what its name resolves to, every redirect checked) is", + " refused before any request, and so is a page that is not text (a PDF, an", + " image). Read only, on the same web queue as web-search.", + "", "Env: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN,", " ARCHILYZER_AGENT (provenance of a tag write; default \"cli\").", " WORKER_TOKEN and ARCHILYZER_EDITOR_URL, when unset, are read from",