@deepagents/orchestrator 7.0.1 → 7.1.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 (51) hide show
  1. package/dist/lib/arxiv/arxiv.d.ts +9 -3
  2. package/dist/lib/arxiv/arxiv.d.ts.map +1 -1
  3. package/dist/lib/arxiv/arxiv.js +3 -11
  4. package/dist/lib/arxiv/arxiv.js.map +2 -2
  5. package/dist/lib/citation.js +3 -6
  6. package/dist/lib/citation.js.map +2 -2
  7. package/dist/lib/deepplan/demo.js.map +1 -1
  8. package/dist/lib/deepplan/executors/research-executor.js.map +2 -2
  9. package/dist/lib/deepplan/plan-and-solve.js +2 -6
  10. package/dist/lib/deepplan/plan-and-solve.js.map +2 -2
  11. package/dist/lib/deepplan/planner-agent.d.ts.map +1 -1
  12. package/dist/lib/deepplan/planner-agent.js +1 -4
  13. package/dist/lib/deepplan/planner-agent.js.map +2 -2
  14. package/dist/lib/deepplan/replanner-agent.d.ts.map +1 -1
  15. package/dist/lib/deepplan/replanner-agent.js +1 -2
  16. package/dist/lib/deepplan/replanner-agent.js.map +2 -2
  17. package/dist/lib/deepresearch.v0.d.ts.map +1 -1
  18. package/dist/lib/deepresearch.v0.js +21 -18
  19. package/dist/lib/deepresearch.v0.js.map +2 -2
  20. package/dist/lib/deepresearch.v1.d.ts.map +1 -1
  21. package/dist/lib/deepresearch.v1.js +3 -5
  22. package/dist/lib/deepresearch.v1.js.map +2 -2
  23. package/dist/lib/deepwiki/complete-wiki.js +4 -2
  24. package/dist/lib/deepwiki/complete-wiki.js.map +2 -2
  25. package/dist/lib/deepwiki/deepwiki.js +4 -2
  26. package/dist/lib/deepwiki/deepwiki.js.map +2 -2
  27. package/dist/lib/deepwiki/gitignore-agent.d.ts +4 -2
  28. package/dist/lib/deepwiki/gitignore-agent.d.ts.map +1 -1
  29. package/dist/lib/deepwiki/gitignore-agent.js +2 -3
  30. package/dist/lib/deepwiki/gitignore-agent.js.map +2 -2
  31. package/dist/lib/deepwiki/outline-agent.d.ts.map +1 -1
  32. package/dist/lib/deepwiki/outline-agent.js +4 -2
  33. package/dist/lib/deepwiki/outline-agent.js.map +2 -2
  34. package/dist/lib/deepwiki/wiki-writer.js +4 -2
  35. package/dist/lib/deepwiki/wiki-writer.js.map +2 -2
  36. package/dist/lib/deepwiki/writer.d.ts.map +1 -1
  37. package/dist/lib/deepwiki/writer.js +5 -5
  38. package/dist/lib/deepwiki/writer.js.map +2 -2
  39. package/dist/lib/evolving.js +1 -1
  40. package/dist/lib/evolving.js.map +2 -2
  41. package/dist/lib/openai-deepresearch/clarrify-agent.d.ts +5 -1
  42. package/dist/lib/openai-deepresearch/clarrify-agent.d.ts.map +1 -1
  43. package/dist/lib/openai-deepresearch/lead-research.d.ts.map +1 -1
  44. package/dist/lib/openai-deepresearch/lead-research.js +2 -3
  45. package/dist/lib/openai-deepresearch/lead-research.js.map +2 -2
  46. package/dist/lib/openai-deepresearch/openai-deepresearch.js +6 -8
  47. package/dist/lib/openai-deepresearch/openai-deepresearch.js.map +3 -3
  48. package/dist/lib/openai-deepresearch/reasearcher.js.map +2 -2
  49. package/dist/lib/openai-deepresearch/research-brief.d.ts +3 -1
  50. package/dist/lib/openai-deepresearch/research-brief.d.ts.map +1 -1
  51. package/package.json +8 -8
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/deepwiki/gitignore-agent.ts"],
4
- "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { tool } from 'ai';\nimport z from 'zod';\n\nimport { agent, instructions, toState } from '@deepagents/agent';\nimport { read_dir_tool, read_file_tool } from '@deepagents/toolbox';\n\nexport const ignoreAgent = agent<{ repo_path: string }>({\n name: 'Ignore Agent',\n model: groq('openai/gpt-oss-20b'),\n prompt: instructions({\n purpose:\n 'To generate a comprehensive .gitignore file tailored to the specific technologies and frameworks used in a given code repository, ensuring that unnecessary or sensitive files are excluded from version control.',\n routine: [\n 'Analyze the repository structure and identify key files and directories that should be ignored based on common development practices.',\n 'Identify the primary programming languages, frameworks, and tools used in the repository by looking for specific configuration files (e.g., package.json for Node.js, requirements.txt for Python, pom.xml for Java).',\n \"Based on the identified technologies, include standard ignore patterns from established templates (e.g., GitHub's collection of .gitignore templates) to cover common build artifacts, dependencies, and environment-specific files.\",\n 'Consider any custom or unique files in the repository that may need to be ignored, such as local configuration files, logs, or temporary files generated during development.',\n 'Compile a comprehensive .gitignore file that includes all relevant patterns, ensuring it is well-organized and easy to understand.',\n 'Present the final .gitignore content, ready to be added to the repository to optimize version control practices.',\n ],\n }),\n tools: {\n read_dir: read_dir_tool,\n read_file: read_file_tool,\n store_gitignore: tool({\n description: 'Use this tool to store the generated .gitignore content.',\n inputSchema: z.object({\n content: z\n .string()\n .min(1)\n .describe('The content of the .gitignore file.'),\n }),\n execute: async ({ content }, options) => {\n const context = toState<{ repo_path: string }>(options);\n console.log('Generated .gitignore content:\\n', content);\n // await fs.promises.writeFile(join(context.repo_path, '.gitignore'), content);\n return 'Successfully wrote .gitignore file.';\n },\n }),\n },\n});\n"],
5
- "mappings": ";AAAA,SAAS,YAAY;AACrB,SAAS,YAAY;AACrB,OAAO,OAAO;AAEd,SAAS,OAAO,cAAc,eAAe;AAC7C,SAAS,eAAe,sBAAsB;AAEvC,IAAM,cAAc,MAA6B;AAAA,EACtD,MAAM;AAAA,EACN,OAAO,KAAK,oBAAoB;AAAA,EAChC,QAAQ,aAAa;AAAA,IACnB,SACE;AAAA,IACF,SAAS;AAAA,MACP;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF,CAAC;AAAA,EACD,OAAO;AAAA,IACL,UAAU;AAAA,IACV,WAAW;AAAA,IACX,iBAAiB,KAAK;AAAA,MACpB,aAAa;AAAA,MACb,aAAa,EAAE,OAAO;AAAA,QACpB,SAAS,EACN,OAAO,EACP,IAAI,CAAC,EACL,SAAS,qCAAqC;AAAA,MACnD,CAAC;AAAA,MACD,SAAS,OAAO,EAAE,QAAQ,GAAG,YAAY;AACvC,cAAM,UAAU,QAA+B,OAAO;AACtD,gBAAQ,IAAI,mCAAmC,OAAO;AAEtD,eAAO;AAAA,MACT;AAAA,IACF,CAAC;AAAA,EACH;AACF,CAAC;",
4
+ "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { type ToolExecutionOptions, tool } from 'ai';\nimport z from 'zod';\n\nimport { agent, instructions } from '@deepagents/agent';\nimport { read_dir_tool, read_file_tool } from '@deepagents/toolbox';\n\ntype IgnoreAgentContext = { repo_path: string };\n\nexport const ignoreAgent = agent<unknown, IgnoreAgentContext>({\n name: 'Ignore Agent',\n model: groq('openai/gpt-oss-20b'),\n prompt: instructions({\n purpose:\n 'To generate a comprehensive .gitignore file tailored to the specific technologies and frameworks used in a given code repository, ensuring that unnecessary or sensitive files are excluded from version control.',\n routine: [\n 'Analyze the repository structure and identify key files and directories that should be ignored based on common development practices.',\n 'Identify the primary programming languages, frameworks, and tools used in the repository by looking for specific configuration files (e.g., package.json for Node.js, requirements.txt for Python, pom.xml for Java).',\n \"Based on the identified technologies, include standard ignore patterns from established templates (e.g., GitHub's collection of .gitignore templates) to cover common build artifacts, dependencies, and environment-specific files.\",\n 'Consider any custom or unique files in the repository that may need to be ignored, such as local configuration files, logs, or temporary files generated during development.',\n 'Compile a comprehensive .gitignore file that includes all relevant patterns, ensuring it is well-organized and easy to understand.',\n 'Present the final .gitignore content, ready to be added to the repository to optimize version control practices.',\n ],\n }),\n tools: {\n read_dir: read_dir_tool,\n read_file: read_file_tool,\n store_gitignore: tool({\n description: 'Use this tool to store the generated .gitignore content.',\n inputSchema: z.object({\n content: z\n .string()\n .min(1)\n .describe('The content of the .gitignore file.'),\n }),\n execute: async (\n { content },\n { context }: ToolExecutionOptions<IgnoreAgentContext>,\n ) => {\n console.log('Generated .gitignore content:\\n', content);\n // await fs.promises.writeFile(join(context.repo_path, '.gitignore'), content);\n return 'Successfully wrote .gitignore file.';\n },\n }),\n },\n});\n"],
5
+ "mappings": ";AAAA,SAAS,YAAY;AACrB,SAAoC,YAAY;AAChD,OAAO,OAAO;AAEd,SAAS,OAAO,oBAAoB;AACpC,SAAS,eAAe,sBAAsB;AAIvC,IAAM,cAAc,MAAmC;AAAA,EAC5D,MAAM;AAAA,EACN,OAAO,KAAK,oBAAoB;AAAA,EAChC,QAAQ,aAAa;AAAA,IACnB,SACE;AAAA,IACF,SAAS;AAAA,MACP;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF,CAAC;AAAA,EACD,OAAO;AAAA,IACL,UAAU;AAAA,IACV,WAAW;AAAA,IACX,iBAAiB,KAAK;AAAA,MACpB,aAAa;AAAA,MACb,aAAa,EAAE,OAAO;AAAA,QACpB,SAAS,EACN,OAAO,EACP,IAAI,CAAC,EACL,SAAS,qCAAqC;AAAA,MACnD,CAAC;AAAA,MACD,SAAS,OACP,EAAE,QAAQ,GACV,EAAE,QAAQ,MACP;AACH,gBAAQ,IAAI,mCAAmC,OAAO;AAEtD,eAAO;AAAA,MACT;AAAA,IACF,CAAC;AAAA,EACH;AACF,CAAC;",
6
6
  "names": []
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"outline-agent.d.ts","sourceRoot":"","sources":["../../../src/lib/deepwiki/outline-agent.ts"],"names":[],"mappings":"AAEA,OAAO,CAAC,MAAM,KAAK,CAAC;AAWpB,QAAA,MAAM,eAAe;;iBAEnB,CAAC;AACH,KAAK,WAAW,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,eAAe,CAAC,GAAG;IACpD,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,OAAO,iBAAiB,CAAC,EAAE,CAAC;CACjD,CAAC;AACF,QAAA,MAAM,iBAAiB,EAAE,CAAC,CAAC,OAAO,CAAC,WAAW,CAI7C,CAAC;AACF,QAAA,MAAM,aAAa,6FAA6B,CAAC;AACjD,MAAM,MAAM,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AAO,MAAM,YAAY,sFAwEvB,CAAC;AAEH,eAAO,MAAM,qBAAqB,sFAyBhC,CAAC;AAEH,wBAAsB,eAAe,CAAC,KAAK,EAAE,mBAAmB,oBA0C/D;AAWD,wBAAgB,QAAQ,CACtB,KAAK,EAAE,WAAW,EAAE,EACpB,SAAS,SAAI,EACb,MAAM,GAAE,MAAM,EAAO,YAatB"}
@@ -78,8 +78,10 @@ var outlineAgent = agent({
78
78
  inputSchema: z.object({
79
79
  outline: OutlineSchema
80
80
  })
81
- // execute: ({ outline }, options) => {
82
- // const context = toState<OutlineAgentContext>(options);
81
+ // execute: (
82
+ // { outline },
83
+ // { context }: ToolExecutionOptions<OutlineAgentContext>,
84
+ // ) => {
83
85
  // // Store the outline in a file or database
84
86
  // console.log('Generated Outline:\n', outline);
85
87
  // context.outline = outline;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/deepwiki/outline-agent.ts"],
4
- "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { type UIMessage, generateId, toUIMessageStream, tool } from 'ai';\nimport z from 'zod';\n\nimport {\n agent,\n execute,\n generate,\n instructions,\n user,\n} from '@deepagents/agent';\nimport { read_file_tool, scratchpad_tool } from '@deepagents/toolbox';\n\nconst BaseOutlineItem = z.object({\n title: z.string().trim().min(1, 'Title is required'),\n});\ntype OutlineItem = z.output<typeof BaseOutlineItem> & {\n sections?: z.output<typeof OutlineItemSchema>[];\n};\nconst OutlineItemSchema: z.ZodType<OutlineItem> = z.lazy(() =>\n BaseOutlineItem.extend({\n sections: z.array(OutlineItemSchema).optional(),\n }),\n);\nconst OutlineSchema = z.array(OutlineItemSchema);\nexport type Outline = z.output<typeof OutlineSchema>;\nexport type OutlineAgentContext = {\n repo_path: string;\n outline: z.output<typeof OutlineSchema>;\n scratchpad: string;\n tree: string;\n};\n\nexport const outlineAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n // model: lmstudio('qwen/qwen3-8b'),\n // model: lmstudio('openai/gpt-oss-20b'),\n\n // temperature: 0.1,\n prompt: (context) =>\n instructions({\n purpose: [\n \"You are wiki architect, meticulously analyzing a repository's structure and content to automatically generate a comprehensive, intelligent, and perfectly structured outline, laying the bedrock for exceptional documentation.\",\n '\\n',\n '<RepositoryTree>',\n context?.tree || '',\n '</RepositoryTree>',\n ],\n routine: [],\n // routine: [\n // 'Your primary tool for memory is your `scratchpad`. After every action, you MUST summarize your findings and add them to the scratchpad using the `update_scratchpad` tool.',\n // 'Systematically investigate key files and directories use `search_files`. For each finding add it as a new note to your scratchpad.',\n // 'When you read a file like `README.md` or `package.json`, do not keep the whole content in your head. Instead, summarize the important parts (like headings, dependencies, or scripts) and add that summary to your scratchpad.',\n // 'Continue this process of exploring, summarizing, and adding to your scratchpad until you are confident you have a full picture of the repository.',\n // 'Once you believe you have gathered enough information, your second-to-last step is to review your entire scratchpad to synthesize a plan for the final outline.',\n // 'Finally, based *only* on the information you have gathered in your scratchpad, generate the complete, detailed outline and store it using the `store_outline` tool. You must only call `store_outline` ONCE at the very end.',\n // ],\n }),\n tools: {\n read_file: read_file_tool,\n // read_dir: read_dir_tool,\n // search_files: search_files_tool,\n // file_exists: file_exists_tool,\n update_scratchpad: scratchpad_tool,\n store_outline: tool({\n description: `Use this tool to store the generated outline.\n\t\tThe outline should be a detailed hierarchical structure representing the sections and subsections of the repository documentation. In thory you can nest sections as deep as you want, but try to keep it to 4 levels deep maximum.\n\n\t\t## Example outline\n\t\t[\n\t\t\t{\n\t\t\t\t\"title\": \"xxxx\",\n\t\t\t\t\"sections\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"yyyy\",\n\t\t\t\t\t\tsections: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"title\": \"vvvv\",\n\t\t\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"gggg\",\n\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t},\n\t\t]\n\t\t\t`,\n inputSchema: z.object({\n outline: OutlineSchema,\n }),\n // execute: ({ outline }, options) => {\n // const context = toState<OutlineAgentContext>(options);\n // // Store the outline in a file or database\n // console.log('Generated Outline:\\n', outline);\n // context.outline = outline;\n // return 'Outline stored successfully.';\n // },\n }),\n },\n});\n\nexport const outlineCondensedAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Condensed Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n prompt: instructions({\n purpose: [\n 'To intelligently condense and optimize an existing outline by merging redundant sections, removing overly granular subdivisions, and creating a more streamlined, maintainable documentation structure.',\n 'Your goal is to reduce complexity while preserving all essential information and maintaining logical hierarchy.',\n ],\n routine: [\n 'Examine the current outline structure stored in the context. Use your scratchpad to track your analysis.',\n 'Identify sections that are too granular (e.g., sections with only 1-2 subsections that could be merged with their parent).',\n 'Look for redundant or overlapping sections that cover similar topics and can be consolidated.',\n 'Note sections with excessive nesting depth (more than 3-4 levels) that could be flattened.',\n 'Identify sections with very similar titles that could be merged (e.g., \"API Overview\" and \"API Introduction\").',\n 'For each potential consolidation, add a note to your scratchpad explaining the rationale.',\n 'Create a condensed version of the outline that:',\n ' - Merges related subsections into broader topics',\n ' - Reduces nesting depth where appropriate',\n ' - Eliminates redundancy while keeping all unique content areas',\n ' - Maintains a maximum depth of 3 levels unless absolutely necessary',\n ' - Ensures each section has substantial content to document',\n 'Return the condensed outline as structured output.',\n ],\n }),\n output: OutlineSchema,\n});\n\nexport async function generateOutline(state: OutlineAgentContext) {\n const messages: UIMessage[] = [\n user(\n 'Walk through the repository and generate a detailed outline. Make sure to avoid looking into framework generated files and folders. when outline is complete, call the store_outline tool.',\n ),\n ];\n const max_iterations = 3;\n let current_iteration = 0;\n while (current_iteration < max_iterations) {\n console.log(`\\n=== Outline Iteration ${current_iteration + 1} ===\\n`);\n const result = await execute(outlineAgent, messages, state);\n await Array.fromAsync(\n toUIMessageStream({\n stream: result.stream,\n tools: outlineAgent.toToolset(),\n generateMessageId: generateId,\n originalMessages: messages,\n onEnd: async ({ responseMessage }: { responseMessage: UIMessage }) => {\n messages.push(responseMessage);\n },\n }),\n );\n await result.consumeStream();\n const calls = await result.toolCalls;\n const outlineCall = calls.find(\n (t: { toolName: string }) => t.toolName === 'store_outline',\n );\n if (outlineCall) {\n console.log('\\n=== Outline Generation Complete ===\\n');\n state.outline = outlineCall.input.outline;\n break;\n }\n current_iteration++;\n }\n if (!state.outline.length) {\n throw new Error('Outline generation failed.');\n }\n return generate(\n outlineCondensedAgent,\n `Condense and optimize the following outline:\\n\\n${buildToc(state.outline)}`,\n state,\n ).then(({ output }) => output);\n}\n\nfunction slugify(text: string) {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, '')\n .trim()\n .replace(/\\s+/g, '-')\n .replace(/-+/g, '-');\n}\n\nexport function buildToc(\n items: OutlineItem[],\n baseDepth = 1,\n prefix: string[] = [],\n) {\n const lines: string[] = [];\n for (const it of items) {\n const path = [...prefix, it.title];\n const indent = ' '.repeat(Math.max(0, path.length - 1));\n const anchor = slugify(it.title);\n lines.push(`${indent}- [${it.title}](#${anchor})`);\n if (it.sections?.length) {\n lines.push(...buildToc(it.sections, baseDepth + 1, path));\n }\n }\n return lines;\n}\n"],
5
- "mappings": ";AAAA,SAAS,YAAY;AACrB,SAAyB,YAAY,mBAAmB,YAAY;AACpE,OAAO,OAAO;AAEd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB,uBAAuB;AAEhD,IAAM,kBAAkB,EAAE,OAAO;AAAA,EAC/B,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,GAAG,mBAAmB;AACrD,CAAC;AAID,IAAM,oBAA4C,EAAE;AAAA,EAAK,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tB,UAAM,OAAO,CAAC,GAAG,QAAQ,GAAG,KAAK;AACjC,UAAM,SAAS,KAAK,OAAO,KAAK,IAAI,GAAG,KAAK,SAAS,CAAC,CAAC;AACvD,UAAM,SAAS,QAAQ,GAAG,KAAK;AAC/B,UAAM,KAAK,GAAG,MAAM,MAAM,GAAG,KAAK,MAAM,MAAM,GAAG;AACjD,QAAI,GAAG,UAAU,QAAQ;AACvB,YAAM,KAAK,GAAG,SAAS,GAAG,UAAU,YAAY,GAAG,IAAI,CAAC;AAAA,IAC1D;AAAA,EACF;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { type UIMessage, generateId, toUIMessageStream, tool } from 'ai';\nimport z from 'zod';\n\nimport {\n agent,\n execute,\n generate,\n instructions,\n user,\n} from '@deepagents/agent';\nimport { read_file_tool, scratchpad_tool } from '@deepagents/toolbox';\n\nconst BaseOutlineItem = z.object({\n title: z.string().trim().min(1, 'Title is required'),\n});\ntype OutlineItem = z.output<typeof BaseOutlineItem> & {\n sections?: z.output<typeof OutlineItemSchema>[];\n};\nconst OutlineItemSchema: z.ZodType<OutlineItem> = z.lazy(() =>\n BaseOutlineItem.extend({\n sections: z.array(OutlineItemSchema).optional(),\n }),\n);\nconst OutlineSchema = z.array(OutlineItemSchema);\nexport type Outline = z.output<typeof OutlineSchema>;\nexport type OutlineAgentContext = {\n repo_path: string;\n outline: z.output<typeof OutlineSchema>;\n scratchpad: string;\n tree: string;\n};\n\nexport const outlineAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n // model: lmstudio('qwen/qwen3-8b'),\n // model: lmstudio('openai/gpt-oss-20b'),\n\n // temperature: 0.1,\n prompt: (context) =>\n instructions({\n purpose: [\n \"You are wiki architect, meticulously analyzing a repository's structure and content to automatically generate a comprehensive, intelligent, and perfectly structured outline, laying the bedrock for exceptional documentation.\",\n '\\n',\n '<RepositoryTree>',\n context?.tree || '',\n '</RepositoryTree>',\n ],\n routine: [],\n // routine: [\n // 'Your primary tool for memory is your `scratchpad`. After every action, you MUST summarize your findings and add them to the scratchpad using the `update_scratchpad` tool.',\n // 'Systematically investigate key files and directories use `search_files`. For each finding add it as a new note to your scratchpad.',\n // 'When you read a file like `README.md` or `package.json`, do not keep the whole content in your head. Instead, summarize the important parts (like headings, dependencies, or scripts) and add that summary to your scratchpad.',\n // 'Continue this process of exploring, summarizing, and adding to your scratchpad until you are confident you have a full picture of the repository.',\n // 'Once you believe you have gathered enough information, your second-to-last step is to review your entire scratchpad to synthesize a plan for the final outline.',\n // 'Finally, based *only* on the information you have gathered in your scratchpad, generate the complete, detailed outline and store it using the `store_outline` tool. You must only call `store_outline` ONCE at the very end.',\n // ],\n }),\n tools: {\n read_file: read_file_tool,\n // read_dir: read_dir_tool,\n // search_files: search_files_tool,\n // file_exists: file_exists_tool,\n update_scratchpad: scratchpad_tool,\n store_outline: tool({\n description: `Use this tool to store the generated outline.\n\t\tThe outline should be a detailed hierarchical structure representing the sections and subsections of the repository documentation. In thory you can nest sections as deep as you want, but try to keep it to 4 levels deep maximum.\n\n\t\t## Example outline\n\t\t[\n\t\t\t{\n\t\t\t\t\"title\": \"xxxx\",\n\t\t\t\t\"sections\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"yyyy\",\n\t\t\t\t\t\tsections: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"title\": \"vvvv\",\n\t\t\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"gggg\",\n\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t},\n\t\t]\n\t\t\t`,\n inputSchema: z.object({\n outline: OutlineSchema,\n }),\n // execute: (\n // { outline },\n // { context }: ToolExecutionOptions<OutlineAgentContext>,\n // ) => {\n // // Store the outline in a file or database\n // console.log('Generated Outline:\\n', outline);\n // context.outline = outline;\n // return 'Outline stored successfully.';\n // },\n }),\n },\n});\n\nexport const outlineCondensedAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Condensed Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n prompt: instructions({\n purpose: [\n 'To intelligently condense and optimize an existing outline by merging redundant sections, removing overly granular subdivisions, and creating a more streamlined, maintainable documentation structure.',\n 'Your goal is to reduce complexity while preserving all essential information and maintaining logical hierarchy.',\n ],\n routine: [\n 'Examine the current outline structure stored in the context. Use your scratchpad to track your analysis.',\n 'Identify sections that are too granular (e.g., sections with only 1-2 subsections that could be merged with their parent).',\n 'Look for redundant or overlapping sections that cover similar topics and can be consolidated.',\n 'Note sections with excessive nesting depth (more than 3-4 levels) that could be flattened.',\n 'Identify sections with very similar titles that could be merged (e.g., \"API Overview\" and \"API Introduction\").',\n 'For each potential consolidation, add a note to your scratchpad explaining the rationale.',\n 'Create a condensed version of the outline that:',\n ' - Merges related subsections into broader topics',\n ' - Reduces nesting depth where appropriate',\n ' - Eliminates redundancy while keeping all unique content areas',\n ' - Maintains a maximum depth of 3 levels unless absolutely necessary',\n ' - Ensures each section has substantial content to document',\n 'Return the condensed outline as structured output.',\n ],\n }),\n output: OutlineSchema,\n});\n\nexport async function generateOutline(state: OutlineAgentContext) {\n const messages: UIMessage[] = [\n user(\n 'Walk through the repository and generate a detailed outline. Make sure to avoid looking into framework generated files and folders. when outline is complete, call the store_outline tool.',\n ),\n ];\n const max_iterations = 3;\n let current_iteration = 0;\n while (current_iteration < max_iterations) {\n console.log(`\\n=== Outline Iteration ${current_iteration + 1} ===\\n`);\n const result = await execute(outlineAgent, messages, state);\n await Array.fromAsync(\n toUIMessageStream({\n stream: result.stream,\n tools: outlineAgent.toToolset(),\n generateMessageId: generateId,\n originalMessages: messages,\n onEnd: async ({ responseMessage }: { responseMessage: UIMessage }) => {\n messages.push(responseMessage);\n },\n }),\n );\n await result.consumeStream();\n const calls = await result.toolCalls;\n const outlineCall = calls.find(\n (t: { toolName: string }) => t.toolName === 'store_outline',\n );\n if (outlineCall) {\n console.log('\\n=== Outline Generation Complete ===\\n');\n state.outline = outlineCall.input.outline;\n break;\n }\n current_iteration++;\n }\n if (!state.outline.length) {\n throw new Error('Outline generation failed.');\n }\n return generate(\n outlineCondensedAgent,\n `Condense and optimize the following outline:\\n\\n${buildToc(state.outline)}`,\n state,\n ).then(({ output }) => output);\n}\n\nfunction slugify(text: string) {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, '')\n .trim()\n .replace(/\\s+/g, '-')\n .replace(/-+/g, '-');\n}\n\nexport function buildToc(\n items: OutlineItem[],\n baseDepth = 1,\n prefix: string[] = [],\n) {\n const lines: string[] = [];\n for (const it of items) {\n const path = [...prefix, it.title];\n const indent = ' '.repeat(Math.max(0, path.length - 1));\n const anchor = slugify(it.title);\n lines.push(`${indent}- [${it.title}](#${anchor})`);\n if (it.sections?.length) {\n lines.push(...buildToc(it.sections, baseDepth + 1, path));\n }\n }\n return lines;\n}\n"],
5
+ "mappings": ";AAAA,SAAS,YAAY;AACrB,SAAyB,YAAY,mBAAmB,YAAY;AACpE,OAAO,OAAO;AAEd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB,uBAAuB;AAEhD,IAAM,kBAAkB,EAAE,OAAO;AAAA,EAC/B,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,GAAG,mBAAmB;AACrD,CAAC;AAID,IAAM,oBAA4C,EAAE;AAAA,EAAK,MACvD,gBAAgB,OAAO;AAAA,IACrB,UAAU,EAAE,MAAM,iBAAiB,EAAE,SAAS;AAAA,EAChD,CAAC;AACH;AACA,IAAM,gBAAgB,EAAE,MAAM,iBAAiB;AASxC,IAAM,eAAe,MAAoC;AAAA,EAC9D,MAAM;AAAA,EACN,OAAO,KAAK,kCAAkC;AAAA;AAAA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AM,MAAM,GAAG;AACjD,QAAI,GAAG,UAAU,QAAQ;AACvB,YAAM,KAAK,GAAG,SAAS,GAAG,UAAU,YAAY,GAAG,IAAI,CAAC;AAAA,IAC1D;AAAA,EACF;AACA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -93,8 +93,10 @@ var outlineAgent = agent({
93
93
  inputSchema: z.object({
94
94
  outline: OutlineSchema
95
95
  })
