@deepagents/orchestrator 6.1.2 → 7.0.0

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.
Files changed (61) hide show
  1. package/dist/index.d.ts +1 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/lib/arxiv/arxiv.js +153 -0
  4. package/dist/lib/arxiv/arxiv.js.map +7 -0
  5. package/dist/lib/citation.js +120 -0
  6. package/dist/lib/citation.js.map +7 -0
  7. package/dist/lib/deepplan/demo.js +518 -0
  8. package/dist/lib/deepplan/demo.js.map +7 -0
  9. package/dist/lib/deepplan/executors/generic-executor.js +196 -0
  10. package/dist/lib/deepplan/executors/generic-executor.js.map +7 -0
  11. package/dist/lib/deepplan/executors/hackernews-executor.js +210 -0
  12. package/dist/lib/deepplan/executors/hackernews-executor.js.map +7 -0
  13. package/dist/lib/deepplan/executors/product-manager-executor.js +226 -0
  14. package/dist/lib/deepplan/executors/product-manager-executor.js.map +7 -0
  15. package/dist/lib/deepplan/executors/repo-search-executor.js +76 -0
  16. package/dist/lib/deepplan/executors/repo-search-executor.js.map +7 -0
  17. package/dist/lib/deepplan/executors/research-executor.js +196 -0
  18. package/dist/lib/deepplan/executors/research-executor.js.map +7 -0
  19. package/dist/lib/deepplan/next/plan.js +1 -0
  20. package/dist/lib/deepplan/next/plan.js.map +7 -0
  21. package/dist/lib/deepplan/plan-and-solve.js +826 -0
  22. package/dist/lib/deepplan/plan-and-solve.js.map +7 -0
  23. package/dist/lib/deepplan/planner-agent.js +416 -0
  24. package/dist/lib/deepplan/planner-agent.js.map +7 -0
  25. package/dist/lib/deepplan/replanner-agent.js +418 -0
  26. package/dist/lib/deepplan/replanner-agent.js.map +7 -0
  27. package/dist/lib/deepplan/synthesizer.js +75 -0
  28. package/dist/lib/deepplan/synthesizer.js.map +7 -0
  29. package/dist/lib/deepresearch.v0.js +297 -0
  30. package/dist/lib/deepresearch.v0.js.map +7 -0
  31. package/dist/lib/deepresearch.v1.js +260 -0
  32. package/dist/lib/deepresearch.v1.js.map +7 -0
  33. package/dist/lib/deepwiki/complete-wiki.js +319 -0
  34. package/dist/lib/deepwiki/complete-wiki.js.map +7 -0
  35. package/dist/lib/deepwiki/deepwiki.js +370 -0
  36. package/dist/lib/deepwiki/deepwiki.js.map +7 -0
  37. package/dist/lib/deepwiki/gitignore-agent.js +40 -0
  38. package/dist/lib/deepwiki/gitignore-agent.js.map +7 -0
  39. package/dist/lib/deepwiki/outline-agent.js +186 -0
  40. package/dist/lib/deepwiki/outline-agent.js.map +7 -0
  41. package/dist/lib/deepwiki/wiki-writer.js +242 -0
  42. package/dist/lib/deepwiki/wiki-writer.js.map +7 -0
  43. package/dist/lib/deepwiki/writer.js +407 -0
  44. package/dist/lib/deepwiki/writer.js.map +7 -0
  45. package/dist/lib/evolving.js +204 -0
  46. package/dist/lib/evolving.js.map +7 -0
  47. package/dist/lib/graph.js +12 -0
  48. package/dist/lib/graph.js.map +7 -0
  49. package/dist/lib/openai-deepresearch/clarrify-agent.js +67 -0
  50. package/dist/lib/openai-deepresearch/clarrify-agent.js.map +7 -0
  51. package/dist/lib/openai-deepresearch/lead-research.js +168 -0
  52. package/dist/lib/openai-deepresearch/lead-research.js.map +7 -0
  53. package/dist/lib/openai-deepresearch/openai-deepresearch.js +179 -0
  54. package/dist/lib/openai-deepresearch/openai-deepresearch.js.map +7 -0
  55. package/dist/lib/openai-deepresearch/reasearcher.js +62 -0
  56. package/dist/lib/openai-deepresearch/reasearcher.js.map +7 -0
  57. package/dist/lib/openai-deepresearch/research-brief.js +59 -0
  58. package/dist/lib/openai-deepresearch/research-brief.js.map +7 -0
  59. package/dist/lib/repo-context.js +11 -0
  60. package/dist/lib/repo-context.js.map +7 -0
  61. package/package.json +8 -8
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
+ export {};
1
2
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":""}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC"}
@@ -0,0 +1,153 @@
1
+ // packages/orchestrator/src/lib/arxiv/arxiv.ts
2
+ import { openai } from "@ai-sdk/openai";
3
+ import { tool } from "ai";
4
+ import { z } from "zod";
5
+ import {
6
+ agent,
7
+ execute,
8
+ input,
9
+ instructions,
10
+ toState,
11
+ user
12
+ } from "@deepagents/agent";
13
+ import {
14
+ fastembed,
15
+ nodeSQLite,
16
+ similaritySearch
17
+ } from "@deepagents/retrieval";
18
+ import { pdfFile } from "@deepagents/retrieval/connectors";
19
+ var QueryPaperSchema = z.object({
20
+ query: z.string().min(1).describe("The question to ask about the paper")
21
+ });
22
+ var PaperSummarySchema = z.object({
23
+ title: z.string().describe("Paper title"),
24
+ abstract: z.string().describe("Paper abstract or overview"),
25
+ main_contribution: z.string().describe("Main contribution of the paper"),
26
+ methodology: z.string().describe("Key methodology or approach used"),
27
+ key_results: z.string().describe("Main results and findings"),
28
+ limitations: z.string().optional().describe("Limitations mentioned in the paper"),
29
+ future_work: z.string().optional().describe("Future work suggestions")
30
+ });
31
+ async function queryArxivPaper(query, pdfUrl, storePath) {
32
+ const results = await similaritySearch(query, {
33
+ connector: pdfFile(pdfUrl),
34
+ store: nodeSQLite(storePath, 384),
35
+ embedder: fastembed()
36
+ });
37
+ return results.slice(0, 5).map((r) => r.content);
38
+ }
39
+ var queryPaperTool = tool({
40
+ description: "Query the ingested arXiv paper using semantic search. Returns relevant sections from the paper.",
41
+ inputSchema: QueryPaperSchema,
42
+ execute: async ({ query }, options) => {
43
+ const context = toState(options);
44
+ try {
45
+ const results = await queryArxivPaper(
46
+ query,
47
+ context.pdf_url,
48
+ context.store_path
49
+ );
50
+ if (results.length === 0) {
51
+ return "No relevant information found in the paper.";
52
+ }
53
+ const formattedResults = results.map(
54
+ (r, i) => `[Chunk ${i + 1}] (similarity: ${r.similarity.toFixed(3)})
55
+ ${r.content}
56
+ `
57
+ ).join("\n---\n\n");
58
+ return formattedResults;
59
+ } catch (error) {
60
+ return `Error querying paper: ${error instanceof Error ? error.message : "Unknown error"}`;
61
+ }
62
+ }
63
+ });
64
+ var summarizerAgent = agent({
65
+ name: "paper_summarizer",
66
+ model: openai("gpt-4.1-nano"),
67
+ output: PaperSummarySchema,
68
+ prompt: instructions({
69
+ purpose: [
70
+ "You are a research paper analyst.",
71
+ "Given relevant sections from an academic paper, extract and summarize key information."
72
+ ],
73
+ routine: [
74
+ "Read through the provided paper sections carefully",
75
+ "Extract the title, abstract, main contribution, methodology, key results, and any limitations",
76
+ "If certain sections are not available, infer from context or leave blank",
77
+ "Return a structured summary following the schema"
78
+ ]
79
+ })
80
+ });
81
+ var arxivAgent = agent({
82
+ name: "arxiv_researcher",
83
+ model: openai("gpt-4o"),
84
+ prompt: instructions({
85
+ purpose: [
86
+ "You are an arXiv research assistant.",
87
+ "You help users analyze academic papers by ingesting PDFs and answering questions about them."
88
+ ],
89
+ routine: [
90
+ "Answer questions about the paper using the query_paper tool to find relevant sections",
91
+ "Synthesize information from multiple chunks to provide comprehensive answers",
92
+ "When asked for a summary, gather relevant information and provide a structured overview"
93
+ ]
94
+ }),
95
+ tools: {
96
+ query_paper: queryPaperTool
97
+ }
98
+ });
99
+ if (import.meta.main) {
100
+ console.log("<\uFFFD ArXiv Research Assistant\n");
101
+ const pdfUrl = await input("https://arxiv.org/pdf/2103.00020.pdf");
102
+ const url = pdfUrl.trim();
103
+ console.log(`
104
+ Using URL: ${url}
105
+ `);
106
+ const context = {
107
+ pdf_url: url,
108
+ store_path: "./arxiv_papers.db"
109
+ };
110
+ console.log("\nPaper ready for questions!\n");
111
+ console.log("Example questions:");
112
+ console.log(" - What is the main contribution of this paper?");
113
+ console.log(" - Explain the methodology used");
114
+ console.log(" - What are the key results?");
115
+ console.log(" - What are the limitations mentioned?\n");
116
+ while (true) {
117
+ const question = await input('\nYour question (or "quit" to exit): ');
118
+ if (question.toLowerCase() === "quit" || question.toLowerCase() === "exit") {
119
+ console.log("\n=K Goodbye!");
120
+ break;
121
+ }
122
+ if (!question.trim()) {
123
+ continue;
124
+ }
125
+ console.log("\n> Searching paper...\n");
126
+ const results = await queryArxivPaper(question, url, context.store_path);
127
+ if (results.length === 0) {
128
+ console.log("L No relevant information found.\n");
129
+ continue;
130
+ }
131
+ const answer = (await execute(
132
+ arxivAgent,
133
+ [
134
+ user(
135
+ `Based on these sections from the paper, answer: ${question}
136
+
137
+ Sections:
138
+ ${results.map((r) => r.content).join("\n\n")}`
139
+ )
140
+ ],
141
+ context
142
+ )).text;
143
+ console.log(`
144
+ =\uFFFD Answer:
145
+ ${answer}
146
+ `);
147
+ }
148
+ }
149
+ export {
150
+ arxivAgent,
151
+ queryArxivPaper
152
+ };
153
+ //# sourceMappingURL=arxiv.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/lib/arxiv/arxiv.ts"],
4
+ "sourcesContent": ["import { openai } from '@ai-sdk/openai';\nimport { tool } from 'ai';\nimport { z } from 'zod';\n\nimport {\n agent,\n execute,\n input,\n instructions,\n toState,\n user,\n} from '@deepagents/agent';\nimport {\n fastembed,\n ingest,\n nodeSQLite,\n similaritySearch,\n} from '@deepagents/retrieval';\nimport { pdfFile } from '@deepagents/retrieval/connectors';\n\nconst QueryPaperSchema = z.object({\n query: z.string().min(1).describe('The question to ask about the paper'),\n});\n\nconst PaperSummarySchema = z.object({\n title: z.string().describe('Paper title'),\n abstract: z.string().describe('Paper abstract or overview'),\n main_contribution: z.string().describe('Main contribution of the paper'),\n methodology: z.string().describe('Key methodology or approach used'),\n key_results: z.string().describe('Main results and findings'),\n limitations: z\n .string()\n .optional()\n .describe('Limitations mentioned in the paper'),\n future_work: z.string().optional().describe('Future work suggestions'),\n});\n\n// ============================\n// State Management\n// ============================\n\ninterface ArxivAgentContext {\n pdf_url: string;\n store_path: string;\n}\n\nexport async function queryArxivPaper(\n query: string,\n pdfUrl: string,\n storePath: string,\n) {\n const results = await similaritySearch(query, {\n connector: pdfFile(pdfUrl),\n store: nodeSQLite(storePath, 384),\n embedder: fastembed(),\n });\n\n return results.slice(0, 5).map((r) => r.content);\n}\n\nconst queryPaperTool = tool({\n description:\n 'Query the ingested arXiv paper using semantic search. Returns relevant sections from the paper.',\n inputSchema: QueryPaperSchema,\n execute: async ({ query }, options) => {\n const context = toState<ArxivAgentContext>(options);\n try {\n const results = await queryArxivPaper(\n query,\n context.pdf_url,\n context.store_path,\n );\n\n if (results.length === 0) {\n return 'No relevant information found in the paper.';\n }\n\n const formattedResults = results\n .map(\n (r, i) =>\n `[Chunk ${i + 1}] (similarity: ${r.similarity.toFixed(3)})\\n${r.content}\\n`,\n )\n .join('\\n---\\n\\n');\n\n return formattedResults;\n } catch (error) {\n return `Error querying paper: ${error instanceof Error ? error.message : 'Unknown error'}`;\n }\n },\n});\n\n// ============================\n// Agents\n// ============================\n\nconst summarizerAgent = agent({\n name: 'paper_summarizer',\n model: openai('gpt-4.1-nano'),\n output: PaperSummarySchema,\n prompt: instructions({\n purpose: [\n 'You are a research paper analyst.',\n 'Given relevant sections from an academic paper, extract and summarize key information.',\n ],\n routine: [\n 'Read through the provided paper sections carefully',\n 'Extract the title, abstract, main contribution, methodology, key results, and any limitations',\n 'If certain sections are not available, infer from context or leave blank',\n 'Return a structured summary following the schema',\n ],\n }),\n});\n\nexport const arxivAgent = agent<unknown, ArxivAgentContext>({\n name: 'arxiv_researcher',\n model: openai('gpt-4o'),\n prompt: instructions({\n purpose: [\n 'You are an arXiv research assistant.',\n 'You help users analyze academic papers by ingesting PDFs and answering questions about them.',\n ],\n routine: [\n 'Answer questions about the paper using the query_paper tool to find relevant sections',\n 'Synthesize information from multiple chunks to provide comprehensive answers',\n 'When asked for a summary, gather relevant information and provide a structured overview',\n ],\n }),\n tools: {\n query_paper: queryPaperTool,\n },\n});\n\n// ============================\n// Interactive Example\n// ============================\n\nif (import.meta.main) {\n console.log('<\uFFFD ArXiv Research Assistant\\n');\n\n // Get PDF URL from user\n const pdfUrl = await input('https://arxiv.org/pdf/2103.00020.pdf');\n const url = pdfUrl.trim();\n\n console.log(`\\nUsing URL: ${url}\\n`);\n\n // Initialize context\n const context: ArxivAgentContext = {\n pdf_url: url,\n store_path: './arxiv_papers.db',\n };\n\n console.log('\\nPaper ready for questions!\\n');\n console.log('Example questions:');\n console.log(' - What is the main contribution of this paper?');\n console.log(' - Explain the methodology used');\n console.log(' - What are the key results?');\n console.log(' - What are the limitations mentioned?\\n');\n\n // Interactive Q&A loop\n while (true) {\n const question = await input('\\nYour question (or \"quit\" to exit): ');\n\n if (\n question.toLowerCase() === 'quit' ||\n question.toLowerCase() === 'exit'\n ) {\n console.log('\\n=K Goodbye!');\n break;\n }\n\n if (!question.trim()) {\n continue;\n }\n\n console.log('\\n> Searching paper...\\n');\n\n const results = await queryArxivPaper(question, url, context.store_path);\n\n if (results.length === 0) {\n console.log('L No relevant information found.\\n');\n continue;\n }\n\n const answer = (\n await execute(\n arxivAgent,\n [\n user(\n `Based on these sections from the paper, answer: ${question}\\n\\nSections:\\n${results.map((r) => r.content).join('\\n\\n')}`,\n ),\n ],\n context,\n )\n ).text;\n\n console.log(`\\n=\uFFFD Answer:\\n${answer}\\n`);\n }\n}\n"],
5
+ "mappings": ";AAAA,SAAS,cAAc;AACvB,SAAS,YAAY;AACrB,SAAS,SAAS;AAElB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AACP,SAAS,eAAe;AAExB,IAAM,mBAAmB,EAAE,OAAO;AAAA,EAChC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS,qCAAqC;AACzE,CAAC;AAED,IAAM,qBAAqB,EAAE,OAAO;AAAA,EAClC,OAAO,EAAE,OAAO,EAAE,SAAS,aAAa;AAAA,EACx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AAG;AACxB,cAAQ,IAAI,oCAAoC;AAChD;AAAA,IACF;AAEA,UAAM,UACJ,MAAM;AAAA,MACJ;AAAA,MACA;AAAA,QACE;AAAA,UACE,mDAAmD,QAAQ;AAAA;AAAA;AAAA,EAAkB,QAAQ,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,MAAM,CAAC;AAAA,QACzH;AAAA,MACF;AAAA,MACA;AAAA,IACF,GACA;AAEF,YAAQ,IAAI;AAAA;AAAA,EAAiB,MAAM;AAAA,CAAI;AAAA,EACzC;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,120 @@
1
+ // packages/orchestrator/src/lib/citation.ts
2
+ import { groq } from "@ai-sdk/groq";
3
+ import { defaultSettingsMiddleware, wrapLanguageModel } from "ai";
4
+ import dedent from "dedent";
5
+ import { createWriteStream } from "node:fs";
6
+ import { cwd } from "node:process";
7
+ import { Readable } from "node:stream";
8
+ import {
9
+ agent,
10
+ stepBackPrompt,
11
+ stream,
12
+ user
13
+ } from "@deepagents/agent";
14
+ import { repoTree, search_content_tool } from "@deepagents/toolbox";
15
+ var CODE_SEARCH_STEP_BACK_EXAMPLES = [
16
+ {
17
+ originalQuestion: "How to build an agent?",
18
+ stepBackQuestion: "What is agent architecture? What are the core components and patterns for building agents?",
19
+ stepBackAnswer: "Agent architecture consists of: 1) An agent definition with model and prompt, 2) Tools that provide capabilities, 3) State management for context, 4) A streaming interface for responses. The core pattern involves defining the agent's behavior through prompts and equipping it with tools to accomplish tasks.",
20
+ finalAnswer: "Use the agent() function from @deepagents/agent with a prompt, model, and tools. Define the agent's behavior in the prompt and provide tools for specific capabilities."
21
+ },
22
+ {
23
+ originalQuestion: "How does code search work in this codebase?",
24
+ stepBackQuestion: "What are the fundamental principles of code search and content retrieval?",
25
+ stepBackAnswer: "Code search requires: 1) Keyword-based content search across files, 2) Multiple search iterations with varied terms (broad and specific), 3) Result aggregation and citation tracking, 4) Balancing between high-level concepts and specific implementations.",
26
+ finalAnswer: "Search using varied keywords (3-5 searches minimum), combine broad queries (architecture, patterns) with specific queries (class names, function names), and cite all sources."
27
+ }
28
+ ];
29
+ var searchAgent = agent({
30
+ name: "search_agent",
31
+ model: wrapLanguageModel({
32
+ model: groq("openai/gpt-oss-20b"),
33
+ middleware: defaultSettingsMiddleware({
34
+ settings: { temperature: 0.2 }
35
+ })
36
+ }),
37
+ prompt: dedent`
38
+ <context>
39
+ This agent is Freya, a code search assistant that searches repositories thoroughly and answers questions with inline citations. This agent speaks in third person, referring to itself as "this agent" or "Freya".
40
+ </context>
41
+
42
+ <instructions>
43
+ <task>
44
+ Search the code repository to answer the user's question. All claims must be supported by citations from search results.
45
+ </task>
46
+
47
+ <strategy>
48
+ ${stepBackPrompt("general", {
49
+ examples: CODE_SEARCH_STEP_BACK_EXAMPLES,
50
+ stepBackQuestionTemplate: "What are the high-level concepts, architectural patterns, and fundamental principles related to this code search question?"
51
+ })}
52
+
53
+ <search_requirements>
54
+ - Conduct minimum 3-5 searches with different keywords and variations
55
+ - Use both broad queries (abstractions) and specific queries (details)
56
+ - Search for related concepts and alternative implementations
57
+ - Before responding, verify: "Has this agent searched enough different ways to be thorough?"
58
+ </search_requirements>
59
+ </strategy>
60
+
61
+ <requirements>
62
+ <tool_usage>
63
+ - This agent uses search_content_tool to find all information
64
+ - This agent only makes claims backed by actual search results - never guesses
65
+ - If this agent cannot find sufficient information, it states this clearly
66
+ </tool_usage>
67
+
68
+ <citation_rules>
69
+ Each search result includes a pre-formatted "Citation:" field. This agent must copy it exactly and place it immediately after the supported claim.
70
+
71
+ CRITICAL: Never modify the citation format - copy it exactly as provided.
72
+ </citation_rules>
73
+ </requirements>
74
+ </instructions>
75
+
76
+ <examples>
77
+ <example>
78
+ <search_result>
79
+ File: packages/agent/src/lib/agent.ts
80
+ Citation: [agent.ts](./packages/agent/src/lib/agent.ts)
81
+ (followed by code snippet)
82
+ </search_result>
83
+
84
+ <correct_usage>
85
+ "This agent found that the Agent class is defined in the core module [agent.ts](./packages/agent/src/lib/agent.ts)."
86
+ </correct_usage>
87
+
88
+ <incorrect_usage>
89
+ "This agent found info in agent.ts" (missing citation)
90
+ "[packages/agent/src/lib/agent.ts]" (wrong format)
91
+ </incorrect_usage>
92
+ </example>
93
+ </examples>
94
+
95
+ <quality_checklist>
96
+ Before responding, this agent must verify:
97
+ ✓ Has this agent searched at least 3-5 times with different queries?
98
+ ✓ Are all claims backed by search results?
99
+ ✓ Has this agent copied Citation fields exactly from search results?
100
+ ✓ Are citations placed immediately after the claims they support?
101
+ </quality_checklist>
102
+ `,
103
+ tools: {
104
+ search_content_tool
105
+ }
106
+ });
107
+ var state = {
108
+ repo_path: cwd(),
109
+ tree: await repoTree(cwd())
110
+ };
111
+ stream(
112
+ searchAgent,
113
+ [user(`How can we build an sqlite readonly agent chatbot?`)],
114
+ state
115
+ ).then((result) => {
116
+ Readable.fromWeb(result.textStream).pipe(
117
+ createWriteStream("output.md")
118
+ );
119
+ });
120
+ //# sourceMappingURL=citation.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/lib/citation.ts"],
4
+ "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { defaultSettingsMiddleware, wrapLanguageModel } from 'ai';\nimport dedent from 'dedent';\nimport { createWriteStream } from 'node:fs';\nimport { cwd } from 'node:process';\nimport { Readable } from 'node:stream';\n\nimport {\n type StepBackExample,\n agent,\n stepBackPrompt,\n stream,\n user,\n} from '@deepagents/agent';\nimport { repoTree, search_content_tool } from '@deepagents/toolbox';\n\ntype State = {\n tree: string;\n};\n\nconst CODE_SEARCH_STEP_BACK_EXAMPLES: StepBackExample[] = [\n {\n originalQuestion: 'How to build an agent?',\n stepBackQuestion:\n 'What is agent architecture? What are the core components and patterns for building agents?',\n stepBackAnswer:\n \"Agent architecture consists of: 1) An agent definition with model and prompt, 2) Tools that provide capabilities, 3) State management for context, 4) A streaming interface for responses. The core pattern involves defining the agent's behavior through prompts and equipping it with tools to accomplish tasks.\",\n finalAnswer:\n \"Use the agent() function from @deepagents/agent with a prompt, model, and tools. Define the agent's behavior in the prompt and provide tools for specific capabilities.\",\n },\n {\n originalQuestion: 'How does code search work in this codebase?',\n stepBackQuestion:\n 'What are the fundamental principles of code search and content retrieval?',\n stepBackAnswer:\n 'Code search requires: 1) Keyword-based content search across files, 2) Multiple search iterations with varied terms (broad and specific), 3) Result aggregation and citation tracking, 4) Balancing between high-level concepts and specific implementations.',\n finalAnswer:\n 'Search using varied keywords (3-5 searches minimum), combine broad queries (architecture, patterns) with specific queries (class names, function names), and cite all sources.',\n },\n];\n\nconst searchAgent = agent<unknown, State>({\n name: 'search_agent',\n model: wrapLanguageModel({\n model: groq('openai/gpt-oss-20b'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0.2 },\n }),\n }),\n prompt: dedent`\n<context>\nThis agent is Freya, a code search assistant that searches repositories thoroughly and answers questions with inline citations. This agent speaks in third person, referring to itself as \"this agent\" or \"Freya\".\n</context>\n\n<instructions>\n <task>\n Search the code repository to answer the user's question. All claims must be supported by citations from search results.\n </task>\n\n <strategy>\n ${stepBackPrompt('general', {\n examples: CODE_SEARCH_STEP_BACK_EXAMPLES,\n stepBackQuestionTemplate:\n 'What are the high-level concepts, architectural patterns, and fundamental principles related to this code search question?',\n })}\n\n <search_requirements>\n - Conduct minimum 3-5 searches with different keywords and variations\n - Use both broad queries (abstractions) and specific queries (details)\n - Search for related concepts and alternative implementations\n - Before responding, verify: \"Has this agent searched enough different ways to be thorough?\"\n </search_requirements>\n </strategy>\n\n <requirements>\n <tool_usage>\n - This agent uses search_content_tool to find all information\n - This agent only makes claims backed by actual search results - never guesses\n - If this agent cannot find sufficient information, it states this clearly\n </tool_usage>\n\n <citation_rules>\n Each search result includes a pre-formatted \"Citation:\" field. This agent must copy it exactly and place it immediately after the supported claim.\n\n CRITICAL: Never modify the citation format - copy it exactly as provided.\n </citation_rules>\n </requirements>\n</instructions>\n\n<examples>\n <example>\n <search_result>\n File: packages/agent/src/lib/agent.ts\n Citation: [agent.ts](./packages/agent/src/lib/agent.ts)\n (followed by code snippet)\n </search_result>\n\n <correct_usage>\n \"This agent found that the Agent class is defined in the core module [agent.ts](./packages/agent/src/lib/agent.ts).\"\n </correct_usage>\n\n <incorrect_usage>\n \"This agent found info in agent.ts\" (missing citation)\n \"[packages/agent/src/lib/agent.ts]\" (wrong format)\n </incorrect_usage>\n </example>\n</examples>\n\n<quality_checklist>\nBefore responding, this agent must verify:\n\u2713 Has this agent searched at least 3-5 times with different queries?\n\u2713 Are all claims backed by search results?\n\u2713 Has this agent copied Citation fields exactly from search results?\n\u2713 Are citations placed immediately after the claims they support?\n</quality_checklist>\n\t`,\n tools: {\n search_content_tool,\n },\n});\n\nconst state = {\n repo_path: cwd(),\n tree: await repoTree(cwd()),\n};\n\n// await printer.stdout(\n// stream(searchAgent, [user(`How do I build an agent?`)], state),\n// );\n\nstream(\n searchAgent,\n [user(`How can we build an sqlite readonly agent chatbot?`)],\n state,\n).then((result) => {\n Readable.fromWeb(result.textStream as any).pipe(\n createWriteStream('output.md'),\n );\n});\n"],
5
+ "mappings": ";AAAA,SAAS,YAAY;AACrB,SAAS,2BAA2B,yBAAyB;AAC7D,OAAO,YAAY;AACnB,SAAS,yBAAyB;AAClC,SAAS,WAAW;AACpB,SAAS,gBAAgB;AAEzB;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,UAAU,2BAA2B;AAM9C,IAAM,iCAAoD;AAAA,EACxD;AAAA,IACE,kBAAkB;AAAA,IAClB,kBACE;AAAA,IACF,gBACE;AAAA,IACF,aACE;AAAA,EACJ;AAAA,EACA;AAAA,IACE,kBAAkB;AAAA,IAClB,kBACE;AAAA,IACF,gBACE;AAAA,IACF,aACE;AAAA,EACJ;AACF;AAEA,IAAM,cAAc,MAAsB;AAAA,EACxC,MAAM;AAAA,EACN,OAAO,kBAAkB;AAAA,IACvB,OAAO,KAAK,oBAAoB;AAAA,IAChC,Y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