src/index.js
// AgentRove native agent: social-publisher (MIT).
// Prepares posts; it does not post by default. draft_posts and schedule_queue are offline and
// side-effect free. publish is an external write to ONE official platform API, refused unless
// "confirm": true, the item is approved, and the user's own token for that platform is set.
import { readFileSync } from "node:fs";
import { defineAgent, makeContext, handleMcpMessage, runCli, runMcpStdio, validateManifest } from "../sdk/index.js";
import { ToolError } from "./errors.js";
import { PLATFORMS, cleanText, composePost, normalizeHashtag, stripFraming, tagLink } from "./text.js";
import { contentHash, idempotencyKey, scheduleQueue } from "./queue.js";
import { ADAPTERS, send } from "./adapters.js";
import { isoUtc, parseInstant } from "./tz.js";
export { makeContext, handleMcpMessage, runCli, runMcpStdio, validateManifest };
export const manifest = JSON.parse(readFileSync(new URL("../agent.json", import.meta.url), "utf8"));
// ------------------------------------------------------------------------------------------------
// draft_posts
// ------------------------------------------------------------------------------------------------
const fold = (s) => cleanText(s).toLowerCase().replace(/\s+/g, " ").trim();
/**
* The units a shortened post may use, each a whole paragraph with announcing sentences removed.
* Script: body segments (not hook or call to action), ranked by how many sources support them (the
* script's claims[].sources, else the hosts named in "According to a and b:"), with the lead claim's
* source URL. Brief: paragraphs in the author's order. Nothing is reworded.
*/
function buildPoints(input, paragraphs) {
if (input.script === undefined) return { points: paragraphs.map((p, order) => ({ text: stripFraming(p), support: 0, order })), ranked: false };
const segs = input.script.segments.map((s) => ({ text: cleanText(s.text).replace(/\n+/g, " "), kind: String(s.kind ?? "body").toLowerCase() })).filter((s) => s.text);
const body = segs.filter((s) => s.kind !== "hook" && s.kind !== "cta");
const claims = Array.isArray(input.script.claims) ? input.script.claims.filter((c) => c && typeof c.text === "string" && c.text.trim()) : [];
const points = (body.length ? body : segs).map((s, order) => {
const claim = claims.find((c) => fold(s.text).includes(fold(c.text)));
const listed = claim ? [...new Set([...(Array.isArray(claim.sources) ? claim.sources : []), ...(claim.source_url ? [claim.source_url] : [])])] : [];
const named = /^according to ([^:]{1,300}):/i.exec(s.text)?.[1].split(/\s*(?:,|\band\b)\s*/).filter(Boolean).length ?? 0;
const url = claim?.source_url ?? (Array.isArray(claim?.sources) ? claim.sources[0] : undefined);
return { text: stripFraming(s.text), support: Math.max(listed.length, named), order, ...(typeof url === "string" && /^https:\/\//.test(url) ? { source_url: url } : {}) };
});
points.sort((a, b) => b.support - a.support || a.order - b.order);
const tail = segs.filter((s) => s.kind === "cta").map((s) => stripFraming(s.text)).filter(Boolean).join(" ") || undefined;
return { points, tail, ranked: true };
}
async function draft_posts(input, ctx) {
if ((input.brief === undefined) === (input.script === undefined)) throw new ToolError("invalid_input", "Provide exactly one of brief or script.");
const paragraphs =
input.brief !== undefined
? cleanText(input.brief).split(/\n{2,}/).map((p) => p.trim()).filter(Boolean)
: input.script.segments.map((s) => cleanText(s.text).replace(/\n+/g, " ")).filter(Boolean);
if (!paragraphs.length) throw new ToolError("invalid_input", "The brief or script contains no text.");
const warnings = [];
const hashtags = [];
const seen = new Set();
for (const raw of input.hashtags ?? []) {
const h = normalizeHashtag(raw);
if (!h) {
warnings.push(`Ignored hashtag "${String(raw).slice(0, 40)}": nothing usable left after removing spaces and punctuation (digit-only tags do not link).`);
continue;
}
if (h !== String(raw).replace(/^#+/, "").trim()) warnings.push(`Hashtag "${String(raw).slice(0, 40)}" was normalised to #${h}.`);
if (seen.has(h.toLowerCase())) continue;
seen.add(h.toLowerCase());
hashtags.push(h);
}
const cta = input.cta !== undefined ? cleanText(input.cta) : undefined;
const title = input.title ?? input.script?.title;
const { points, tail, ranked } = buildPoints(input, paragraphs);
const posts = [...new Set(input.platforms ?? PLATFORMS)].map((platform) =>
composePost(platform, {
paragraphs,
title,
cta,
link: input.link !== undefined ? tagLink(input.link, input.utm, platform) : undefined,
hashtags,
points,
tail,
ranked,
maxHashtags: input.max_hashtags,
account: input.accounts?.[platform],
}),
);
if (input.utm && input.link === undefined) warnings.push("utm was given without link, so no link was tagged.");
// Instagram and TikTok captions carry no link, so a call to action that points at "the link" misleads there.
const linkless = posts.filter((p) => p.link !== undefined && p.link_in_text === false).map((p) => p.platform);
if (cta && linkless.length && /\blinks?\b|\burl\b|\bclick\b|\btap\b|\bbelow\b/i.test(cta)) {
warnings.push(`The call to action mentions a link, but ${linkless.join(" and ")} captions do not include it. Adjust the CTA for those drafts (for example point to the link in your bio) before approving.`);
}
const over = posts.filter((p) => !p.within_limit).map((p) => p.platform);
if (over.length) warnings.push(`Over the limit even after shortening: ${over.join(", ")}.`);
warnings.push("Drafts only reformat your text; check facts, claims and rights before approving. Nothing was posted.");
return { posts, generated_at: isoUtc(ctx.now().getTime()), warnings };
}
// ------------------------------------------------------------------------------------------------
// schedule_queue
// ------------------------------------------------------------------------------------------------
async function schedule_queue(input, ctx) {
const nowMs = ctx.now().getTime();
const r = scheduleQueue(input, nowMs);
return {
queue: { format: "agentrove.social-queue/1", timezone: r.tz, generated_at: isoUtc(nowMs), items: r.items },
added: r.added,
skipped: r.skipped,
warnings: r.warnings,
};
}
// ------------------------------------------------------------------------------------------------
// publish (external_write; the SDK refuses to run it unless input.confirm === true)
// ------------------------------------------------------------------------------------------------
async function publish(input, ctx) {
const item = input.item;
if (item.approved !== true) throw new ToolError("not_approved", "item.approved must be true: the account owner has to approve this exact content in the queue before it is published.");
if (item.platform === "instagram" || item.platform === "tiktok") {
throw new ToolError(
"unsupported_platform",
`publish has no ${item.platform} adapter in this version (Instagram content publishing needs a professional account and publicly hosted media; TikTok's Content Posting API needs an audited app). Post it yourself from the approved draft.`,
);
}
const platform = item.platform;
const account = String(item.account ?? "").trim();
const hash = contentHash(item);
const key = idempotencyKey(platform, account, hash);
const notes = [];
if (item.content_hash !== undefined && item.content_hash !== hash) notes.push("The item's text, title or link changed since it was queued; the idempotency key was derived from the current content.");
if ((input.published_keys ?? []).includes(key)) {
return { platform, status: "already_published", published: false, already_published: true, idempotency_key: key, request: {}, attempts: 0, notes: [...notes, "This key is in published_keys, so nothing was sent."] };
}
const nowMs = ctx.now().getTime();
if (item.publish_at !== undefined) {
const t = parseInstant(item.publish_at);
if (t === null) throw new ToolError("invalid_input", "item.publish_at must be an ISO date-time with Z or an offset.");
if (t > nowMs + 5 * 60000 && input.publish_now !== true) {
throw new ToolError("not_due", `This item is scheduled for ${isoUtc(t)}. Run publish at that time from your own scheduler, or pass publish_now: true to post it now.`);
}
}
if (item.link !== undefined) {
try {
const u = new URL(item.link);
if (!["https:", "http:"].includes(u.protocol) || u.username || u.password) throw new Error("bad");
} catch {
throw new ToolError("invalid_input", "item.link must be an http(s) URL without embedded credentials.");
}
}
const adapter = ADAPTERS[platform];
const token = ctx.env[adapter.credential];
if (!token) throw new ToolError("missing_credential", `Set ${adapter.credential} to an OAuth access token for your own ${platform} account (see README). Nothing was sent.`);
const req = adapter.build({ item, input, account, token });
const { res, attempts } = await send(ctx, req, token, input.max_rate_limit_wait_seconds ?? 10, key);
const r = await adapter.parse(res);
if (r.note) notes.push(r.note);
if (r.status === "upload_session_created") {
notes.push(
"No video exists yet: upload the file bytes with an HTTP PUT to upload_url (Content-Type and Content-Length as declared). Treat upload_url like a password: anyone holding it can upload to your channel until it expires.",
);
if ((input.youtube?.privacy_status ?? "private") === "private") notes.push("The video will be private until you change it in YouTube Studio.");
}
const out = {
platform,
status: r.status,
published: r.status === "published",
already_published: r.status === "already_published",
idempotency_key: key,
request: { method: "POST", url: req.url, payload: req.payload },
attempts,
notes,
};
if (r.remote_id) out.remote_id = r.remote_id;
if (r.url) out.url = r.url;
if (r.upload_url) out.upload_url = r.upload_url;
if (out.published) notes.push("Store idempotency_key in your published log and pass it in published_keys next time to prevent a repeat post.");
return out;
}
const agent = defineAgent(manifest, { draft_posts, schedule_queue, publish });
export default agent;