import { describeEditorFailure, editorGet, type EditorDeps } from "./editorOps"; import type { ToolAnswer } from "./archivalTools"; // ─── x_trending_topics / x_trending_posts (lane x-trending, slice 1) ─── // // An X TRENDING LIBRARY, read through the local editor // (GET /api/ops/trending?slug=[&topic=][&limit=]): the operator's // topics with the trending pages read into each, and the posts those pages // showed — id, author, words, media by kind, the reads that showed each, its // topic. Read only. A library is PRIVATE: on no site and in no index build, // so no corpus tool (search_transcripts, get_post, …) and no published // archive carries its posts; only the editor can answer, and these tools read // nothing else of it — never a raw capture, a cookie or a token. // // Reading a page into a library is the operator's or an agent's ask of the // editor: `pnpm ops read-x-trending` (one job on X's queue, on a fresh cookie // jar — `pnpm ops get x-session` says whether one would start). Judging a post // (`judge-trending`) and watching a topic (`watch-trending`) are asks of the // editor too; these tools only show what they left (lane x-trending-2). const SLUG_RE = /^[a-z0-9][a-z0-9._-]*$/i; export const X_TRENDING_POSTS_MAX = 500; type Topic = { id: string; title: string; posts: number; sources?: Array<{ trendId: string; url: string; title?: string; summary?: string; // When X last rewrote its title and summary; the page's tabs by label; the tab the last read saw. lastUpdatedAt?: string; tabs?: string[]; lastReadTab?: string; lastReadTabs?: string[]; reads: number; lastReadAt: string | null; }>; // The topic's watch, once it has been watched; `sentence` says what it is doing. watch?: { on: boolean; sentence: string; paused?: { reason: string }; ended?: { reason: string } }; }; type PostRow = { id: string; author: string; authorName?: string; createdAt: string; url: string; text: string; media?: { count: number; kinds?: string[]; thumbnail?: string }; topic: string; reads?: Array<{ read: string; trendId: string; at: string; tab?: string }>; judgement?: { state: string; note?: string; by: string; at: string; from?: string }; thread?: string; // A page that showed it before did not show it at `at` (never "deleted"). gone?: { at: string; read: string; trendId: string }; // A tab's read reached its end without it while another tab still shows it. goneTabs?: Array<{ tab: string; at: string; read: string }>; capture?: { at: string; state: string; shot: boolean; files: number; mediaState: string; mediaOwed?: string }; }; type ListingBody = { name?: string; topics?: Topic[]; posts?: PostRow[]; total?: number; reads?: string[] }; // X's summary of a page, at most this long here (the editor's listing cuts it // the same way; the whole text stays in the library). export const X_TRENDING_SUMMARY_MAX = 600; function listedSummary(summary: string): string { if (summary.length <= X_TRENDING_SUMMARY_MAX) return summary; const cut = summary.slice(0, X_TRENDING_SUMMARY_MAX - 1); const word = cut.lastIndexOf(" "); return `${(word > X_TRENDING_SUMMARY_MAX * 0.8 ? cut.slice(0, word) : cut).trimEnd()}…`; } const day = (iso: string | null | undefined) => (iso ? iso.slice(0, 16).replace("T", " ") : "?"); export function renderXTrendingTopics(slug: string, body: ListingBody): string { const topics = body.topics ?? []; const lines = [`X trending library ${slug}: ${topics.length} topic${topics.length === 1 ? "" : "s"}, ${body.total ?? 0} posts (private: on no site, in no index)`]; if (topics.length === 0) lines.push("No topic yet: no trending page has been read into it (pnpm ops read-x-trending)."); for (const t of topics) { lines.push(`- ${t.id} — "${t.title}": ${t.posts} post${t.posts === 1 ? "" : "s"}`); for (const s of t.sources ?? []) { const tab = s.lastReadTabs?.length ? ` · the last read saw the ${s.lastReadTabs.map((t) => `"${t}"`).join(" and ")} tabs` : s.lastReadTab ? ` · the last read saw the "${s.lastReadTab}" tab${s.tabs && s.tabs.length > 1 ? ` of ${s.tabs.map((t) => `"${t}"`).join(", ")}` : ""}` : ""; lines.push(` ${s.url} · read ${s.reads}×, last ${day(s.lastReadAt)} UTC${tab}`); if (s.title) lines.push(` X's title: ${s.title}${s.lastUpdatedAt ? ` (X updated it ${day(s.lastUpdatedAt)} UTC)` : ""}`); if (s.summary) lines.push(` X's summary: ${listedSummary(s.summary)}`); } if (t.watch) lines.push(` watch: ${t.watch.sentence}`); } if (body.reads?.length) lines.push(`Saved reads (newest first): ${body.reads.join(", ")}`); return lines.join("\n"); } function mediaText(m: PostRow["media"]): string { if (!m || !m.count) return "no media"; return `${m.count} media${m.kinds?.length ? ` (${m.kinds.join(", ")})` : ""}`; } export function renderXTrendingPosts(slug: string, body: ListingBody, topic?: string): string { const posts = body.posts ?? []; const total = body.total ?? posts.length; const lines = [`X trending library ${slug}${topic ? `, topic ${topic}` : ""}: ${posts.length} of ${total} post${total === 1 ? "" : "s"}`]; if (posts.length === 0) lines.push("No post."); for (const [i, p] of posts.entries()) { const reads = (p.reads ?? []).map((r) => `${r.read} (${day(r.at)} UTC${r.tab ? `, the "${r.tab}" tab` : ""})`).join(", "); lines.push( `${i + 1}. ${p.id} @${p.author}${p.authorName ? ` (${p.authorName})` : ""} · ${day(p.createdAt)} UTC · ${mediaText(p.media)} · topic ${p.topic}`, ); lines.push(` ${p.url}`); lines.push(` ${p.text.replace(/\s*\n\s*/g, " / ")}`); if (reads) lines.push(` shown by: ${reads}`); if (p.thread && p.thread !== p.id) lines.push(` in thread ${p.thread}`); for (const g of p.goneTabs ?? []) lines.push(` gone from the "${g.tab}" tab at ${day(g.at)} UTC (read ${g.read}); another tab still shows it`); if (p.gone) lines.push(` gone from the page at ${day(p.gone.at)} UTC (read ${p.gone.read}; the page stopped showing it, which is not "deleted")`); if (p.capture) { const owed = p.capture.mediaOwed === "kept" ? "; more media owed once it is kept" : p.capture.mediaOwed === "next" ? "; more media owed to the next capture" : ""; lines.push( ` captured ${day(p.capture.at)} UTC: ${p.capture.state}${p.capture.shot ? ", shot" : ""}, ${p.capture.files} media file${p.capture.files === 1 ? "" : "s"}${owed}` + (p.media?.thumbnail ? ` (${p.media.thumbnail})` : ""), ); } else if (p.media?.thumbnail) lines.push(` captured: ${p.media.thumbnail}`); if (p.judgement) { lines.push( ` judged ${p.judgement.state} by ${p.judgement.by}${p.judgement.from === "thread" ? " (its thread)" : ""} (${day(p.judgement.at)} UTC)${p.judgement.note ? `: ${p.judgement.note}` : ""}`, ); } } if (total > posts.length) lines.push(`… ${total - posts.length} more (raise limit, or narrow by topic).`); return lines.join("\n"); } function slugOf(tool: string, args: Record): string | ToolAnswer { const channel = typeof args.channel === "string" ? args.channel.trim() : ""; if (!channel || !SLUG_RE.test(channel)) { return { text: `${tool}: channel is required (the X trending library's slug)`, isError: true }; } return channel; } export async function xTrendingTopicsTool(args: Record, deps: EditorDeps): Promise { const channel = slugOf("x_trending_topics", args); if (typeof channel !== "string") return channel; // The topics need no post: one is asked for, the smallest listing. const q = new URLSearchParams({ slug: channel, limit: "1" }); const a = await editorGet(deps, `/api/ops/trending?${q.toString()}`); if (a.kind !== "ok") return { text: describeEditorFailure("x_trending_topics", a), isError: true }; return { text: renderXTrendingTopics(channel, a.body as ListingBody) }; } export async function xTrendingPostsTool(args: Record, deps: EditorDeps): Promise { const channel = slugOf("x_trending_posts", args); if (typeof channel !== "string") return channel; const q = new URLSearchParams({ slug: channel }); let topic: string | undefined; if (args.topic !== undefined) { if (typeof args.topic !== "string" || !args.topic.trim()) { return { text: "x_trending_posts: topic is a topic's id (x_trending_topics lists them)", isError: true }; } topic = args.topic.trim(); q.set("topic", topic); } if (args.limit !== undefined) { const n = Number(args.limit); if (!Number.isInteger(n) || n < 1 || n > X_TRENDING_POSTS_MAX) { return { text: `x_trending_posts: limit is a whole number, 1–${X_TRENDING_POSTS_MAX}`, isError: true }; } q.set("limit", String(n)); } const a = await editorGet(deps, `/api/ops/trending?${q.toString()}`); if (a.kind !== "ok") return { text: describeEditorFailure("x_trending_posts", a), isError: true }; return { text: renderXTrendingPosts(channel, a.body as ListingBody, topic) }; } // ─── x_trending_accounts (lane x-trending-publish, slice 4) ─── // // THE LIBRARY'S ACCOUNTS, like an X search channel's leads: who wrote the // posts it holds (GET /api/ops/trending?slug=&accounts=1[&topic=][&limit=]). // Read only. Organising a library's topics and publishing one are asks of the // editor (`pnpm ops`), and a publish is the operator's: this server has no // tool for either. type AccountRow = { handle: string; name?: string; posts: number; kept: number; keptByOperator?: number; topics?: string[]; last?: string; archivedAs?: string[] }; type AccountsBody = { accounts?: AccountRow[]; total?: number; posts?: number; more?: number }; export const X_TRENDING_ACCOUNTS_MAX = 500; export function renderXTrendingAccounts(slug: string, body: AccountsBody, topic?: string): string { const rows = body.accounts ?? []; const where = topic ? `${slug}, topic ${topic}` : slug; const lines = [`X trending library ${where}: ${body.total ?? rows.length} account${(body.total ?? rows.length) === 1 ? "" : "s"} over ${body.posts ?? 0} post${body.posts === 1 ? "" : "s"}${body.more ? ` (${rows.length} listed, ${body.more} more)` : ""}.`]; if (rows.length === 0) lines.push("No account yet: read a trending page into the library first (`pnpm ops read-x-trending`)."); for (const a of rows) { const kept = a.kept ? `, ${a.kept} kept${a.keptByOperator !== undefined && a.keptByOperator !== a.kept ? ` (${a.keptByOperator} by the operator)` : ""}` : ""; lines.push( `- @${a.handle}${a.name ? ` (${a.name})` : ""}: ${a.posts} post${a.posts === 1 ? "" : "s"}${kept}` + `${a.topics?.length ? `; topics: ${a.topics.join(", ")}` : ""}` + `${a.last ? `; newest ${day(a.last)}` : ""}` + `${a.archivedAs?.length ? `; already archived as ${a.archivedAs.join(", ")}` : ""}`, ); } lines.push( "", "Archiving an account as its own X channel (-x, on no site) is the operator's or an agent's ask of the editor: " + "`pnpm ops x-search-lead --json '{\"slug\":\"\",\"handle\":\"\",\"action\":\"archive\",\"dryRun\":true}'`. From a library it asks X nothing: the first fetch is a separate step.", ); return lines.join("\n"); } export async function xTrendingAccountsTool(args: Record, deps: EditorDeps): Promise { const channel = slugOf("x_trending_accounts", args); if (typeof channel !== "string") return channel; const q = new URLSearchParams({ slug: channel, accounts: "1" }); let topic: string | undefined; if (args.topic !== undefined) { if (typeof args.topic !== "string" || !args.topic.trim()) { return { text: "x_trending_accounts: topic is a topic's id (x_trending_topics lists them)", isError: true }; } topic = args.topic.trim(); q.set("topic", topic); } if (args.limit !== undefined) { const n = Number(args.limit); if (!Number.isInteger(n) || n < 1 || n > X_TRENDING_ACCOUNTS_MAX) { return { text: `x_trending_accounts: limit is a whole number, 1–${X_TRENDING_ACCOUNTS_MAX}`, isError: true }; } q.set("limit", String(n)); } const a = await editorGet(deps, `/api/ops/trending?${q.toString()}`); if (a.kind !== "ok") return { text: describeEditorFailure("x_trending_accounts", a), isError: true }; return { text: renderXTrendingAccounts(channel, a.body as AccountsBody, topic) }; } export const X_TRENDING_TOOLS = [ { name: "x_trending_topics", description: "An X TRENDING LIBRARY's topics: the operator's topics, each with the X trending pages " + "(x.com/i/trending/) read into it, how often and when, X's own title and summary of " + "the page (X's words, not the operator's), which of the page's tabs the last read saw (a " + "read covers Top and Latest in one job unless asked for one), and its post count; and the " + "ids of the saved reads; and each topic's WATCH, when it has one — whether it is being " + "read again on an interval, until when, and why it is paused (a watch runs only while " + "X's cookie jar is fresh, so a stale jar pauses it until the operator refreshes). A library is PRIVATE — on no site, in no index, so no other " + "tool here finds its posts. Read only: a page is read into a library with " + "`pnpm ops read-x-trending` (one job on X's queue, on a fresh cookie jar). " + "Needs ARCHILYZER_EDITOR_URL and WORKER_TOKEN.", inputSchema: { type: "object", properties: { channel: { type: "string", description: "The X trending library's slug (the editor's)." }, }, required: ["channel"], additionalProperties: false, }, }, { name: "x_trending_posts", description: "The posts of an X TRENDING LIBRARY (or of one of its topics): each post's id, author, " + "date, words, media by kind and count, the reads that showed it (and the page's tab), its topic, and — once " + "it has them — the thread it belongs to, what its capture holds (and what media it is " + "still owed), its judgement (keep / drop / later; none is undecided; its own, or its " + "thread's), whether ONE TAB of the page stopped showing it while another still does, and whether a page stopped showing it (\"gone from the page at