96
- // execute: ({ outline }, options) => {
97
- // const context = toState<OutlineAgentContext>(options);
96
+ // execute: (
97
+ // { outline },
98
+ // { context }: ToolExecutionOptions<OutlineAgentContext>,
99
+ // ) => {
98
100
  // // Store the outline in a file or database
99
101
  // console.log('Generated Outline:\n', outline);
100
102
  // context.outline = outline;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/deepwiki/wiki-writer.ts", "../../../src/lib/deepwiki/outline-agent.ts"],
4
- "sourcesContent": ["import {\n type UIMessage,\n defaultSettingsMiddleware,\n wrapLanguageModel,\n} from 'ai';\nimport { writeFile } from 'node:fs/promises';\n\nimport {\n agent,\n execute,\n instructions,\n lmstudio,\n user,\n} from '@deepagents/agent';\nimport { scratchpad_tool, search_content_tool } from '@deepagents/toolbox';\n\nimport { buildToc } from './outline-agent.ts';\n\ntype OutlineItem = { title: string; sections?: OutlineItem[] };\n\ntype SectionAgentContext = {\n repo_path: string;\n section_path: string[];\n scratchpad: string;\n};\n\nconst sectionWriter = agent<SectionAgentContext>({\n name: 'wiki-section-writer',\n model: wrapLanguageModel({\n // model: lmstudio('openai/gpt-oss-20b'),\n model: lmstudio('qwen/qwen3-4b-2507'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0 },\n }),\n }),\n prompt: instructions({\n purpose: [\n 'You write comprehensive, accurate, and actionable documentation sections for a repository wiki.',\n 'You can inspect files and directory structure using provided tools to ground your writing in the actual codebase.',\n ],\n routine: [\n 'Use the scratchpad to note findings from reading files or directories; keep it concise and relevant.',\n 'Clarify scope: write ONLY for the current section path you are working on; do not expand into subsections (those are handled separately).',\n 'When pasting code, include only short, illustrative snippets\u2014do not dump large files.',\n 'Avoid references to unknown frameworks or generated folders; ground claims in actual repo contents when possible.',\n 'Make use of the `search_content` tool to find relevant information in the codebase. this tool can search the entire repository for keywords or topics. use it to find code examples, explanations, or relevant files.',\n 'Return ONLY the final markdown for this section.',\n ],\n }),\n tools: {\n // read_file: read_file_tool,\n // read_dir: read_dir_tool,\n // search_files: search_files_tool,\n search_content: search_content_tool,\n update_scratchpad: scratchpad_tool,\n },\n});\n\nfunction headingFor(level: number, title: string) {\n const capped = Math.min(Math.max(level, 1), 6);\n return `${'#'.repeat(capped)} ${title}`;\n}\n\nasync function renderSection(\n outline: OutlineItem,\n path: string[],\n ctx: { repo_path: string },\n) {\n const messages: UIMessage[] = [\n user(\n [\n `You are part of an AI team writing a project wiki based on a structured outline.`,\n `You are writing the section: ${path.join(' > ')}`,\n 'Provide the final markdown for this section (no JSON, no commentary).',\n ].join('\\n'),\n ),\n ];\n\n return (\n await execute(sectionWriter, messages, {\n repo_path: ctx.repo_path,\n section_path: path,\n scratchpad: '## Scratchpad\\n\\n',\n })\n ).text;\n}\n\nasync function renderOutline(\n items: OutlineItem[],\n ctx: { repo_path: string },\n depth = 1,\n path: string[] = [],\n): Promise<string> {\n let out = '';\n for (const item of items) {\n const currentPath = [...path, item.title];\n out += `\\n\\n${headingFor(depth, item.title)}\\n\\n`;\n const content = await renderSection(item, currentPath, ctx);\n await writeFile(`./${currentPath.join('-')}.md`, content, 'utf-8');\n if (content) {\n out += `${content}\\n`;\n }\n if (item.sections?.length) {\n out += await renderOutline(item.sections, ctx, depth + 1, currentPath);\n }\n }\n return out;\n}\n\nexport async function generateWiki(\n outline: OutlineItem[],\n options: { repo_path: string },\n) {\n const header = [\n '# Project Wiki',\n '',\n '## Table of Contents',\n ...buildToc(outline),\n ].join('\\n');\n\n const body = await renderOutline(\n outline,\n { repo_path: options.repo_path },\n 1,\n );\n return `${header}\\n\\n${body}\\n`;\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { type UIMessage, generateId, toUIMessageStream, tool } from 'ai';\nimport z from 'zod';\n\nimport {\n agent,\n execute,\n generate,\n instructions,\n user,\n} from '@deepagents/agent';\nimport { read_file_tool, scratchpad_tool } from '@deepagents/toolbox';\n\nconst BaseOutlineItem = z.object({\n title: z.string().trim().min(1, 'Title is required'),\n});\ntype OutlineItem = z.output<typeof BaseOutlineItem> & {\n sections?: z.output<typeof OutlineItemSchema>[];\n};\nconst OutlineItemSchema: z.ZodType<OutlineItem> = z.lazy(() =>\n BaseOutlineItem.extend({\n sections: z.array(OutlineItemSchema).optional(),\n }),\n);\nconst OutlineSchema = z.array(OutlineItemSchema);\nexport type Outline = z.output<typeof OutlineSchema>;\nexport type OutlineAgentContext = {\n repo_path: string;\n outline: z.output<typeof OutlineSchema>;\n scratchpad: string;\n tree: string;\n};\n\nexport const outlineAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n // model: lmstudio('qwen/qwen3-8b'),\n // model: lmstudio('openai/gpt-oss-20b'),\n\n // temperature: 0.1,\n prompt: (context) =>\n instructions({\n purpose: [\n \"You are wiki architect, meticulously analyzing a repository's structure and content to automatically generate a comprehensive, intelligent, and perfectly structured outline, laying the bedrock for exceptional documentation.\",\n '\\n',\n '<RepositoryTree>',\n context?.tree || '',\n '</RepositoryTree>',\n ],\n routine: [],\n // routine: [\n // 'Your primary tool for memory is your `scratchpad`. After every action, you MUST summarize your findings and add them to the scratchpad using the `update_scratchpad` tool.',\n // 'Systematically investigate key files and directories use `search_files`. For each finding add it as a new note to your scratchpad.',\n // 'When you read a file like `README.md` or `package.json`, do not keep the whole content in your head. Instead, summarize the important parts (like headings, dependencies, or scripts) and add that summary to your scratchpad.',\n // 'Continue this process of exploring, summarizing, and adding to your scratchpad until you are confident you have a full picture of the repository.',\n // 'Once you believe you have gathered enough information, your second-to-last step is to review your entire scratchpad to synthesize a plan for the final outline.',\n // 'Finally, based *only* on the information you have gathered in your scratchpad, generate the complete, detailed outline and store it using the `store_outline` tool. You must only call `store_outline` ONCE at the very end.',\n // ],\n }),\n tools: {\n read_file: read_file_tool,\n // read_dir: read_dir_tool,\n // search_files: search_files_tool,\n // file_exists: file_exists_tool,\n update_scratchpad: scratchpad_tool,\n store_outline: tool({\n description: `Use this tool to store the generated outline.\n\t\tThe outline should be a detailed hierarchical structure representing the sections and subsections of the repository documentation. In thory you can nest sections as deep as you want, but try to keep it to 4 levels deep maximum.\n\n\t\t## Example outline\n\t\t[\n\t\t\t{\n\t\t\t\t\"title\": \"xxxx\",\n\t\t\t\t\"sections\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"yyyy\",\n\t\t\t\t\t\tsections: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"title\": \"vvvv\",\n\t\t\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"gggg\",\n\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t},\n\t\t]\n\t\t\t`,\n inputSchema: z.object({\n outline: OutlineSchema,\n }),\n // execute: ({ outline }, options) => {\n // const context = toState<OutlineAgentContext>(options);\n // // Store the outline in a file or database\n // console.log('Generated Outline:\\n', outline);\n // context.outline = outline;\n // return 'Outline stored successfully.';\n // },\n }),\n },\n});\n\nexport const outlineCondensedAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Condensed Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n prompt: instructions({\n purpose: [\n 'To intelligently condense and optimize an existing outline by merging redundant sections, removing overly granular subdivisions, and creating a more streamlined, maintainable documentation structure.',\n 'Your goal is to reduce complexity while preserving all essential information and maintaining logical hierarchy.',\n ],\n routine: [\n 'Examine the current outline structure stored in the context. Use your scratchpad to track your analysis.',\n 'Identify sections that are too granular (e.g., sections with only 1-2 subsections that could be merged with their parent).',\n 'Look for redundant or overlapping sections that cover similar topics and can be consolidated.',\n 'Note sections with excessive nesting depth (more than 3-4 levels) that could be flattened.',\n 'Identify sections with very similar titles that could be merged (e.g., \"API Overview\" and \"API Introduction\").',\n 'For each potential consolidation, add a note to your scratchpad explaining the rationale.',\n 'Create a condensed version of the outline that:',\n ' - Merges related subsections into broader topics',\n ' - Reduces nesting depth where appropriate',\n ' - Eliminates redundancy while keeping all unique content areas',\n ' - Maintains a maximum depth of 3 levels unless absolutely necessary',\n ' - Ensures each section has substantial content to document',\n 'Return the condensed outline as structured output.',\n ],\n }),\n output: OutlineSchema,\n});\n\nexport async function generateOutline(state: OutlineAgentContext) {\n const messages: UIMessage[] = [\n user(\n 'Walk through the repository and generate a detailed outline. Make sure to avoid looking into framework generated files and folders. when outline is complete, call the store_outline tool.',\n ),\n ];\n const max_iterations = 3;\n let current_iteration = 0;\n while (current_iteration < max_iterations) {\n console.log(`\\n=== Outline Iteration ${current_iteration + 1} ===\\n`);\n const result = await execute(outlineAgent, messages, state);\n await Array.fromAsync(\n toUIMessageStream({\n stream: result.stream,\n tools: outlineAgent.toToolset(),\n generateMessageId: generateId,\n originalMessages: messages,\n onEnd: async ({ responseMessage }: { responseMessage: UIMessage }) => {\n messages.push(responseMessage);\n },\n }),\n );\n await result.consumeStream();\n const calls = await result.toolCalls;\n const outlineCall = calls.find(\n (t: { toolName: string }) => t.toolName === 'store_outline',\n );\n if (outlineCall) {\n console.log('\\n=== Outline Generation Complete ===\\n');\n state.outline = outlineCall.input.outline;\n break;\n }\n current_iteration++;\n }\n if (!state.outline.length) {\n throw new Error('Outline generation failed.');\n }\n return generate(\n outlineCondensedAgent,\n `Condense and optimize the following outline:\\n\\n${buildToc(state.outline)}`,\n state,\n ).then(({ output }) => output);\n}\n\nfunction slugify(text: string) {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, '')\n .trim()\n .replace(/\\s+/g, '-')\n .replace(/-+/g, '-');\n}\n\nexport function buildToc(\n items: OutlineItem[],\n baseDepth = 1,\n prefix: string[] = [],\n) {\n const lines: string[] = [];\n for (const it of items) {\n const path = [...prefix, it.title];\n const indent = ' '.repeat(Math.max(0, path.length - 1));\n const anchor = slugify(it.title);\n lines.push(`${indent}- [${it.title}](#${anchor})`);\n if (it.sections?.length) {\n lines.push(...buildToc(it.sections, baseDepth + 1, path));\n }\n }\n return lines;\n}\n"],
5
- "mappings": ";AAAA;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB;AAE1B;AAAA,EACE,SAAAA;AAAA,EACA,WAAAC;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA,QAAAC;AAAA,OACK;AACP,SAAS,mBAAAC,kBAAiB,2BAA2B;;;ACdrD,SAAS,YAAY;AACrB,SAAyB,YAAY,mBAAmB,YAAY;AACpE,OAAO,OAAO;AAEd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB,uBAAuB;AAEhD,IAAM,kBAAkB,EAAE,OAAO;AAAA,EAC/B,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,GAAG,mBAAmB;AACrD,CAAC;AAID,IAAM,oBAA4C,EAAE;AAAA,EAAK,MACvD,gBAAgB,OAAO;AAAA,IACrB,UAAU,EAAE,MAAM,iBAAiB,EAAE,SAAS;AAAA,EAChD,CAAC;AACH;AACA,IAAM,gBAAgB,EAAE,MAAM,iBAAiB;AASxC,IAAM,eAAe,MAAoC;AAAA,EAC9D,MAAM;AAAA,EACN,OAAO,KAAK,kCAAkC;AAAA;AAAA;AAAA;AAAA,EAK9C,QAAQ,CAAC,YACP,aAAa;AAAA,IACX,SAAS;AAAA,MACP;AAAA,MACA;AAAA,MACA;AAAA,MACA,SAAS,QAAQ;AAAA,MACjB;AAAA,IACF;AAAA,IACA,SAAS,CAAC;AAAA;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CAAC,GACD;AACjB,MAAI,MAAM;AACV,aAAW,QAAQ,OAAO;AACxB,UAAM,cAAc,CAAC,GAAG,MAAM,KAAK,KAAK;AACxC,WAAO;AAAA;AAAA,EAAO,WAAW,OAAO,KAAK,KAAK,CAAC;AAAA;AAAA;AAC3C,UAAM,UAAU,MAAM,cAAc,MAAM,aAAa,GAAG;AAC1D,UAAM,UAAU,KAAK,YAAY,KAAK,GAAG,CAAC,OAAO,SAAS,OAAO;AACjE,QAAI,SAAS;AACX,aAAO,GAAG,OAAO;AAAA;AAAA,IACnB;AACA,QAAI,KAAK,UAAU,QAAQ;AACzB,aAAO,MAAM,cAAc,KAAK,UAAU,KAAK,QAAQ,GAAG,WAAW;AAAA,IACvE;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAsB,aACpB,SACA,SACA;AACA,QAAM,SAAS;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG,SAAS,OAAO;AAAA,EACrB,EAAE,KAAK,IAAI;AAEX,QAAM,OAAO,MAAM;AAAA,IACjB;AAAA,IACA,EAAE,WAAW,QAAQ,UAAU;AAAA,IAC/B;AAAA,EACF;AACA,SAAO,GAAG,MAAM;AAAA;AAAA,EAAO,IAAI;AAAA;AAC7B;",
4
+ "sourcesContent": ["import {\n type UIMessage,\n defaultSettingsMiddleware,\n wrapLanguageModel,\n} from 'ai';\nimport { writeFile } from 'node:fs/promises';\n\nimport {\n agent,\n execute,\n instructions,\n lmstudio,\n user,\n} from '@deepagents/agent';\nimport { scratchpad_tool, search_content_tool } from '@deepagents/toolbox';\n\nimport { buildToc } from './outline-agent.ts';\n\ntype OutlineItem = { title: string; sections?: OutlineItem[] };\n\ntype SectionAgentContext = {\n repo_path: string;\n section_path: string[];\n scratchpad: string;\n};\n\nconst sectionWriter = agent<unknown, SectionAgentContext>({\n name: 'wiki-section-writer',\n model: wrapLanguageModel({\n // model: lmstudio('openai/gpt-oss-20b'),\n model: lmstudio('qwen/qwen3-4b-2507'),\n middleware: defaultSettingsMiddleware({\n settings: { temperature: 0 },\n }),\n }),\n prompt: instructions({\n purpose: [\n 'You write comprehensive, accurate, and actionable documentation sections for a repository wiki.',\n 'You can inspect files and directory structure using provided tools to ground your writing in the actual codebase.',\n ],\n routine: [\n 'Use the scratchpad to note findings from reading files or directories; keep it concise and relevant.',\n 'Clarify scope: write ONLY for the current section path you are working on; do not expand into subsections (those are handled separately).',\n 'When pasting code, include only short, illustrative snippets\u2014do not dump large files.',\n 'Avoid references to unknown frameworks or generated folders; ground claims in actual repo contents when possible.',\n 'Make use of the `search_content` tool to find relevant information in the codebase. this tool can search the entire repository for keywords or topics. use it to find code examples, explanations, or relevant files.',\n 'Return ONLY the final markdown for this section.',\n ],\n }),\n tools: {\n // read_file: read_file_tool,\n // read_dir: read_dir_tool,\n // search_files: search_files_tool,\n search_content: search_content_tool,\n update_scratchpad: scratchpad_tool,\n },\n});\n\nfunction headingFor(level: number, title: string) {\n const capped = Math.min(Math.max(level, 1), 6);\n return `${'#'.repeat(capped)} ${title}`;\n}\n\nasync function renderSection(\n outline: OutlineItem,\n path: string[],\n ctx: { repo_path: string },\n) {\n const messages: UIMessage[] = [\n user(\n [\n `You are part of an AI team writing a project wiki based on a structured outline.`,\n `You are writing the section: ${path.join(' > ')}`,\n 'Provide the final markdown for this section (no JSON, no commentary).',\n ].join('\\n'),\n ),\n ];\n\n return (\n await execute(sectionWriter, messages, {\n repo_path: ctx.repo_path,\n section_path: path,\n scratchpad: '## Scratchpad\\n\\n',\n })\n ).text;\n}\n\nasync function renderOutline(\n items: OutlineItem[],\n ctx: { repo_path: string },\n depth = 1,\n path: string[] = [],\n): Promise<string> {\n let out = '';\n for (const item of items) {\n const currentPath = [...path, item.title];\n out += `\\n\\n${headingFor(depth, item.title)}\\n\\n`;\n const content = await renderSection(item, currentPath, ctx);\n await writeFile(`./${currentPath.join('-')}.md`, content, 'utf-8');\n if (content) {\n out += `${content}\\n`;\n }\n if (item.sections?.length) {\n out += await renderOutline(item.sections, ctx, depth + 1, currentPath);\n }\n }\n return out;\n}\n\nexport async function generateWiki(\n outline: OutlineItem[],\n options: { repo_path: string },\n) {\n const header = [\n '# Project Wiki',\n '',\n '## Table of Contents',\n ...buildToc(outline),\n ].join('\\n');\n\n const body = await renderOutline(\n outline,\n { repo_path: options.repo_path },\n 1,\n );\n return `${header}\\n\\n${body}\\n`;\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { type UIMessage, generateId, toUIMessageStream, tool } from 'ai';\nimport z from 'zod';\n\nimport {\n agent,\n execute,\n generate,\n instructions,\n user,\n} from '@deepagents/agent';\nimport { read_file_tool, scratchpad_tool } from '@deepagents/toolbox';\n\nconst BaseOutlineItem = z.object({\n title: z.string().trim().min(1, 'Title is required'),\n});\ntype OutlineItem = z.output<typeof BaseOutlineItem> & {\n sections?: z.output<typeof OutlineItemSchema>[];\n};\nconst OutlineItemSchema: z.ZodType<OutlineItem> = z.lazy(() =>\n BaseOutlineItem.extend({\n sections: z.array(OutlineItemSchema).optional(),\n }),\n);\nconst OutlineSchema = z.array(OutlineItemSchema);\nexport type Outline = z.output<typeof OutlineSchema>;\nexport type OutlineAgentContext = {\n repo_path: string;\n outline: z.output<typeof OutlineSchema>;\n scratchpad: string;\n tree: string;\n};\n\nexport const outlineAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n // model: lmstudio('qwen/qwen3-8b'),\n // model: lmstudio('openai/gpt-oss-20b'),\n\n // temperature: 0.1,\n prompt: (context) =>\n instructions({\n purpose: [\n \"You are wiki architect, meticulously analyzing a repository's structure and content to automatically generate a comprehensive, intelligent, and perfectly structured outline, laying the bedrock for exceptional documentation.\",\n '\\n',\n '<RepositoryTree>',\n context?.tree || '',\n '</RepositoryTree>',\n ],\n routine: [],\n // routine: [\n // 'Your primary tool for memory is your `scratchpad`. After every action, you MUST summarize your findings and add them to the scratchpad using the `update_scratchpad` tool.',\n // 'Systematically investigate key files and directories use `search_files`. For each finding add it as a new note to your scratchpad.',\n // 'When you read a file like `README.md` or `package.json`, do not keep the whole content in your head. Instead, summarize the important parts (like headings, dependencies, or scripts) and add that summary to your scratchpad.',\n // 'Continue this process of exploring, summarizing, and adding to your scratchpad until you are confident you have a full picture of the repository.',\n // 'Once you believe you have gathered enough information, your second-to-last step is to review your entire scratchpad to synthesize a plan for the final outline.',\n // 'Finally, based *only* on the information you have gathered in your scratchpad, generate the complete, detailed outline and store it using the `store_outline` tool. You must only call `store_outline` ONCE at the very end.',\n // ],\n }),\n tools: {\n read_file: read_file_tool,\n // read_dir: read_dir_tool,\n // search_files: search_files_tool,\n // file_exists: file_exists_tool,\n update_scratchpad: scratchpad_tool,\n store_outline: tool({\n description: `Use this tool to store the generated outline.\n\t\tThe outline should be a detailed hierarchical structure representing the sections and subsections of the repository documentation. In thory you can nest sections as deep as you want, but try to keep it to 4 levels deep maximum.\n\n\t\t## Example outline\n\t\t[\n\t\t\t{\n\t\t\t\t\"title\": \"xxxx\",\n\t\t\t\t\"sections\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"yyyy\",\n\t\t\t\t\t\tsections: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"title\": \"vvvv\",\n\t\t\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"gggg\",\n\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t},\n\t\t]\n\t\t\t`,\n inputSchema: z.object({\n outline: OutlineSchema,\n }),\n // execute: (\n // { outline },\n // { context }: ToolExecutionOptions<OutlineAgentContext>,\n // ) => {\n // // Store the outline in a file or database\n // console.log('Generated Outline:\\n', outline);\n // context.outline = outline;\n // return 'Outline stored successfully.';\n // },\n }),\n },\n});\n\nexport const outlineCondensedAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Condensed Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n prompt: instructions({\n purpose: [\n 'To intelligently condense and optimize an existing outline by merging redundant sections, removing overly granular subdivisions, and creating a more streamlined, maintainable documentation structure.',\n 'Your goal is to reduce complexity while preserving all essential information and maintaining logical hierarchy.',\n ],\n routine: [\n 'Examine the current outline structure stored in the context. Use your scratchpad to track your analysis.',\n 'Identify sections that are too granular (e.g., sections with only 1-2 subsections that could be merged with their parent).',\n 'Look for redundant or overlapping sections that cover similar topics and can be consolidated.',\n 'Note sections with excessive nesting depth (more than 3-4 levels) that could be flattened.',\n 'Identify sections with very similar titles that could be merged (e.g., \"API Overview\" and \"API Introduction\").',\n 'For each potential consolidation, add a note to your scratchpad explaining the rationale.',\n 'Create a condensed version of the outline that:',\n ' - Merges related subsections into broader topics',\n ' - Reduces nesting depth where appropriate',\n ' - Eliminates redundancy while keeping all unique content areas',\n ' - Maintains a maximum depth of 3 levels unless absolutely necessary',\n ' - Ensures each section has substantial content to document',\n 'Return the condensed outline as structured output.',\n ],\n }),\n output: OutlineSchema,\n});\n\nexport async function generateOutline(state: OutlineAgentContext) {\n const messages: UIMessage[] = [\n user(\n 'Walk through the repository and generate a detailed outline. Make sure to avoid looking into framework generated files and folders. when outline is complete, call the store_outline tool.',\n ),\n ];\n const max_iterations = 3;\n let current_iteration = 0;\n while (current_iteration < max_iterations) {\n console.log(`\\n=== Outline Iteration ${current_iteration + 1} ===\\n`);\n const result = await execute(outlineAgent, messages, state);\n await Array.fromAsync(\n toUIMessageStream({\n stream: result.stream,\n tools: outlineAgent.toToolset(),\n generateMessageId: generateId,\n originalMessages: messages,\n onEnd: async ({ responseMessage }: { responseMessage: UIMessage }) => {\n messages.push(responseMessage);\n },\n }),\n );\n await result.consumeStream();\n const calls = await result.toolCalls;\n const outlineCall = calls.find(\n (t: { toolName: string }) => t.toolName === 'store_outline',\n );\n if (outlineCall) {\n console.log('\\n=== Outline Generation Complete ===\\n');\n state.outline = outlineCall.input.outline;\n break;\n }\n current_iteration++;\n }\n if (!state.outline.length) {\n throw new Error('Outline generation failed.');\n }\n return generate(\n outlineCondensedAgent,\n `Condense and optimize the following outline:\\n\\n${buildToc(state.outline)}`,\n state,\n ).then(({ output }) => output);\n}\n\nfunction slugify(text: string) {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, '')\n .trim()\n .replace(/\\s+/g, '-')\n .replace(/-+/g, '-');\n}\n\nexport function buildToc(\n items: OutlineItem[],\n baseDepth = 1,\n prefix: string[] = [],\n) {\n const lines: string[] = [];\n for (const it of items) {\n const path = [...prefix, it.title];\n const indent = ' '.repeat(Math.max(0, path.length - 1));\n const anchor = slugify(it.title);\n lines.push(`${indent}- [${it.title}](#${anchor})`);\n if (it.sections?.length) {\n lines.push(...buildToc(it.sections, baseDepth + 1, path));\n }\n }\n return lines;\n}\n"],
5
+ "mappings": ";AAAA;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB;AAE1B;AAAA,EACE,SAAAA;AAAA,EACA,WAAAC;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA,QAAAC;AAAA,OACK;AACP,SAAS,mBAAAC,kBAAiB,2BAA2B;;;ACdrD,SAAS,YAAY;AACrB,SAAyB,YAAY,mBAAmB,YAAY;AACpE,OAAO,OAAO;AAEd;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB,uBAAuB;AAEhD,IAAM,kBAAkB,EAAE,OAAO;AAAA,EAC/B,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,IAAI,GAAG,mBAAmB;AACrD,CAAC;AAID,IAAM,oBAA4C,EAAE;AAAA,EAAK,MACvD,gBAAgB,OAAO;AAAA,IACrB,UAAU,EAAE,MAAM,iBAAiB,EAAE,SAAS;AAAA,EAChD,CAAC;AACH;AACA,IAAM,gBAAgB,EAAE,MAAM,iBAAiB;AASxC,IAAM,eAAe,MAAoC;AA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K,CAAC;AAAA,QAChD;AAAA,MACF,EAAE,KAAK,IAAI;AAAA,IACb;AAAA,EACF;AAEA,UACE,MAAMC,SAAQ,eAAe,UAAU;AAAA,IACrC,WAAW,IAAI;AAAA,IACf,cAAc;AAAA,IACd,YAAY;AAAA,EACd,CAAC,GACD;AACJ;AAEA,eAAe,cACb,OACA,KACA,QAAQ,GACR,OAAiB,CAAC,GACD;AACjB,MAAI,MAAM;AACV,aAAW,QAAQ,OAAO;AACxB,UAAM,cAAc,CAAC,GAAG,MAAM,KAAK,KAAK;AACxC,WAAO;AAAA;AAAA,EAAO,WAAW,OAAO,KAAK,KAAK,CAAC;AAAA;AAAA;AAC3C,UAAM,UAAU,MAAM,cAAc,MAAM,aAAa,GAAG;AAC1D,UAAM,UAAU,KAAK,YAAY,KAAK,GAAG,CAAC,OAAO,SAAS,OAAO;AACjE,QAAI,SAAS;AACX,aAAO,GAAG,OAAO;AAAA;AAAA,IACnB;AACA,QAAI,KAAK,UAAU,QAAQ;AACzB,aAAO,MAAM,cAAc,KAAK,UAAU,KAAK,QAAQ,GAAG,WAAW;AAAA,IACvE;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAsB,aACpB,SACA,SACA;AACA,QAAM,SAAS;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAG,SAAS,OAAO;AAAA,EACrB,EAAE,KAAK,IAAI;AAEX,QAAM,OAAO,MAAM;AAAA,IACjB;AAAA,IACA,EAAE,WAAW,QAAQ,UAAU;AAAA,IAC/B;AAAA,EACF;AACA,SAAO,GAAG,MAAM;AAAA;AAAA,EAAO,IAAI;AAAA;AAC7B;",
6
6
  "names": ["agent", "execute", "instructions", "user", "scratchpad_tool", "agent", "instructions", "scratchpad_tool", "user", "execute"]
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"writer.d.ts","sourceRoot":"","sources":["../../../src/lib/deepwiki/writer.ts"],"names":[],"mappings":"AAsBA,OAAO,EAAE,KAAK,OAAO,EAAY,MAAM,oBAAoB,CAAC;AAgI5D,wBAAsB,YAAY,CAAC,OAAO,EAAE;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd,mBA6CA;AAuKD,wBAAsB,cAAc,CAAC,KAAK,EAAE;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd,mBAiDA"}
1
+ {"version":3,"file":"writer.d.ts","sourceRoot":"","sources":["../../../src/lib/deepwiki/writer.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAE,KAAK,OAAO,EAAY,MAAM,oBAAoB,CAAC;AA+H5D,wBAAsB,YAAY,CAAC,OAAO,EAAE;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd,mBA6CA;AAuKD,wBAAsB,cAAc,CAAC,KAAK,EAAE;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACd,mBAiDA"}
@@ -10,7 +10,6 @@ import {
10
10
  instructions as instructions2,
11
11
  lmstudio,
12
12
  printer,
13
- toState,
14
13
  user as user2
15
14
  } from "@deepagents/agent";
16
15
  import {
@@ -108,8 +107,10 @@ var outlineAgent = agent({
108
107
  inputSchema: z.object({
109
108
  outline: OutlineSchema
110
109
  })
111
- // execute: ({ outline }, options) => {
112
- // const context = toState<OutlineAgentContext>(options);
110
+ // execute: (
111
+ // { outline },
112
+ // { context }: ToolExecutionOptions<OutlineAgentContext>,
113
+ // ) => {
113
114
  // // Store the outline in a file or database
114
115
  // console.log('Generated Outline:\n', outline);
115
116
  // context.outline = outline;
@@ -175,8 +176,7 @@ var write_section_tool = tool2({
175
176
  execute: async ({
176
177
  sectionTitle,
177
178
  sectionContent
178
- }, options) => {
179
- const context = toState(options);
179
+ }, { context }) => {
180
180
  const p = `./docs/section_${snakeCase(sectionTitle)}.md`;
181
181
  await writeFile(p, sectionContent, "utf-8");
182
182
  context.section_path[sectionTitle] = p;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/deepwiki/writer.ts", "../../../src/lib/graph.ts", "../../../src/lib/deepwiki/outline-agent.ts"],
4
- "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { type ToolExecutionOptions, tool } from 'ai';\nimport { snakeCase } from 'lodash-es';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport z from 'zod';\n\nimport {\n agent,\n execute,\n instructions,\n lmstudio,\n printer,\n toState,\n user,\n} from '@deepagents/agent';\nimport {\n read_file_tool,\n scratchpad_tool,\n search_content_tool,\n} from '@deepagents/toolbox';\n\nimport { fold } from '../graph.ts';\nimport { type Outline, buildToc } from './outline-agent.ts';\n\ntype SectionAgentContext = {\n repo_path: string;\n scratchpad: string;\n tree: string;\n toc: string[];\n section_path: Record<string, string>;\n};\n\n// Define tool outside agent to help TypeScript with type inference\nconst write_section_tool = tool({\n description:\n 'Use this tool to return the final markdown content for the current section. You MUST use this tool to return your final output.',\n inputSchema: z.object({\n sectionTitle: z\n .string()\n .describe(\n 'The title of the section being written. Prefer the FULL hierarchical path like \"Parent > Child\" to ensure uniqueness.',\n ),\n sectionContent: z\n .string()\n .describe(\n 'The markdown content for the section excluding section heading.',\n ),\n }),\n execute: async (\n {\n sectionTitle,\n sectionContent,\n }: { sectionTitle: string; sectionContent: string },\n options: ToolExecutionOptions<any>,\n ) => {\n const context = toState<SectionAgentContext>(options);\n const p = `./docs/section_${snakeCase(sectionTitle)}.md`;\n await writeFile(p, sectionContent, 'utf-8');\n context.section_path[sectionTitle] = p;\n return `Section \"${sectionTitle}\" written to file.`;\n },\n});\n\nconst writer = agent<SectionAgentContext>({\n name: 'Wiki Writer',\n model: lmstudio('qwen/qwen3-8b'),\n // model: groq('openai/gpt-oss-120b'),\n // model: groq('openai/gpt-oss-20b'),\n prompt: instructions({\n purpose: [\n 'You write comprehensive, accurate, and actionable documentation sections for a repository wiki.',\n 'You can inspect files and directory structure using provided tools to ground your writing in the actual codebase.',\n ],\n routine: [\n 'Use the scratchpad to note findings from reading files or directories; keep it concise and relevant.',\n 'Clarify scope: write ONLY for the current section path you are working on; do not expand into subsections (those are handled separately).',\n 'Avoid references to unknown frameworks or generated folders; ground claims in actual repo contents when possible.',\n 'Make use of the `search_content` tool to find relevant information in the codebase. this tool can search the entire repository for keywords or topics. use it to find code examples, explanations, or relevant files.',\n 'When you return a section via write_section, set sectionTitle to the FULL hierarchical path of the section using \">\" as a separator (e.g., \"Parent > Child > Subchild\").',\n ],\n }),\n tools: {\n read_file: read_file_tool,\n // read_dir: read_dir_tool,\n // search_files: search_files_tool,\n write_section: write_section_tool,\n search_content: search_content_tool,\n update_scratchpad: scratchpad_tool,\n },\n});\n\nfunction headingFor(level: number, title: string) {\n const capped = Math.min(Math.max(level, 1), 6);\n return `${'#'.repeat(capped)} ${title}`;\n}\n\nasync function readIfExists(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf-8');\n } catch {\n return undefined;\n }\n}\n\nasync function aggregateSections(\n items: Outline,\n depth: number,\n state: SectionAgentContext,\n path: string[] = [],\n): Promise<string> {\n let out = '';\n for (const item of items) {\n const currentPath = [...path, item.title];\n const pathKey = currentPath.join(' > ');\n const directKey = item.title;\n\n // Prefer mapped file based on full path, fall back to title, then inferred filename(s)\n const mappedPath =\n state.section_path[pathKey] || state.section_path[directKey];\n const inferredCandidates = [\n `./section_${snakeCase(pathKey)}.md`,\n `./section_${snakeCase(directKey)}.md`,\n ];\n\n let content: string | undefined;\n if (mappedPath) {\n content = await readIfExists(mappedPath);\n }\n if (!content) {\n for (const p of inferredCandidates) {\n content = await readIfExists(p);\n if (content) break;\n }\n }\n\n out += `\\n\\n${headingFor(depth, item.title)}\\n\\n`;\n if (content) out += `${content}\\n`;\n\n if (item.sections?.length) {\n out += await aggregateSections(\n item.sections,\n depth + 1,\n state,\n currentPath,\n );\n }\n }\n return out;\n}\n\nexport async function generateWiki(options: {\n repo_path: string;\n outline: Outline;\n tree: string;\n}) {\n const toc = buildToc(options.outline);\n const state: SectionAgentContext = {\n repo_path: options.repo_path,\n scratchpad: '## Scratchpad\\n\\n',\n tree: options.tree,\n toc: toc,\n section_path: {},\n };\n\n // await execute(\n // writer,\n // [\n // user(`You are tasked with writing a comprehensive wiki for a code repository. The wiki will be structured according to the provided outline, which details the sections and subsections to be covered.\n\n // <RepositoryTree>\n // ${options.tree}\n // </RepositoryTree>\n\n // <WikiOutline>\n // ${toc}\n // </WikiOutline>\n\n // Your job is to write each section of the wiki based on this outline. For each section, you should:\n\n // 1. Understand the section title and its place in the overall structure.\n // 2. Use the provided tools to inspect relevant files and directories in the repository to gather information for that section.\n // 3. Write clear, concise, and informative markdown content for the section, including code examples where appropriate.\n // 4. Ensure that each section is self-contained and provides value to someone reading the wiki.\n\n // Begin by writing the top-level sections of the outline. For each section, if there are subsections, you will handle those separately after completing the parent section.\n\n // Important: When calling write_section, set sectionTitle to the FULL hierarchical path (e.g., \"Parent > Child > Subchild\").\n\n // ],\n // state,\n // ).text;\n\n // const header = ['# Project Wiki', '', '## Table of Contents', ...toc].join(\n // '\\n',\n // );\n\n // const body = await aggregateSections(options.outline, 1, state);\n // return `${header}\\n\\n${body}\\n`;\n return '';\n}\n\ntype IsolatedSectionAgentContext = {\n repo_path: string;\n scratchpad: string;\n tree: string;\n toc: string[];\n};\nconst sectionWriterAgent = agent<IsolatedSectionAgentContext>({\n name: 'Section Writer',\n // model: lmstudio('qwen/qwen3-8b'),\n model: groq('openai/gpt-oss-20b'),\n // temperature: 0.3,\n tools: {\n read_file: read_file_tool,\n search_content: search_content_tool,\n },\n prompt: '',\n});\n\ntype StitchAgentContext = {\n repo_path: string;\n scratchpad: string;\n tree: string;\n toc: string[];\n};\nconst stitchAgent = agent<StitchAgentContext>({\n name: 'Stitch Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n prompt: instructions({\n purpose: [\n 'You synthesize and stitch together child subsections into a cohesive parent section for a wiki.',\n 'Your role is to create an introduction and transitions that bind child sections together while maintaining clarity and flow.',\n ],\n routine: [\n 'Review all child section contents provided to understand their focus and relationships.',\n 'Create a cohesive parent section that introduces the topic and smoothly connects to the child sections.',\n 'Add transitions and context that help readers understand how child sections relate to each other.',\n 'Do NOT duplicate content from child sections; reference and introduce them instead.',\n 'Keep your writing clear, concise, and focused on synthesis rather than repetition.',\n ],\n }),\n});\n\nasync function write(\n state: IsolatedSectionAgentContext,\n item: Outline[number],\n) {\n console.log(buildToc([item]));\n return await execute(\n sectionWriterAgent,\n [\n user(\n `\n You are part of a team writing a comprehensive wiki for a code repository. Your specific task is to write the following section of the wiki:\n\n<SectionTitle>\n ${item.title}\n</SectionTitle>\n<ActiveSectionWiki>\n ${buildToc([item])}\n</ActiveSectionWiki>\n\nThe complete wiki outline is as follows:\n<WikiOutline>\n${state.toc}\n</WikiOutline>\n\nThe repository structure is as follows:\n\n<RepositoryTree>\n${state.tree}\n</RepositoryTree>\n\nYou should:\n\n1. Understand the section title and its place in the overall structure.\n2. Use the provided tools to inspect relevant files and directories in the repository to gather information for that section.\n3. Write clear, concise, and informative markdown content for the section, including code examples where appropriate.\n4. Ensure that the section is self-contained and provides value to someone reading the wiki.\n\nRemember to keep your writing clear, concise, and focused on the current section topic. Do not include information about other sections or subsections.\n`,\n ),\n ],\n state,\n );\n}\n\nasync function stitch(\n state: StitchAgentContext,\n item: Outline[number],\n childSections: Array<{ title: string; content: string }>,\n) {\n const childSectionsList = childSections\n .map(\n (child) => `\n### ${child.title}\n${child.content}\n`,\n )\n .join('\\n');\n\n return await execute(\n stitchAgent,\n [\n user(\n `\n You are stitching together child subsections into a cohesive parent section for a wiki. Your task is to create an introduction and transitions that bind the following child sections together.\n\n<ParentSectionTitle>\n ${item.title}\n</ParentSectionTitle>\n\n<ChildSections>\n${childSectionsList}\n</ChildSections>\n\nThe complete wiki outline is as follows:\n<WikiOutline>\n${state.toc}\n</WikiOutline>\n\nThe repository structure is as follows:\n\n<RepositoryTree>\n${state.tree}\n</RepositoryTree>\n\nYour task is to:\n\n1. Create an introduction to the parent section that sets the context for the child sections.\n2. Add smooth transitions between child sections that explain their relationships.\n3. Synthesize the content into a cohesive narrative rather than just concatenating the children.\n4. Do NOT duplicate the full content of child sections - assume readers will see them in context.\n5. Focus on creating connections and providing high-level overview.\n\n`,\n ),\n ],\n state,\n );\n}\n\nfunction assembleDocument(\n items: Outline,\n local: Record<string, string>,\n depth: number,\n): string {\n let output = '';\n\n for (const item of items) {\n const content = local[item.title];\n\n // Add heading for this section\n output += `${headingFor(depth, item.title)}\\n\\n`;\n\n // Add the content - if this is a parent section,\n // the stitched content already includes all children inline\n if (content) {\n output += `${content}\\n\\n`;\n }\n }\n\n return output;\n}\n\nexport async function singlePageWiki(state: {\n repo_path: string;\n outline: Outline;\n tree: string;\n}) {\n const root = state.outline[0];\n const local: Record<string, string> = {};\n const store = {\n async set(key: string, value: string) {\n await writeFile(`./docs/section_${snakeCase(key)}.md`, value, 'utf-8');\n local[key] = value;\n },\n };\n await fold(\n root,\n { title: root.title },\n async (item) => {\n if (!item.sections || item.sections.length === 0) {\n const result = await write(\n {\n repo_path: state.repo_path,\n tree: state.tree,\n scratchpad: '## Scratchpad\\n\\n',\n toc: buildToc(state.outline),\n },\n item,\n );\n // await printer.stdout(result);\n return result.text;\n } else {\n // Stitch the parent section from child sections\n const stitchResult = await stitch(\n {\n repo_path: state.repo_path,\n tree: state.tree,\n scratchpad: '## Scratchpad\\n\\n',\n toc: buildToc(state.outline),\n },\n item,\n Object.entries(local)\n .filter(([k]) => item.sections!.some((key) => key.title === k))\n .map(([title, content]) => ({ title, content })),\n );\n console.log('=== STITCH RESULT ===');\n await printer.stdout(stitchResult);\n return stitchResult.text;\n }\n },\n store,\n );\n\n // Assemble the final document from all processed sections\n return assembleDocument(state.outline, local, 1);\n}\n", "import type { Outline } from './deepwiki/outline-agent.ts';\n\ntype WithParent = {\n title: string;\n parent?: WithParent;\n sections?: WithParent[];\n};\n\nfunction flat(item: WithParent) {\n const paths: string[][] = [];\n if (!item.sections || item.sections.length === 0) {\n let current: WithParent | undefined = item;\n const path: string[] = [];\n while (current.parent) {\n current = current.parent;\n path.unshift(current.title);\n }\n path.push(item.title);\n paths.push(path);\n return paths;\n }\n for (const section of item.sections) {\n paths.push(...flat({ ...section, parent: item }));\n }\n return paths;\n}\n\nexport async function fold(\n item: Outline[number],\n parent: Outline[number],\n write: (section: Outline[number]) => Promise<string>,\n store: {\n set: (key: string, value: string) => Promise<void>;\n },\n) {\n const sections = item.sections || [];\n for (const section of sections) {\n await fold(section, item, write, store);\n }\n await store.set(item.title, await write(item));\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { type UIMessage, generateId, toUIMessageStream, tool } from 'ai';\nimport z from 'zod';\n\nimport {\n agent,\n execute,\n generate,\n instructions,\n user,\n} from '@deepagents/agent';\nimport { read_file_tool, scratchpad_tool } from '@deepagents/toolbox';\n\nconst BaseOutlineItem = z.object({\n title: z.string().trim().min(1, 'Title is required'),\n});\ntype OutlineItem = z.output<typeof BaseOutlineItem> & {\n sections?: z.output<typeof OutlineItemSchema>[];\n};\nconst OutlineItemSchema: z.ZodType<OutlineItem> = z.lazy(() =>\n BaseOutlineItem.extend({\n sections: z.array(OutlineItemSchema).optional(),\n }),\n);\nconst OutlineSchema = z.array(OutlineItemSchema);\nexport type Outline = z.output<typeof OutlineSchema>;\nexport type OutlineAgentContext = {\n repo_path: string;\n outline: z.output<typeof OutlineSchema>;\n scratchpad: string;\n tree: string;\n};\n\nexport const outlineAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n // model: lmstudio('qwen/qwen3-8b'),\n // model: lmstudio('openai/gpt-oss-20b'),\n\n // temperature: 0.1,\n prompt: (context) =>\n instructions({\n purpose: [\n \"You are wiki architect, meticulously analyzing a repository's structure and content to automatically generate a comprehensive, intelligent, and perfectly structured outline, laying the bedrock for exceptional documentation.\",\n '\\n',\n '<RepositoryTree>',\n context?.tree || '',\n '</RepositoryTree>',\n ],\n routine: [],\n // routine: [\n // 'Your primary tool for memory is your `scratchpad`. After every action, you MUST summarize your findings and add them to the scratchpad using the `update_scratchpad` tool.',\n // 'Systematically investigate key files and directories use `search_files`. For each finding add it as a new note to your scratchpad.',\n // 'When you read a file like `README.md` or `package.json`, do not keep the whole content in your head. Instead, summarize the important parts (like headings, dependencies, or scripts) and add that summary to your scratchpad.',\n // 'Continue this process of exploring, summarizing, and adding to your scratchpad until you are confident you have a full picture of the repository.',\n // 'Once you believe you have gathered enough information, your second-to-last step is to review your entire scratchpad to synthesize a plan for the final outline.',\n // 'Finally, based *only* on the information you have gathered in your scratchpad, generate the complete, detailed outline and store it using the `store_outline` tool. You must only call `store_outline` ONCE at the very end.',\n // ],\n }),\n tools: {\n read_file: read_file_tool,\n // read_dir: read_dir_tool,\n // search_files: search_files_tool,\n // file_exists: file_exists_tool,\n update_scratchpad: scratchpad_tool,\n store_outline: tool({\n description: `Use this tool to store the generated outline.\n\t\tThe outline should be a detailed hierarchical structure representing the sections and subsections of the repository documentation. In thory you can nest sections as deep as you want, but try to keep it to 4 levels deep maximum.\n\n\t\t## Example outline\n\t\t[\n\t\t\t{\n\t\t\t\t\"title\": \"xxxx\",\n\t\t\t\t\"sections\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"yyyy\",\n\t\t\t\t\t\tsections: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"title\": \"vvvv\",\n\t\t\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"gggg\",\n\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t},\n\t\t]\n\t\t\t`,\n inputSchema: z.object({\n outline: OutlineSchema,\n }),\n // execute: ({ outline }, options) => {\n // const context = toState<OutlineAgentContext>(options);\n // // Store the outline in a file or database\n // console.log('Generated Outline:\\n', outline);\n // context.outline = outline;\n // return 'Outline stored successfully.';\n // },\n }),\n },\n});\n\nexport const outlineCondensedAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Condensed Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n prompt: instructions({\n purpose: [\n 'To intelligently condense and optimize an existing outline by merging redundant sections, removing overly granular subdivisions, and creating a more streamlined, maintainable documentation structure.',\n 'Your goal is to reduce complexity while preserving all essential information and maintaining logical hierarchy.',\n ],\n routine: [\n 'Examine the current outline structure stored in the context. Use your scratchpad to track your analysis.',\n 'Identify sections that are too granular (e.g., sections with only 1-2 subsections that could be merged with their parent).',\n 'Look for redundant or overlapping sections that cover similar topics and can be consolidated.',\n 'Note sections with excessive nesting depth (more than 3-4 levels) that could be flattened.',\n 'Identify sections with very similar titles that could be merged (e.g., \"API Overview\" and \"API Introduction\").',\n 'For each potential consolidation, add a note to your scratchpad explaining the rationale.',\n 'Create a condensed version of the outline that:',\n ' - Merges related subsections into broader topics',\n ' - Reduces nesting depth where appropriate',\n ' - Eliminates redundancy while keeping all unique content areas',\n ' - Maintains a maximum depth of 3 levels unless absolutely necessary',\n ' - Ensures each section has substantial content to document',\n 'Return the condensed outline as structured output.',\n ],\n }),\n output: OutlineSchema,\n});\n\nexport async function generateOutline(state: OutlineAgentContext) {\n const messages: UIMessage[] = [\n user(\n 'Walk through the repository and generate a detailed outline. Make sure to avoid looking into framework generated files and folders. when outline is complete, call the store_outline tool.',\n ),\n ];\n const max_iterations = 3;\n let current_iteration = 0;\n while (current_iteration < max_iterations) {\n console.log(`\\n=== Outline Iteration ${current_iteration + 1} ===\\n`);\n const result = await execute(outlineAgent, messages, state);\n await Array.fromAsync(\n toUIMessageStream({\n stream: result.stream,\n tools: outlineAgent.toToolset(),\n generateMessageId: generateId,\n originalMessages: messages,\n onEnd: async ({ responseMessage }: { responseMessage: UIMessage }) => {\n messages.push(responseMessage);\n },\n }),\n );\n await result.consumeStream();\n const calls = await result.toolCalls;\n const outlineCall = calls.find(\n (t: { toolName: string }) => t.toolName === 'store_outline',\n );\n if (outlineCall) {\n console.log('\\n=== Outline Generation Complete ===\\n');\n state.outline = outlineCall.input.outline;\n break;\n }\n current_iteration++;\n }\n if (!state.outline.length) {\n throw new Error('Outline generation failed.');\n }\n return generate(\n outlineCondensedAgent,\n `Condense and optimize the following outline:\\n\\n${buildToc(state.outline)}`,\n state,\n ).then(({ output }) => output);\n}\n\nfunction slugify(text: string) {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, '')\n .trim()\n .replace(/\\s+/g, '-')\n .replace(/-+/g, '-');\n}\n\nexport function buildToc(\n items: OutlineItem[],\n baseDepth = 1,\n prefix: string[] = [],\n) {\n const lines: string[] = [];\n for (const it of items) {\n const path = [...prefix, it.title];\n const indent = ' '.repeat(Math.max(0, path.length - 1));\n const anchor = slugify(it.title);\n lines.push(`${indent}- [${it.title}](#${anchor})`);\n if (it.sections?.length) {\n lines.push(...buildToc(it.sections, baseDepth + 1, path));\n }\n }\n return lines;\n}\n"],
5
- "mappings": ";AAAA,SAAS,QAAAA,aAAY;AACrB,SAAoC,QAAAC,aAAY;AAChD,SAAS,iBAAiB;AAC1B,SAAS,UAAU,iBAAiB;AACpC,OAAOC,QAAO;AAEd;AAAA,EACE,SAAAC;AAAA,EACA,WAAAC;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,QAAAC;AAAA,OACK;AACP;AAAA,EACE,kBAAAC;AAAA,EACA,mBAAAC;AAAA,EACA;AAAA,OACK;;;ACQP,eAAsB,KACpB,MACA,QACAC,QACA,OAGA;AACA,QAAM,WAAW,KAAK,YAAY,CAAC;AACnC,aAAW,WAAW,UAAU;AAC9B,UAAM,KAAK,SAAS,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BAAQ,IAAI,uBAAuB;AACnC,cAAM,QAAQ,OAAO,YAAY;AACjC,eAAO,aAAa;AAAA,MACtB;AAAA,IACF;AAAA,IACA;AAAA,EACF;AAGA,SAAO,iBAAiB,MAAM,SAAS,OAAO,CAAC;AACjD;",
4
+ "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { type ToolExecutionOptions, tool } from 'ai';\nimport { snakeCase } from 'lodash-es';\nimport { readFile, writeFile } from 'node:fs/promises';\nimport z from 'zod';\n\nimport {\n agent,\n execute,\n instructions,\n lmstudio,\n printer,\n user,\n} from '@deepagents/agent';\nimport {\n read_file_tool,\n scratchpad_tool,\n search_content_tool,\n} from '@deepagents/toolbox';\n\nimport { fold } from '../graph.ts';\nimport { type Outline, buildToc } from './outline-agent.ts';\n\ntype SectionAgentContext = {\n repo_path: string;\n scratchpad: string;\n tree: string;\n toc: string[];\n section_path: Record<string, string>;\n};\n\n// Define tool outside agent to help TypeScript with type inference\nconst write_section_tool = tool({\n description:\n 'Use this tool to return the final markdown content for the current section. You MUST use this tool to return your final output.',\n inputSchema: z.object({\n sectionTitle: z\n .string()\n .describe(\n 'The title of the section being written. Prefer the FULL hierarchical path like \"Parent > Child\" to ensure uniqueness.',\n ),\n sectionContent: z\n .string()\n .describe(\n 'The markdown content for the section excluding section heading.',\n ),\n }),\n execute: async (\n {\n sectionTitle,\n sectionContent,\n }: { sectionTitle: string; sectionContent: string },\n { context }: ToolExecutionOptions<SectionAgentContext>,\n ) => {\n const p = `./docs/section_${snakeCase(sectionTitle)}.md`;\n await writeFile(p, sectionContent, 'utf-8');\n context.section_path[sectionTitle] = p;\n return `Section \"${sectionTitle}\" written to file.`;\n },\n});\n\nconst writer = agent<unknown, SectionAgentContext>({\n name: 'Wiki Writer',\n model: lmstudio('qwen/qwen3-8b'),\n // model: groq('openai/gpt-oss-120b'),\n // model: groq('openai/gpt-oss-20b'),\n prompt: instructions({\n purpose: [\n 'You write comprehensive, accurate, and actionable documentation sections for a repository wiki.',\n 'You can inspect files and directory structure using provided tools to ground your writing in the actual codebase.',\n ],\n routine: [\n 'Use the scratchpad to note findings from reading files or directories; keep it concise and relevant.',\n 'Clarify scope: write ONLY for the current section path you are working on; do not expand into subsections (those are handled separately).',\n 'Avoid references to unknown frameworks or generated folders; ground claims in actual repo contents when possible.',\n 'Make use of the `search_content` tool to find relevant information in the codebase. this tool can search the entire repository for keywords or topics. use it to find code examples, explanations, or relevant files.',\n 'When you return a section via write_section, set sectionTitle to the FULL hierarchical path of the section using \">\" as a separator (e.g., \"Parent > Child > Subchild\").',\n ],\n }),\n tools: {\n read_file: read_file_tool,\n // read_dir: read_dir_tool,\n // search_files: search_files_tool,\n write_section: write_section_tool,\n search_content: search_content_tool,\n update_scratchpad: scratchpad_tool,\n },\n});\n\nfunction headingFor(level: number, title: string) {\n const capped = Math.min(Math.max(level, 1), 6);\n return `${'#'.repeat(capped)} ${title}`;\n}\n\nasync function readIfExists(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf-8');\n } catch {\n return undefined;\n }\n}\n\nasync function aggregateSections(\n items: Outline,\n depth: number,\n state: SectionAgentContext,\n path: string[] = [],\n): Promise<string> {\n let out = '';\n for (const item of items) {\n const currentPath = [...path, item.title];\n const pathKey = currentPath.join(' > ');\n const directKey = item.title;\n\n // Prefer mapped file based on full path, fall back to title, then inferred filename(s)\n const mappedPath =\n state.section_path[pathKey] || state.section_path[directKey];\n const inferredCandidates = [\n `./section_${snakeCase(pathKey)}.md`,\n `./section_${snakeCase(directKey)}.md`,\n ];\n\n let content: string | undefined;\n if (mappedPath) {\n content = await readIfExists(mappedPath);\n }\n if (!content) {\n for (const p of inferredCandidates) {\n content = await readIfExists(p);\n if (content) break;\n }\n }\n\n out += `\\n\\n${headingFor(depth, item.title)}\\n\\n`;\n if (content) out += `${content}\\n`;\n\n if (item.sections?.length) {\n out += await aggregateSections(\n item.sections,\n depth + 1,\n state,\n currentPath,\n );\n }\n }\n return out;\n}\n\nexport async function generateWiki(options: {\n repo_path: string;\n outline: Outline;\n tree: string;\n}) {\n const toc = buildToc(options.outline);\n const state: SectionAgentContext = {\n repo_path: options.repo_path,\n scratchpad: '## Scratchpad\\n\\n',\n tree: options.tree,\n toc: toc,\n section_path: {},\n };\n\n // await execute(\n // writer,\n // [\n // user(`You are tasked with writing a comprehensive wiki for a code repository. The wiki will be structured according to the provided outline, which details the sections and subsections to be covered.\n\n // <RepositoryTree>\n // ${options.tree}\n // </RepositoryTree>\n\n // <WikiOutline>\n // ${toc}\n // </WikiOutline>\n\n // Your job is to write each section of the wiki based on this outline. For each section, you should:\n\n // 1. Understand the section title and its place in the overall structure.\n // 2. Use the provided tools to inspect relevant files and directories in the repository to gather information for that section.\n // 3. Write clear, concise, and informative markdown content for the section, including code examples where appropriate.\n // 4. Ensure that each section is self-contained and provides value to someone reading the wiki.\n\n // Begin by writing the top-level sections of the outline. For each section, if there are subsections, you will handle those separately after completing the parent section.\n\n // Important: When calling write_section, set sectionTitle to the FULL hierarchical path (e.g., \"Parent > Child > Subchild\").\n\n // ],\n // state,\n // ).text;\n\n // const header = ['# Project Wiki', '', '## Table of Contents', ...toc].join(\n // '\\n',\n // );\n\n // const body = await aggregateSections(options.outline, 1, state);\n // return `${header}\\n\\n${body}\\n`;\n return '';\n}\n\ntype IsolatedSectionAgentContext = {\n repo_path: string;\n scratchpad: string;\n tree: string;\n toc: string[];\n};\nconst sectionWriterAgent = agent<unknown, IsolatedSectionAgentContext>({\n name: 'Section Writer',\n // model: lmstudio('qwen/qwen3-8b'),\n model: groq('openai/gpt-oss-20b'),\n // temperature: 0.3,\n tools: {\n read_file: read_file_tool,\n search_content: search_content_tool,\n },\n prompt: '',\n});\n\ntype StitchAgentContext = {\n repo_path: string;\n scratchpad: string;\n tree: string;\n toc: string[];\n};\nconst stitchAgent = agent<unknown, StitchAgentContext>({\n name: 'Stitch Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n prompt: instructions({\n purpose: [\n 'You synthesize and stitch together child subsections into a cohesive parent section for a wiki.',\n 'Your role is to create an introduction and transitions that bind child sections together while maintaining clarity and flow.',\n ],\n routine: [\n 'Review all child section contents provided to understand their focus and relationships.',\n 'Create a cohesive parent section that introduces the topic and smoothly connects to the child sections.',\n 'Add transitions and context that help readers understand how child sections relate to each other.',\n 'Do NOT duplicate content from child sections; reference and introduce them instead.',\n 'Keep your writing clear, concise, and focused on synthesis rather than repetition.',\n ],\n }),\n});\n\nasync function write(\n state: IsolatedSectionAgentContext,\n item: Outline[number],\n) {\n console.log(buildToc([item]));\n return await execute(\n sectionWriterAgent,\n [\n user(\n `\n You are part of a team writing a comprehensive wiki for a code repository. Your specific task is to write the following section of the wiki:\n\n<SectionTitle>\n ${item.title}\n</SectionTitle>\n<ActiveSectionWiki>\n ${buildToc([item])}\n</ActiveSectionWiki>\n\nThe complete wiki outline is as follows:\n<WikiOutline>\n${state.toc}\n</WikiOutline>\n\nThe repository structure is as follows:\n\n<RepositoryTree>\n${state.tree}\n</RepositoryTree>\n\nYou should:\n\n1. Understand the section title and its place in the overall structure.\n2. Use the provided tools to inspect relevant files and directories in the repository to gather information for that section.\n3. Write clear, concise, and informative markdown content for the section, including code examples where appropriate.\n4. Ensure that the section is self-contained and provides value to someone reading the wiki.\n\nRemember to keep your writing clear, concise, and focused on the current section topic. Do not include information about other sections or subsections.\n`,\n ),\n ],\n state,\n );\n}\n\nasync function stitch(\n state: StitchAgentContext,\n item: Outline[number],\n childSections: Array<{ title: string; content: string }>,\n) {\n const childSectionsList = childSections\n .map(\n (child) => `\n### ${child.title}\n${child.content}\n`,\n )\n .join('\\n');\n\n return await execute(\n stitchAgent,\n [\n user(\n `\n You are stitching together child subsections into a cohesive parent section for a wiki. Your task is to create an introduction and transitions that bind the following child sections together.\n\n<ParentSectionTitle>\n ${item.title}\n</ParentSectionTitle>\n\n<ChildSections>\n${childSectionsList}\n</ChildSections>\n\nThe complete wiki outline is as follows:\n<WikiOutline>\n${state.toc}\n</WikiOutline>\n\nThe repository structure is as follows:\n\n<RepositoryTree>\n${state.tree}\n</RepositoryTree>\n\nYour task is to:\n\n1. Create an introduction to the parent section that sets the context for the child sections.\n2. Add smooth transitions between child sections that explain their relationships.\n3. Synthesize the content into a cohesive narrative rather than just concatenating the children.\n4. Do NOT duplicate the full content of child sections - assume readers will see them in context.\n5. Focus on creating connections and providing high-level overview.\n\n`,\n ),\n ],\n state,\n );\n}\n\nfunction assembleDocument(\n items: Outline,\n local: Record<string, string>,\n depth: number,\n): string {\n let output = '';\n\n for (const item of items) {\n const content = local[item.title];\n\n // Add heading for this section\n output += `${headingFor(depth, item.title)}\\n\\n`;\n\n // Add the content - if this is a parent section,\n // the stitched content already includes all children inline\n if (content) {\n output += `${content}\\n\\n`;\n }\n }\n\n return output;\n}\n\nexport async function singlePageWiki(state: {\n repo_path: string;\n outline: Outline;\n tree: string;\n}) {\n const root = state.outline[0];\n const local: Record<string, string> = {};\n const store = {\n async set(key: string, value: string) {\n await writeFile(`./docs/section_${snakeCase(key)}.md`, value, 'utf-8');\n local[key] = value;\n },\n };\n await fold(\n root,\n { title: root.title },\n async (item) => {\n if (!item.sections || item.sections.length === 0) {\n const result = await write(\n {\n repo_path: state.repo_path,\n tree: state.tree,\n scratchpad: '## Scratchpad\\n\\n',\n toc: buildToc(state.outline),\n },\n item,\n );\n // await printer.stdout(result);\n return result.text;\n } else {\n // Stitch the parent section from child sections\n const stitchResult = await stitch(\n {\n repo_path: state.repo_path,\n tree: state.tree,\n scratchpad: '## Scratchpad\\n\\n',\n toc: buildToc(state.outline),\n },\n item,\n Object.entries(local)\n .filter(([k]) => item.sections!.some((key) => key.title === k))\n .map(([title, content]) => ({ title, content })),\n );\n console.log('=== STITCH RESULT ===');\n await printer.stdout(stitchResult);\n return stitchResult.text;\n }\n },\n store,\n );\n\n // Assemble the final document from all processed sections\n return assembleDocument(state.outline, local, 1);\n}\n", "import type { Outline } from './deepwiki/outline-agent.ts';\n\ntype WithParent = {\n title: string;\n parent?: WithParent;\n sections?: WithParent[];\n};\n\nfunction flat(item: WithParent) {\n const paths: string[][] = [];\n if (!item.sections || item.sections.length === 0) {\n let current: WithParent | undefined = item;\n const path: string[] = [];\n while (current.parent) {\n current = current.parent;\n path.unshift(current.title);\n }\n path.push(item.title);\n paths.push(path);\n return paths;\n }\n for (const section of item.sections) {\n paths.push(...flat({ ...section, parent: item }));\n }\n return paths;\n}\n\nexport async function fold(\n item: Outline[number],\n parent: Outline[number],\n write: (section: Outline[number]) => Promise<string>,\n store: {\n set: (key: string, value: string) => Promise<void>;\n },\n) {\n const sections = item.sections || [];\n for (const section of sections) {\n await fold(section, item, write, store);\n }\n await store.set(item.title, await write(item));\n}\n", "import { groq } from '@ai-sdk/groq';\nimport { type UIMessage, generateId, toUIMessageStream, tool } from 'ai';\nimport z from 'zod';\n\nimport {\n agent,\n execute,\n generate,\n instructions,\n user,\n} from '@deepagents/agent';\nimport { read_file_tool, scratchpad_tool } from '@deepagents/toolbox';\n\nconst BaseOutlineItem = z.object({\n title: z.string().trim().min(1, 'Title is required'),\n});\ntype OutlineItem = z.output<typeof BaseOutlineItem> & {\n sections?: z.output<typeof OutlineItemSchema>[];\n};\nconst OutlineItemSchema: z.ZodType<OutlineItem> = z.lazy(() =>\n BaseOutlineItem.extend({\n sections: z.array(OutlineItemSchema).optional(),\n }),\n);\nconst OutlineSchema = z.array(OutlineItemSchema);\nexport type Outline = z.output<typeof OutlineSchema>;\nexport type OutlineAgentContext = {\n repo_path: string;\n outline: z.output<typeof OutlineSchema>;\n scratchpad: string;\n tree: string;\n};\n\nexport const outlineAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n // model: lmstudio('qwen/qwen3-8b'),\n // model: lmstudio('openai/gpt-oss-20b'),\n\n // temperature: 0.1,\n prompt: (context) =>\n instructions({\n purpose: [\n \"You are wiki architect, meticulously analyzing a repository's structure and content to automatically generate a comprehensive, intelligent, and perfectly structured outline, laying the bedrock for exceptional documentation.\",\n '\\n',\n '<RepositoryTree>',\n context?.tree || '',\n '</RepositoryTree>',\n ],\n routine: [],\n // routine: [\n // 'Your primary tool for memory is your `scratchpad`. After every action, you MUST summarize your findings and add them to the scratchpad using the `update_scratchpad` tool.',\n // 'Systematically investigate key files and directories use `search_files`. For each finding add it as a new note to your scratchpad.',\n // 'When you read a file like `README.md` or `package.json`, do not keep the whole content in your head. Instead, summarize the important parts (like headings, dependencies, or scripts) and add that summary to your scratchpad.',\n // 'Continue this process of exploring, summarizing, and adding to your scratchpad until you are confident you have a full picture of the repository.',\n // 'Once you believe you have gathered enough information, your second-to-last step is to review your entire scratchpad to synthesize a plan for the final outline.',\n // 'Finally, based *only* on the information you have gathered in your scratchpad, generate the complete, detailed outline and store it using the `store_outline` tool. You must only call `store_outline` ONCE at the very end.',\n // ],\n }),\n tools: {\n read_file: read_file_tool,\n // read_dir: read_dir_tool,\n // search_files: search_files_tool,\n // file_exists: file_exists_tool,\n update_scratchpad: scratchpad_tool,\n store_outline: tool({\n description: `Use this tool to store the generated outline.\n\t\tThe outline should be a detailed hierarchical structure representing the sections and subsections of the repository documentation. In thory you can nest sections as deep as you want, but try to keep it to 4 levels deep maximum.\n\n\t\t## Example outline\n\t\t[\n\t\t\t{\n\t\t\t\t\"title\": \"xxxx\",\n\t\t\t\t\"sections\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"yyyy\",\n\t\t\t\t\t\tsections: [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"title\": \"vvvv\",\n\t\t\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"title\": \"gggg\",\n\t\t\t\t\t\t\"sections\": [...],\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t},\n\t\t]\n\t\t\t`,\n inputSchema: z.object({\n outline: OutlineSchema,\n }),\n // execute: (\n // { outline },\n // { context }: ToolExecutionOptions<OutlineAgentContext>,\n // ) => {\n // // Store the outline in a file or database\n // console.log('Generated Outline:\\n', outline);\n // context.outline = outline;\n // return 'Outline stored successfully.';\n // },\n }),\n },\n});\n\nexport const outlineCondensedAgent = agent<unknown, OutlineAgentContext>({\n name: 'Outline Condensed Agent',\n model: groq('moonshotai/kimi-k2-instruct-0905'),\n prompt: instructions({\n purpose: [\n 'To intelligently condense and optimize an existing outline by merging redundant sections, removing overly granular subdivisions, and creating a more streamlined, maintainable documentation structure.',\n 'Your goal is to reduce complexity while preserving all essential information and maintaining logical hierarchy.',\n ],\n routine: [\n 'Examine the current outline structure stored in the context. Use your scratchpad to track your analysis.',\n 'Identify sections that are too granular (e.g., sections with only 1-2 subsections that could be merged with their parent).',\n 'Look for redundant or overlapping sections that cover similar topics and can be consolidated.',\n 'Note sections with excessive nesting depth (more than 3-4 levels) that could be flattened.',\n 'Identify sections with very similar titles that could be merged (e.g., \"API Overview\" and \"API Introduction\").',\n 'For each potential consolidation, add a note to your scratchpad explaining the rationale.',\n 'Create a condensed version of the outline that:',\n ' - Merges related subsections into broader topics',\n ' - Reduces nesting depth where appropriate',\n ' - Eliminates redundancy while keeping all unique content areas',\n ' - Maintains a maximum depth of 3 levels unless absolutely necessary',\n ' - Ensures each section has substantial content to document',\n 'Return the condensed outline as structured output.',\n ],\n }),\n output: OutlineSchema,\n});\n\nexport async function generateOutline(state: OutlineAgentContext) {\n const messages: UIMessage[] = [\n user(\n 'Walk through the repository and generate a detailed outline. Make sure to avoid looking into framework generated files and folders. when outline is complete, call the store_outline tool.',\n ),\n ];\n const max_iterations = 3;\n let current_iteration = 0;\n while (current_iteration < max_iterations) {\n console.log(`\\n=== Outline Iteration ${current_iteration + 1} ===\\n`);\n const result = await execute(outlineAgent, messages, state);\n await Array.fromAsync(\n toUIMessageStream({\n stream: result.stream,\n tools: outlineAgent.toToolset(),\n generateMessageId: generateId,\n originalMessages: messages,\n onEnd: async ({ responseMessage }: { responseMessage: UIMessage }) => {\n messages.push(responseMessage);\n },\n }),\n );\n await result.consumeStream();\n const calls = await result.toolCalls;\n const outlineCall = calls.find(\n (t: { toolName: string }) => t.toolName === 'store_outline',\n );\n if (outlineCall) {\n console.log('\\n=== Outline Generation Complete ===\\n');\n state.outline = outlineCall.input.outline;\n break;\n }\n current_iteration++;\n }\n if (!state.outline.length) {\n throw new Error('Outline generation failed.');\n }\n return generate(\n outlineCondensedAgent,\n `Condense and optimize the following outline:\\n\\n${buildToc(state.outline)}`,\n state,\n ).then(({ output }) => output);\n}\n\nfunction slugify(text: string) {\n return text\n .toLowerCase()\n .replace(/[^a-z0-9\\s-]/g, '')\n .trim()\n .replace(/\\s+/g, '-')\n .replace(/-+/g, '-');\n}\n\nexport function buildToc(\n items: OutlineItem[],\n baseDepth = 1,\n prefix: string[] = [],\n) {\n const lines: string[] = [];\n for (const it of items) {\n const path = [...prefix, it.title];\n const indent = ' '.repeat(Math.max(0, path.length - 1));\n const anchor = slugify(it.title);\n lines.push(`${indent}- [${it.title}](#${anchor})`);\n if (it.sections?.length) {\n lines.push(...buildToc(it.sections, baseDepth + 1, path));\n }\n }\n return lines;\n}\n"],
5
+ "mappings": ";AAAA,SAAS,QAAAA,aAAY;AACrB,SAAoC,QAAAC,aAAY;AAChD,SAAS,iBAAiB;AAC1B,SAAS,UAAU,iBAAiB;AACpC,OAAOC,QAAO;AAEd;AAAA,EACE,SAAAC;AAAA,EACA,WAAAC;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,QAAAC;AAAA,OACK;AACP;AAAA,EACE,kBAAAC;AAAA,EACA,mBAAAC;AAAA,EACA;AAAA,OACK;;;ACSP,eAAsB,KACpB,MACA,QACAC,QACA,OAGA;AACA,QAAM,WAAW,KAAK,YAAY,CAAC;AACnC,aAAW,WAAW,UAAU;AAC9B,UAAM,KAAK,SAAS,MAAMA,QAAO,KAAK;AAAA,EACxC;AACA,QAAM,MAAM,IAAI,KAAK,OAAO,MAAMA,OAAM,IAA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F;AAAA,IACA;AAAA,EACF;AAGA,SAAO,iBAAiB,MAAM,SAAS,OAAO,CAAC;AACjD;",
6
6
  "names": ["groq", "tool", "z", "agent", "execute", "instructions", "user", "read_file_tool", "scratchpad_tool", "write", "tool", "z", "agent", "instructions", "read_file_tool", "scratchpad_tool", "agent", "groq", "read_file_tool", "instructions", "execute", "user"]
7
7
  }
@@ -200,5 +200,5 @@ async function runAdaptationCycle() {
200
200
  }
201
201
  console.log("\n========== Adaptation Complete ==========");
202
202
  }
203
- runAdaptationCycle();
203
+ await runAdaptationCycle();
204
204
  //# sourceMappingURL=evolving.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/lib/evolving.ts"],
4
- "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { type ToolExecutionOptions, toUIMessageStream, tool } from 'ai';\nimport dedent from 'dedent';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, extname, join } from 'node:path';\nimport z from 'zod';\n\nimport { agent, generate, stream, user } from '@deepagents/agent';\n\nconst defaultPrompt = dedent`\n\n<SystemContext>\n\tYou are a code execution agent that writes and runs TypeScript code to accomplish user requests.\n\n\t<Identity>\n\tYour role is to translate user instructions into executable TypeScript code that produces results.\n\tYou excel at:\n\t- Breaking down requests into simple, executable code\n\t- Choosing appropriate Node.js APIs for the task\n\t- Writing clear, correct TypeScript with proper imports\n\t- Analyzing errors and adjusting approach when needed\n\t</Identity>\n\n\t<ExecutionEnvironment>\n\tRuntime: Node.js with ES module support\n\tExecution Model: Files are dynamically imported after creation\n\tProject Root: Accessible via process.cwd()\n\t</ExecutionEnvironment>\n\n\t<Tools>\n\twrite_content(fileName: string, content: string)\n\t- Creates or overwrites a .ts file in .evolving/ directory\n\t- Only .ts extensions permitted\n\t- Parent directories created automatically\n\n\trun_code(fileName: string)\n\t- Executes a TypeScript file via dynamic import()\n\t- File must exist before execution (write first, then run)\n\t- Returns module exports object\n\t</Tools>\n\n\t<Methodology>\n\tPhase 1: Analysis\n\t- Understand what data or result the user needs\n\t- Identify which Node.js APIs are appropriate (fs, path, etc.)\n\n\tPhase 2: Implementation\n\t- Write TypeScript code using appropriate imports\n\t- Use process.cwd() for project root references\n\t- Include console.log statements for output visibility\n\t- Export data if needed for further processing\n\n\tPhase 3: Execution\n\t- Run the code file\n\t- Observe results and determine if goal is achieved\n\t</Methodology>\n\n\t<Principles>\n\tCode Approach:\n\t\u2713 Start with synchronous operations (readdirSync, readFileSync)\n\t\u2713 Use ES module imports (import { x } from 'module')\n\t\u2713 Reference project root with process.cwd()\n\t\u2713 Write self-contained code with clear variable names\n\t\u2717 Avoid async callbacks when synchronous versions exist\n\t\u2717 Avoid complex path manipulations when simple ones suffice\n\t\u2717 Avoid mixing CommonJS (require) with ES modules (import)\n\n\tError Handling:\n\t\u2713 Read error messages carefully to understand root cause\n\t\u2713 Check if the issue is environmental, syntactic, or logical\n\t\u2713 Adjust approach based on specific error, not generic retries\n\t\u2717 Avoid repeating the same approach if it failed\n\t\u2717 Avoid trying multiple variations without understanding why previous attempts failed\n\n\tIteration Management:\n\t\u2713 Attempt a straightforward solution first\n\t\u2713 If first attempt fails, analyze the error and make ONE targeted fix\n\t\u2713 If second attempt fails, reconsider the approach entirely\n\t\u2717 Stop after 3 failed attempts and report the issue\n\t\u2717 Avoid trial-and-error loops without clear reasoning\n\t</Principles>\n\n\t<CriticalInstructions>\n\t- Maximum 3 retry attempts per task before reporting the issue\n\t- Each file write should be purposeful, not exploratory\n\t- run_code must only be called on files that were written via write_content\n\t- Follow the user's instructions precisely and deliver the requested results\n\t</CriticalInstructions>\n\n</SystemContext>\n\n`;\n\nconst PROMPT_FILE_PATH = join(\n process.cwd(),\n '.evolving',\n 'executor-prompt.txt',\n);\n\nconst prompt =\n (await readFile(PROMPT_FILE_PATH, 'utf-8').catch(() => defaultPrompt)) ||\n defaultPrompt;\n\nasync function savePrompt(promptText: string): Promise<void> {\n await mkdir(dirname(PROMPT_FILE_PATH), { recursive: true });\n await writeFile(PROMPT_FILE_PATH, promptText, 'utf-8');\n console.log('Saved revised prompt to file');\n}\n\nconst write_content_tool = tool({\n description: 'Writes content based on given instructions.',\n inputSchema: z.object({\n fileName: z.string().describe('The name of the file to write to.'),\n content: z.string().describe('The content to be written.'),\n }),\n execute: async (\n { fileName, content }: { fileName: string; content: string },\n _options: ToolExecutionOptions<any>,\n ) => {\n if (extname(fileName) !== '.ts') {\n return 'Error: Can only write .ts files.';\n }\n await mkdir(dirname(join(process.cwd(), '.evolving', fileName)), {\n recursive: true,\n });\n await writeFile(\n join(process.cwd(), '.evolving', fileName),\n content,\n 'utf-8',\n );\n return `File written: ${fileName}`;\n },\n});\n\nconst run_code_tool = tool({\n description: 'Executes provided code snippets and returns the output.',\n inputSchema: z.object({\n fileName: z\n .string()\n .describe('The name of the file containing the code to run.'),\n }),\n execute: async (\n { fileName }: { fileName: string },\n _options: ToolExecutionOptions<any>,\n ) => {\n return await import(join(process.cwd(), '.evolving', fileName));\n },\n});\n\nconst executorTools = {\n write_content: write_content_tool,\n run_code: run_code_tool,\n};\n\nconst adaptingAgent = agent({\n model: groq('openai/gpt-oss-20b'),\n name: 'adapting_agent',\n prompt: dedent`\n\t\tYou are an adapting agent that update other agents system prompt and behavior based on execution results.\n\t\tYour job is to analyze execution results and refine the executor agent's prompt to improve future performance.\n\t\tConsider what changes to the system context, identity, methodology, principles, or critical instructions could help the executor succeed.\n\t\tProvide a revised prompt that addresses any shortcomings revealed by the execution results.\n`,\n output: z.object({\n revisedPrompt: z\n .string()\n .describe('The revised system prompt for the executor.'),\n }),\n});\n\nconst USER_TASK = `Using typescript compiler, count how many times the agent function have been invoked. use tsconfig.base.json as project configuration.`;\nconst MAX_REFINEMENTS = 3;\n\n// Main adaptation loop\nasync function runAdaptationCycle() {\n let currentPrompt = prompt;\n for (let iteration = 1; iteration <= MAX_REFINEMENTS; iteration++) {\n console.log(\n `\\n========== Iteration ${iteration}/${MAX_REFINEMENTS} ==========`,\n );\n\n // Create executor with current prompt\n const executor = agent({\n name: 'executor_agent',\n model: groq('openai/gpt-oss-120b'),\n prompt: currentPrompt,\n tools: executorTools,\n });\n\n // Run executor\n const result$ = await stream(executor, [user(USER_TASK)], {});\n const messages = await Array.fromAsync(\n toUIMessageStream({\n stream: result$.stream,\n tools: executor.toToolset(),\n }),\n );\n await result$.consumeStream();\n\n const reasoning = messages\n .filter((it) => it.type === 'reasoning-delta')\n .map((it) => it.delta)\n .join('');\n\n const text = messages\n .filter((it) => it.type === 'text-delta')\n .map((it) => it.delta)\n .join('');\n\n console.log('Final Result Text:', text);\n\n // Run adapting agent\n const { output } = await generate(\n adaptingAgent,\n [\n user(\n `\n\t\t\t\t\t<ExecutionResults>\n\t\t\t\t\t\t${text}\n\t\t\t\t\t</ExecutionResults>\n\n\t\t\t\t\t<AgentReasoning>\n\t\t\t\t\t\t${reasoning}\n\t\t\t\t\t</AgentReasoning>\n\n\t\t\t\t\t<AgentPrompt>\n\t\t\t\t\t\t${currentPrompt}\n\t\t\t\t\t</AgentPrompt>\n\t\t\t\t`,\n ),\n ],\n {},\n );\n const { revisedPrompt } = output as { revisedPrompt: string };\n\n // Save and use revised prompt for next iteration\n await savePrompt(revisedPrompt);\n currentPrompt = revisedPrompt;\n }\n\n console.log('\\n========== Adaptation Complete ==========');\n}\n\nrunAdaptationCycle();\n"],
5
- "mappings": ";AAAA,SAAS,YAAY;AACrB,SAAoC,mBAAmB,YAAY;AACnE,OAAO,YAAY;AACnB,SAAS,OAAO,UAAU,iBAAiB;AAC3C,SAAS,SAAS,SAAS,YAAY;AACvC,OAAO,OAAO;AAEd,SAAS,OAAO,UAAU,QAAQ,YAAY;AAE9C,IAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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O,CAAC,OAAO,GAAG,SAAS,YAAY,EACvC,IAAI,CAAC,OAAO,GAAG,KAAK,EACpB,KAAK,EAAE;AAEV,YAAQ,IAAI,sBAAsB,IAAI;AAGtC,UAAM,EAAE,OAAO,IAAI,MAAM;AAAA,MACvB;AAAA,MACA;AAAA,QACE;AAAA,UACE;AAAA;AAAA,QAEF,IAAI;AAAA;AAAA;AAAA;AAAA,QAIJ,SAAS;AAAA;AAAA;AAAA;AAAA,QAIT,aAAa;AAAA;AAAA;AAAA,QAGb;AAAA,MACF;AAAA,MACA,CAAC;AAAA,IACH;AACA,UAAM,EAAE,cAAc,IAAI;AAG1B,UAAM,WAAW,aAAa;AAC9B,oBAAgB;AAAA,EAClB;AAEA,UAAQ,IAAI,6CAA6C;AAC3D;AAEA,mBAAmB;",
4
+ "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { type ToolExecutionOptions, toUIMessageStream, tool } from 'ai';\nimport dedent from 'dedent';\nimport { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname, extname, join } from 'node:path';\nimport z from 'zod';\n\nimport { agent, generate, stream, user } from '@deepagents/agent';\n\nconst defaultPrompt = dedent`\n\n<SystemContext>\n\tYou are a code execution agent that writes and runs TypeScript code to accomplish user requests.\n\n\t<Identity>\n\tYour role is to translate user instructions into executable TypeScript code that produces results.\n\tYou excel at:\n\t- Breaking down requests into simple, executable code\n\t- Choosing appropriate Node.js APIs for the task\n\t- Writing clear, correct TypeScript with proper imports\n\t- Analyzing errors and adjusting approach when needed\n\t</Identity>\n\n\t<ExecutionEnvironment>\n\tRuntime: Node.js with ES module support\n\tExecution Model: Files are dynamically imported after creation\n\tProject Root: Accessible via process.cwd()\n\t</ExecutionEnvironment>\n\n\t<Tools>\n\twrite_content(fileName: string, content: string)\n\t- Creates or overwrites a .ts file in .evolving/ directory\n\t- Only .ts extensions permitted\n\t- Parent directories created automatically\n\n\trun_code(fileName: string)\n\t- Executes a TypeScript file via dynamic import()\n\t- File must exist before execution (write first, then run)\n\t- Returns module exports object\n\t</Tools>\n\n\t<Methodology>\n\tPhase 1: Analysis\n\t- Understand what data or result the user needs\n\t- Identify which Node.js APIs are appropriate (fs, path, etc.)\n\n\tPhase 2: Implementation\n\t- Write TypeScript code using appropriate imports\n\t- Use process.cwd() for project root references\n\t- Include console.log statements for output visibility\n\t- Export data if needed for further processing\n\n\tPhase 3: Execution\n\t- Run the code file\n\t- Observe results and determine if goal is achieved\n\t</Methodology>\n\n\t<Principles>\n\tCode Approach:\n\t\u2713 Start with synchronous operations (readdirSync, readFileSync)\n\t\u2713 Use ES module imports (import { x } from 'module')\n\t\u2713 Reference project root with process.cwd()\n\t\u2713 Write self-contained code with clear variable names\n\t\u2717 Avoid async callbacks when synchronous versions exist\n\t\u2717 Avoid complex path manipulations when simple ones suffice\n\t\u2717 Avoid mixing CommonJS (require) with ES modules (import)\n\n\tError Handling:\n\t\u2713 Read error messages carefully to understand root cause\n\t\u2713 Check if the issue is environmental, syntactic, or logical\n\t\u2713 Adjust approach based on specific error, not generic retries\n\t\u2717 Avoid repeating the same approach if it failed\n\t\u2717 Avoid trying multiple variations without understanding why previous attempts failed\n\n\tIteration Management:\n\t\u2713 Attempt a straightforward solution first\n\t\u2713 If first attempt fails, analyze the error and make ONE targeted fix\n\t\u2713 If second attempt fails, reconsider the approach entirely\n\t\u2717 Stop after 3 failed attempts and report the issue\n\t\u2717 Avoid trial-and-error loops without clear reasoning\n\t</Principles>\n\n\t<CriticalInstructions>\n\t- Maximum 3 retry attempts per task before reporting the issue\n\t- Each file write should be purposeful, not exploratory\n\t- run_code must only be called on files that were written via write_content\n\t- Follow the user's instructions precisely and deliver the requested results\n\t</CriticalInstructions>\n\n</SystemContext>\n\n`;\n\nconst PROMPT_FILE_PATH = join(\n process.cwd(),\n '.evolving',\n 'executor-prompt.txt',\n);\n\nconst prompt =\n (await readFile(PROMPT_FILE_PATH, 'utf-8').catch(() => defaultPrompt)) ||\n defaultPrompt;\n\nasync function savePrompt(promptText: string): Promise<void> {\n await mkdir(dirname(PROMPT_FILE_PATH), { recursive: true });\n await writeFile(PROMPT_FILE_PATH, promptText, 'utf-8');\n console.log('Saved revised prompt to file');\n}\n\nconst write_content_tool = tool({\n description: 'Writes content based on given instructions.',\n inputSchema: z.object({\n fileName: z.string().describe('The name of the file to write to.'),\n content: z.string().describe('The content to be written.'),\n }),\n execute: async (\n { fileName, content }: { fileName: string; content: string },\n _options: ToolExecutionOptions<any>,\n ) => {\n if (extname(fileName) !== '.ts') {\n return 'Error: Can only write .ts files.';\n }\n await mkdir(dirname(join(process.cwd(), '.evolving', fileName)), {\n recursive: true,\n });\n await writeFile(\n join(process.cwd(), '.evolving', fileName),\n content,\n 'utf-8',\n );\n return `File written: ${fileName}`;\n },\n});\n\nconst run_code_tool = tool({\n description: 'Executes provided code snippets and returns the output.',\n inputSchema: z.object({\n fileName: z\n .string()\n .describe('The name of the file containing the code to run.'),\n }),\n execute: async (\n { fileName }: { fileName: string },\n _options: ToolExecutionOptions<any>,\n ) => {\n return await import(join(process.cwd(), '.evolving', fileName));\n },\n});\n\nconst executorTools = {\n write_content: write_content_tool,\n run_code: run_code_tool,\n};\n\nconst adaptingAgent = agent({\n model: groq('openai/gpt-oss-20b'),\n name: 'adapting_agent',\n prompt: dedent`\n\t\tYou are an adapting agent that update other agents system prompt and behavior based on execution results.\n\t\tYour job is to analyze execution results and refine the executor agent's prompt to improve future performance.\n\t\tConsider what changes to the system context, identity, methodology, principles, or critical instructions could help the executor succeed.\n\t\tProvide a revised prompt that addresses any shortcomings revealed by the execution results.\n`,\n output: z.object({\n revisedPrompt: z\n .string()\n .describe('The revised system prompt for the executor.'),\n }),\n});\n\nconst USER_TASK = `Using typescript compiler, count how many times the agent function have been invoked. use tsconfig.base.json as project configuration.`;\nconst MAX_REFINEMENTS = 3;\n\n// Main adaptation loop\nasync function runAdaptationCycle() {\n let currentPrompt = prompt;\n for (let iteration = 1; iteration <= MAX_REFINEMENTS; iteration++) {\n console.log(\n `\\n========== Iteration ${iteration}/${MAX_REFINEMENTS} ==========`,\n );\n\n // Create executor with current prompt\n const executor = agent({\n name: 'executor_agent',\n model: groq('openai/gpt-oss-120b'),\n prompt: currentPrompt,\n tools: executorTools,\n });\n\n // Run executor\n const result$ = await stream(executor, [user(USER_TASK)], {});\n const messages = await Array.fromAsync(\n toUIMessageStream({\n stream: result$.stream,\n tools: executor.toToolset(),\n }),\n );\n await result$.consumeStream();\n\n const reasoning = messages\n .filter((it) => it.type === 'reasoning-delta')\n .map((it) => it.delta)\n .join('');\n\n const text = messages\n .filter((it) => it.type === 'text-delta')\n .map((it) => it.delta)\n .join('');\n\n console.log('Final Result Text:', text);\n\n // Run adapting agent\n const { output } = await generate(\n adaptingAgent,\n [\n user(\n `\n\t\t\t\t\t<ExecutionResults>\n\t\t\t\t\t\t${text}\n\t\t\t\t\t</ExecutionResults>\n\n\t\t\t\t\t<AgentReasoning>\n\t\t\t\t\t\t${reasoning}\n\t\t\t\t\t</AgentReasoning>\n\n\t\t\t\t\t<AgentPrompt>\n\t\t\t\t\t\t${currentPrompt}\n\t\t\t\t\t</AgentPrompt>\n\t\t\t\t`,\n ),\n ],\n {},\n );\n const { revisedPrompt } = output;\n\n // Save and use revised prompt for next iteration\n await savePrompt(revisedPrompt);\n currentPrompt = revisedPrompt;\n }\n\n console.log('\\n========== Adaptation Complete ==========');\n}\n\nawait runAdaptationCycle();\n"],
5
+ "mappings": ";AAAA,SAAS,YAAY;AACrB,SAAoC,mBAAmB,YAAY;AACnE,OAAO,YAAY;AACnB,SAAS,OAAO,UAAU,iBAAiB;AAC3C,SAAS,SAAS,SAAS,YAAY;AACvC,OAAO,OAAO;AAEd,SAAS,OAAO,UAAU,QAAQ,YAAY;AAE9C,IAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AAE;AAEV,UAAM,OAAO,SACV,OAAO,CAAC,OAAO,GAAG,SAAS,YAAY,EACvC,IAAI,CAAC,OAAO,GAAG,KAAK,EACpB,KAAK,EAAE;AAEV,YAAQ,IAAI,sBAAsB,IAAI;AAGtC,UAAM,EAAE,OAAO,IAAI,MAAM;AAAA,MACvB;AAAA,MACA;AAAA,QACE;AAAA,UACE;AAAA;AAAA,QAEF,IAAI;AAAA;AAAA;AAAA;AAAA,QAIJ,SAAS;AAAA;AAAA;AAAA;AAAA,QAIT,aAAa;AAAA;AAAA;AAAA,QAGb;AAAA,MACF;AAAA,MACA,CAAC;AAAA,IACH;AACA,UAAM,EAAE,cAAc,IAAI;AAG1B,UAAM,WAAW,aAAa;AAC9B,oBAAgB;AAAA,EAClB;AAEA,UAAQ,IAAI,6CAA6C;AAC3D;AAEA,MAAM,mBAAmB;",
6
6
  "names": []
