@deepagents/toolbox 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/lib/container.ts", "../src/lib/ddg-search.ts", "../src/lib/ddg-stocks.ts", "../src/lib/scratchbad.ts", "../../agent/src/lib/agent.ts", "../../agent/src/lib/prompts.ts", "../../agent/src/lib/stream_utils.ts", "../../agent/src/lib/visualize.ts", "../../agent/src/lib/swarm.ts", "../../agent/src/lib/models.ts", "../src/lib/weather.ts", "../src/lib/web-search.ts", "../src/lib/user-story-formatter.ts", "../src/lib/hackernews-search.ts"],
4
- "sourcesContent": ["import { tool } from 'ai';\nimport spawn from 'nano-spawn';\nimport { z } from 'zod';\n\nexport const execute_os_command = tool({\n description:\n 'Tool to execute Linux commands in an isolated Docker container with Node.js runtime. Use when you need OS operations like file management, package installation, network requests, or system commands.',\n inputSchema: z.object({\n command: z\n .array(z.string().min(1, 'Command parts cannot be empty'))\n .min(1, 'At least one command part is required')\n .max(20, 'Command cannot exceed 20 parts for security')\n .describe(\n 'Command and arguments as array. Examples: [\"ls\", \"-la\"], [\"npm\", \"install\", \"lodash\"], [\"curl\", \"-s\", \"https://api.github.com\"], [\"node\", \"--version\"]',\n ),\n working_directory: z\n .string()\n .regex(/^\\/[a-zA-Z0-9_/.,-]*$/, 'Must be a valid absolute Linux path')\n .optional()\n .describe(\n 'Absolute working directory path. Examples: \"/tmp\", \"/workspace\", \"/app\". Defaults to container root.',\n ),\n environment_vars: z\n .record(\n z.string().min(1, 'Environment variable values cannot be empty'),\n z.string(),\n )\n .optional()\n .describe(\n 'Environment variables as key-value pairs. Examples: {\"NODE_ENV\": \"development\", \"API_KEY\": \"secret123\"}',\n ),\n }),\n execute: ({ command, working_directory, environment_vars }) => {\n return exec(command, working_directory, environment_vars);\n },\n});\n\nfunction exec(\n command: string[],\n working_directory?: string,\n environment_vars?: Record<string, string>,\n) {\n const args = ['exec', '-i'];\n\n if (working_directory) {\n args.push('-w', working_directory);\n }\n\n if (environment_vars) {\n Object.entries(environment_vars).forEach(([key, value]) => {\n args.push('-e', `${key}=${value}`);\n });\n }\n\n args.push('toolos', ...command);\n\n return spawn('docker', args, {\n stdio: 'pipe',\n });\n}\n", "import { tool } from 'ai';\nimport * as ddg from 'duck-duck-scrape';\nimport { uniqBy } from 'lodash-es';\nimport { z } from 'zod';\n\nexport type Source = 'text' | 'news' | 'images';\n\nexport async function serp({\n query,\n source,\n locale = 'en-us',\n maxResults = 50,\n ...input\n}: z.input<typeof ddgSearchSchema>) {\n const safeSearch =\n ddg.SafeSearchType[\n 'STRICT'\n // input.safesearch.toUpperCase() as keyof typeof ddg.SafeSearchType\n ];\n const time =\n ddg.SearchTimeType[\n (input.time || 'y')?.toUpperCase() as keyof typeof ddg.SearchTimeType\n ];\n\n if (source === 'text') {\n const res = await ddg.search(\n query,\n {\n region: 'wt-wt',\n safeSearch,\n time,\n locale,\n },\n {\n uri_modifier: (rawUrl: string) => {\n const url = new URL(rawUrl);\n url.searchParams.delete('ss_mkt');\n return url.toString();\n },\n },\n );\n const items = res.results.slice(0, maxResults).map((r) => ({\n snippet: r.description,\n title: r.title,\n link: r.url,\n hostname: r.hostname,\n }));\n return { items, total: res.results.length, vqd: res.vqd } as const;\n }\n\n if (source === 'news') {\n const res = await ddg.searchNews(query, {\n safeSearch,\n time,\n });\n const items = res.results.slice(0, maxResults).map((r) => ({\n snippet: r.excerpt,\n title: r.title,\n link: r.url,\n date: r.date, // epoch ms\n source: r.syndicate,\n image: r.image,\n relativeTime: r.relativeTime,\n }));\n return { items, total: res.results.length, vqd: res.vqd } as const;\n }\n\n const res = await ddg.searchImages(query, { safeSearch });\n const items = res.results.slice(0, maxResults).map((r) => ({\n title: r.title,\n thumbnail: r.thumbnail,\n image: r.image,\n link: r.url,\n height: r.height,\n width: r.width,\n source: r.source,\n }));\n return { items, total: res.results.length, vqd: res.vqd } as const;\n}\n\nasync function performSearch(query: string) {\n const results = await serp({\n source: 'news',\n query: query,\n });\n const result = uniqBy(results.items as { link: string }[], (it) => it.link);\n return result as typeof results.items;\n}\n\nexport const ddgSearchSchema = z.object({\n query: z.string().min(1),\n source: z.enum(['text', 'news', 'images']).default('text'),\n locale: z.string().optional().default('en-us'),\n // region: z.string().default('wt-wt'),\n // safesearch: z.enum(['strict', 'moderate', 'off']).default('moderate'),\n time: z.enum(['d', 'w', 'm', 'y']).optional().default('y'),\n maxResults: z.number().int().positive().max(50).default(5),\n});\nexport const duckDuckGoSearch = tool({\n description:\n 'A tool for searching the web. Useful for when you need to find information about current events or topics that are not covered in your training data.',\n inputSchema: ddgSearchSchema,\n execute: serp,\n});\n", "import { tool } from 'ai';\nimport { stocks as ddgStocks } from 'duck-duck-scrape';\nimport { z } from 'zod';\n\ntype Quote = {\n symbol: string;\n name: string | null;\n exchange: string | null;\n currency: string | null;\n last: number | null;\n change: number | null;\n percentChange: number | null;\n open: number | null;\n high: number | null;\n low: number | null;\n prevClose: number | null;\n volume: number | null;\n date: string | null; // ET\n time: string | null; // ET\n halted: boolean | null;\n source: 'DuckDuckGo/Xignite';\n raw?: unknown; // optional raw for debugging\n};\n\nconst toQuote = (r: any): Quote => ({\n symbol: r?.Security?.Symbol ?? null,\n name: r?.Security?.Name ?? null,\n exchange: r?.Security?.Market ?? null,\n currency: r?.Currency ?? null,\n last: r?.Last ?? null,\n change: r?.ChangeFromPreviousClose ?? null,\n percentChange: r?.PercentChangeFromPreviousClose ?? null,\n open: r?.Open ?? null,\n high: r?.High ?? null,\n low: r?.Low ?? null,\n prevClose: r?.PreviousClose ?? null,\n volume: r?.Volume ?? null,\n date: r?.Date ?? null,\n time: r?.Time ?? null,\n halted: r?.TradingHalted ?? null,\n source: 'DuckDuckGo/Xignite',\n raw: r,\n});\n\nexport const duckStocks = tool({\n description: 'A tool for fetching stock market quotes. Useful for when you need to get the latest stock price and related information for one or more stock symbols.',\n inputSchema: z.object({\n symbols: z\n .union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .transform((s) => (Array.isArray(s) ? s : [s])),\n includeRaw: z.boolean().default(false),\n }),\n execute: async ({ symbols, includeRaw }) => {\n const tasks = symbols.map(async (s) => {\n const sym = s.trim().toUpperCase();\n try {\n const r = await ddgStocks(sym);\n if (!r || (r.Outcome && r.Outcome !== 'Success')) {\n return { symbol: sym, error: r?.Message || 'No quote' };\n }\n const q = toQuote(r);\n if (!includeRaw) delete q.raw;\n return q;\n } catch (e: any) {\n return { symbol: sym, error: e?.message || 'fetch_failed' };\n }\n });\n const results = await Promise.all(tasks);\n return { results };\n },\n});\n", "import { tool } from 'ai';\nimport z from 'zod';\n\nimport { toState } from '@deepagents/agent';\n\nexport const scratchpad_tool = tool({\n description: `Tool for strategic reflection on research progress and decision-making.\n\n Use this tool after each search to analyze results and plan next steps systematically.\n This creates a deliberate pause in the research workflow for quality decision-making.\n\n When to use:\n - After receiving search results: What key information did I find?\n - Before deciding next steps: Do I have enough to answer comprehensively?\n - When assessing research gaps: What specific information am I still missing?\n - Before concluding research: Can I provide a complete answer now?\n\n Reflection should address:\n 1. Analysis of current findings - What concrete information have I gathered?\n 2. Gap assessment - What crucial information is still missing?\n 3. Quality evaluation - Do I have sufficient evidence/examples for a good answer?\n 4. Strategic decision - Should I continue searching or provide my answer?\n`,\n inputSchema: z.object({\n reflection: z\n .string()\n .describe('Your detailed reflection on research progress.'),\n }),\n execute: async ({ reflection }, options) => {\n const context = toState<{ scratchpad: string }>(options);\n context.scratchpad += `- ${reflection}\\n`;\n return `Reflection recorded. Current scratchpad now:\\n---\\n${context.scratchpad}`;\n },\n});\n", "import {\n type GenerateTextResult,\n type LanguageModel,\n type ModelMessage,\n Output,\n type StreamTextResult,\n type ToolChoice,\n type ToolSet,\n type UIDataTypes,\n type UIMessage,\n type UITools,\n dynamicTool,\n generateText,\n jsonSchema,\n stepCountIs,\n tool,\n} from 'ai';\nimport chalk from 'chalk';\nimport { snakecase } from 'stringcase';\nimport z from 'zod';\n\nimport {\n RECOMMENDED_PROMPT_PREFIX,\n SUPERVISOR_PROMPT_PREFIX,\n} from './prompts.ts';\nimport { toState } from './stream_utils.ts';\nimport { prepareStep } from './swarm.ts';\n\nexport interface Handoff<C> {\n name: string;\n instructions: Instruction<C>;\n handoffDescription?: string;\n tools: ToolSet;\n}\nexport type Handoffs<C> = (Agent<unknown, C> | (() => Agent<unknown, C>))[];\n\nexport type Runner<T, C> = (\n prompt: string,\n agent: Agent<C>,\n messages: ModelMessage[],\n) => Promise<T>;\n\ntype transfer_tool = `transfer_to_${string}`;\n\nexport type ContextVariables = Record<string, unknown>;\n\nexport function agent<Output, C = ContextVariables>(\n config: CreateAgent<Output, C>,\n): Agent<Output, C> {\n return new Agent<Output, C>(config);\n}\n\nexport type ResponseMessage = UIMessage<unknown, UIDataTypes, UITools>;\n\nexport type AgentModel = Exclude<LanguageModel, string>;\nexport type OutputExtractorFn = (\n output: GenerateTextResult<ToolSet, any>,\n) => string | Promise<string>;\nexport type PrepareHandoffFn = (\n messages: ModelMessage[],\n) => void | Promise<void>;\nexport type PrepareEndFn<C, O> = (config: {\n messages: ResponseMessage[];\n responseMessage: ResponseMessage;\n contextVariables: C;\n abortSignal?: AbortSignal;\n}) => StreamTextResult<ToolSet, O> | undefined | void;\n\nexport interface CreateAgent<Output, C> {\n name: string;\n prompt: Instruction<C>;\n temperature?: number;\n handoffDescription?: string;\n prepareHandoff?: PrepareHandoffFn;\n prepareEnd?: PrepareEndFn<C, Output>;\n handoffs?: Handoffs<C>;\n tools?: ToolSet;\n model: AgentModel;\n toolChoice?: ToolChoice<Record<string, unknown>>;\n output?: z.Schema<Output>;\n providerOptions?: Parameters<typeof generateText>[0]['providerOptions'];\n}\nexport class Agent<Output = unknown, C = ContextVariables> {\n model: AgentModel;\n toolChoice: ToolChoice<Record<string, unknown>> | undefined;\n parent?: Agent<unknown, C>;\n handoffs: Handoffs<C>;\n readonly prepareHandoff?: PrepareHandoffFn;\n readonly prepareEnd?: PrepareEndFn<C, Output>;\n readonly internalName: string;\n readonly handoff: Handoff<C>;\n readonly handoffToolName: transfer_tool;\n readonly handoffTool: ToolSet;\n readonly output?: z.Schema<Output>;\n readonly temperature?: number;\n readonly providerOptions?: CreateAgent<Output, C>['providerOptions'];\n constructor(config: CreateAgent<Output, C>) {\n this.model = config.model;\n this.toolChoice = config.toolChoice || 'auto';\n this.handoffs = config.handoffs ?? [];\n this.prepareHandoff = config.prepareHandoff;\n this.prepareEnd = config.prepareEnd;\n this.output = config.output;\n this.temperature = config.temperature;\n this.internalName = snakecase(config.name);\n this.providerOptions = config.providerOptions;\n this.handoff = {\n name: this.internalName,\n instructions: config.prompt,\n tools: config.tools ?? {},\n handoffDescription: config.handoffDescription,\n };\n this.handoffToolName = `transfer_to_${this.internalName}`;\n this.handoffTool = {\n [this.handoffToolName]: dynamicTool({\n description: [\n `An input/parameter/argument less tool to transfer control to the ${this.internalName} agent.`,\n // `Handoff to the ${this.internalName} agent to handle the request`,\n // `Do not include any parameters/inputs. The agent have access to all the context it needs.`,\n config.handoffDescription,\n ]\n .filter(Boolean)\n .join(' '),\n inputSchema: jsonSchema({\n type: 'object',\n properties: {},\n additionalProperties: true,\n }),\n execute: async (_, options) => {\n const state = toState(options) as any;\n state.currentActiveAgent = this.internalName;\n return `Transfer successful to ${this.internalName}.`;\n },\n }),\n };\n }\n\n get transfer_tools() {\n return Object.fromEntries(\n this.toHandoffs().flatMap((it) => Object.entries(it.handoffTool)),\n );\n }\n\n get toolsNames() {\n return [\n // Note: do not add the handoff tool itself otherwise it'd create a agent recursion/loop\n ...Object.keys(this.transfer_tools),\n ...Object.keys(this.handoff.tools),\n ];\n }\n\n #prepareInstructions(contextVariables?: C) {\n return [\n typeof this.handoff.instructions === 'function'\n ? this.handoff.instructions(contextVariables)\n : Array.isArray(this.handoff.instructions)\n ? this.handoff.instructions.join('\\n')\n : this.handoff.instructions,\n '',\n '',\n ].join('\\n');\n }\n\n instructions(contextVariables?: C) {\n const text = this.#prepareInstructions(contextVariables);\n const handoffsData = this.toHandoffs();\n\n if (handoffsData.length === 0) {\n return text.replace('<specialized_agents_placeholder>', ' ');\n }\n\n const handoffs = [\n '## Specialized Agents',\n\n '| Agent Name | Agent Description |',\n '| --- | --- |',\n ...handoffsData.map(\n (hf) =>\n `| ${hf.handoff.name} | ${hf.handoff.handoffDescription || 'No description available'} |`,\n ),\n '',\n '',\n ].join('\\n');\n\n return text.replace('<specialized_agents_placeholder>', handoffs);\n }\n\n toHandoffs() {\n const hfs: Agent<unknown, C>[] = [];\n for (const it of this.handoffs ?? []) {\n const hf = typeof it === 'function' ? it() : it;\n hf.parent = this;\n hfs.push(hf);\n }\n return hfs;\n }\n\n asTool(props?: {\n toolDescription?: string;\n outputExtractor?: OutputExtractorFn;\n }) {\n return tool({\n description: props?.toolDescription || this.handoff.handoffDescription,\n inputSchema: z.object({\n input: z.string(),\n output: z\n .string()\n .optional()\n .describe(\n 'Optional instructions on how the final output should be formatted. this would be passed to the underlying llm as part of the prompt.',\n ),\n }),\n execute: async ({ input, output }, options) => {\n try {\n const result = await generateText({\n model: this.model!,\n system: this.#prepareInstructions(),\n prompt: `\n <Input>\n ${input}\n </Input>\n ${output ? `<OutputInstructions>\\n${output}\\n</OutputInstructions>` : ''}\n `,\n temperature: 0,\n tools: this.handoff.tools,\n abortSignal: options.abortSignal,\n stopWhen: stepCountIs(25),\n experimental_context: options.experimental_context,\n experimental_output: this.output\n ? Output.object({ schema: this.output })\n : undefined,\n onStepFinish: (step) => {\n const toolCall = step.toolCalls.at(-1);\n if (toolCall) {\n console.log(\n `Debug: ${chalk.yellow('ToolCalled')}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`,\n );\n }\n },\n prepareStep: prepareStep(\n this,\n this.model!,\n options.experimental_context,\n ),\n });\n if (props?.outputExtractor) {\n return await props.outputExtractor(result);\n }\n return result.steps.map((it) => it.toolResults).flat();\n } catch (error) {\n console.error(error);\n return `An error thrown from a tool call. \\n<ErrorDetails>\\n${JSON.stringify(error)}\\n</ErrorDetails>`;\n }\n },\n });\n }\n\n toTool(props?: {\n toolDescription?: string;\n outputExtractor?: OutputExtractorFn;\n }) {\n return { [this.handoffToolName]: this.asTool(props) };\n }\n\n debug(prefix = '') {\n console.log(\n `Debug: ${chalk.bgMagenta('Agent')}: ${chalk.dim.black(this.handoff.name)}`,\n );\n // console.log(\n // `Debug: ${chalk.blue('Tools')}: ${Object.keys(toToolset(agent))}`,\n // );\n const transferTools = this.toolsNames\n .filter((toolName) => toolName.startsWith('transfer_to'))\n .map((toolName) => toolName.replace('transfer_to_', ''));\n const agentTools = this.toolsNames.filter(\n (toolName) => !toolName.startsWith('transfer_to'),\n );\n console.log(\n `Debug: ${chalk.blue('TransferTools')}: ${transferTools.length ? transferTools : 'None'}`,\n );\n console.log(\n `Debug: ${chalk.blue('Agent Tools')}: ${agentTools.length ? agentTools : 'None'}`,\n );\n // if (!isEmpty(agent.handoff.handoffs)) {\n // console.log(`${prefix}Handoffs:`);\n // for (const handoff of agent.handoff.handoffs) {\n // debugAgent(handoff, `${prefix} `);\n // }\n // }\n }\n\n toToolset(options?: {\n includeTransferTool?: boolean;\n includeHandoffs?: boolean;\n }): ToolSet {\n const tools = flattenTools(\n this as Agent<unknown, C>,\n (node) => node.toHandoffs(),\n (node) => node.handoff.tools,\n );\n\n return {\n ...Object.fromEntries(tools.flatMap((it) => Object.entries(it))),\n ...(options?.includeTransferTool !== false ? this.transfer_tools : {}),\n ...(options?.includeHandoffs !== false ? this.handoffTool : {}),\n };\n }\n\n clone(\n agent?: Omit<Partial<CreateAgent<Output, C>>, 'handoffs'>,\n ): Agent<Output, C> {\n return new Agent<Output, C>({\n prepareHandoff: (messages) => {\n this.prepareHandoff?.(messages);\n },\n model: agent?.model ?? this.model,\n toolChoice: agent?.toolChoice ?? this.toolChoice,\n prompt: agent?.prompt ?? this.handoff.instructions,\n tools: agent?.tools ?? this.handoff.tools,\n name: agent?.name ?? this.handoff.name,\n handoffDescription:\n agent?.handoffDescription ?? this.handoff.handoffDescription,\n handoffs: [...this.handoffs],\n output: agent?.output ?? this.output,\n });\n }\n}\n\nfunction flattenTools<T, R>(\n root: T,\n getChildren: (node: T) => T[],\n extract: (node: T) => R,\n): R[] {\n const stack: T[] = [root];\n const visited = new Set<T>();\n const result: R[] = [];\n\n while (stack.length) {\n const node = stack.pop()!;\n if (visited.has(node)) continue;\n visited.add(node);\n result.push(extract(node));\n stack.push(...getChildren(node));\n }\n\n return result;\n}\n\nexport type Instruction<C> =\n | string\n | string[]\n | ((contextVariables?: C) => string);\n\nexport interface PurposeRoutineInstructions {\n purpose: string | string[];\n routine: string[];\n}\n\nexport function instructions({ purpose, routine }: PurposeRoutineInstructions) {\n const lines = [\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n '',\n '<specialized_agents_placeholder>',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task.`,\n `# Routine`,\n ...routine.map((it, i) => `${i + 1}. ${it}`),\n );\n }\n\n return lines.join('\\n');\n}\n\ninstructions.swarm = ({ purpose, routine }: PurposeRoutineInstructions) => {\n const lines = [\n RECOMMENDED_PROMPT_PREFIX,\n '',\n '',\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n '',\n '<specialized_agents_placeholder>',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task.`,\n `# Routine`,\n ...routine.map((it, i) => `${i + 1}. ${it}`),\n );\n }\n\n return lines.join('\\n');\n};\n\ninstructions.supervisor = ({\n purpose,\n routine,\n}: PurposeRoutineInstructions) => {\n const lines = [\n SUPERVISOR_PROMPT_PREFIX,\n '',\n '',\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n '',\n '<specialized_agents_placeholder>',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task.`,\n `# Routine`,\n ...routine.filter(Boolean).map((it, i) => `${i + 1}. ${it}`),\n );\n }\n\n return lines.join('\\n');\n};\n\ninstructions.supervisor_subagent = ({\n purpose,\n routine,\n}: PurposeRoutineInstructions) => {\n const lines = [\n SUPERVISOR_PROMPT_PREFIX,\n '',\n '',\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task. Execute ALL steps immediately.`,\n `# Routine`,\n ...routine.map((it, i) => `${i + 1}. ${it}`),\n `${routine.length + 1}. transfer_to_supervisor_agent`,\n // `1. IMMEDIATELY START: ${routine[0]}`,\n // ...routine.slice(1).map((it, i) => `${i + 2}. ${it}`),\n // `${routine.length + 1}. STOP HERE - Do not do any other agent's work`,\n // `${routine.length + 2}. MANDATORY: You MUST call transfer_to_supervisor_agent function RIGHT NOW to return control`,\n // `${routine.length + 3}. DO NOT END YOUR RESPONSE WITHOUT CALLING THE TRANSFER FUNCTION`,\n );\n } else {\n lines.push(\n 'CRITICAL: end the generation by calling transfer_to_supervisor_agent tool',\n );\n }\n\n return lines.join('\\n');\n};\n\ntype TransferResult = { lastActiveAgent: string; currentActiveAgent: string };\nexport type TransferTool = { output: TransferResult };\nexport function isTransferToolResult(\n call: unknown | undefined,\n): call is TransferTool {\n if (!call) {\n return false;\n }\n if (typeof call !== 'object') {\n return false;\n }\n if (!('output' in call)) {\n return false;\n }\n const lastActiveAgent = (call.output as Record<string, string>)\n .lastActiveAgent;\n\n if (!lastActiveAgent) {\n return false;\n }\n return true;\n}\n\nexport function lastTransferResult(messages: ResponseMessage[]) {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n for (let i = message.parts.length - 1; i >= 0; i--) {\n const part = message.parts[i];\n if (\n part.type === 'dynamic-tool' &&\n part.toolName.startsWith('transfer_to_') &&\n part.state === 'output-available' &&\n isTransferToolResult(part)\n ) {\n return part.output;\n }\n }\n }\n return undefined;\n}\n", "import dedent from 'dedent';\n\nexport const RECOMMENDED_PROMPT_PREFIX = [\n `# System context`,\n `You are part of a multi-agent system called the DeepAgents SDK, designed to make agent coordination and execution easy.`,\n `Agents uses two primary abstraction: **Agents** and **Handoffs**.`,\n `An agent encompasses instructions and tools and can hand off a conversation to another agent when appropriate.`,\n `Handoffs are achieved by calling a handoff function, generally named \\`transfer_to_<agent_name>\\`.`,\n `Transfers between agents are handled seamlessly in the background; do not mention or draw attention to these transfers in your conversation with the user.`,\n // 'Do not pass context between agents. the agents already have the complete context without agent to agent communication.',\n\n // From 4.1 beast mode\n // `Please keep going until the user\u2019s query is completely resolved, before ending your turn and yielding back to the user.`,\n // `Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough.`,\n // `You MUST iterate and keep going until the problem is solved.`,\n // `You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me.`,\n // `Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.`,\n // `Always tell the user what you are going to do before making a tool call with a single concise sentence. This will help them understand what you are doing and why.`,\n // `If the user request is \"resume\" or \"continue\" or \"try again\", check the previous conversation history to see what the next incomplete step in the todo list is. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all items are checked off. Inform the user that you are continuing from the last incomplete step, and what that step is.`,\n // `Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Use the sequential thinking tool if available. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.`,\n // `You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.`,\n // `You MUST keep working until the problem is completely solved, and all items in the todo list are checked off. Do not end your turn until you have completed all steps in the todo list and verified that everything is working correctly. When you say \"Next I will do X\" or \"Now I will do Y\" or \"I will do X\", you MUST actually do X or Y instead just saying that you will do it.`,\n // `You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input.`,\n].join('\\n');\n\nexport const SUPERVISOR_PROMPT_PREFIX = dedent`\n# System Context\nYou are part of a multi-agent system called the DeepAgents SDK, designed to facilitate agent coordination and execution.\n\n- The primary agent, known as the \"Supervisor Agent,\" coordinates communication between specialized agents. The Supervisor Agent does not perform specialized tasks but acts as the central point for communication.\n- Specialized agents must transfer control back to the Supervisor Agent upon completing their tasks.\n\n**Core Directives:**\n- Begin with a concise checklist (3-7 bullets) of what you will do for each user query; items should be conceptual, not implementation-level.\n- Continue working until the user's query is completely resolved; only then yield control back to the user.\n- Your thinking must be thorough and step-by-step. Aim for completeness and rigor while avoiding unnecessary repetition and verbosity.\n- You must iterate and keep working until the problem is fully solved. You have all the requirements and information needed; solve the problem autonomously without user intervention.\n- Do not terminate your turn unless you are certain all issues are resolved and the entire todo list is complete and verified.\n- When making tool calls, explicitly state, in a single concise sentence, the purpose and minimal inputs for the action before executing it.\n- After each tool call or code edit, validate the result in 1-2 lines and proceed or self-correct if validation fails.\n- For requests such as \"resume\", \"continue\", or \"try again\":\n - Check previous conversation history to determine the next incomplete todo step, continue from there, and do not return control until all items are complete.\n - Inform the user you are resuming from the last incomplete step, and specify what that step is.\n- Take your time and rigorously check your solution, especially edge and boundary cases. Use sequential thinking tools when available. Your solution must be robust and perfect; continue iterating and retesting as needed.\n- Always test your code using all available tools and provided tests, with repetition as necessary to catch edge cases.\n- Plan extensively before each function/tool call and reflect thoroughly on previous actions before proceeding. Do not proceed solely by chaining function calls\u2014use stepwise planning and reflection.\n- Explicitly complete every todo list item and confirm all steps are working before ending your turn. Always follow through on stated actions.\n- You are a highly capable, autonomous agent, and should not require additional user input to fully solve the task.\n`;\n", "import {\n type GenerateTextResult,\n type InferUIMessageChunk,\n type StreamTextResult,\n type ToolCallOptions,\n type ToolSet,\n type UIDataTypes,\n type UIMessage,\n type UITools,\n generateId,\n} from 'ai';\nimport { flow } from 'lodash-es';\nimport { createWriteStream } from 'node:fs';\nimport { createInterface } from 'node:readline/promises';\nimport { Readable } from 'node:stream';\nimport { isPromise } from 'node:util/types';\n\nimport {\n visualizeMermaid,\n visualizeRichSemantic,\n visualizeSemantic,\n} from './visualize.ts';\n\nexport async function streamWrite(response: StreamTextResult<ToolSet, never>) {\n response.consumeStream();\n const writeStream = createWriteStream('blog_writer_output.md');\n Readable.fromWeb(response.textStream as any).pipe(writeStream);\n\n // for await (const chunk of response.toUIMessageStream()) {\n // if (chunk.type === 'reasoning-start') {\n // writeStream.write('\\n# reasoning\\n');\n // }\n // if (chunk.type === 'reasoning-delta') {\n // writeStream.write(chunk.delta);\n // }\n // if (chunk.type === 'reasoning-end') {\n // writeStream.write('\\n# /reasoning\\n');\n // }\n // if (chunk.type === 'text-start') {\n // writeStream.write('\\n# text\\n');\n // }\n // if (chunk.type === 'text-delta') {\n // writeStream.write(chunk.delta);\n // }\n // if (chunk.type === 'text-end') {\n // writeStream.write('\\n# /text\\n');\n // }\n // }\n console.log(await response.totalUsage);\n}\n\nfunction printChunk(\n chunk: InferUIMessageChunk<UIMessage<unknown, UIDataTypes, UITools>>,\n options: { reasoning: boolean; wrapInTags: boolean; text: boolean },\n) {\n const {\n reasoning: includeReasoning,\n wrapInTags,\n text: includeText,\n } = options;\n if (includeReasoning) {\n if (chunk.type === 'reasoning-start') {\n process.stdout.write(`\\n${wrapInTags ? '<reasoning>' : ''}\\n`);\n }\n if (chunk.type === 'reasoning-delta') {\n process.stdout.write(chunk.delta);\n }\n if (chunk.type === 'reasoning-end') {\n process.stdout.write(`\\n${wrapInTags ? '</reasoning>' : ''}\\n`);\n }\n }\n if (includeText) {\n if (chunk.type === 'text-start') {\n process.stdout.write(`\\n${wrapInTags ? '<text>' : ''}\\n`);\n }\n if (chunk.type === 'text-delta') {\n process.stdout.write(chunk.delta);\n }\n if (chunk.type === 'text-end') {\n process.stdout.write(`\\n${wrapInTags ? '</text>' : ''}\\n`);\n }\n }\n}\n\nexport const printer = {\n readableStream: async (\n stream: ReadableStream<\n InferUIMessageChunk<UIMessage<unknown, UIDataTypes, UITools>>\n >,\n options?: { reasoning?: boolean; wrapInTags?: boolean; text?: boolean },\n ) => {\n const includeReasoning = options?.reasoning ?? true;\n const wrapInTags = options?.wrapInTags ?? true;\n const includeText = options?.text ?? true;\n for await (const chunk of stream as any) {\n printChunk(chunk, {\n reasoning: includeReasoning,\n wrapInTags,\n text: includeText,\n });\n }\n },\n stdout: async (\n response: StreamTextResult<ToolSet, unknown>,\n options?: { reasoning?: boolean; text?: boolean; wrapInTags?: boolean },\n ) => {\n const includeReasoning = options?.reasoning ?? true;\n const includeText = options?.text ?? true;\n const wrapInTags = options?.wrapInTags ?? true;\n for await (const chunk of response.toUIMessageStream()) {\n printChunk(chunk, {\n reasoning: includeReasoning,\n text: includeText,\n wrapInTags,\n });\n }\n console.log(await response.totalUsage);\n },\n mermaid: flow(visualizeMermaid, console.log),\n semantic: flow(visualizeSemantic, console.log),\n richSemantic: flow(visualizeRichSemantic, console.log),\n};\n\nexport function messageToUiMessage(message: string): UIMessage {\n return {\n id: generateId(),\n role: 'user',\n parts: [\n {\n type: 'text',\n text: message,\n },\n ],\n };\n}\nexport const user = messageToUiMessage;\n\nexport async function input(defaultValue?: string): Promise<string> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n const answer = await rl.question(\n `Please enter your input${defaultValue ? ` (default: ${defaultValue})` : ''}: `,\n );\n rl.close();\n return answer || defaultValue || '';\n}\n\nexport async function confirm(\n message: string,\n defaultValue = true,\n): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const defaultText = defaultValue ? 'Y/n' : 'y/N';\n\n while (true) {\n const answer = await rl.question(`${message} (${defaultText}): `);\n const normalized = answer.toLowerCase().trim();\n\n // If empty answer, use default\n if (normalized === '') {\n rl.close();\n return defaultValue;\n }\n\n if (normalized === 'y' || normalized === 'yes') {\n rl.close();\n return true;\n } else if (normalized === 'n' || normalized === 'no') {\n rl.close();\n return false;\n } else {\n console.log(\n 'Please answer with y/yes or n/no (or press Enter for default)',\n );\n }\n }\n}\n\nexport async function last<T>(iterable: AsyncIterable<T>, position = -1) {\n const arr = await Array.fromAsync(iterable);\n return arr.at(position)!;\n}\nexport async function finished<T>(iterable: AsyncIterable<T>) {\n await Array.fromAsync(iterable);\n}\n\nexport function toOutput<T>(\n result:\n | Promise<GenerateTextResult<ToolSet, T>>\n | StreamTextResult<ToolSet, T>,\n) {\n return isPromise(result)\n ? result.then((res) => res.experimental_output)\n : last(result.experimental_partialOutputStream);\n}\n\nexport function toState<C>(options: ToolCallOptions) {\n return options.experimental_context as C;\n}\n", "import { titlecase } from 'stringcase';\n\nimport type { Agent } from './agent.ts';\n\nexport type VisualizeOptions = {\n direction?: 'LR' | 'TB' | 'BT' | 'RL';\n showTools?: boolean;\n};\n\ntype Node = {\n id: string;\n name: string;\n tools: string[];\n};\n\ntype Edge = {\n from: string; // node id\n to: string; // node id\n label: string; // e.g., transfer_to_X\n};\n\n/**\n * Build a minimal Mermaid flowchart to visualize agents, their local tools, and handoff transfers.\n *\n * - Agent nodes include their name and (optionally) their tool names.\n * - Edges represent transfer tools (handoffs) from one agent to another, labeled by the transfer tool name.\n */\nexport function visualizeMermaid(\n root: Agent<any>,\n options: VisualizeOptions = {},\n): string {\n const { direction = 'LR', showTools = true } = options;\n\n const nodes: Node[] = [];\n const edges: Edge[] = [];\n\n const seen = new Set<string>();\n const nameToId = new Map<string, string>();\n\n const sanitizeId = (name: string) =>\n name\n .toLowerCase()\n .replace(/[^a-z0-9]+/gi, '_')\n .replace(/^_+|_+$/g, '');\n\n const ensureNode = (agent: Agent) => {\n const name = agent.handoff.name;\n if (!nameToId.has(name)) {\n // Guarantee unique ids even if sanitize collides\n const base = sanitizeId(name) || 'agent';\n let id = base;\n let i = 1;\n while (nodes.some((n) => n.id === id)) id = `${base}_${i++}`;\n nameToId.set(name, id);\n\n nodes.push({\n id,\n name,\n tools: Object.keys(agent.handoff.tools ?? {}),\n });\n }\n return nameToId.get(name)!;\n };\n\n const stack: Agent[] = [root];\n while (stack.length) {\n const current = stack.pop()!;\n const currentName = current.handoff.name;\n if (seen.has(currentName)) continue;\n seen.add(currentName);\n\n const fromId = ensureNode(current);\n\n for (const child of current.toHandoffs()) {\n const toId = ensureNode(child);\n // Prefer the child's declared handoff tool key (usually transfer_to_{childName})\n const label = Object.keys(child.handoffTool)[0].replace(\n /transfer_to_/g,\n '',\n );\n edges.push({ from: fromId, to: toId, label });\n stack.push(child);\n }\n }\n\n const lines: string[] = [];\n lines.push(`flowchart ${direction}`);\n\n // Nodes\n for (const n of nodes) {\n const name = titlecase(n.name.replace(/_agent/g, '').replace(/_/g, ' '));\n const toolLine =\n showTools && n.tools.length\n ? `<br/>tools: ${n.tools.map((it) => it.replace(/transfer_to_/g, '')).join(', ')}`\n : '';\n // Use double quotes for label to allow <br/>\n lines.push(`${n.id}[\"${escapeLabel(`Agent: ${name}${toolLine}`)}\"]`);\n }\n\n // Edges\n for (const e of edges) {\n lines.push(`${e.from} -- ${escapeLabel(e.label)} --> ${e.to}`);\n }\n\n return lines.join('\\n');\n}\n\nfunction escapeLabel(s: string): string {\n // Minimal escaping for quotes in Mermaid node labels\n return s.replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Convenience alias with simpler name.\n */\nexport const visualize = visualizeMermaid;\n\n/**\n * Produce a semantic, human-readable map of transfers between agents.\n * Example lines:\n * supervisor transfers to: agentx, agenty\n * agentx transfers to: supervisor\n */\nexport function visualizeSemantic(root: Agent): string {\n const lines: string[] = [];\n const seen = new Set<string>();\n const stack: Agent[] = [root];\n\n while (stack.length) {\n const current = stack.pop()!;\n const currentName = current.handoff.name;\n if (seen.has(currentName)) continue;\n seen.add(currentName);\n\n const from = current.handoff.name;\n const transfers = current.toHandoffs().map((h) => h.handoff.name);\n const uniqueTransfers = Array.from(new Set(transfers));\n const rhs = uniqueTransfers.length ? uniqueTransfers.join(', ') : 'none';\n lines.push(`${from} transfers to: ${rhs}`);\n\n for (const child of current.toHandoffs()) stack.push(child);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Minimal arrow-based semantic visualizer.\n * Prints one line per transfer using Unicode arrows, e.g.:\n * supervisor \u2500\u2500\u25B6 agentx\n * supervisor \u2500\u2500\u25B6 agenty\n * agentx \u2500\u2500\u25B6 supervisor\n */\nexport function visualizeRichSemantic(root: Agent): string {\n const stack: Agent[] = [root];\n const seen = new Set<string>();\n const edgeSet = new Set<string>();\n const edges: Array<{ from: string; to: string }> = [];\n\n while (stack.length) {\n const current = stack.pop()!;\n const from = current.handoff.name;\n if (!seen.has(from)) {\n seen.add(from);\n for (const child of current.toHandoffs()) {\n const to = child.handoff.name;\n const key = `${from}->${to}`;\n if (!edgeSet.has(key)) {\n edgeSet.add(key);\n edges.push({ from, to });\n }\n stack.push(child);\n }\n }\n }\n\n if (edges.length === 0) return `${root.handoff.name} \u2500\u2500\u25B6 none`;\n return edges.map(({ from, to }) => `${from} \u2500\u2500\u25B6 ${to}`).join('\\n');\n}\n", "import { groq } from '@ai-sdk/groq';\nimport {\n type CoreMessage,\n type ModelMessage,\n NoSuchToolError,\n Output,\n type PrepareStepFunction,\n type PrepareStepResult,\n type StepResult,\n type ToolCallRepairFunction,\n type ToolSet,\n type UIDataTypes,\n type UIMessage,\n type UIMessagePart,\n type UITools,\n convertToModelMessages,\n createUIMessageStream,\n generateId,\n generateText,\n smoothStream,\n stepCountIs,\n streamText,\n wrapLanguageModel,\n} from 'ai';\nimport chalk from 'chalk';\nimport dedent from 'dedent';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\n\nimport {\n type Agent,\n type AgentModel,\n type TransferTool,\n isTransferToolResult,\n} from './agent.ts';\nimport { last, messageToUiMessage, user } from './stream_utils.ts';\n\nexport type OutputMode = 'full_history' | 'last_message';\n\nexport interface ExecuteOptions {\n contextVariables?: Record<string, unknown>;\n systemPrompt?: string;\n abortSignal?: AbortSignal;\n outputMode?: OutputMode;\n}\n\nfunction isToolMessage(message: CoreMessage): boolean {\n return message.role === 'tool';\n}\n\nfunction filterAgentOutput(\n allMessages: CoreMessage[],\n startIndex: number,\n outputMode: OutputMode,\n): CoreMessage[] {\n if (outputMode === 'full_history') {\n return allMessages; // Include all messages generated by agent\n }\n\n if (outputMode === 'last_message') {\n const agentMessages = allMessages.slice(startIndex);\n if (agentMessages.length === 0) return allMessages;\n\n const lastMsg = agentMessages[agentMessages.length - 1];\n\n // LangChain logic: if isinstance(messages[-1], ToolMessage): messages = messages[-2:]\n // If last message is a tool message, keep AI message + tool message pair\n if (isToolMessage(lastMsg) && agentMessages.length > 1) {\n const beforeLastMsg = agentMessages[agentMessages.length - 2];\n if (beforeLastMsg.role === 'assistant') {\n return [...allMessages.slice(0, startIndex), beforeLastMsg, lastMsg];\n }\n }\n\n // LangChain logic: else: messages = messages[-1:]\n // Otherwise, keep just the last message\n return [...allMessages.slice(0, startIndex), lastMsg];\n }\n\n return allMessages;\n}\n\nexport function generate<O, C>(\n agent: Agent<O, C>,\n messages: UIMessage[] | string,\n contextVariables: C,\n config?: {\n abortSignal?: AbortSignal;\n providerOptions?: Parameters<typeof streamText>[0]['providerOptions'];\n },\n) {\n return generateText({\n abortSignal: config?.abortSignal,\n providerOptions: agent.providerOptions ?? config?.providerOptions,\n model: agent.model,\n system: agent.instructions(contextVariables),\n messages: convertToModelMessages(\n Array.isArray(messages) ? messages : [user(messages)],\n ),\n temperature: agent.temperature,\n stopWhen: stepCountIs(25),\n tools: agent.toToolset(),\n activeTools: agent.toolsNames,\n experimental_context: contextVariables,\n toolChoice: agent.toolChoice,\n experimental_output: agent.output\n ? Output.object({ schema: agent.output })\n : undefined,\n // onStepFinish: (step) => tagAgents(step, agent.handoff.name),\n onStepFinish: (step) => {\n const toolCall = step.toolCalls.at(-1);\n if (toolCall) {\n console.log(\n `Debug: ${chalk.yellow('ToolCalled')}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`,\n );\n }\n },\n prepareStep: prepareStep(agent, agent.model, contextVariables),\n // onFinish: (result) => {\n // (contextVariables as any).content = result.content;\n // },\n });\n}\n\nexport function execute<O, C>(\n agent: Agent<O, C>,\n messages: UIMessage[] | string,\n contextVariables: C,\n config?: {\n abortSignal?: AbortSignal;\n providerOptions?: Parameters<typeof streamText>[0]['providerOptions'];\n },\n) {\n const runId = generateId();\n return streamText({\n abortSignal: config?.abortSignal,\n providerOptions: config?.providerOptions,\n model: agent.model,\n system: agent.instructions(contextVariables),\n messages: convertToModelMessages(\n Array.isArray(messages) ? messages : [user(messages)],\n ),\n temperature: agent.temperature,\n stopWhen: stepCountIs(25),\n experimental_transform: smoothStream(),\n tools: agent.toToolset(),\n activeTools: agent.toolsNames,\n experimental_context: contextVariables,\n toolChoice: agent.toolChoice,\n experimental_repairToolCall: repairToolCall,\n onError: (error) => {\n console.error(\n chalk.red(\n `Error during agent (${agent.internalName})(${runId}) execution: `,\n ),\n error instanceof Error ? error.message : error,\n );\n console.dir(error, { depth: null });\n },\n experimental_output: agent.output\n ? Output.object({ schema: agent.output })\n : undefined,\n // onStepFinish: (step) => tagAgents(step, agent.handoff.name),\n onStepFinish: (step) => {\n const toolCall = step.toolCalls.at(-1);\n if (toolCall) {\n console.log(\n `Debug: (${runId}) ${chalk.bold.yellow('ToolCalled')}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`,\n );\n }\n },\n prepareStep: prepareStep(agent, agent.model, contextVariables),\n // onFinish: (result) => {\n // (contextVariables as any).content = result.content;\n // },\n });\n}\n\nexport const stream = execute;\n\nexport const prepareStep = <C>(\n agent: Agent<unknown, C>,\n model: AgentModel,\n contextVariables: C,\n): PrepareStepFunction<NoInfer<ToolSet>> => {\n return async ({ steps, messages }) => {\n const step = steps.at(-1);\n const agentName = (contextVariables as any).currentActiveAgent;\n if (!step) {\n return await prepareAgent(model, agent, messages, contextVariables);\n }\n if (!agentName) {\n return await prepareAgent(model, agent, messages, contextVariables);\n }\n\n const nextAgent = findAgent(agent, agentName);\n if (!nextAgent) {\n console.error(`Debug: ${chalk.red('NotFound')}: Agent ${agentName}`);\n console.dir(\n {\n steps: steps.map(({ request, response, ...etc }) => etc),\n messages,\n },\n { depth: null },\n );\n return void 0;\n }\n return await prepareAgent(model, nextAgent, messages, contextVariables);\n };\n};\n\nexport function swarm<C>(\n agent: Agent<unknown, C>,\n messages: UIMessage[] | string,\n contextVariables: C,\n abortSignal?: AbortSignal,\n) {\n const originalMessages = Array.isArray(messages)\n ? messages\n : [messageToUiMessage(messages)];\n return createUIMessageStream({\n originalMessages,\n generateId: generateId,\n async execute({ writer }) {\n const stream = execute(agent, originalMessages, contextVariables, {\n abortSignal,\n });\n const parts: UIMessagePart<UIDataTypes, UITools>[] = [];\n\n writer.merge(\n stream.toUIMessageStream({\n sendFinish: false,\n sendStart: true,\n onFinish: (event) => {\n parts.push(...event.responseMessage.parts);\n },\n }),\n );\n await stream.consumeStream({ onError: console.error });\n await last(stream.fullStream);\n\n if (!agent.prepareEnd) return;\n\n while (true) {\n const state = contextVariables as any;\n if (state.currentActiveAgent === undefined) {\n console.warn(\n `swarm: active agent was never set, so no prepareEnd call will be made`,\n );\n return;\n }\n if (state.currentActiveAgent === agent.internalName) {\n console.warn(\n `swarm: active agent is the root agent, so no prepareEnd call will be made`,\n );\n return;\n }\n const responseMessage = { id: '', parts, role: 'assistant' } as const;\n\n const stream = agent.prepareEnd({\n responseMessage,\n messages: [...originalMessages, responseMessage],\n contextVariables,\n abortSignal,\n });\n if (!stream) break;\n\n writer.merge(\n stream.toUIMessageStream({\n sendFinish: false,\n sendStart: false,\n onFinish: (event) => {\n parts.push(...event.responseMessage.parts);\n },\n }),\n );\n await stream.consumeStream({ onError: console.error });\n await last(stream.fullStream);\n }\n\n writer.write({ type: 'finish' });\n },\n });\n}\n\nexport async function prepareAgent<C>(\n defaultModel: AgentModel,\n agent: Agent<unknown, C>,\n messages: ModelMessage[],\n contextVariables?: C,\n): Promise<PrepareStepResult<NoInfer<ToolSet>>> {\n agent.debug();\n await agent.prepareHandoff?.(messages);\n\n let stepModel = agent.model ?? defaultModel;\n if (agent.output) {\n const json_schema = zodToJsonSchema(agent.output, {\n $refStrategy: 'root',\n });\n stepModel = wrapLanguageModel({\n model: stepModel,\n middleware: {\n transformParams: async ({ params }) => ({\n ...params,\n response_format: {\n type: 'json_schema',\n json_schema,\n name: `${agent.handoff.name}_output`,\n },\n }),\n },\n });\n }\n return {\n system: agent.instructions(contextVariables),\n activeTools: agent.toolsNames,\n model: stepModel,\n messages,\n // messages: removeTransferCalls(messages),\n toolChoice: agent.toolChoice,\n } as const;\n}\n\nfunction getLastAgentFromSteps(\n steps: StepResult<NoInfer<ToolSet>>[],\n): string | undefined {\n for (let i = steps.length - 1; i >= 0; i--) {\n const step = steps[i];\n for (const it of step.dynamicToolResults) {\n if (isTransferToolResult(it)) {\n return it.output.currentActiveAgent;\n }\n }\n }\n return void 0;\n}\n\nfunction findAgent<C>(agent: Agent<unknown, C>, agentName: string) {\n // FIXME: first argument agent not always the first passed agent.\n return [...agent.toHandoffs(), agent].find(\n (it) => it.handoff.name === agentName,\n );\n}\n\nfunction getActiveAgentName(messages: ModelMessage[]): string | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n\n if (message.role === 'tool') {\n for (const block of message.content) {\n if (\n block.type === 'tool-result' &&\n block.toolName.startsWith('transfer_to_') &&\n block.output.type === 'json' &&\n isTransferToolResult({ output: block.output.value })\n ) {\n return (block.output.value as TransferTool['output'])\n .currentActiveAgent;\n }\n }\n }\n }\n return undefined;\n}\n\nfunction tagAgents(\n step: StepResult<NoInfer<ToolSet>>,\n defaultAgentName: string,\n) {\n const { request, response, ...stepResult } = step;\n // let transferToolResultIdx = -1;\n const messages = response.messages;\n let agentName: string | undefined;\n\n // look for the last agent from the step\n for (let i = stepResult.content.length - 1; i >= 0; i--) {\n const block = stepResult.content[i];\n if (\n block.type === 'tool-result' &&\n block.dynamic &&\n block.toolName.startsWith('transfer_to_') &&\n isTransferToolResult(block)\n ) {\n // If we found a dynamic tool result, we can use it\n agentName = block.output.lastActiveAgent;\n // transferToolResultIdx = i;\n break;\n }\n }\n\n // if no agent in the step result, look for for it in the messages\n // todo: can we just use this instead of looking into the step result?\n if (!agentName) {\n for (const message of messages.slice(0).reverse()) {\n if (\n message.role === 'tool' &&\n message.content[0].type === 'tool-result' &&\n message.content[0].toolName.startsWith('transfer_to_') &&\n isTransferToolResult({\n output: message.content[0].output.value,\n })\n ) {\n agentName = (message.content[0].output.value as TransferTool['output'])\n .currentActiveAgent;\n break;\n }\n }\n }\n\n if (!agentName) {\n agentName = defaultAgentName;\n }\n\n for (const block of stepResult.content) {\n if (block.type === 'text' && !block.text.startsWith('<name>')) {\n block.text = `<name>${agentName}</name><content>${dedent(block.text)}</content>`;\n }\n }\n // console.log(\n // `Debug: ${chalk.red('NoOp')}: No transfer tool result found.`,\n // );\n // console.dir({ stepResult, messages }, { depth: null });\n}\n\nfunction removeTransferCalls(messages: ModelMessage[]): ModelMessage[] {\n for (const message of messages) {\n if (message.role === 'assistant') {\n if (typeof message.content === 'string') continue;\n\n for (let i = message.content.length - 1; i >= 0; i--) {\n const block = message.content[i];\n if (typeof block === 'string') continue;\n\n if (\n (block.type === 'tool-call' || block.type === 'tool-result') &&\n block.toolName.startsWith('transfer_to_')\n ) {\n message.content.splice(i, 1);\n }\n }\n }\n }\n return messages;\n}\n\nconst repairToolCall: ToolCallRepairFunction<ToolSet> = async ({\n toolCall,\n tools,\n inputSchema,\n error,\n}) => {\n if (NoSuchToolError.isInstance(error)) {\n return null; // do not attempt to fix invalid tool names\n }\n\n console.log(\n `Debug: ${chalk.yellow('RepairingToolCall')}: ${toolCall.toolName}`,\n );\n\n const tool = tools[toolCall.toolName as keyof typeof tools];\n\n const { experimental_output } = await generateText({\n model: groq('openai/gpt-oss-20b'),\n experimental_output: Output.object({ schema: tool.inputSchema }),\n prompt: [\n `The model tried to call the tool \"${toolCall.toolName}\"` +\n ` with the following inputs:`,\n JSON.stringify(toolCall.input),\n `The tool accepts the following schema:`,\n JSON.stringify(inputSchema(toolCall)),\n 'Please fix the inputs.',\n ].join('\\n'),\n });\n\n return { ...toolCall, input: JSON.stringify(experimental_output) };\n};\n", "import { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport { embedMany } from 'ai';\n\nexport const lmstudio = createOpenAICompatible({\n name: 'lmstudio',\n baseURL: 'http://127.0.0.1:1234/v1',\n supportsStructuredOutputs: true,\n includeUsage: true,\n});\n\nexport const glm = createOpenAICompatible({\n name: 'z.ai',\n baseURL: 'https://api.z.ai/api/paas/v4/',\n apiKey: process.env.ZAI_API_KEY,\n});\n\nexport async function embed(documents: string[]): Promise<{\n embeddings: number[][];\n dimensions: number;\n}> {\n const dimensions = 1024;\n const { embeddings } = await embedMany({\n model: lmstudio.textEmbeddingModel('text-embedding-qwen3-embedding-0.6b'),\n values: documents,\n providerOptions: { lmstudio: { dimensions } },\n });\n return { embeddings, dimensions };\n}\n", "import { type UIToolInvocation, tool } from 'ai';\nimport { z } from 'zod';\n\nexport const GetWeatherSchema = z.object({\n location: z.string(),\n unit: z.enum(['C', 'F']),\n temperature: z.number(),\n condition: z.string(),\n high: z.number(),\n low: z.number(),\n humidity: z.number(),\n windKph: z.number(),\n icon: z.string().optional(),\n});\n\nexport type GetWeatherResult = z.infer<typeof GetWeatherSchema>;\n\nexport const getWeatherTool = tool({\n name: 'weather',\n description: 'Get the current weather for a location.',\n inputSchema: z.object({\n location: z.string().describe('City name, address or coordinates'),\n unit: z.enum(['C', 'F']).default('C'),\n }),\n outputSchema: GetWeatherSchema,\n execute: async ({ location, unit }) => {\n const { latitude, longitude, name } = await geocodeLocation(location);\n\n const params = new URLSearchParams({\n latitude: String(latitude),\n longitude: String(longitude),\n current: [\n 'temperature_2m',\n 'relative_humidity_2m',\n 'wind_speed_10m',\n 'weather_code',\n ].join(','),\n daily: ['temperature_2m_max', 'temperature_2m_min'].join(','),\n timezone: 'auto',\n temperature_unit: unit === 'F' ? 'fahrenheit' : 'celsius',\n wind_speed_unit: 'kmh',\n });\n\n const url = `https://api.open-meteo.com/v1/forecast?${params.toString()}`;\n const res = await fetch(url);\n if (!res.ok) throw new Error(`Weather API failed: ${res.status}`);\n const data = (await res.json()) as ForecastResponse;\n\n const current = data?.current;\n const daily = data?.daily;\n if (!current || !daily) throw new Error('Malformed weather API response');\n\n const weatherCode = Number(current.weather_code);\n const mapped = mapWeatherCode(weatherCode);\n\n const result: GetWeatherResult = {\n location: name,\n unit,\n temperature: Math.round(Number(current.temperature_2m)),\n condition: mapped.condition,\n high: Math.round(Number(daily.temperature_2m_max?.[0])),\n low: Math.round(Number(daily.temperature_2m_min?.[0])),\n humidity: Math.max(\n 0,\n Math.min(1, Number(current.relative_humidity_2m) / 100),\n ),\n windKph: Math.round(Number(current.wind_speed_10m)),\n icon: mapped.icon,\n };\n\n return result;\n },\n});\n\ninterface GeocodeItem {\n id: number;\n name: string;\n latitude: number;\n longitude: number;\n elevation?: number;\n country_code?: string;\n admin1?: string;\n timezone?: string;\n}\n\ninterface GeocodeResponse {\n results?: GeocodeItem[];\n}\n\ninterface ForecastCurrent {\n time: string;\n interval: number;\n temperature_2m: number;\n relative_humidity_2m: number;\n wind_speed_10m: number;\n weather_code: number;\n}\n\ninterface ForecastDaily {\n time: string[];\n temperature_2m_max: number[];\n temperature_2m_min: number[];\n}\n\ninterface ForecastResponse {\n current: ForecastCurrent;\n daily: ForecastDaily;\n}\n\nasync function geocodeLocation(location: string): Promise<{\n latitude: number;\n longitude: number;\n name: string;\n}> {\n // Allow \"lat,lon\" inputs without geocoding\n const coordMatch = location\n .trim()\n .match(/^\\s*(-?\\d+(?:\\.\\d+)?)\\s*,\\s*(-?\\d+(?:\\.\\d+)?)\\s*$/);\n if (coordMatch) {\n const latitude = parseFloat(coordMatch[1]);\n const longitude = parseFloat(coordMatch[2]);\n return {\n latitude,\n longitude,\n name: `${latitude.toFixed(3)}, ${longitude.toFixed(3)}`,\n };\n }\n\n const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(\n location,\n )}&count=1&language=en&format=json`;\n const res = await fetch(url);\n if (!res.ok) throw new Error(`Geocoding failed: ${res.status}`);\n const data = (await res.json()) as GeocodeResponse;\n const first = data?.results?.[0];\n if (!first) throw new Error(`Location not found: ${location}`);\n const nameParts = [first.name, first.admin1, first.country_code].filter(\n Boolean,\n );\n return {\n latitude: first.latitude,\n longitude: first.longitude,\n name: nameParts.join(', '),\n };\n}\n\nfunction mapWeatherCode(code: number): { condition: string; icon?: string } {\n switch (code) {\n case 0:\n return { condition: 'Clear sky', icon: 'weather-sun' };\n case 1:\n return { condition: 'Mainly clear', icon: 'weather-sun' };\n case 2:\n return { condition: 'Partly cloudy', icon: 'weather-partly' };\n case 3:\n return { condition: 'Overcast', icon: 'weather-cloud' };\n case 45:\n case 48:\n return { condition: 'Fog', icon: 'weather-fog' };\n case 51:\n case 53:\n case 55:\n case 56:\n case 57:\n return { condition: 'Drizzle', icon: 'weather-drizzle' };\n case 61:\n case 63:\n case 65:\n case 66:\n case 67:\n return { condition: 'Rain', icon: 'weather-rain' };\n case 71:\n case 73:\n case 75:\n case 77:\n return { condition: 'Snow', icon: 'weather-snow' };\n case 80:\n case 81:\n case 82:\n return { condition: 'Showers', icon: 'weather-showers' };\n case 85:\n case 86:\n return { condition: 'Snow showers', icon: 'weather-snow' };\n case 95:\n case 96:\n case 99:\n return { condition: 'Thunderstorm', icon: 'weather-thunder' };\n default:\n return { condition: 'Unknown' };\n }\n}\n\nexport type WeatherToolType = UIToolInvocation<typeof getWeatherTool>;\n", "import { groq } from '@ai-sdk/groq';\n\nimport { agent } from '@deepagents/agent';\n\nimport { duckDuckGoSearch } from './ddg-search.ts';\n\n\nexport const web_search_tool = duckDuckGoSearch;\n\nexport const searchAgent = agent({\n name: 'research_agent',\n model: groq('openai/gpt-oss-20b'),\n prompt:\n 'You are a diligent research assistant. Your task is to gather accurate and relevant information on a given topic using web search. Use the browser_search tool to find up-to-date information, and synthesize your findings into a concise summary.',\n tools: {\n browser_search: duckDuckGoSearch,\n },\n});\n", "import { tool } from 'ai';\nimport z from 'zod';\n\nimport { toState } from '@deepagents/agent';\n\nconst AcceptanceCriteriaSchema = z.object({\n criterion: z.string().describe('A specific, testable acceptance criterion'),\n});\n\nconst UserStorySchema = z.object({\n title: z.string().describe('Clear, concise title for the user story'),\n userRole: z\n .string()\n .describe('The user role or persona (e.g., \"developer\", \"end user\")'),\n action: z.string().describe('What the user wants to do'),\n benefit: z.string().describe('The value or benefit the user gets'),\n acceptanceCriteria: z\n .array(AcceptanceCriteriaSchema)\n .describe('List of specific, testable conditions that must be met'),\n technicalNotes: z\n .string()\n .optional()\n .describe(\n 'Relevant files, components, or dependencies from the repository',\n ),\n priority: z\n .enum(['High', 'Medium', 'Low'])\n .describe('Priority level based on complexity and dependencies'),\n storyPoints: z\n .enum(['1', '2', '3', '5', '8', '13'])\n .describe('Estimated complexity using Fibonacci sequence'),\n epicOrFeature: z\n .string()\n .optional()\n .describe('The epic or feature group this story belongs to'),\n});\n\nexport const user_story_formatter_tool = tool({\n description: `Tool for formatting and recording user stories in a standardized format.\n\n Use this tool to create well-structured user stories following product management best practices.\n Each story should follow the format: \"As a [role], I want to [action], so that [benefit]\"\n\n When to use:\n - After analyzing a feature or component in the codebase\n - When you've gathered enough information to write a complete user story\n - To document findings in a structured, actionable format\n - To maintain consistency across all generated user stories\n\n The tool will:\n 1. Format the story in the standard user story template\n 2. Store it in the context for later synthesis\n 3. Return a formatted version for immediate review\n`,\n inputSchema: UserStorySchema,\n execute: async (story, options) => {\n const context = toState<{ userStories: (typeof story)[] }>(options);\n context.userStories ??= [];\n context.userStories.push(story);\n\n // Format the user story for output\n const formatted = `\n## ${story.title}\n\n**User Story:**\nAs a **${story.userRole}**, I want to **${story.action}**, so that **${story.benefit}**.\n\n**Acceptance Criteria:**\n${story.acceptanceCriteria.map((ac, i) => `${i + 1}. ${ac.criterion}`).join('\\n')}\n\n**Technical Notes:**\n${story.technicalNotes || 'N/A'}\n\n**Priority:** ${story.priority}\n**Story Points:** ${story.storyPoints}\n${story.epicOrFeature ? `**Epic/Feature:** ${story.epicOrFeature}` : ''}\n\n---\n`.trim();\n\n return `User story recorded successfully!\\n\\n${formatted}\\n\\nTotal stories recorded: ${context.userStories.length}`;\n },\n});\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport { toState } from '@deepagents/agent';\n\nexport interface HNSearchItem {\n objectID: string;\n title: string | null;\n url: string | null;\n author: string;\n points: number | null;\n story_text: string | null;\n comment_text: string | null;\n num_comments: number | null;\n created_at: string;\n created_at_i: number;\n _tags: string[];\n}\n\nexport interface HNSearchResponse {\n query: string;\n hits: HNSearchItem[];\n nbHits: number;\n page: number;\n nbPages: number;\n hitsPerPage: number;\n}\n\nexport interface HNItemResponse {\n id: string;\n created_at: string;\n created_at_i: number;\n type: 'story' | 'comment' | 'poll' | 'pollopt' | 'show' | 'ask' | 'job';\n author: string;\n title?: string;\n url?: string;\n text?: string;\n points?: number;\n parent_id?: string;\n children?: HNItemResponse[];\n story_id?: string;\n story_title?: string;\n story_url?: string;\n}\n\nexport interface HNUserResponse {\n username: string;\n about?: string;\n karma: number;\n created_at: string;\n created_at_i: number;\n}\n\nfunction buildTags(options: {\n type?: 'story' | 'comment' | 'all';\n author?: string;\n}): string | undefined {\n const tags: string[] = [];\n\n if (options.type && options.type !== 'all') {\n tags.push(options.type);\n }\n\n if (options.author) {\n tags.push(`author_${options.author}`);\n }\n\n return tags.length > 0 ? tags.join(',') : undefined;\n}\n\nfunction buildNumericFilters(options: {\n timeFilter?: 'd' | 'w' | 'm' | 'y' | 'all';\n minPoints?: number;\n minComments?: number;\n maxAgeHours?: number;\n}): string | undefined {\n const filters: string[] = [];\n\n if (options.timeFilter && options.timeFilter !== 'all') {\n const now = Math.floor(Date.now() / 1000);\n const timeMap = {\n d: 86400, // 1 day in seconds\n w: 604800, // 1 week\n m: 2592000, // ~30 days\n y: 31536000, // ~365 days\n };\n const seconds = timeMap[options.timeFilter];\n const timestamp = now - seconds;\n filters.push(`created_at_i>${timestamp}`);\n }\n\n if (options.maxAgeHours !== undefined && options.maxAgeHours > 0) {\n const now = Math.floor(Date.now() / 1000);\n const seconds = options.maxAgeHours * 3600;\n const timestamp = now - seconds;\n filters.push(`created_at_i>${timestamp}`);\n }\n\n if (options.minPoints !== undefined && options.minPoints > 0) {\n filters.push(`points>=${options.minPoints}`);\n }\n\n if (options.minComments !== undefined && options.minComments > 0) {\n filters.push(`num_comments>=${options.minComments}`);\n }\n\n return filters.length > 0 ? filters.join(',') : undefined;\n}\n\nasync function searchHackerNewsAPI(params: {\n query?: string;\n tags?: string;\n numericFilters?: string;\n sortBy?: 'relevance' | 'date';\n page?: number;\n hitsPerPage?: number;\n}): Promise<HNSearchResponse> {\n const {\n query = '',\n tags,\n numericFilters,\n sortBy = 'relevance',\n page = 0,\n hitsPerPage = 20,\n } = params;\n\n const endpoint =\n sortBy === 'date'\n ? 'http://hn.algolia.com/api/v1/search_by_date'\n : 'http://hn.algolia.com/api/v1/search';\n\n const urlParams = new URLSearchParams();\n\n if (query) {\n urlParams.set('query', query);\n }\n\n if (tags) {\n urlParams.set('tags', tags);\n }\n\n if (numericFilters) {\n urlParams.set('numericFilters', numericFilters);\n }\n\n urlParams.set('page', page.toString());\n urlParams.set('hitsPerPage', Math.min(hitsPerPage, 1000).toString());\n\n const url = `${endpoint}?${urlParams.toString()}`;\n\n try {\n const response = await fetch(url, {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `HN API error: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n return data as HNSearchResponse;\n } catch (error) {\n throw new Error(\n `Failed to search HackerNews: ${error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n}\n\nasync function fetchHNItem(id: string): Promise<HNItemResponse> {\n const url = `http://hn.algolia.com/api/v1/items/${id}`;\n\n try {\n const response = await fetch(url, {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `HN API error: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n return data as HNItemResponse;\n } catch (error) {\n throw new Error(\n `Failed to fetch HN item: ${error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n}\n\nasync function fetchHNUser(username: string): Promise<HNUserResponse> {\n const url = `http://hn.algolia.com/api/v1/users/${username}`;\n\n try {\n const response = await fetch(url, {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `HN API error: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n return data as HNUserResponse;\n } catch (error) {\n throw new Error(\n `Failed to fetch HN user: ${error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n}\n\nfunction formatDate(timestamp: number): string {\n return new Date(timestamp * 1000).toLocaleString();\n}\n\nfunction formatHNLink(id: string): string {\n return `https://news.ycombinator.com/item?id=${id}`;\n}\n\nfunction truncateText(text: string, maxLength: number): string {\n if (text.length <= maxLength) return text;\n return `${text.substring(0, maxLength)}...`;\n}\n\nfunction formatStoryItem(\n hit: HNSearchItem,\n index: number,\n page: number,\n hitsPerPage: number,\n): string {\n const lines: string[] = [];\n const itemNumber = page * hitsPerPage + index + 1;\n\n lines.push(`\\n${itemNumber}. ${hit.title || '(No title)'}`);\n\n if (hit.url) {\n lines.push(` URL: ${hit.url}`);\n }\n\n if (hit.points !== null) {\n lines.push(\n ` ${hit.points} points | by ${hit.author} | ${hit.num_comments || 0} comments`,\n );\n } else {\n lines.push(` by ${hit.author}`);\n }\n\n lines.push(` Date: ${formatDate(hit.created_at_i)}`);\n\n if (hit.story_text) {\n lines.push(` Text: ${truncateText(hit.story_text, 200)}`);\n }\n\n lines.push(` HN Link: ${formatHNLink(hit.objectID)}`);\n\n return lines.join('\\n');\n}\n\nfunction formatCommentItem(\n hit: HNSearchItem,\n index: number,\n page: number,\n hitsPerPage: number,\n): string {\n const lines: string[] = [];\n const itemNumber = page * hitsPerPage + index + 1;\n\n lines.push(`\\n${itemNumber}. Comment by ${hit.author}`);\n\n if (hit.comment_text) {\n lines.push(` ${truncateText(hit.comment_text, 300)}`);\n }\n\n lines.push(` Date: ${formatDate(hit.created_at_i)}`);\n lines.push(` HN Link: ${formatHNLink(hit.objectID)}`);\n\n return lines.join('\\n');\n}\n\nfunction formatMixedItem(\n hit: HNSearchItem,\n index: number,\n page: number,\n hitsPerPage: number,\n): string {\n const lines: string[] = [];\n const itemNumber = page * hitsPerPage + index + 1;\n const isStory = hit._tags.includes('story');\n const isComment = hit._tags.includes('comment');\n const type = isStory ? 'Story' : 'Comment';\n\n lines.push(`\\n${itemNumber}. [${type}] ${hit.title || 'Comment'}`);\n\n if (isStory) {\n if (hit.url) {\n lines.push(` URL: ${hit.url}`);\n }\n if (hit.points !== null) {\n lines.push(` ${hit.points} points | ${hit.num_comments || 0} comments`);\n }\n if (hit.story_text) {\n lines.push(` Text: ${truncateText(hit.story_text, 200)}`);\n }\n } else if (isComment && hit.comment_text) {\n lines.push(` ${truncateText(hit.comment_text, 200)}`);\n }\n\n lines.push(` Date: ${formatDate(hit.created_at_i)}`);\n lines.push(` HN Link: ${formatHNLink(hit.objectID)}`);\n\n return lines.join('\\n');\n}\n\nfunction formatSearchResults(\n response: HNSearchResponse,\n options: {\n itemType: 'story' | 'comment' | 'mixed';\n emptyMessage: string;\n },\n): string {\n const { hits, nbHits, page, nbPages } = response;\n const { itemType, emptyMessage } = options;\n\n if (hits.length === 0) {\n return emptyMessage;\n }\n\n const formatItem = (hit: HNSearchItem, index: number) => {\n switch (itemType) {\n case 'story':\n return formatStoryItem(hit, index, page, response.hitsPerPage);\n case 'comment':\n return formatCommentItem(hit, index, page, response.hitsPerPage);\n case 'mixed':\n return formatMixedItem(hit, index, page, response.hitsPerPage);\n }\n };\n\n const results = hits.map(formatItem);\n const typeLabel =\n itemType === 'mixed'\n ? 'results'\n : `${itemType === 'story' ? 'stories' : 'comments'}`;\n const header = `Found ${nbHits} ${typeLabel} (showing page ${page + 1} of ${nbPages}):\\n`;\n\n return header + results.join('\\n');\n}\n\nfunction formatStoryResults(response: HNSearchResponse): string {\n return formatSearchResults(response, {\n itemType: 'story',\n emptyMessage: `No stories found for query: \"${response.query}\"`,\n });\n}\n\nfunction formatCommentResults(response: HNSearchResponse): string {\n return formatSearchResults(response, {\n itemType: 'comment',\n emptyMessage: `No comments found for query: \"${response.query}\"`,\n });\n}\n\nfunction formatAuthorResults(response: HNSearchResponse): string {\n return formatSearchResults(response, {\n itemType: 'mixed',\n emptyMessage: 'No results found for this author',\n });\n}\n\nfunction formatItemDetails(item: HNItemResponse): string {\n const lines: string[] = [];\n\n if (item.type === 'story') {\n lines.push(`Story: ${item.title || '(No title)'}`);\n if (item.url) {\n lines.push(`URL: ${item.url}`);\n }\n lines.push(`By: ${item.author}`);\n if (item.points !== undefined) {\n lines.push(`Points: ${item.points}`);\n }\n lines.push(`Date: ${formatDate(item.created_at_i)}`);\n if (item.text) {\n lines.push(`\\nText:\\n${item.text}`);\n }\n lines.push(`\\nHN Link: ${formatHNLink(item.id)}`);\n } else if (item.type === 'comment') {\n lines.push(`Comment by ${item.author}`);\n if (item.story_title) {\n lines.push(`On story: ${item.story_title}`);\n }\n lines.push(`Date: ${formatDate(item.created_at_i)}`);\n if (item.text) {\n lines.push(`\\n${item.text}`);\n }\n lines.push(`\\nHN Link: ${formatHNLink(item.id)}`);\n }\n\n return lines.join('\\n');\n}\n\nfunction formatUserProfile(user: HNUserResponse): string {\n const lines: string[] = [];\n\n lines.push(`User: ${user.username}`);\n lines.push(`Karma: ${user.karma.toLocaleString()}`);\n lines.push(`Member since: ${formatDate(user.created_at_i)}`);\n\n if (user.about) {\n lines.push(`\\nAbout:\\n${user.about}`);\n }\n\n lines.push(\n `\\nProfile: https://news.ycombinator.com/user?id=${user.username}`,\n );\n\n return lines.join('\\n');\n}\n\nfunction formatJobItem(\n hit: HNSearchItem,\n index: number,\n page: number,\n hitsPerPage: number,\n): string {\n const lines: string[] = [];\n const itemNumber = page * hitsPerPage + index + 1;\n\n lines.push(`\\n${itemNumber}. ${hit.title || '(No title)'}`);\n\n if (hit.url) {\n lines.push(` URL: ${hit.url}`);\n }\n\n lines.push(` Posted by: ${hit.author}`);\n lines.push(` Date: ${formatDate(hit.created_at_i)}`);\n\n if (hit.story_text) {\n lines.push(` Description: ${truncateText(hit.story_text, 300)}`);\n }\n\n lines.push(` HN Link: ${formatHNLink(hit.objectID)}`);\n\n return lines.join('\\n');\n}\n\nfunction formatJobResults(response: HNSearchResponse): string {\n const { hits, nbHits, page, nbPages } = response;\n\n if (hits.length === 0) {\n return `No job postings found for query: \"${response.query}\"`;\n }\n\n const results = hits.map((hit, index) =>\n formatJobItem(hit, index, page, response.hitsPerPage),\n );\n\n const header = `Found ${nbHits} job postings (showing page ${page + 1} of ${nbPages}):\\n`;\n return header + results.join('\\n');\n}\n\nexport const search_by_query = tool({\n description:\n 'Tool to search HackerNews stories by keywords and filters. Use when you need to find HN stories matching specific search criteria, time periods, or popularity thresholds.',\n inputSchema: z.object({\n query: z\n .string()\n .describe(\n 'Search query for story titles and content. Examples: \"artificial intelligence\", \"python\"',\n ),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minPoints: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum points threshold'),\n minComments: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum comments threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('relevance')\n .describe('Sort results by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'story',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const search_by_author = tool({\n description:\n 'Tool to search HackerNews content by author username. Use when you need to find all stories, comments, or both by a specific HN user.',\n inputSchema: z.object({\n author: z\n .string()\n .describe('HackerNews username to search for. Examples: \"pg\", \"tptacek\"'),\n type: z\n .enum(['story', 'comment', 'all'])\n .default('all')\n .describe('Type of content: story, comment, or all'),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minComments: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum comments threshold (for stories only)'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort results by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const tags = buildTags({ type: input.type, author: input.author });\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n tags,\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatAuthorResults(response);\n },\n});\n\nexport const get_story_item = tool({\n description:\n 'Tool to get detailed information about a specific HackerNews story by ID. Use when you need full details about a particular HN story including title, URL, author, points, and comments.',\n inputSchema: z.object({\n storyId: z.string().describe('HackerNews story ID. Example: \"38709478\"'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const item = await fetchHNItem(input.storyId);\n\n if (item.type !== 'story') {\n throw new Error(\n `Item ${input.storyId} is not a story (type: ${item.type})`,\n );\n }\n\n context.hackernews_sources.push({\n title: item.title || 'Untitled',\n hn_url: `https://news.ycombinator.com/item?id=${item.id}`,\n story_url: item.url || '',\n });\n\n return formatItemDetails(item);\n },\n});\n\nexport const get_story_comment = tool({\n description:\n 'Tool to get detailed information about a specific HackerNews comment by ID. Use when you need full details about a particular comment including text, author, and parent story information.',\n inputSchema: z.object({\n commentId: z\n .string()\n .describe('HackerNews comment ID. Example: \"38710123\"'),\n }),\n execute: async (input) => {\n const item = await fetchHNItem(input.commentId);\n\n if (item.type !== 'comment') {\n throw new Error(\n `Item ${input.commentId} is not a comment (type: ${item.type})`,\n );\n }\n\n return formatItemDetails(item);\n },\n});\n\nexport const get_front_page_stories = tool({\n description:\n 'Tool to get current HackerNews front page stories. Use when you need to see the latest trending and popular stories on HN.',\n inputSchema: z.object({\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(50)\n .default(30)\n .describe('Results per page (max 50)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const response = await searchHackerNewsAPI({\n tags: 'front_page',\n sortBy: 'date',\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const get_story_comments = tool({\n description:\n 'Tool to get all comments for a specific HackerNews story. Use when you need to read the discussion and comments on a particular HN story.',\n inputSchema: z.object({\n storyId: z.string().describe('HackerNews story ID. Example: \"38709478\"'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort comments by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(50)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input) => {\n const response = await searchHackerNewsAPI({\n tags: `comment,story_${input.storyId}`,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n return formatCommentResults(response);\n },\n});\n\nexport const search_ask_hn = tool({\n description:\n 'Tool to search Ask HN posts - questions posed to the HackerNews community. Use when you need to find community questions and discussions on specific topics.',\n inputSchema: z.object({\n query: z\n .string()\n .default('')\n .describe(\n 'Search query for Ask HN posts. Examples: \"artificial intelligence\", \"career\"',\n ),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minPoints: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum points threshold'),\n minComments: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum comments threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('relevance')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'ask_hn',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const search_show_hn = tool({\n description:\n 'Tool to search Show HN posts - projects and products shared with the HackerNews community. Use when you need to discover community projects, demos, or products on specific topics.',\n inputSchema: z.object({\n query: z\n .string()\n .default('')\n .describe(\n 'Search query for Show HN posts. Examples: \"web app\", \"open source\"',\n ),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minPoints: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum points threshold'),\n minComments: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum comments threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('relevance')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'show_hn',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const search_jobs = tool({\n description:\n 'Tool to search HackerNews job postings. Use when you need to find tech job opportunities posted on HN.',\n inputSchema: z.object({\n query: z\n .string()\n .default('')\n .describe(\n 'Search query for job postings. Examples: \"remote\", \"machine learning\"',\n ),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'job',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatJobResults(response);\n },\n});\n\nexport const search_polls = tool({\n description:\n 'Tool to search HackerNews polls - community surveys and voting. Use when you need to find community polls on various topics.',\n inputSchema: z.object({\n query: z\n .string()\n .default('')\n .describe('Search query for polls. Example: \"programming language\"'),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'poll',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const get_user_profile = tool({\n description:\n \"Tool to get HackerNews user profile information. Use when you need to view a user's karma, account creation date, and bio.\",\n inputSchema: z.object({\n username: z.string().describe('HackerNews username. Example: \"pg\"'),\n }),\n execute: async (input) => {\n const user = await fetchHNUser(input.username);\n return formatUserProfile(user);\n },\n});\n\nexport const search_by_domain = tool({\n description:\n 'Tool to search HackerNews stories from a specific domain or website. Use when you need to find all HN posts from a particular domain or track discussions about content from specific websites.',\n inputSchema: z.object({\n domain: z\n .string()\n .describe('Domain to search. Examples: \"github.com\", \"arxiv.org\"'),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minPoints: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum points threshold'),\n minComments: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum comments threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const urlParams = new URLSearchParams();\n urlParams.set('query', input.domain);\n urlParams.set('restrictSearchableAttributes', 'url');\n urlParams.set('tags', 'story');\n if (numericFilters) {\n urlParams.set('numericFilters', numericFilters);\n }\n urlParams.set('page', input.page.toString());\n urlParams.set('hitsPerPage', input.hitsPerPage.toString());\n\n const endpoint =\n input.sortBy === 'date'\n ? 'http://hn.algolia.com/api/v1/search_by_date'\n : 'http://hn.algolia.com/api/v1/search';\n\n const url = `${endpoint}?${urlParams.toString()}`;\n\n const response = await fetch(url, {\n headers: { 'Content-Type': 'application/json' },\n });\n\n if (!response.ok) {\n throw new Error(\n `HN API error: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = (await response.json()) as HNSearchResponse;\n fillContext(context, data);\n return formatStoryResults(data);\n },\n});\n\nexport const search_highly_discussed = tool({\n description:\n 'Tool to search for highly discussed HackerNews stories with many comments. Use when you need to find engaging or controversial discussions with significant community participation.',\n inputSchema: z.object({\n minComments: z\n .number()\n .int()\n .min(1)\n .describe(\n 'Minimum number of comments (required). Example: 100 for highly discussed stories',\n ),\n query: z\n .string()\n .default('')\n .describe('Optional search query. Example: \"AI\"'),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minPoints: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum points threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'story',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const search_trending = tool({\n description:\n \"Tool to find currently trending HackerNews stories - recent posts with high engagement. Use when you need to discover what's hot right now on HN by combining recency with high points and comments.\",\n inputSchema: z.object({\n minPoints: z\n .number()\n .int()\n .min(10)\n .default(50)\n .describe(\n 'Minimum points threshold. Example: 100 for highly upvoted stories',\n ),\n maxAgeHours: z\n .number()\n .int()\n .min(1)\n .max(72)\n .default(24)\n .describe('Maximum age in hours. Example: 24 for stories from today'),\n minComments: z\n .number()\n .int()\n .min(0)\n .default(10)\n .describe('Minimum comments threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(30)\n .describe('Results per page (max 100)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n maxAgeHours: input.maxAgeHours,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n tags: 'story',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nfunction fillContext(\n context: {\n hackernews_sources: {\n title?: string | null;\n hn_url?: string | null;\n story_url?: string | null;\n story_text?: string | null;\n comment_text?: string | null;\n }[];\n },\n result: HNSearchResponse,\n) {\n result.hits.forEach((hit) => {\n context.hackernews_sources.push({\n title: hit.title,\n hn_url: hit.objectID\n ? `https://news.ycombinator.com/item?id=${hit.objectID}`\n : undefined,\n story_url: hit.url,\n story_text: hit.story_text,\n comment_text: hit.comment_text,\n });\n });\n}\n\nexport const hackernewsTools = {\n search_by_query,\n search_by_author,\n get_story_item,\n get_story_comment,\n get_front_page_stories,\n get_story_comments,\n search_ask_hn,\n search_show_hn,\n search_jobs,\n search_polls,\n get_user_profile,\n search_by_domain,\n search_highly_discussed,\n search_trending,\n};\n"],
5
- "mappings": ";AAAA,SAAS,YAAY;AACrB,OAAO,WAAW;AAClB,SAAS,S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b,OAAO;AACV,YAAQ,uBAAuB,CAAC;AAEhC,UAAM,iBAAiB,oBAAoB;AAAA,MACzC,aAAa,MAAM;AAAA,MACnB,WAAW,MAAM;AAAA,MACjB,aAAa,MAAM;AAAA,IACrB,CAAC;AAED,UAAM,WAAW,MAAM,oBAAoB;AAAA,MACzC,MAAM;AAAA,MACN;AAAA,MACA,QAAQ,MAAM;AAAA,MACd,MAAM,MAAM;AAAA,MACZ,aAAa,MAAM;AAAA,IACrB,CAAC;AAED,gBAAY,SAAS,QAAQ;AAC7B,WAAO,mBAAmB,QAAQ;AAAA,EACpC;AACF,CAAC;AAED,SAAS,YACP,SASA,QACA;AACA,SAAO,KAAK,QAAQ,CAAC,QAAQ;AAC3B,YAAQ,mBAAmB,KAAK;AAAA,MAC9B,OAAO,IAAI;AAAA,MACX,QAAQ,IAAI,WACR,wCAAwC,IAAI,QAAQ,KACpD;AAAA,MACJ,WAAW,IAAI;AAAA,MACf,YAAY,IAAI;AAAA,MAChB,cAAc,IAAI;AAAA,IACpB,CAAC;AAAA,EACH,CAAC;AACH;AAEO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
6
- "names": ["tool", "z", "res", "items", "z", "tool", "tool", "z", "tool", "z", "Output", "generateText", "stepCountIs", "tool", "chalk", "z", "generateId", "dedent", "agent", "stream", "agent", "agent", "tool", "z", "input", "generateText", "stepCountIs", "Output", "chalk", "agent", "tool", "z", "tool", "z", "groq", "groq", "tool", "z", "z", "tool", "tool", "z", "tool", "z"]
3
+ "sources": ["../src/lib/container.ts", "../src/lib/ddg-search.ts", "../src/lib/ddg-stocks.ts", "../src/lib/scratchbad.ts", "../src/lib/weather.ts", "../src/lib/web-search.ts", "../src/lib/user-story-formatter.ts", "../src/lib/hackernews-search.ts"],
4
+ "sourcesContent": ["import { tool } from 'ai';\nimport spawn from 'nano-spawn';\nimport { z } from 'zod';\n\nexport const execute_os_command = tool({\n description:\n 'Tool to execute Linux commands in an isolated Docker container with Node.js runtime. Use when you need OS operations like file management, package installation, network requests, or system commands.',\n inputSchema: z.object({\n command: z\n .array(z.string().min(1, 'Command parts cannot be empty'))\n .min(1, 'At least one command part is required')\n .max(20, 'Command cannot exceed 20 parts for security')\n .describe(\n 'Command and arguments as array. Examples: [\"ls\", \"-la\"], [\"npm\", \"install\", \"lodash\"], [\"curl\", \"-s\", \"https://api.github.com\"], [\"node\", \"--version\"]',\n ),\n working_directory: z\n .string()\n .regex(/^\\/[a-zA-Z0-9_/.,-]*$/, 'Must be a valid absolute Linux path')\n .optional()\n .describe(\n 'Absolute working directory path. Examples: \"/tmp\", \"/workspace\", \"/app\". Defaults to container root.',\n ),\n environment_vars: z\n .record(\n z.string().min(1, 'Environment variable values cannot be empty'),\n z.string(),\n )\n .optional()\n .describe(\n 'Environment variables as key-value pairs. Examples: {\"NODE_ENV\": \"development\", \"API_KEY\": \"secret123\"}',\n ),\n }),\n execute: ({ command, working_directory, environment_vars }) => {\n return exec(command, working_directory, environment_vars);\n },\n});\n\nfunction exec(\n command: string[],\n working_directory?: string,\n environment_vars?: Record<string, string>,\n) {\n const args = ['exec', '-i'];\n\n if (working_directory) {\n args.push('-w', working_directory);\n }\n\n if (environment_vars) {\n Object.entries(environment_vars).forEach(([key, value]) => {\n args.push('-e', `${key}=${value}`);\n });\n }\n\n args.push('toolos', ...command);\n\n return spawn('docker', args, {\n stdio: 'pipe',\n });\n}\n", "import { tool } from 'ai';\nimport * as ddg from 'duck-duck-scrape';\nimport { uniqBy } from 'lodash-es';\nimport { z } from 'zod';\n\nexport type Source = 'text' | 'news' | 'images';\n\nexport async function serp({\n query,\n source,\n locale = 'en-us',\n maxResults = 50,\n ...input\n}: z.input<typeof ddgSearchSchema>) {\n const safeSearch =\n ddg.SafeSearchType[\n 'STRICT'\n // input.safesearch.toUpperCase() as keyof typeof ddg.SafeSearchType\n ];\n const time =\n ddg.SearchTimeType[\n (input.time || 'y')?.toUpperCase() as keyof typeof ddg.SearchTimeType\n ];\n\n if (source === 'text') {\n const res = await ddg.search(\n query,\n {\n region: 'wt-wt',\n safeSearch,\n time,\n locale,\n },\n {\n uri_modifier: (rawUrl: string) => {\n const url = new URL(rawUrl);\n url.searchParams.delete('ss_mkt');\n return url.toString();\n },\n },\n );\n const items = res.results.slice(0, maxResults).map((r) => ({\n snippet: r.description,\n title: r.title,\n link: r.url,\n hostname: r.hostname,\n }));\n return { items, total: res.results.length, vqd: res.vqd } as const;\n }\n\n if (source === 'news') {\n const res = await ddg.searchNews(query, {\n safeSearch,\n time,\n });\n const items = res.results.slice(0, maxResults).map((r) => ({\n snippet: r.excerpt,\n title: r.title,\n link: r.url,\n date: r.date, // epoch ms\n source: r.syndicate,\n image: r.image,\n relativeTime: r.relativeTime,\n }));\n return { items, total: res.results.length, vqd: res.vqd } as const;\n }\n\n const res = await ddg.searchImages(query, { safeSearch });\n const items = res.results.slice(0, maxResults).map((r) => ({\n title: r.title,\n thumbnail: r.thumbnail,\n image: r.image,\n link: r.url,\n height: r.height,\n width: r.width,\n source: r.source,\n }));\n return { items, total: res.results.length, vqd: res.vqd } as const;\n}\n\nasync function performSearch(query: string) {\n const results = await serp({\n source: 'news',\n query: query,\n });\n const result = uniqBy(results.items as { link: string }[], (it) => it.link);\n return result as typeof results.items;\n}\n\nexport const ddgSearchSchema = z.object({\n query: z.string().min(1),\n source: z.enum(['text', 'news', 'images']).default('text'),\n locale: z.string().optional().default('en-us'),\n // region: z.string().default('wt-wt'),\n // safesearch: z.enum(['strict', 'moderate', 'off']).default('moderate'),\n time: z.enum(['d', 'w', 'm', 'y']).optional().default('y'),\n maxResults: z.number().int().positive().max(50).default(5),\n});\nexport const duckDuckGoSearch = tool({\n description:\n 'A tool for searching the web. Useful for when you need to find information about current events or topics that are not covered in your training data.',\n inputSchema: ddgSearchSchema,\n execute: serp,\n});\n", "import { tool } from 'ai';\nimport { stocks as ddgStocks } from 'duck-duck-scrape';\nimport { z } from 'zod';\n\ntype Quote = {\n symbol: string;\n name: string | null;\n exchange: string | null;\n currency: string | null;\n last: number | null;\n change: number | null;\n percentChange: number | null;\n open: number | null;\n high: number | null;\n low: number | null;\n prevClose: number | null;\n volume: number | null;\n date: string | null; // ET\n time: string | null; // ET\n halted: boolean | null;\n source: 'DuckDuckGo/Xignite';\n raw?: unknown; // optional raw for debugging\n};\n\nconst toQuote = (r: any): Quote => ({\n symbol: r?.Security?.Symbol ?? null,\n name: r?.Security?.Name ?? null,\n exchange: r?.Security?.Market ?? null,\n currency: r?.Currency ?? null,\n last: r?.Last ?? null,\n change: r?.ChangeFromPreviousClose ?? null,\n percentChange: r?.PercentChangeFromPreviousClose ?? null,\n open: r?.Open ?? null,\n high: r?.High ?? null,\n low: r?.Low ?? null,\n prevClose: r?.PreviousClose ?? null,\n volume: r?.Volume ?? null,\n date: r?.Date ?? null,\n time: r?.Time ?? null,\n halted: r?.TradingHalted ?? null,\n source: 'DuckDuckGo/Xignite',\n raw: r,\n});\n\nexport const duckStocks = tool({\n description: 'A tool for fetching stock market quotes. Useful for when you need to get the latest stock price and related information for one or more stock symbols.',\n inputSchema: z.object({\n symbols: z\n .union([z.string().min(1), z.array(z.string().min(1)).min(1)])\n .transform((s) => (Array.isArray(s) ? s : [s])),\n includeRaw: z.boolean().default(false),\n }),\n execute: async ({ symbols, includeRaw }) => {\n const tasks = symbols.map(async (s) => {\n const sym = s.trim().toUpperCase();\n try {\n const r = await ddgStocks(sym);\n if (!r || (r.Outcome && r.Outcome !== 'Success')) {\n return { symbol: sym, error: r?.Message || 'No quote' };\n }\n const q = toQuote(r);\n if (!includeRaw) delete q.raw;\n return q;\n } catch (e: any) {\n return { symbol: sym, error: e?.message || 'fetch_failed' };\n }\n });\n const results = await Promise.all(tasks);\n return { results };\n },\n});\n", "import { tool } from 'ai';\nimport z from 'zod';\n\nimport { toState } from '@deepagents/agent';\n\nexport const scratchpad_tool = tool({\n description: `Tool for strategic reflection on research progress and decision-making.\n\n Use this tool after each search to analyze results and plan next steps systematically.\n This creates a deliberate pause in the research workflow for quality decision-making.\n\n When to use:\n - After receiving search results: What key information did I find?\n - Before deciding next steps: Do I have enough to answer comprehensively?\n - When assessing research gaps: What specific information am I still missing?\n - Before concluding research: Can I provide a complete answer now?\n\n Reflection should address:\n 1. Analysis of current findings - What concrete information have I gathered?\n 2. Gap assessment - What crucial information is still missing?\n 3. Quality evaluation - Do I have sufficient evidence/examples for a good answer?\n 4. Strategic decision - Should I continue searching or provide my answer?\n`,\n inputSchema: z.object({\n reflection: z\n .string()\n .describe('Your detailed reflection on research progress.'),\n }),\n execute: async ({ reflection }, options) => {\n const context = toState<{ scratchpad: string }>(options);\n context.scratchpad += `- ${reflection}\\n`;\n return `Reflection recorded. Current scratchpad now:\\n---\\n${context.scratchpad}`;\n },\n});\n", "import { type UIToolInvocation, tool } from 'ai';\nimport { z } from 'zod';\n\nexport const GetWeatherSchema = z.object({\n location: z.string(),\n unit: z.enum(['C', 'F']),\n temperature: z.number(),\n condition: z.string(),\n high: z.number(),\n low: z.number(),\n humidity: z.number(),\n windKph: z.number(),\n icon: z.string().optional(),\n});\n\nexport type GetWeatherResult = z.infer<typeof GetWeatherSchema>;\n\nexport const getWeatherTool = tool({\n name: 'weather',\n description: 'Get the current weather for a location.',\n inputSchema: z.object({\n location: z.string().describe('City name, address or coordinates'),\n unit: z.enum(['C', 'F']).default('C'),\n }),\n outputSchema: GetWeatherSchema,\n execute: async ({ location, unit }) => {\n const { latitude, longitude, name } = await geocodeLocation(location);\n\n const params = new URLSearchParams({\n latitude: String(latitude),\n longitude: String(longitude),\n current: [\n 'temperature_2m',\n 'relative_humidity_2m',\n 'wind_speed_10m',\n 'weather_code',\n ].join(','),\n daily: ['temperature_2m_max', 'temperature_2m_min'].join(','),\n timezone: 'auto',\n temperature_unit: unit === 'F' ? 'fahrenheit' : 'celsius',\n wind_speed_unit: 'kmh',\n });\n\n const url = `https://api.open-meteo.com/v1/forecast?${params.toString()}`;\n const res = await fetch(url);\n if (!res.ok) throw new Error(`Weather API failed: ${res.status}`);\n const data = (await res.json()) as ForecastResponse;\n\n const current = data?.current;\n const daily = data?.daily;\n if (!current || !daily) throw new Error('Malformed weather API response');\n\n const weatherCode = Number(current.weather_code);\n const mapped = mapWeatherCode(weatherCode);\n\n const result: GetWeatherResult = {\n location: name,\n unit,\n temperature: Math.round(Number(current.temperature_2m)),\n condition: mapped.condition,\n high: Math.round(Number(daily.temperature_2m_max?.[0])),\n low: Math.round(Number(daily.temperature_2m_min?.[0])),\n humidity: Math.max(\n 0,\n Math.min(1, Number(current.relative_humidity_2m) / 100),\n ),\n windKph: Math.round(Number(current.wind_speed_10m)),\n icon: mapped.icon,\n };\n\n return result;\n },\n});\n\ninterface GeocodeItem {\n id: number;\n name: string;\n latitude: number;\n longitude: number;\n elevation?: number;\n country_code?: string;\n admin1?: string;\n timezone?: string;\n}\n\ninterface GeocodeResponse {\n results?: GeocodeItem[];\n}\n\ninterface ForecastCurrent {\n time: string;\n interval: number;\n temperature_2m: number;\n relative_humidity_2m: number;\n wind_speed_10m: number;\n weather_code: number;\n}\n\ninterface ForecastDaily {\n time: string[];\n temperature_2m_max: number[];\n temperature_2m_min: number[];\n}\n\ninterface ForecastResponse {\n current: ForecastCurrent;\n daily: ForecastDaily;\n}\n\nasync function geocodeLocation(location: string): Promise<{\n latitude: number;\n longitude: number;\n name: string;\n}> {\n // Allow \"lat,lon\" inputs without geocoding\n const coordMatch = location\n .trim()\n .match(/^\\s*(-?\\d+(?:\\.\\d+)?)\\s*,\\s*(-?\\d+(?:\\.\\d+)?)\\s*$/);\n if (coordMatch) {\n const latitude = parseFloat(coordMatch[1]);\n const longitude = parseFloat(coordMatch[2]);\n return {\n latitude,\n longitude,\n name: `${latitude.toFixed(3)}, ${longitude.toFixed(3)}`,\n };\n }\n\n const url = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(\n location,\n )}&count=1&language=en&format=json`;\n const res = await fetch(url);\n if (!res.ok) throw new Error(`Geocoding failed: ${res.status}`);\n const data = (await res.json()) as GeocodeResponse;\n const first = data?.results?.[0];\n if (!first) throw new Error(`Location not found: ${location}`);\n const nameParts = [first.name, first.admin1, first.country_code].filter(\n Boolean,\n );\n return {\n latitude: first.latitude,\n longitude: first.longitude,\n name: nameParts.join(', '),\n };\n}\n\nfunction mapWeatherCode(code: number): { condition: string; icon?: string } {\n switch (code) {\n case 0:\n return { condition: 'Clear sky', icon: 'weather-sun' };\n case 1:\n return { condition: 'Mainly clear', icon: 'weather-sun' };\n case 2:\n return { condition: 'Partly cloudy', icon: 'weather-partly' };\n case 3:\n return { condition: 'Overcast', icon: 'weather-cloud' };\n case 45:\n case 48:\n return { condition: 'Fog', icon: 'weather-fog' };\n case 51:\n case 53:\n case 55:\n case 56:\n case 57:\n return { condition: 'Drizzle', icon: 'weather-drizzle' };\n case 61:\n case 63:\n case 65:\n case 66:\n case 67:\n return { condition: 'Rain', icon: 'weather-rain' };\n case 71:\n case 73:\n case 75:\n case 77:\n return { condition: 'Snow', icon: 'weather-snow' };\n case 80:\n case 81:\n case 82:\n return { condition: 'Showers', icon: 'weather-showers' };\n case 85:\n case 86:\n return { condition: 'Snow showers', icon: 'weather-snow' };\n case 95:\n case 96:\n case 99:\n return { condition: 'Thunderstorm', icon: 'weather-thunder' };\n default:\n return { condition: 'Unknown' };\n }\n}\n\nexport type WeatherToolType = UIToolInvocation<typeof getWeatherTool>;\n", "import { groq } from '@ai-sdk/groq';\n\nimport { agent } from '@deepagents/agent';\n\nimport { duckDuckGoSearch } from './ddg-search.ts';\n\n\nexport const web_search_tool = duckDuckGoSearch;\n\nexport const searchAgent = agent({\n name: 'research_agent',\n model: groq('openai/gpt-oss-20b'),\n prompt:\n 'You are a diligent research assistant. Your task is to gather accurate and relevant information on a given topic using web search. Use the browser_search tool to find up-to-date information, and synthesize your findings into a concise summary.',\n tools: {\n browser_search: duckDuckGoSearch,\n },\n});\n", "import { tool } from 'ai';\nimport z from 'zod';\n\nimport { toState } from '@deepagents/agent';\n\nconst AcceptanceCriteriaSchema = z.object({\n criterion: z.string().describe('A specific, testable acceptance criterion'),\n});\n\nconst UserStorySchema = z.object({\n title: z.string().describe('Clear, concise title for the user story'),\n userRole: z\n .string()\n .describe('The user role or persona (e.g., \"developer\", \"end user\")'),\n action: z.string().describe('What the user wants to do'),\n benefit: z.string().describe('The value or benefit the user gets'),\n acceptanceCriteria: z\n .array(AcceptanceCriteriaSchema)\n .describe('List of specific, testable conditions that must be met'),\n technicalNotes: z\n .string()\n .optional()\n .describe(\n 'Relevant files, components, or dependencies from the repository',\n ),\n priority: z\n .enum(['High', 'Medium', 'Low'])\n .describe('Priority level based on complexity and dependencies'),\n storyPoints: z\n .enum(['1', '2', '3', '5', '8', '13'])\n .describe('Estimated complexity using Fibonacci sequence'),\n epicOrFeature: z\n .string()\n .optional()\n .describe('The epic or feature group this story belongs to'),\n});\n\nexport const user_story_formatter_tool = tool({\n description: `Tool for formatting and recording user stories in a standardized format.\n\n Use this tool to create well-structured user stories following product management best practices.\n Each story should follow the format: \"As a [role], I want to [action], so that [benefit]\"\n\n When to use:\n - After analyzing a feature or component in the codebase\n - When you've gathered enough information to write a complete user story\n - To document findings in a structured, actionable format\n - To maintain consistency across all generated user stories\n\n The tool will:\n 1. Format the story in the standard user story template\n 2. Store it in the context for later synthesis\n 3. Return a formatted version for immediate review\n`,\n inputSchema: UserStorySchema,\n execute: async (story, options) => {\n const context = toState<{ userStories: (typeof story)[] }>(options);\n context.userStories ??= [];\n context.userStories.push(story);\n\n // Format the user story for output\n const formatted = `\n## ${story.title}\n\n**User Story:**\nAs a **${story.userRole}**, I want to **${story.action}**, so that **${story.benefit}**.\n\n**Acceptance Criteria:**\n${story.acceptanceCriteria.map((ac, i) => `${i + 1}. ${ac.criterion}`).join('\\n')}\n\n**Technical Notes:**\n${story.technicalNotes || 'N/A'}\n\n**Priority:** ${story.priority}\n**Story Points:** ${story.storyPoints}\n${story.epicOrFeature ? `**Epic/Feature:** ${story.epicOrFeature}` : ''}\n\n---\n`.trim();\n\n return `User story recorded successfully!\\n\\n${formatted}\\n\\nTotal stories recorded: ${context.userStories.length}`;\n },\n});\n", "import { tool } from 'ai';\nimport { z } from 'zod';\n\nimport { toState } from '@deepagents/agent';\n\nexport interface HNSearchItem {\n objectID: string;\n title: string | null;\n url: string | null;\n author: string;\n points: number | null;\n story_text: string | null;\n comment_text: string | null;\n num_comments: number | null;\n created_at: string;\n created_at_i: number;\n _tags: string[];\n}\n\nexport interface HNSearchResponse {\n query: string;\n hits: HNSearchItem[];\n nbHits: number;\n page: number;\n nbPages: number;\n hitsPerPage: number;\n}\n\nexport interface HNItemResponse {\n id: string;\n created_at: string;\n created_at_i: number;\n type: 'story' | 'comment' | 'poll' | 'pollopt' | 'show' | 'ask' | 'job';\n author: string;\n title?: string;\n url?: string;\n text?: string;\n points?: number;\n parent_id?: string;\n children?: HNItemResponse[];\n story_id?: string;\n story_title?: string;\n story_url?: string;\n}\n\nexport interface HNUserResponse {\n username: string;\n about?: string;\n karma: number;\n created_at: string;\n created_at_i: number;\n}\n\nfunction buildTags(options: {\n type?: 'story' | 'comment' | 'all';\n author?: string;\n}): string | undefined {\n const tags: string[] = [];\n\n if (options.type && options.type !== 'all') {\n tags.push(options.type);\n }\n\n if (options.author) {\n tags.push(`author_${options.author}`);\n }\n\n return tags.length > 0 ? tags.join(',') : undefined;\n}\n\nfunction buildNumericFilters(options: {\n timeFilter?: 'd' | 'w' | 'm' | 'y' | 'all';\n minPoints?: number;\n minComments?: number;\n maxAgeHours?: number;\n}): string | undefined {\n const filters: string[] = [];\n\n if (options.timeFilter && options.timeFilter !== 'all') {\n const now = Math.floor(Date.now() / 1000);\n const timeMap = {\n d: 86400, // 1 day in seconds\n w: 604800, // 1 week\n m: 2592000, // ~30 days\n y: 31536000, // ~365 days\n };\n const seconds = timeMap[options.timeFilter];\n const timestamp = now - seconds;\n filters.push(`created_at_i>${timestamp}`);\n }\n\n if (options.maxAgeHours !== undefined && options.maxAgeHours > 0) {\n const now = Math.floor(Date.now() / 1000);\n const seconds = options.maxAgeHours * 3600;\n const timestamp = now - seconds;\n filters.push(`created_at_i>${timestamp}`);\n }\n\n if (options.minPoints !== undefined && options.minPoints > 0) {\n filters.push(`points>=${options.minPoints}`);\n }\n\n if (options.minComments !== undefined && options.minComments > 0) {\n filters.push(`num_comments>=${options.minComments}`);\n }\n\n return filters.length > 0 ? filters.join(',') : undefined;\n}\n\nasync function searchHackerNewsAPI(params: {\n query?: string;\n tags?: string;\n numericFilters?: string;\n sortBy?: 'relevance' | 'date';\n page?: number;\n hitsPerPage?: number;\n}): Promise<HNSearchResponse> {\n const {\n query = '',\n tags,\n numericFilters,\n sortBy = 'relevance',\n page = 0,\n hitsPerPage = 20,\n } = params;\n\n const endpoint =\n sortBy === 'date'\n ? 'http://hn.algolia.com/api/v1/search_by_date'\n : 'http://hn.algolia.com/api/v1/search';\n\n const urlParams = new URLSearchParams();\n\n if (query) {\n urlParams.set('query', query);\n }\n\n if (tags) {\n urlParams.set('tags', tags);\n }\n\n if (numericFilters) {\n urlParams.set('numericFilters', numericFilters);\n }\n\n urlParams.set('page', page.toString());\n urlParams.set('hitsPerPage', Math.min(hitsPerPage, 1000).toString());\n\n const url = `${endpoint}?${urlParams.toString()}`;\n\n try {\n const response = await fetch(url, {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `HN API error: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n return data as HNSearchResponse;\n } catch (error) {\n throw new Error(\n `Failed to search HackerNews: ${error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n}\n\nasync function fetchHNItem(id: string): Promise<HNItemResponse> {\n const url = `http://hn.algolia.com/api/v1/items/${id}`;\n\n try {\n const response = await fetch(url, {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `HN API error: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n return data as HNItemResponse;\n } catch (error) {\n throw new Error(\n `Failed to fetch HN item: ${error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n}\n\nasync function fetchHNUser(username: string): Promise<HNUserResponse> {\n const url = `http://hn.algolia.com/api/v1/users/${username}`;\n\n try {\n const response = await fetch(url, {\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `HN API error: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n return data as HNUserResponse;\n } catch (error) {\n throw new Error(\n `Failed to fetch HN user: ${error instanceof Error ? error.message : 'Unknown error'}`,\n );\n }\n}\n\nfunction formatDate(timestamp: number): string {\n return new Date(timestamp * 1000).toLocaleString();\n}\n\nfunction formatHNLink(id: string): string {\n return `https://news.ycombinator.com/item?id=${id}`;\n}\n\nfunction truncateText(text: string, maxLength: number): string {\n if (text.length <= maxLength) return text;\n return `${text.substring(0, maxLength)}...`;\n}\n\nfunction formatStoryItem(\n hit: HNSearchItem,\n index: number,\n page: number,\n hitsPerPage: number,\n): string {\n const lines: string[] = [];\n const itemNumber = page * hitsPerPage + index + 1;\n\n lines.push(`\\n${itemNumber}. ${hit.title || '(No title)'}`);\n\n if (hit.url) {\n lines.push(` URL: ${hit.url}`);\n }\n\n if (hit.points !== null) {\n lines.push(\n ` ${hit.points} points | by ${hit.author} | ${hit.num_comments || 0} comments`,\n );\n } else {\n lines.push(` by ${hit.author}`);\n }\n\n lines.push(` Date: ${formatDate(hit.created_at_i)}`);\n\n if (hit.story_text) {\n lines.push(` Text: ${truncateText(hit.story_text, 200)}`);\n }\n\n lines.push(` HN Link: ${formatHNLink(hit.objectID)}`);\n\n return lines.join('\\n');\n}\n\nfunction formatCommentItem(\n hit: HNSearchItem,\n index: number,\n page: number,\n hitsPerPage: number,\n): string {\n const lines: string[] = [];\n const itemNumber = page * hitsPerPage + index + 1;\n\n lines.push(`\\n${itemNumber}. Comment by ${hit.author}`);\n\n if (hit.comment_text) {\n lines.push(` ${truncateText(hit.comment_text, 300)}`);\n }\n\n lines.push(` Date: ${formatDate(hit.created_at_i)}`);\n lines.push(` HN Link: ${formatHNLink(hit.objectID)}`);\n\n return lines.join('\\n');\n}\n\nfunction formatMixedItem(\n hit: HNSearchItem,\n index: number,\n page: number,\n hitsPerPage: number,\n): string {\n const lines: string[] = [];\n const itemNumber = page * hitsPerPage + index + 1;\n const isStory = hit._tags.includes('story');\n const isComment = hit._tags.includes('comment');\n const type = isStory ? 'Story' : 'Comment';\n\n lines.push(`\\n${itemNumber}. [${type}] ${hit.title || 'Comment'}`);\n\n if (isStory) {\n if (hit.url) {\n lines.push(` URL: ${hit.url}`);\n }\n if (hit.points !== null) {\n lines.push(` ${hit.points} points | ${hit.num_comments || 0} comments`);\n }\n if (hit.story_text) {\n lines.push(` Text: ${truncateText(hit.story_text, 200)}`);\n }\n } else if (isComment && hit.comment_text) {\n lines.push(` ${truncateText(hit.comment_text, 200)}`);\n }\n\n lines.push(` Date: ${formatDate(hit.created_at_i)}`);\n lines.push(` HN Link: ${formatHNLink(hit.objectID)}`);\n\n return lines.join('\\n');\n}\n\nfunction formatSearchResults(\n response: HNSearchResponse,\n options: {\n itemType: 'story' | 'comment' | 'mixed';\n emptyMessage: string;\n },\n): string {\n const { hits, nbHits, page, nbPages } = response;\n const { itemType, emptyMessage } = options;\n\n if (hits.length === 0) {\n return emptyMessage;\n }\n\n const formatItem = (hit: HNSearchItem, index: number) => {\n switch (itemType) {\n case 'story':\n return formatStoryItem(hit, index, page, response.hitsPerPage);\n case 'comment':\n return formatCommentItem(hit, index, page, response.hitsPerPage);\n case 'mixed':\n return formatMixedItem(hit, index, page, response.hitsPerPage);\n }\n };\n\n const results = hits.map(formatItem);\n const typeLabel =\n itemType === 'mixed'\n ? 'results'\n : `${itemType === 'story' ? 'stories' : 'comments'}`;\n const header = `Found ${nbHits} ${typeLabel} (showing page ${page + 1} of ${nbPages}):\\n`;\n\n return header + results.join('\\n');\n}\n\nfunction formatStoryResults(response: HNSearchResponse): string {\n return formatSearchResults(response, {\n itemType: 'story',\n emptyMessage: `No stories found for query: \"${response.query}\"`,\n });\n}\n\nfunction formatCommentResults(response: HNSearchResponse): string {\n return formatSearchResults(response, {\n itemType: 'comment',\n emptyMessage: `No comments found for query: \"${response.query}\"`,\n });\n}\n\nfunction formatAuthorResults(response: HNSearchResponse): string {\n return formatSearchResults(response, {\n itemType: 'mixed',\n emptyMessage: 'No results found for this author',\n });\n}\n\nfunction formatItemDetails(item: HNItemResponse): string {\n const lines: string[] = [];\n\n if (item.type === 'story') {\n lines.push(`Story: ${item.title || '(No title)'}`);\n if (item.url) {\n lines.push(`URL: ${item.url}`);\n }\n lines.push(`By: ${item.author}`);\n if (item.points !== undefined) {\n lines.push(`Points: ${item.points}`);\n }\n lines.push(`Date: ${formatDate(item.created_at_i)}`);\n if (item.text) {\n lines.push(`\\nText:\\n${item.text}`);\n }\n lines.push(`\\nHN Link: ${formatHNLink(item.id)}`);\n } else if (item.type === 'comment') {\n lines.push(`Comment by ${item.author}`);\n if (item.story_title) {\n lines.push(`On story: ${item.story_title}`);\n }\n lines.push(`Date: ${formatDate(item.created_at_i)}`);\n if (item.text) {\n lines.push(`\\n${item.text}`);\n }\n lines.push(`\\nHN Link: ${formatHNLink(item.id)}`);\n }\n\n return lines.join('\\n');\n}\n\nfunction formatUserProfile(user: HNUserResponse): string {\n const lines: string[] = [];\n\n lines.push(`User: ${user.username}`);\n lines.push(`Karma: ${user.karma.toLocaleString()}`);\n lines.push(`Member since: ${formatDate(user.created_at_i)}`);\n\n if (user.about) {\n lines.push(`\\nAbout:\\n${user.about}`);\n }\n\n lines.push(\n `\\nProfile: https://news.ycombinator.com/user?id=${user.username}`,\n );\n\n return lines.join('\\n');\n}\n\nfunction formatJobItem(\n hit: HNSearchItem,\n index: number,\n page: number,\n hitsPerPage: number,\n): string {\n const lines: string[] = [];\n const itemNumber = page * hitsPerPage + index + 1;\n\n lines.push(`\\n${itemNumber}. ${hit.title || '(No title)'}`);\n\n if (hit.url) {\n lines.push(` URL: ${hit.url}`);\n }\n\n lines.push(` Posted by: ${hit.author}`);\n lines.push(` Date: ${formatDate(hit.created_at_i)}`);\n\n if (hit.story_text) {\n lines.push(` Description: ${truncateText(hit.story_text, 300)}`);\n }\n\n lines.push(` HN Link: ${formatHNLink(hit.objectID)}`);\n\n return lines.join('\\n');\n}\n\nfunction formatJobResults(response: HNSearchResponse): string {\n const { hits, nbHits, page, nbPages } = response;\n\n if (hits.length === 0) {\n return `No job postings found for query: \"${response.query}\"`;\n }\n\n const results = hits.map((hit, index) =>\n formatJobItem(hit, index, page, response.hitsPerPage),\n );\n\n const header = `Found ${nbHits} job postings (showing page ${page + 1} of ${nbPages}):\\n`;\n return header + results.join('\\n');\n}\n\nexport const search_by_query = tool({\n description:\n 'Tool to search HackerNews stories by keywords and filters. Use when you need to find HN stories matching specific search criteria, time periods, or popularity thresholds.',\n inputSchema: z.object({\n query: z\n .string()\n .describe(\n 'Search query for story titles and content. Examples: \"artificial intelligence\", \"python\"',\n ),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minPoints: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum points threshold'),\n minComments: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum comments threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('relevance')\n .describe('Sort results by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'story',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const search_by_author = tool({\n description:\n 'Tool to search HackerNews content by author username. Use when you need to find all stories, comments, or both by a specific HN user.',\n inputSchema: z.object({\n author: z\n .string()\n .describe('HackerNews username to search for. Examples: \"pg\", \"tptacek\"'),\n type: z\n .enum(['story', 'comment', 'all'])\n .default('all')\n .describe('Type of content: story, comment, or all'),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minComments: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum comments threshold (for stories only)'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort results by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const tags = buildTags({ type: input.type, author: input.author });\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n tags,\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatAuthorResults(response);\n },\n});\n\nexport const get_story_item = tool({\n description:\n 'Tool to get detailed information about a specific HackerNews story by ID. Use when you need full details about a particular HN story including title, URL, author, points, and comments.',\n inputSchema: z.object({\n storyId: z.string().describe('HackerNews story ID. Example: \"38709478\"'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const item = await fetchHNItem(input.storyId);\n\n if (item.type !== 'story') {\n throw new Error(\n `Item ${input.storyId} is not a story (type: ${item.type})`,\n );\n }\n\n context.hackernews_sources.push({\n title: item.title || 'Untitled',\n hn_url: `https://news.ycombinator.com/item?id=${item.id}`,\n story_url: item.url || '',\n });\n\n return formatItemDetails(item);\n },\n});\n\nexport const get_story_comment = tool({\n description:\n 'Tool to get detailed information about a specific HackerNews comment by ID. Use when you need full details about a particular comment including text, author, and parent story information.',\n inputSchema: z.object({\n commentId: z\n .string()\n .describe('HackerNews comment ID. Example: \"38710123\"'),\n }),\n execute: async (input) => {\n const item = await fetchHNItem(input.commentId);\n\n if (item.type !== 'comment') {\n throw new Error(\n `Item ${input.commentId} is not a comment (type: ${item.type})`,\n );\n }\n\n return formatItemDetails(item);\n },\n});\n\nexport const get_front_page_stories = tool({\n description:\n 'Tool to get current HackerNews front page stories. Use when you need to see the latest trending and popular stories on HN.',\n inputSchema: z.object({\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(50)\n .default(30)\n .describe('Results per page (max 50)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const response = await searchHackerNewsAPI({\n tags: 'front_page',\n sortBy: 'date',\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const get_story_comments = tool({\n description:\n 'Tool to get all comments for a specific HackerNews story. Use when you need to read the discussion and comments on a particular HN story.',\n inputSchema: z.object({\n storyId: z.string().describe('HackerNews story ID. Example: \"38709478\"'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort comments by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(50)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input) => {\n const response = await searchHackerNewsAPI({\n tags: `comment,story_${input.storyId}`,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n return formatCommentResults(response);\n },\n});\n\nexport const search_ask_hn = tool({\n description:\n 'Tool to search Ask HN posts - questions posed to the HackerNews community. Use when you need to find community questions and discussions on specific topics.',\n inputSchema: z.object({\n query: z\n .string()\n .default('')\n .describe(\n 'Search query for Ask HN posts. Examples: \"artificial intelligence\", \"career\"',\n ),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minPoints: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum points threshold'),\n minComments: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum comments threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('relevance')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'ask_hn',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const search_show_hn = tool({\n description:\n 'Tool to search Show HN posts - projects and products shared with the HackerNews community. Use when you need to discover community projects, demos, or products on specific topics.',\n inputSchema: z.object({\n query: z\n .string()\n .default('')\n .describe(\n 'Search query for Show HN posts. Examples: \"web app\", \"open source\"',\n ),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minPoints: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum points threshold'),\n minComments: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum comments threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('relevance')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'show_hn',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const search_jobs = tool({\n description:\n 'Tool to search HackerNews job postings. Use when you need to find tech job opportunities posted on HN.',\n inputSchema: z.object({\n query: z\n .string()\n .default('')\n .describe(\n 'Search query for job postings. Examples: \"remote\", \"machine learning\"',\n ),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'job',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatJobResults(response);\n },\n});\n\nexport const search_polls = tool({\n description:\n 'Tool to search HackerNews polls - community surveys and voting. Use when you need to find community polls on various topics.',\n inputSchema: z.object({\n query: z\n .string()\n .default('')\n .describe('Search query for polls. Example: \"programming language\"'),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'poll',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const get_user_profile = tool({\n description:\n \"Tool to get HackerNews user profile information. Use when you need to view a user's karma, account creation date, and bio.\",\n inputSchema: z.object({\n username: z.string().describe('HackerNews username. Example: \"pg\"'),\n }),\n execute: async (input) => {\n const user = await fetchHNUser(input.username);\n return formatUserProfile(user);\n },\n});\n\nexport const search_by_domain = tool({\n description:\n 'Tool to search HackerNews stories from a specific domain or website. Use when you need to find all HN posts from a particular domain or track discussions about content from specific websites.',\n inputSchema: z.object({\n domain: z\n .string()\n .describe('Domain to search. Examples: \"github.com\", \"arxiv.org\"'),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minPoints: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum points threshold'),\n minComments: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum comments threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const urlParams = new URLSearchParams();\n urlParams.set('query', input.domain);\n urlParams.set('restrictSearchableAttributes', 'url');\n urlParams.set('tags', 'story');\n if (numericFilters) {\n urlParams.set('numericFilters', numericFilters);\n }\n urlParams.set('page', input.page.toString());\n urlParams.set('hitsPerPage', input.hitsPerPage.toString());\n\n const endpoint =\n input.sortBy === 'date'\n ? 'http://hn.algolia.com/api/v1/search_by_date'\n : 'http://hn.algolia.com/api/v1/search';\n\n const url = `${endpoint}?${urlParams.toString()}`;\n\n const response = await fetch(url, {\n headers: { 'Content-Type': 'application/json' },\n });\n\n if (!response.ok) {\n throw new Error(\n `HN API error: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = (await response.json()) as HNSearchResponse;\n fillContext(context, data);\n return formatStoryResults(data);\n },\n});\n\nexport const search_highly_discussed = tool({\n description:\n 'Tool to search for highly discussed HackerNews stories with many comments. Use when you need to find engaging or controversial discussions with significant community participation.',\n inputSchema: z.object({\n minComments: z\n .number()\n .int()\n .min(1)\n .describe(\n 'Minimum number of comments (required). Example: 100 for highly discussed stories',\n ),\n query: z\n .string()\n .default('')\n .describe('Optional search query. Example: \"AI\"'),\n timeFilter: z\n .enum(['d', 'w', 'm', 'y', 'all'])\n .default('all')\n .describe('Time filter: d=day, w=week, m=month, y=year, all=no filter'),\n minPoints: z\n .number()\n .int()\n .min(0)\n .optional()\n .describe('Minimum points threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(1000)\n .default(20)\n .describe('Results per page (max 1000)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n timeFilter: input.timeFilter,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n query: input.query,\n tags: 'story',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nexport const search_trending = tool({\n description:\n \"Tool to find currently trending HackerNews stories - recent posts with high engagement. Use when you need to discover what's hot right now on HN by combining recency with high points and comments.\",\n inputSchema: z.object({\n minPoints: z\n .number()\n .int()\n .min(10)\n .default(50)\n .describe(\n 'Minimum points threshold. Example: 100 for highly upvoted stories',\n ),\n maxAgeHours: z\n .number()\n .int()\n .min(1)\n .max(72)\n .default(24)\n .describe('Maximum age in hours. Example: 24 for stories from today'),\n minComments: z\n .number()\n .int()\n .min(0)\n .default(10)\n .describe('Minimum comments threshold'),\n sortBy: z\n .enum(['relevance', 'date'])\n .default('date')\n .describe('Sort by relevance or date'),\n page: z\n .number()\n .int()\n .min(0)\n .default(0)\n .describe('Page number (0-indexed)'),\n hitsPerPage: z\n .number()\n .int()\n .min(1)\n .max(100)\n .default(30)\n .describe('Results per page (max 100)'),\n }),\n execute: async (input, options) => {\n const context = toState<{\n hackernews_sources: {\n title: string;\n hn_url: string;\n story_url: string;\n }[];\n }>(options);\n context.hackernews_sources ??= [];\n\n const numericFilters = buildNumericFilters({\n maxAgeHours: input.maxAgeHours,\n minPoints: input.minPoints,\n minComments: input.minComments,\n });\n\n const response = await searchHackerNewsAPI({\n tags: 'story',\n numericFilters,\n sortBy: input.sortBy,\n page: input.page,\n hitsPerPage: input.hitsPerPage,\n });\n\n fillContext(context, response);\n return formatStoryResults(response);\n },\n});\n\nfunction fillContext(\n context: {\n hackernews_sources: {\n title?: string | null;\n hn_url?: string | null;\n story_url?: string | null;\n story_text?: string | null;\n comment_text?: string | null;\n }[];\n },\n result: HNSearchResponse,\n) {\n result.hits.forEach((hit) => {\n context.hackernews_sources.push({\n title: hit.title,\n hn_url: hit.objectID\n ? `https://news.ycombinator.com/item?id=${hit.objectID}`\n : undefined,\n story_url: hit.url,\n story_text: hit.story_text,\n comment_text: hit.comment_text,\n });\n });\n}\n\nexport const hackernewsTools = {\n search_by_query,\n search_by_author,\n get_story_item,\n get_story_comment,\n get_front_page_stories,\n get_story_comments,\n search_ask_hn,\n search_show_hn,\n search_jobs,\n search_polls,\n get_user_profile,\n search_by_domain,\n search_highly_discussed,\n search_trending,\n};\n"],
5
+ "mappings": ";AAAA,SAAS,YAAY;AACrB,OAAO,WAAW;AAClB,SAAS,SAAS;AAEX,IAAM,qBAAqB,KAAK;AAAA,EACrC,aACE;AAAA,EACF,aAAa,EAAE,OAAO;AAAA,IACpB,SAAS,EACN,MAAM,EAAE,OAAO,EAAE,IA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ACpD;AAAA,MACJ,WAAW,IAAI;AAAA,MACf,YAAY,IAAI;AAAA,MAChB,cAAc,IAAI;AAAA,IACpB,CAAC;AAAA,EACH,CAAC;AACH;AAEO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;",
6
+ "names": ["tool", "z", "res", "items", "z", "tool", "tool", "z", "tool", "z", "tool", "z", "tool", "z", "toState", "tool", "z", "toState"]
7
7
  }
