src/index.js
// AgentRove native agent: video-script (MIT).
// Builds a short-form (15-90 s) script from a research_brief: hook, one body segment per sourced
// key point, call to action. Timings come from word counts (default 2.5 words/second). Every body
// segment's claim is the brief's claim verbatim, linked to its source URLs; nothing else is
// asserted. Exports SubRip captions. Deterministic; no model, no network.
import { readFileSync } from "node:fs";
import { defineAgent, makeContext, handleMcpMessage, runCli, runMcpStdio } from "../sdk/index.js";
import { ToolError } from "./errors.js";
import { toSrt } from "./srt.js";
export { makeContext, handleMcpMessage, runCli, runMcpStdio };
const manifest = JSON.parse(readFileSync(new URL("../agent.json", import.meta.url), "utf8"));
const wordCount = (s) => String(s).trim().split(/\s+/).filter(Boolean).length;
const norm = (s) => String(s).replace(/\s+/g, " ").trim();
const ms3 = (x) => Math.round(x * 1000) / 1000;
function hostOf(url) {
try {
return new URL(url).hostname.replace(/^www\./, "");
} catch {
return null;
}
}
const isHttpUrl = (u) => typeof u === "string" && /^https?:\/\/[^\s]+$/i.test(u) && hostOf(u) !== null;
function defaultHook(topic, n) {
return `What do the sources say about ${norm(topic).replace(/[.?!]+$/, "")}? Here ${n === 1 ? "is 1 point" : `are ${n} points`}.`;
}
const DEFAULT_CTA = "Check the linked sources before you share this.";
// Open questions in a content-research brief quote the key points they are about ("Sources
// disagree, ...: "<claim>" (url) versus "<claim>" (url)", "Only one source supports: "<claim>"").
// A body segment whose claim is quoted in such a question gets a specific warning.
const quotedIn = (question, claim) => {
const head = claim.slice(0, Math.min(60, claim.length));
return head.length >= 12 && question.includes(`"${head}`);
};
const segList = (ids) => (ids.length === 1 ? `Segment ${ids[0]}` : `Segments ${ids.slice(0, -1).join(", ")} and ${ids[ids.length - 1]}`);
function disputeWarnings(questions, claims) {
const out = [];
const inPair = new Set();
const disputed = new Set();
for (const q of questions.filter((x) => /^Sources disagree\b/.test(x))) {
const ids = claims.filter((c) => quotedIn(q, c.text)).map((c) => c.segment);
for (const id of ids) disputed.add(id);
if (ids.length < 2) continue;
for (const id of ids) inPair.add(id);
const what = q.slice(0, q.indexOf(":") > 0 ? q.indexOf(":") : 60).replace(/^Sources disagree,?\s*/, "");
out.push(`${segList(ids)} state points that the sources disagree on (${what}). Decide which is correct, or present the disagreement as such, before recording.`);
}
const lone = [...disputed].filter((id) => !inPair.has(id)).sort((a, b) => a - b);
if (lone.length) out.push(`${segList(lone)} state${lone.length === 1 ? "s" : ""} a point that another source contradicts (see the brief's open questions).`);
const single = claims.filter((c) => !disputed.has(c.segment) && questions.some((q) => /^Only one source supports\b/.test(q) && quotedIn(q, c.text))).map((c) => c.segment);
if (single.length) out.push(`${segList(single)} rest${single.length === 1 ? "s" : ""} on a single source; look for independent confirmation.`);
return out;
}
async function build_script(input, ctx) {
const brief = input.brief;
const target = input.target_seconds ?? 45;
const wps = input.words_per_second ?? 2.5;
const maxPoints = input.max_points ?? 5;
const pause = input.pause_seconds ?? 0;
const attribute = input.attribute_sources ?? true;
const warnings = [];
const totalWords = Math.floor(target * wps);
const hookText = input.hook !== undefined ? norm(input.hook) : null;
const ctaText = norm(input.cta ?? DEFAULT_CTA);
const hookWords = hookText !== null ? wordCount(hookText) : wordCount(defaultHook(brief.topic, 2)); // word count does not depend on n
const ctaWords = wordCount(ctaText);
let remaining = totalWords - hookWords - ctaWords;
const chosen = [];
for (const [i, kp] of brief.key_points.entries()) {
if (chosen.length >= maxPoints) break;
const claim = norm(kp.claim);
const urls = [...new Set(kp.sources.filter(isHttpUrl))];
if (!claim) continue;
if (!urls.length) {
warnings.push(`Key point ${i + 1} was skipped because it has no http(s) source URL. Unsourced claims are never used.`);
continue;
}
const hosts = [...new Set(urls.map(hostOf))];
const lead = attribute ? `According to ${hosts.slice(0, 2).join(" and ")}${hosts.length > 2 ? " and others" : ""}: ` : "";
const text = `${lead}${claim}`;
const words = wordCount(text);
if (words > remaining - pause * wps) {
warnings.push(`Key point ${i + 1} (${words} words) was left out to stay within ${target} s.`);
continue;
}
remaining -= words + pause * wps;
chosen.push({ text, claim, urls, index: i });
}
if (!chosen.length) {
throw new ToolError(
"insufficient_content",
"No sourced key point fits the target duration. Add key points with source URLs, raise target_seconds, or shorten the hook/CTA.",
);
}
const parts = [
{ kind: "hook", text: hookText ?? defaultHook(brief.topic, chosen.length) },
...chosen.map((c) => ({ kind: "body", text: c.text, claim: c })),
{ kind: "cta", text: ctaText },
];
let cursor = 0;
const segments = [];
const claims = [];
for (const [i, p] of parts.entries()) {
const words = wordCount(p.text);
const start = ms3(cursor);
const end = ms3(cursor + words / wps);
segments.push({ index: i, kind: p.kind, start, end, text: p.text, words });
if (p.claim) claims.push({ text: p.claim.claim, source_url: p.claim.urls[0], sources: p.claim.urls, segment: i, brief_point: p.claim.index + 1 });
cursor = end + (i < parts.length - 1 ? pause : 0);
}
const duration = Math.round(segments[segments.length - 1].end * 100) / 100;
if (duration < 15) warnings.push(`The script runs about ${duration} s, below the 15 s short-form minimum. Add more key points or lower words_per_second.`);
if (hookText !== null) warnings.push("The hook text was supplied by you and is not linked to a source. Make sure it makes no factual claim.");
if (input.cta !== undefined) warnings.push("The call to action was supplied by you and is not linked to a source. Make sure it makes no factual claim.");
const questions = Array.isArray(brief.open_questions) ? brief.open_questions.filter((q) => typeof q === "string") : [];
warnings.push(...disputeWarnings(questions, claims));
if (questions.length) warnings.push(`The brief lists ${questions.length} open question(s). Resolve them (or run a fact check) before publishing.`);
warnings.push(`Timings assume ${wps} words per second; real delivery will vary, so re-time captions after recording if needed.`);
const script = { title: norm(input.title ?? brief.topic), duration_seconds: duration, words_per_second: wps, segments, claims };
return {
script,
captions_srt: toSrt(segments, input.max_chars_per_line ?? 42),
word_budget: { target_seconds: target, total: totalWords, used: segments.reduce((a, s) => a + s.words, 0) },
generated_at: ctx.now().toISOString(),
warnings,
};
}
async function captions_from_script(input) {
const segs = input.script.segments.map((s, i) => {
if (!(s.end > s.start)) throw new ToolError("invalid_input", `script.segments[${i}]: end must be after start`);
return { start: s.start, end: s.end, text: norm(s.text) };
});
segs.sort((a, b) => a.start - b.start);
return { captions_srt: toSrt(segs, input.max_chars_per_line ?? 42), cue_source_segments: segs.length };
}
const agent = defineAgent(manifest, { build_script, captions_from_script });
export default agent;