7
7
  }
@@ -9,5 +9,9 @@ export declare const clarrifyAgent: import("@deepagents/agent").Agent<{
9
9
  question: string;
10
10
  verification: string;
11
11
  }, import("@deepagents/agent").ContextVariables, import("@deepagents/agent").ContextVariables>;
12
- export declare function clarrifyUserQuery(state: any, query: string): Promise<unknown>;
12
+ export declare function clarrifyUserQuery(state: any, query: string): Promise<{
13
+ need_clarification: boolean;
14
+ question: string;
15
+ verification: string;
16
+ }>;
13
17
  //# sourceMappingURL=clarrify-agent.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"clarrify-agent.d.ts","sourceRoot":"","sources":["../../../src/lib/openai-deepresearch/clarrify-agent.ts"],"names":[],"mappings":"AACA,OAAO,CAAC,MAAM,KAAK,CAAC;AAuCpB,eAAO,MAAM,gBAAgB;;;;iBAY3B,CAAC;AAEH,eAAO,MAAM,aAAa;;;;8FAMxB,CAAC;AAEH,wBAAsB,iBAAiB,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,oBAQhE"}
1
+ {"version":3,"file":"clarrify-agent.d.ts","sourceRoot":"","sources":["../../../src/lib/openai-deepresearch/clarrify-agent.ts"],"names":[],"mappings":"AACA,OAAO,CAAC,MAAM,KAAK,CAAC;AAuCpB,eAAO,MAAM,gBAAgB;;;;iBAY3B,CAAC;AAEH,eAAO,MAAM,aAAa;;;;8FAMxB,CAAC;AAEH,wBAAsB,iBAAiB,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM;;;;GAQhE"}
@@ -1 +1 @@
1
- {"version":3,"file":"lead-research.d.ts","sourceRoot":"","sources":["../../../src/lib/openai-deepresearch/lead-research.ts"],"names":[],"mappings":"AAwEA,MAAM,MAAM,mBAAmB,GAAG;IAChC,yBAAyB,EAAE,MAAM,CAAC;IAClC,6BAA6B,EAAE,MAAM,CAAC;IACtC,mBAAmB,EAAE,MAAM,CAAC;CAC7B,CAAC;AACF,eAAO,MAAM,mBAAmB,sFAwC9B,CAAC"}
1
+ {"version":3,"file":"lead-research.d.ts","sourceRoot":"","sources":["../../../src/lib/openai-deepresearch/lead-research.ts"],"names":[],"mappings":"AAwEA,MAAM,MAAM,mBAAmB,GAAG;IAChC,yBAAyB,EAAE,MAAM,CAAC;IAClC,6BAA6B,EAAE,MAAM,CAAC;IACtC,mBAAmB,EAAE,MAAM,CAAC;CAC7B,CAAC;AACF,eAAO,MAAM,mBAAmB,sFA0C9B,CAAC"}
@@ -2,7 +2,7 @@
2
2
  import { groq as groq2 } from "@ai-sdk/groq";