@@ -38,5 +38,5 @@ export declare const web_search_tool: import("ai").Tool<{
38
38
  readonly total: number;
39
39
  readonly vqd: string;
40
40
  }>;
41
- export declare const searchAgent: import("@deepagents/agent").Agent<unknown, import("@deepagents/agent").ContextVariables>;
41
+ export declare const searchAgent: import("@deepagents/agent").Agent<unknown, import("@deepagents/agent").ContextVariables, import("@deepagents/agent").ContextVariables>;
42
42
  //# sourceMappingURL=web-search.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"web-search.d.ts","sourceRoot":"","sources":["../../src/lib/web-search.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAmB,CAAC;AAEhD,eAAO,MAAM,WAAW,0FAQtB,CAAC"}
1
+ {"version":3,"file":"web-search.d.ts","sourceRoot":"","sources":["../../src/lib/web-search.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAAmB,CAAC;AAEhD,eAAO,MAAM,WAAW,wIAQtB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepagents/toolbox",
3
- "version": "0.1.2",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -28,7 +28,7 @@
28
28
  },
29
29
  "dependencies": {
30
30
  "@ai-sdk/groq": "2.0.26",
31
- "@deepagents/agent": "0.1.2",
31
+ "@deepagents/agent": "0.2.1",
32
32
  "ai": "^5.0.82",
33
33
  "duck-duck-scrape": "^2.2.7",
34
34
  "lodash-es": "^4.17.21",