import type { ChatCompletionTool } from "openai/resources/chat/completions"; import z from "zod"; import { bot } from "../core"; import { compactPost, resolvePostUri } from "./bsky"; const MAX_REPLIES = 40; export const validator = z.object({ post: z.string().describe("The at:// URI or bsky.app URL of the post."), depth: z.number().int().min(1).max(10).optional().describe( "How many levels of replies to include. Defaults to 3.", ), }); export const definition: ChatCompletionTool = { type: "function", function: { name: "get_thread", description: "Fetches the replies to a post as a tree. Use it to summarize what people are saying or arguing about in the replies.", parameters: z.toJSONSchema(validator), }, }; type Node = { type?: string; post?: any; replies?: Node[] }; export async function handler(args: z.infer) { const uri = await resolvePostUri(args.post); const { data } = await bot.agent.get("app.bsky.feed.getPostThread", { params: { uri: uri as any, depth: args.depth ?? 3, parentHeight: 0 }, }); let remaining = MAX_REPLIES; const walk = (node: Node): any => { if (!node.post) return undefined; const replies: any[] = []; for (const reply of node.replies ?? []) { if (remaining <= 0) break; remaining--; const child = walk(reply); if (child) replies.push(child); } return { ...compactPost(node.post), ...(replies.length && { replies }) }; }; const root = walk(data.thread as Node); if (!root) throw new Error("Post not found or not viewable"); return root; }