3
3
  import { jsonSchema, tool } from "ai";
4
4
  import z from "zod";
5
- import { agent as agent2, execute, toState, user } from "@deepagents/agent";
5
+ import { agent as agent2, execute, user } from "@deepagents/agent";
6
6
  import { scratchpad_tool as scratchpad_tool2 } from "@deepagents/toolbox";
7
7
 
8
8
  // packages/orchestrator/src/lib/openai-deepresearch/reasearcher.ts
@@ -148,8 +148,7 @@ var leadResearcherAgent = agent2({
148
148
  "The topic to research. Should be a single topic, and should be described in high detail (at least a paragraph)."
149
149
  )
150
150
  }),
151
- execute: async ({ research_topic }, options) => {
152
- const context = toState(options);
151
+ execute: async ({ research_topic }, { context }) => {
153
152
  context.research_iterations++;
154
153
  const result = await execute(
155
154
  researcherAgent,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/lib/openai-deepresearch/lead-research.ts", "../../../src/lib/openai-deepresearch/reasearcher.ts"],
4
- "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { jsonSchema, tool } from 'ai';\nimport z from 'zod';\n\nimport { agent, execute, toState, user } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport { researcherAgent } from './reasearcher.ts';\n\nconst lead_researcher_prompt = (\n max_researcher_iterations: number,\n max_concurrent_research_units: number,\n) => `You are a research supervisor. Your job is to conduct research by calling the \"conduct_research\" tool. For context, today's date is ${new Date().toISOString()}.\n\n<Task>\nYour focus is to call the \"conduct_research\" tool to conduct research against the overall research question passed in by the user.\nWhen you are completely satisfied with the research findings returned from the tool calls, then you should call the \"research_complete\" tool to indicate that you are done with your research.\n</Task>\n\n<Available Tools>\nYou have access to three main tools:\n1. **conduct_research**: Delegate research tasks to specialized sub-agents\n2. **research_complete**: Indicate that research is complete\n3. **think_tool**: For reflection and strategic planning during research\n\n**CRITICAL: Use think_tool before calling conduct_research to plan your approach, and after each conduct_research to assess progress. Do not call think_tool with any other tools in parallel.**\n</Available Tools>\n\n<Instructions>\nThink like a research manager with limited time and resources. Follow these steps:\n\n1. **Read the question carefully** - What specific information does the user need?\n2. **Decide how to delegate the research** - Carefully consider the question and decide how to delegate the research. Are there multiple independent directions that can be explored simultaneously?\n3. **After each call to conduct_research, pause and assess** - Do I have enough to answer? What's still missing?\n</Instructions>\n\n<Hard Limits>\n**Task Delegation Budgets** (Prevent excessive delegation):\n- **Bias towards single agent** - Use single agent for simplicity unless the user request has clear opportunity for parallelization\n- **Stop when you can answer confidently** - Don't keep delegating research for perfection\n- **Limit tool calls** - Always stop after ${max_researcher_iterations} tool calls to conduct_research and think_tool if you cannot find the right sources\n\n**Maximum ${max_concurrent_research_units} parallel agents per iteration**\n</Hard Limits>\n\n<Show Your Thinking>\nBefore you call conduct_research tool call, use think_tool to plan your approach:\n- Can the task be broken down into smaller sub-tasks?\n\nAfter each conduct_research tool call, use think_tool to analyze the results:\n- What key information did I find?\n- What's missing?\n- Do I have enough to answer the question comprehensively?\n- Should I delegate more research or call research_complete?\n</Show Your Thinking>\n\n<Scaling Rules>\n**Simple fact-finding, lists, and rankings** can use a single sub-agent:\n- *Example*: List the top 10 coffee shops in San Francisco \u2192 Use 1 sub-agent\n\n**Comparisons presented in the user request** can use a sub-agent for each element of the comparison:\n- *Example*: Compare OpenAI vs. Anthropic vs. DeepMind approaches to AI safety \u2192 Use 3 sub-agents\n- Delegate clear, distinct, non-overlapping subtopics\n\n**Important Reminders:**\n- Each conduct_research call spawns a dedicated research agent for that specific topic\n- A separate agent will write the final report - you just need to gather information\n- When calling conduct_research, provide complete standalone instructions - sub-agents can't see other agents' work\n- Do NOT use acronyms or abbreviations in your research questions, be very clear and specific\n</Scaling Rules>\n`;\n\nexport type LeadResearcherState = {\n max_researcher_iterations: number;\n max_concurrent_research_units: number;\n research_iterations: number;\n};\nexport const leadResearcherAgent = agent<unknown, LeadResearcherState>({\n name: 'lead_researcher',\n model: groq('openai/gpt-oss-20b'),\n prompt: (context) =>\n lead_researcher_prompt(\n context?.max_researcher_iterations || 5,\n context?.max_concurrent_research_units || 3,\n ),\n tools: {\n think_tool: scratchpad_tool,\n research_complete: tool({\n description: 'Call this tool to indicate that research is complete.',\n inputSchema: jsonSchema({\n type: 'object',\n properties: {},\n additionalProperties: true,\n }),\n }),\n conduct_research: tool({\n description: 'Call this tool to conduct research on a specific topic.',\n inputSchema: z.object({\n research_topic: z\n .string()\n .describe(\n 'The topic to research. Should be a single topic, and should be described in high detail (at least a paragraph).',\n ),\n }),\n execute: async ({ research_topic }, options) => {\n const context = toState<LeadResearcherState>(options);\n context.research_iterations++;\n const result = await execute(\n researcherAgent,\n [user(research_topic)],\n {},\n { providerOptions: { groq: { reasoningEffort: 'low' } } },\n );\n return await result.text;\n },\n }),\n },\n});\n", "import { groq } from '@ai-sdk/groq';\n\nimport { agent } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nconst research_system_prompt = `You are a research assistant conducting research on the user's input topic. For context, today's date is ${new Date().toISOString()}.\n\n<Task>\nYour job is to use tools to gather information about the user's input topic.\nYou can use any of the tools provided to you to find resources that can help answer the research question. You can call these tools in series or in parallel, your research is conducted in a tool-calling loop.\n</Task>\n\n<AvailableTools>\nYou have access to two main tools:\n1. **browser_search**: For conducting web searches to gather information\n2. **think_tool**: For reflection and strategic planning during research\n\n**CRITICAL: Use think_tool after each search to reflect on results and plan next steps. Do not call think_tool with the web_search or any other tools. It should be to reflect on the results of the search.**\n</AvailableTools>\n\n<Instructions>\nThink like a human researcher with limited time. Follow these steps:\n\n1. **Read the question carefully** - What specific information does the user need?\n2. **Start with broader searches** - Use broad, comprehensive queries first\n3. **After each search, pause and assess** - Do I have enough to answer? What's still missing?\n4. **Execute narrower searches as you gather information** - Fill in the gaps\n5. **Stop when you can answer confidently** - Don't keep searching for perfection\n</Instructions>\n\n<HardLimits>\n**Tool Call Budgets** (Prevent excessive searching):\n- **Simple queries**: Use 2-3 search tool calls maximum\n- **Complex queries**: Use up to 5 search tool calls maximum\n- **Always stop**: After 5 search tool calls if you cannot find the right sources\n\n**Stop Immediately When**:\n- You can answer the user's question comprehensively\n- You have 3+ relevant examples/sources for the question\n- Your last 2 searches returned similar information\n</HardLimits>\n\n<ShowYourThinking>\nAfter each search tool call, use think_tool to analyze the results:\n- What key information did I find?\n- What's missing?\n- Do I have enough to answer the question comprehensively?\n- Should I search more or provide my answer?\n</ShowYourThinking>\n`;\n\nexport const researcherAgent = agent({\n name: 'researcher_agent',\n model: groq('openai/gpt-oss-20b'),\n prompt: research_system_prompt,\n tools: {\n think_tool: scratchpad_tool,\n browser_search: (groq as any).tools.browserSearch({}),\n },\n});\n"],
5
- "mapp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AAAA,EACrE,MAAM;AAAA,EACN,OAAOC,MAAK,oBAAoB;AAAA,EAChC,QAAQ,CAAC,YACP;AAAA,IACE,SAAS,6BAA6B;AAAA,IACtC,SAAS,iCAAiC;AAAA,EAC5C;AAAA,EACF,OAAO;AAAA,IACL,YAAYC;AAAA,IACZ,mBAAmB,KAAK;AAAA,MACtB,aAAa;AAAA,MACb,aAAa,WAAW;AAAA,QACtB,MAAM;AAAA,QACN,YAAY,CAAC;AAAA,QACb,sBAAsB;AAAA,MACxB,CAAC;AAAA,IACH,CAAC;AAAA,IACD,kBAAkB,KAAK;AAAA,MACrB,aAAa;AAAA,MACb,aAAa,EAAE,OAAO;AAAA,QACpB,gBAAgB,EACb,OAAO,EACP;AAAA,UACC;AAAA,QACF;AAAA,MACJ,CAAC;AAAA,MACD,SAAS,OAAO,EAAE,eAAe,GAAG,YAAY;AAC9C,cAAM,UAAU,QAA6B,OAAO;AACpD,gBAAQ;AACR,cAAM,SAAS,MAAM;AAAA,UACnB;AAAA,UACA,CAAC,KAAK,cAAc,CAAC;AAAA,UACrB,CAAC;AAAA,UACD,EAAE,iBAAiB,EAAE,MAAM,EAAE,iBAAiB,MAAM,EAAE,EAAE;AAAA,QAC1D;AACA,eAAO,MAAM,OAAO;AAAA,MACtB;AAAA,IACF,CAAC;AAAA,EACH;AACF,CAAC;",
4
+ "sourcesContent": ["import { groq } from '@ai-sdk/groq';\nimport { type ToolExecutionOptions, jsonSchema, tool } from 'ai';\nimport z from 'zod';\n\nimport { agent, execute, user } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nimport { researcherAgent } from './reasearcher.ts';\n\nconst lead_researcher_prompt = (\n max_researcher_iterations: number,\n max_concurrent_research_units: number,\n) => `You are a research supervisor. Your job is to conduct research by calling the \"conduct_research\" tool. For context, today's date is ${new Date().toISOString()}.\n\n<Task>\nYour focus is to call the \"conduct_research\" tool to conduct research against the overall research question passed in by the user.\nWhen you are completely satisfied with the research findings returned from the tool calls, then you should call the \"research_complete\" tool to indicate that you are done with your research.\n</Task>\n\n<Available Tools>\nYou have access to three main tools:\n1. **conduct_research**: Delegate research tasks to specialized sub-agents\n2. **research_complete**: Indicate that research is complete\n3. **think_tool**: For reflection and strategic planning during research\n\n**CRITICAL: Use think_tool before calling conduct_research to plan your approach, and after each conduct_research to assess progress. Do not call think_tool with any other tools in parallel.**\n</Available Tools>\n\n<Instructions>\nThink like a research manager with limited time and resources. Follow these steps:\n\n1. **Read the question carefully** - What specific information does the user need?\n2. **Decide how to delegate the research** - Carefully consider the question and decide how to delegate the research. Are there multiple independent directions that can be explored simultaneously?\n3. **After each call to conduct_research, pause and assess** - Do I have enough to answer? What's still missing?\n</Instructions>\n\n<Hard Limits>\n**Task Delegation Budgets** (Prevent excessive delegation):\n- **Bias towards single agent** - Use single agent for simplicity unless the user request has clear opportunity for parallelization\n- **Stop when you can answer confidently** - Don't keep delegating research for perfection\n- **Limit tool calls** - Always stop after ${max_researcher_iterations} tool calls to conduct_research and think_tool if you cannot find the right sources\n\n**Maximum ${max_concurrent_research_units} parallel agents per iteration**\n</Hard Limits>\n\n<Show Your Thinking>\nBefore you call conduct_research tool call, use think_tool to plan your approach:\n- Can the task be broken down into smaller sub-tasks?\n\nAfter each conduct_research tool call, use think_tool to analyze the results:\n- What key information did I find?\n- What's missing?\n- Do I have enough to answer the question comprehensively?\n- Should I delegate more research or call research_complete?\n</Show Your Thinking>\n\n<Scaling Rules>\n**Simple fact-finding, lists, and rankings** can use a single sub-agent:\n- *Example*: List the top 10 coffee shops in San Francisco \u2192 Use 1 sub-agent\n\n**Comparisons presented in the user request** can use a sub-agent for each element of the comparison:\n- *Example*: Compare OpenAI vs. Anthropic vs. DeepMind approaches to AI safety \u2192 Use 3 sub-agents\n- Delegate clear, distinct, non-overlapping subtopics\n\n**Important Reminders:**\n- Each conduct_research call spawns a dedicated research agent for that specific topic\n- A separate agent will write the final report - you just need to gather information\n- When calling conduct_research, provide complete standalone instructions - sub-agents can't see other agents' work\n- Do NOT use acronyms or abbreviations in your research questions, be very clear and specific\n</Scaling Rules>\n`;\n\nexport type LeadResearcherState = {\n max_researcher_iterations: number;\n max_concurrent_research_units: number;\n research_iterations: number;\n};\nexport const leadResearcherAgent = agent<unknown, LeadResearcherState>({\n name: 'lead_researcher',\n model: groq('openai/gpt-oss-20b'),\n prompt: (context) =>\n lead_researcher_prompt(\n context?.max_researcher_iterations || 5,\n context?.max_concurrent_research_units || 3,\n ),\n tools: {\n think_tool: scratchpad_tool,\n research_complete: tool({\n description: 'Call this tool to indicate that research is complete.',\n inputSchema: jsonSchema({\n type: 'object',\n properties: {},\n additionalProperties: true,\n }),\n }),\n conduct_research: tool({\n description: 'Call this tool to conduct research on a specific topic.',\n inputSchema: z.object({\n research_topic: z\n .string()\n .describe(\n 'The topic to research. Should be a single topic, and should be described in high detail (at least a paragraph).',\n ),\n }),\n execute: async (\n { research_topic },\n { context }: ToolExecutionOptions<LeadResearcherState>,\n ) => {\n context.research_iterations++;\n const result = await execute(\n researcherAgent,\n [user(research_topic)],\n {},\n { providerOptions: { groq: { reasoningEffort: 'low' } } },\n );\n return await result.text;\n },\n }),\n },\n});\n", "import { groq } from '@ai-sdk/groq';\n\nimport { agent } from '@deepagents/agent';\nimport { scratchpad_tool } from '@deepagents/toolbox';\n\nconst research_system_prompt = `You are a research assistant conducting research on the user's input topic. For context, today's date is ${new Date().toISOString()}.\n\n<Task>\nYour job is to use tools to gather information about the user's input topic.\nYou can use any of the tools provided to you to find resources that can help answer the research question. You can call these tools in series or in parallel, your research is conducted in a tool-calling loop.\n</Task>\n\n<AvailableTools>\nYou have access to two main tools:\n1. **browser_search**: For conducting web searches to gather information\n2. **think_tool**: For reflection and strategic planning during research\n\n**CRITICAL: Use think_tool after each search to reflect on results and plan next steps. Do not call think_tool with the web_search or any other tools. It should be to reflect on the results of the search.**\n</AvailableTools>\n\n<Instructions>\nThink like a human researcher with limited time. Follow these steps:\n\n1. **Read the question carefully** - What specific information does the user need?\n2. **Start with broader searches** - Use broad, comprehensive queries first\n3. **After each search, pause and assess** - Do I have enough to answer? What's still missing?\n4. **Execute narrower searches as you gather information** - Fill in the gaps\n5. **Stop when you can answer confidently** - Don't keep searching for perfection\n</Instructions>\n\n<HardLimits>\n**Tool Call Budgets** (Prevent excessive searching):\n- **Simple queries**: Use 2-3 search tool calls maximum\n- **Complex queries**: Use up to 5 search tool calls maximum\n- **Always stop**: After 5 search tool calls if you cannot find the right sources\n\n**Stop Immediately When**:\n- You can answer the user's question comprehensively\n- You have 3+ relevant examples/sources for the question\n- Your last 2 searches returned similar information\n</HardLimits>\n\n<ShowYourThinking>\nAfter each search tool call, use think_tool to analyze the results:\n- What key information did I find?\n- What's missing?\n- Do I have enough to answer the question comprehensively?\n- Should I search more or provide my answer?\n</ShowYourThinking>\n`;\n\nexport const researcherAgent = agent({\n name: 'researcher_agent',\n model: groq('openai/gpt-oss-20b'),\n prompt: research_system_prompt,\n tools: {\n think_tool: scratchpad_tool,\n browser_search: groq.tools.browserSearch({}),\n },\n});\n"],
5
+ "mappings": ";AAAA,SAAS,QAAAA,aAAY;AACrB,SAAoC,YAAY,YAAY;AAC5D,OAAO,OAAO;AAEd,SAAS,SAAAC,QAAO,SAAS,YAAY;AACrC,SAAS,mBAAAC,wBAAuB;;;ACLhC,SAAS,YAAY;AAErB,SAAS,aAAa;AACtB,SAAS,uBAAuB;AAEhC,IAAM,yBAAyB,6GAA4G,oBAAI,KAAK,GAAE,YAAY,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA8C5J,IAAM,kBAAkB,MAAM;AAAA,EACnC,MAAM;AAA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