diff options
Diffstat (limited to 'castle-search/src/http.ts')
| -rw-r--r-- | castle-search/src/http.ts | 291 |
1 files changed, 234 insertions, 57 deletions
diff --git a/castle-search/src/http.ts b/castle-search/src/http.ts index 17c8c70..076c624 100644 --- a/castle-search/src/http.ts +++ b/castle-search/src/http.ts @@ -20,17 +20,36 @@ * an address only trusted peers reach. Each search opens and closes one * background tab in a browser someone may be looking at. * - * POST /x-search searches X instead (x-search.ts), through the browser's - * signed-in X session, and GET /openapi.json describes it, so that Open WebUI - * can offer it as a tool: `{ "query", "count", "sort" }` in, `{ "query", "sort", - * "posts": [...] }` out, 502 with `{ "error" }` on failure. + * POST /x-search, /x-post, /x-user and /x-trends read X instead (x-search.ts), + * through the browser's signed-in X session, and GET /openapi.json describes + * them, so that Open WebUI can offer them as tools ("X.com"). POST + * /youtube-transcript files a YouTube video's transcript and returns it + * (youtube.ts), described at GET /youtube/openapi.json ("YouTube"). Each + * answers 502 with `{ "error" }` on failure. */ import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import { messageOf } from "./errors.ts"; import { disconnect, search, type SearchOutcome, type SearchRequest } from "./search.ts"; -import { xSearch, type XSearchOutcome, type XSearchRequest } from "./x-search.ts"; +import { + handleOf, + postIdOf, + TREND_TABS, + type XPostOutcome, + type XPostRequest, + xPost, + xSearch, + type XSearchOutcome, + type XSearchRequest, + type XTrendsOutcome, + type XTrendTab, + xTrends, + xUser, + type XUserOutcome, + type XUserRequest, +} from "./x-search.ts"; +import { DEFAULT_MAX_CHARS, type TranscriptOutcome, type TranscriptRequest, videoIdOf, youtubeTranscript } from "./youtube.ts"; export const DEFAULT_LISTEN = "127.0.0.1:11158"; const MAX_BODY_BYTES = 64 * 1024; @@ -75,47 +94,124 @@ export const handleSearch = async (raw: string, run: Searcher, signal: AbortSign }; export type XSearcher = (request: XSearchRequest, signal: AbortSignal) => Promise<XSearchOutcome>; +export type XPostReader = (request: XPostRequest, signal: AbortSignal) => Promise<XPostOutcome>; +export type XUserReader = (request: XUserRequest, signal: AbortSignal) => Promise<XUserOutcome>; +export type XTrendsReader = (tab: XTrendTab, signal: AbortSignal) => Promise<XTrendsOutcome>; const X_DEFAULT_COUNT = 10; -/** POST /x-search: `{ query, count?, sort? }` in, `{ query, sort, posts }` out. */ -export const handleXSearch = async (raw: string, run: XSearcher, signal: AbortSignal): Promise<Reply> => { - let parsed: unknown; +const jsonBody = (raw: string): Record<string, unknown> | Reply => { try { - parsed = JSON.parse(raw); + const parsed: unknown = JSON.parse(raw || "{}"); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed as Record<string, unknown>; } catch { - return { status: 400, body: { error: "request body is not JSON" } }; + // fall through } - const { query, count, sort } = (parsed ?? {}) as { query?: unknown; count?: unknown; sort?: unknown }; + return { status: 400, body: { error: "request body is not a JSON object" } }; +}; +const isReply = (v: unknown): v is Reply => typeof (v as Reply).status === "number" && "body" in (v as Reply); + +const countOf = (v: unknown, fallback: number, min = 1): number => { + const n = typeof v === "number" && Number.isFinite(v) ? Math.trunc(v) : fallback; + return Math.min(MAX_COUNT, Math.max(min, n)); +}; + +const answer = async (work: () => Promise<unknown>): Promise<Reply> => { + try { + return { status: 200, body: await work() }; + } catch (e) { + return { status: 502, body: { error: messageOf(e) } }; + } +}; + +/** POST /x-search: `{ query, count?, sort? }` in, `{ query, sort, posts }` out. */ +export const handleXSearch = async (raw: string, run: XSearcher, signal: AbortSignal): Promise<Reply> => { + const body = jsonBody(raw); + if (isReply(body)) return body; + const { query, count, sort } = body; if (typeof query !== "string" || query.trim() === "") { return { status: 400, body: { error: "query must be a non-empty string" } }; } if (sort !== undefined && sort !== null && sort !== "latest" && sort !== "top") { return { status: 400, body: { error: 'sort must be "latest" or "top"' } }; } - const n = typeof count === "number" && Number.isFinite(count) ? Math.trunc(count) : X_DEFAULT_COUNT; - try { - const outcome = await run( - { query: query.trim(), count: Math.min(MAX_COUNT, Math.max(1, n)), sort: sort ?? "latest" }, - signal, - ); - return { status: 200, body: { query: outcome.query, sort: outcome.sort, posts: outcome.posts } }; - } catch (e) { - return { status: 502, body: { error: messageOf(e) } }; + return answer(async () => { + const outcome = await run({ query: query.trim(), count: countOf(count, X_DEFAULT_COUNT), sort: sort ?? "latest" }, signal); + return { query: outcome.query, sort: outcome.sort, posts: outcome.posts }; + }); +}; + +/** POST /x-post: `{ url, replies? }` in, `{ post, thread, replies }` out. */ +export const handleXPost = async (raw: string, run: XPostReader, signal: AbortSignal): Promise<Reply> => { + const body = jsonBody(raw); + if (isReply(body)) return body; + if (typeof body["url"] !== "string" || !postIdOf(body["url"])) { + return { status: 400, body: { error: "url must be a link to a post on X (x.com/<handle>/status/<id>) or its id" } }; + } + const url = body["url"]; + return answer(() => run({ url, replies: countOf(body["replies"], X_DEFAULT_COUNT, 0) }, signal)); +}; + +/** POST /x-user: `{ handle, count? }` in, `{ profile, posts }` out. */ +export const handleXUser = async (raw: string, run: XUserReader, signal: AbortSignal): Promise<Reply> => { + const body = jsonBody(raw); + if (isReply(body)) return body; + if (typeof body["handle"] !== "string" || !handleOf(body["handle"])) { + return { status: 400, body: { error: "handle must be an X handle, such as nasa or @nasa" } }; + } + const handle = body["handle"]; + return answer(() => run({ handle, count: countOf(body["count"], X_DEFAULT_COUNT, 0) }, signal)); +}; + +/** POST /x-trends: `{ tab? }` in, `{ tab, trends }` out. */ +export const handleXTrends = async (raw: string, run: XTrendsReader, signal: AbortSignal): Promise<Reply> => { + const body = jsonBody(raw); + if (isReply(body)) return body; + const tab = body["tab"] ?? "trending"; + if (!TREND_TABS.includes(tab as XTrendTab)) { + return { status: 400, body: { error: `tab must be one of ${TREND_TABS.join(", ")}` } }; + } + return answer(() => run(tab as XTrendTab, signal)); +}; + +export type TranscriptFetcher = (request: TranscriptRequest, signal: AbortSignal) => Promise<TranscriptOutcome>; + +/** POST /youtube-transcript: `{ url, language?, max_chars? }` in, the transcript and where it was filed out. */ +export const handleTranscript = async (raw: string, run: TranscriptFetcher, signal: AbortSignal): Promise<Reply> => { + const body = jsonBody(raw); + if (isReply(body)) return body; + if (typeof body["url"] !== "string" || !videoIdOf(body["url"])) { + return { status: 400, body: { error: "url must be a YouTube video link (youtube.com/watch?v=..., youtu.be/..., shorts/...)" } }; + } + const language = body["language"]; + if (language !== undefined && (typeof language !== "string" || !/^[A-Za-z]{2,3}(-[A-Za-z0-9]+)?$/.test(language))) { + return { status: 400, body: { error: "language must be a language code such as en, pt or en-GB" } }; } + const max = body["max_chars"]; + const maxChars = typeof max === "number" && Number.isFinite(max) ? Math.max(1000, Math.trunc(max)) : DEFAULT_MAX_CHARS; + const url = body["url"]; + return answer(() => run({ url, language: language as string | undefined, maxChars }, signal)); +}; + +const jsonSchema = (properties: Record<string, unknown>, required: string[]) => ({ + required: true, + content: { "application/json": { schema: { type: "object", required, properties } } }, +}); +const RESPONSES = { + "200": { description: "What X shows", content: { "application/json": { schema: { type: "object" } } } }, + "502": { description: "X could not be read; error says why", content: { "application/json": { schema: { type: "object" } } } }, }; /** - * The OpenAPI description Open WebUI reads to offer /x-search as a tool. Its - * descriptions are what the model sees, so they say what the tool is for and - * how to write a query. + * The OpenAPI description Open WebUI reads to offer the X reads as tools. Its + * descriptions are what the model sees, so they say what each is for. */ export const OPENAPI = { openapi: "3.1.0", info: { - title: "castle X search", - version: "1.0.0", - description: "Searches posts on X (Twitter) through a signed-in browser. Free per search.", + title: "X.com", + version: "2.0.0", + description: "Reads X (Twitter) through a signed-in browser: search, posts with replies, profiles, trends. Free.", }, paths: { "/x-search": { @@ -127,26 +223,103 @@ export const OPENAPI = { "reactions to news, posts about a topic. The query uses X's search syntax: from:handle, to:handle, " + '"exact phrase", OR, -word, since:YYYY-MM-DD, until:YYYY-MM-DD, min_faves:N, filter:media, ' + "-filter:replies, lang:en. A handle is written without @ after from:. Each post comes with its " + - "link: cite it. Text cut short by X is marked truncated.", - requestBody: { - required: true, - content: { - "application/json": { - schema: { - type: "object", - required: ["query"], - properties: { - query: { type: "string", description: "X search query, e.g. from:nasa since:2026-11-01" }, - count: { type: "integer", minimum: 1, maximum: MAX_COUNT, default: X_DEFAULT_COUNT, description: "How many posts" }, - sort: { type: "string", enum: ["latest", "top"], default: "latest", description: "latest: newest first; top: most engaged" }, - }, - }, - }, + "link: cite it. A post marked truncated was cut short by X: read_x_post gives it whole. Photos " + + "come with their image link and alt text.", + requestBody: jsonSchema( + { + query: { type: "string", description: "X search query, e.g. from:nasa since:2026-11-01" }, + count: { type: "integer", minimum: 1, maximum: MAX_COUNT, default: X_DEFAULT_COUNT, description: "How many posts" }, + sort: { type: "string", enum: ["latest", "top"], default: "latest", description: "latest: newest first; top: most engaged" }, }, - }, + ["query"], + ), + responses: RESPONSES, + }, + }, + "/x-post": { + post: { + operationId: "read_x_post", + summary: "Read one post on X, whole, with its thread and replies", + description: + "Read a post on X from its link: its full text (never truncated), photos with their image link " + + "and alt text, its link card, the posts above it when it is a reply (thread, oldest first), and " + + "the top replies under it. Use it to read a long post, a thread, or what people answered.", + requestBody: jsonSchema( + { + url: { type: "string", description: "The post's link, x.com/<handle>/status/<id>, or the id" }, + replies: { type: "integer", minimum: 0, maximum: MAX_COUNT, default: X_DEFAULT_COUNT, description: "How many replies" }, + }, + ["url"], + ), + responses: RESPONSES, + }, + }, + "/x-user": { + post: { + operationId: "read_x_profile", + summary: "Read an X profile and its latest posts", + description: + "Read an X account's profile: name, bio, location, website, when it joined, exact follower, " + + "following and post counts, then its latest posts as its profile shows them (a pinned post and " + + "reposts included, marked in context).", + requestBody: jsonSchema( + { + handle: { type: "string", description: "The account's handle, such as nasa or @nasa" }, + count: { type: "integer", minimum: 0, maximum: MAX_COUNT, default: X_DEFAULT_COUNT, description: "How many of its posts" }, + }, + ["handle"], + ), + responses: RESPONSES, + }, + }, + "/x-trends": { + post: { + operationId: "x_trends", + summary: "What is trending on X now", + description: + "List what X shows as trending now, for the signed-in account's region (the United Kingdom). " + + "Each trend has a query: pass it to search_x for the posts.", + requestBody: jsonSchema( + { tab: { type: "string", enum: [...TREND_TABS], default: "trending", description: "Which explore tab" } }, + [], + ), + responses: RESPONSES, + }, + }, + }, +} as const; + +/** The YouTube tool's own description, so Open WebUI lists it apart from X.com. */ +export const YOUTUBE_OPENAPI = { + openapi: "3.1.0", + info: { + title: "YouTube", + version: "1.0.0", + description: "A YouTube video's transcript, filed in Igor's Nextcloud transcript folder and returned.", + }, + paths: { + "/youtube-transcript": { + post: { + operationId: "youtube_transcript", + summary: "Get a YouTube video's transcript", + description: + "Fetch a YouTube video's transcript from its link: the video's captions (human-written when it " + + "has them, YouTube's automatic ones otherwise) as clean prose, with its title, channel, upload " + + "date and length. It is also filed in Igor's Nextcloud, in the transcript folder, as " + + "<upload date>-<Title>.txt; a video filed before is read from there. Use it whenever a YouTube " + + "link comes up and its content matters: to summarise it, answer questions about it, or quote " + + "it. Automatic captions garble names and numbers: say so when one matters.", + requestBody: jsonSchema( + { + url: { type: "string", description: "The video's link: youtube.com/watch?v=..., youtu.be/..., shorts/..." }, + language: { type: "string", default: "en", description: "Caption language code, such as en or pt" }, + max_chars: { type: "integer", minimum: 1000, default: DEFAULT_MAX_CHARS, description: "Most characters of text to return; the file always has all of it" }, + }, + ["url"], + ), responses: { - "200": { description: "Matching posts", content: { "application/json": { schema: { type: "object" } } } }, - "502": { description: "The search failed; error says why", content: { "application/json": { schema: { type: "object" } } } }, + "200": { description: "The transcript and where it was filed", content: { "application/json": { schema: { type: "object" } } } }, + "502": { description: "No transcript; error says why", content: { "application/json": { schema: { type: "object" } } } }, }, }, }, @@ -199,9 +372,20 @@ const main = (): void => { send(res, { status: 200, body: OPENAPI }); return; } - const isX = path === "/x-search"; - if (req.method !== "POST" || (path !== "/" && path !== "/search" && !isX)) { - send(res, { status: 404, body: { error: "POST a search to / or /search, or an X search to /x-search" } }); + if (req.method === "GET" && path === "/youtube/openapi.json") { + send(res, { status: 200, body: YOUTUBE_OPENAPI }); + return; + } + const xRoutes: Record<string, (raw: string, signal: AbortSignal) => Promise<Reply>> = { + "/x-search": (raw, signal) => handleXSearch(raw, xSearch, signal), + "/x-post": (raw, signal) => handleXPost(raw, xPost, signal), + "/x-user": (raw, signal) => handleXUser(raw, xUser, signal), + "/x-trends": (raw, signal) => handleXTrends(raw, xTrends, signal), + "/youtube-transcript": (raw, signal) => handleTranscript(raw, youtubeTranscript, signal), + }; + const xRoute = xRoutes[path ?? ""]; + if (req.method !== "POST" || (path !== "/" && path !== "/search" && !xRoute)) { + send(res, { status: 404, body: { error: "POST a search to / or /search, an X read to /x-search, /x-post, /x-user or /x-trends, or a YouTube link to /youtube-transcript" } }); return; } // Stop the search, and free its tab, if the client goes away first. @@ -217,16 +401,9 @@ const main = (): void => { return; } const started = Date.now(); - const reply = isX - ? await handleXSearch(raw, xSearch, controller.signal) - : await handleSearch(raw, runSearch, controller.signal); - const outcome = - reply.status !== 200 - ? `error ${reply.status}` - : isX - ? `${(reply.body as { posts: unknown[] }).posts.length} posts` - : `${(reply.body as unknown[]).length} results`; - console.log(`${isX ? "x-search" : "search"} ${outcome} in ${Date.now() - started} ms`); + const reply = xRoute ? await xRoute(raw, controller.signal) : await handleSearch(raw, runSearch, controller.signal); + const outcome = reply.status !== 200 ? `error ${reply.status}` : xRoute ? "ok" : `${(reply.body as unknown[]).length} results`; + console.log(`${xRoute ? path!.slice(1) : "search"} ${outcome} in ${Date.now() - started} ms`); if (reply.status !== 200) console.log(` ${(reply.body as { error: string }).error}`); send(res, reply); }); |
