agentix-cli 0.6.0 → 0.9.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 (58) hide show
  1. package/README.md +337 -116
  2. package/dist/agent-QYQVGKLM.js +2 -0
  3. package/dist/chunk-34UAFPK4.js +10 -0
  4. package/dist/chunk-34UAFPK4.js.map +1 -0
  5. package/dist/{chunk-X7UN6JAA.js → chunk-6MKAXEE5.js} +2 -2
  6. package/dist/chunk-BAIQJHQF.js +64 -0
  7. package/dist/chunk-BAIQJHQF.js.map +1 -0
  8. package/dist/chunk-BHDLKX3G.js +6 -0
  9. package/dist/chunk-BHDLKX3G.js.map +1 -0
  10. package/dist/chunk-CJ45Y2IR.js +12 -0
  11. package/dist/chunk-CJ45Y2IR.js.map +1 -0
  12. package/dist/chunk-DSYKYZMT.js +2 -0
  13. package/dist/chunk-DSYKYZMT.js.map +1 -0
  14. package/dist/chunk-IVVVYXPH.js +136 -0
  15. package/dist/chunk-IVVVYXPH.js.map +1 -0
  16. package/dist/{chunk-MGMZNJCE.js → chunk-KXZMYLHQ.js} +27 -27
  17. package/dist/chunk-KXZMYLHQ.js.map +1 -0
  18. package/dist/chunk-SBUX74OU.js +108 -0
  19. package/dist/chunk-SBUX74OU.js.map +1 -0
  20. package/dist/chunk-X32247GM.js +2 -0
  21. package/dist/chunk-X32247GM.js.map +1 -0
  22. package/dist/chunk-ZRYBSI5G.js +23 -0
  23. package/dist/chunk-ZRYBSI5G.js.map +1 -0
  24. package/dist/cli.js +289 -9
  25. package/dist/cli.js.map +1 -1
  26. package/dist/compaction-E3MQRLTL.js +28 -0
  27. package/dist/compaction-E3MQRLTL.js.map +1 -0
  28. package/dist/config-MSWKC466.js +2 -0
  29. package/dist/debug-N3B5NVJU.js +2 -0
  30. package/dist/heal-OTGT5HHJ.js +2 -0
  31. package/dist/heal-OTGT5HHJ.js.map +1 -0
  32. package/dist/index.d.ts +707 -164
  33. package/dist/index.js +2 -2
  34. package/dist/index.js.map +1 -1
  35. package/dist/memory-extract-RGPUPMKU.js +2 -0
  36. package/dist/memory-extract-RGPUPMKU.js.map +1 -0
  37. package/dist/{providers-AVYG63KK.js → providers-G3WZ4RVJ.js} +2 -2
  38. package/dist/providers-G3WZ4RVJ.js.map +1 -0
  39. package/dist/registry-FP6FUOXF.js +2 -0
  40. package/dist/registry-FP6FUOXF.js.map +1 -0
  41. package/dist/subagent-WV7QKQ3L.js +3 -0
  42. package/dist/subagent-WV7QKQ3L.js.map +1 -0
  43. package/dist/usage-dashboard-2TJQBFSH.js +404 -0
  44. package/dist/usage-dashboard-2TJQBFSH.js.map +1 -0
  45. package/package.json +4 -1
  46. package/dist/agent-K2YOEOJ5.js +0 -2
  47. package/dist/chunk-F73GPYCO.js +0 -106
  48. package/dist/chunk-F73GPYCO.js.map +0 -1
  49. package/dist/chunk-MGMZNJCE.js.map +0 -1
  50. package/dist/chunk-WT2UJMBC.js +0 -68
  51. package/dist/chunk-WT2UJMBC.js.map +0 -1
  52. package/dist/chunk-Z4GC5D6D.js +0 -12
  53. package/dist/chunk-Z4GC5D6D.js.map +0 -1
  54. package/dist/heal-UV5A6B5T.js +0 -2
  55. /package/dist/{agent-K2YOEOJ5.js.map → agent-QYQVGKLM.js.map} +0 -0
  56. /package/dist/{chunk-X7UN6JAA.js.map → chunk-6MKAXEE5.js.map} +0 -0
  57. /package/dist/{heal-UV5A6B5T.js.map → config-MSWKC466.js.map} +0 -0
  58. /package/dist/{providers-AVYG63KK.js.map → debug-N3B5NVJU.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent/tools/definitions.ts","../src/agent/providers/claude.ts","../src/agent/providers/claude-code.ts","../src/agent/providers/index.ts"],"sourcesContent":["// --- Agent tool definitions in Anthropic tool_use format ---\n\nexport interface ToolDefinition {\n name: string\n description: string\n input_schema: Record<string, unknown>\n permission?: \"file-read\" | \"file-write\" | \"command\" | \"none\"\n}\n\nconst TOOL_DEFINITIONS: ToolDefinition[] = [\n {\n name: \"create_files\",\n description:\n \"Create one or more files as output. Use this when you need to generate code, documents, configs, or any file-based output.\",\n input_schema: {\n type: \"object\",\n properties: {\n files: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"Relative file path from project root (e.g., src/components/Button.tsx)\",\n },\n content: {\n type: \"string\",\n description: \"The full content of the file\",\n },\n language: {\n type: \"string\",\n description: \"Programming language or file type\",\n },\n description: {\n type: \"string\",\n description: \"Brief description of what this file does\",\n },\n },\n required: [\"path\", \"content\"],\n },\n },\n summary: {\n type: \"string\",\n description: \"Brief summary of all generated files\",\n },\n },\n required: [\"files\"],\n },\n permission: \"file-write\",\n },\n {\n name: \"ask_user\",\n description:\n \"Ask the user a clarifying question when you need more information to proceed. Use this when the request is ambiguous or you need to confirm important decisions.\",\n input_schema: {\n type: \"object\",\n properties: {\n question: {\n type: \"string\",\n description: \"The question to ask the user\",\n },\n options: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Optional list of choices for the user\",\n },\n },\n required: [\"question\"],\n },\n permission: \"none\",\n },\n {\n name: \"read_file\",\n description:\n \"Read the contents of a file. Use this to inspect existing code, understand patterns, check implementations, or gather context before generating code.\",\n input_schema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description: \"Relative file path from project root\",\n },\n max_lines: {\n type: \"number\",\n description:\n \"Maximum number of lines to read. Defaults to 500. Use for large files.\",\n },\n },\n required: [\"path\"],\n },\n permission: \"file-read\",\n },\n {\n name: \"search_files\",\n description:\n \"Search for files matching a pattern and optionally search their content with a regex. Use this to find relevant code, understand project structure, or locate specific patterns.\",\n input_schema: {\n type: \"object\",\n properties: {\n pattern: {\n type: \"string\",\n description:\n \"Glob pattern to match files (e.g., 'src/**/*.ts', '*.json')\",\n },\n content_regex: {\n type: \"string\",\n description:\n \"Optional regex to search within matched files. Returns matching lines.\",\n },\n max_results: {\n type: \"number\",\n description: \"Maximum number of results to return. Default: 50.\",\n },\n },\n required: [\"pattern\"],\n },\n permission: \"none\",\n },\n {\n name: \"list_directory\",\n description:\n \"List files and directories at a given path. Use this to explore project structure.\",\n input_schema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description:\n \"Relative directory path from project root. Defaults to '.' (root).\",\n },\n recursive: {\n type: \"boolean\",\n description: \"List recursively. Default: false.\",\n },\n max_depth: {\n type: \"number\",\n description: \"Maximum depth for recursive listing. Default: 3.\",\n },\n },\n },\n permission: \"none\",\n },\n {\n name: \"run_command\",\n description:\n \"Execute a shell command. Use this to run build tools, test commands, linters, or inspect the environment. Commands run in the project root directory.\",\n input_schema: {\n type: \"object\",\n properties: {\n command: {\n type: \"string\",\n description: \"The shell command to execute\",\n },\n timeout: {\n type: \"number\",\n description:\n \"Timeout in milliseconds. Default: 30000 (30 seconds).\",\n },\n },\n required: [\"command\"],\n },\n permission: \"command\",\n },\n {\n name: \"edit_file\",\n description:\n \"Apply search-and-replace edits to an existing file. Use this for targeted modifications to existing code rather than rewriting entire files.\",\n input_schema: {\n type: \"object\",\n properties: {\n path: {\n type: \"string\",\n description: \"Relative file path from project root\",\n },\n edits: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n old_text: {\n type: \"string\",\n description: \"The exact text to find in the file\",\n },\n new_text: {\n type: \"string\",\n description: \"The replacement text\",\n },\n },\n required: [\"old_text\", \"new_text\"],\n },\n description: \"List of search/replace pairs to apply in order\",\n },\n },\n required: [\"path\", \"edits\"],\n },\n permission: \"file-write\",\n },\n {\n name: \"spawn_agent\",\n description:\n \"Spawn a sub-agent to handle a task in the background. The sub-agent runs in its own session and returns results. Use this for parallel research, long-running tasks, or delegating work to a specialized agent.\",\n input_schema: {\n type: \"object\",\n properties: {\n agent_id: {\n type: \"string\",\n description: \"The ID of the agent to spawn (must be a registered agent)\",\n },\n prompt: {\n type: \"string\",\n description: \"The task description for the sub-agent\",\n },\n timeout_seconds: {\n type: \"number\",\n description: \"Maximum time to wait for completion in seconds. Default: 300 (5 minutes).\",\n },\n },\n required: [\"agent_id\", \"prompt\"],\n },\n permission: \"none\",\n },\n]\n\n/**\n * Get all tool definitions in Anthropic API format (for generateRaw()).\n * Optionally filter by enabled tool names.\n */\nexport function getAnthropicTools(enabledTools?: string[]): Array<{\n name: string\n description: string\n input_schema: Record<string, unknown>\n}> {\n const defs = enabledTools\n ? TOOL_DEFINITIONS.filter((t) => enabledTools.includes(t.name))\n : TOOL_DEFINITIONS\n\n return defs.map(({ name, description, input_schema }) => ({\n name,\n description,\n input_schema,\n }))\n}\n\n/**\n * Get the legacy tools (create_files + ask_user) for backward compatibility.\n */\nexport function getLegacyTools(): Array<{\n name: string\n description: string\n input_schema: Record<string, unknown>\n}> {\n return getAnthropicTools([\"create_files\", \"ask_user\"])\n}\n\n/**\n * Format tool descriptions for inclusion in a system prompt.\n * Used when the `claude` CLI binary handles its own tools —\n * we describe our additional tools as text so the binary's built-in\n * capabilities (read, write, bash) handle them natively.\n */\nexport function formatToolsForSystemPrompt(): string {\n const agenticTools = TOOL_DEFINITIONS.filter(\n (t) => t.name !== \"create_files\" && t.name !== \"ask_user\"\n )\n\n if (agenticTools.length === 0) return \"\"\n\n const lines = [\n \"# Available Capabilities\",\n \"In addition to generating files, you have the following capabilities:\",\n \"\",\n ]\n\n for (const tool of agenticTools) {\n lines.push(`## ${tool.name}`)\n lines.push(tool.description)\n lines.push(\"\")\n }\n\n return lines.join(\"\\n\")\n}\n\nexport const ALL_TOOL_NAMES = TOOL_DEFINITIONS.map((t) => t.name)\n","import type {\n AgentProvider,\n GenerationMessage,\n GenerationResult,\n GeneratedFile,\n ProviderOptions,\n StreamEvent,\n AnthropicMessage,\n RawGenerationResult,\n ContentBlock,\n} from \"./types\"\nimport { resolveToken } from \"@/utils/auth-store\"\nimport { getLegacyTools } from \"../tools/definitions\"\n\n// --- Claude provider (default) using Anthropic SDK ---\n\nconst DEFAULT_MODEL = \"claude-sonnet-4-20250514\"\nconst DEFAULT_MAX_TOKENS = 8192\n\ninterface AnthropicResponse {\n id: string\n content: Array<{\n type: \"text\" | \"tool_use\" | \"tool_result\"\n text?: string\n id?: string\n name?: string\n input?: Record<string, unknown>\n tool_use_id?: string\n content?: string\n }>\n model: string\n stop_reason: string\n usage: { input_tokens: number; output_tokens: number }\n}\n\nexport class ClaudeProvider implements AgentProvider {\n name = \"claude\"\n private apiKey: string\n private authType: \"api-key\" | \"oauth\" = \"api-key\"\n\n constructor(apiKey?: string) {\n this.apiKey = apiKey || process.env.ANTHROPIC_API_KEY || \"\"\n if (!this.apiKey) {\n // Fallback to auth store\n const resolved = resolveToken()\n if (resolved) {\n this.apiKey = resolved.token\n this.authType = resolved.authType\n }\n }\n if (!this.apiKey) {\n throw new Error(\n \"Anthropic API key required. Run `agentx model` to configure, set ANTHROPIC_API_KEY, or pass --api-key.\"\n )\n }\n }\n\n async generate(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): Promise<GenerationResult> {\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n // Extract system message\n const systemMsg = messages.find((m) => m.role === \"system\")\n const conversationMsgs = messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({\n role: m.role as \"user\" | \"assistant\",\n content: m.content,\n }))\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n messages: conversationMsgs,\n tools: getLegacyTools(),\n }\n\n if (systemMsg) {\n body.system = systemMsg.content\n }\n\n if (options?.temperature !== undefined) {\n body.temperature = options.temperature\n }\n\n const response = await this.callApi(body)\n\n return this.parseResponse(response)\n }\n\n async generateRaw(\n messages: AnthropicMessage[],\n systemPrompt: string,\n tools: Array<{ name: string; description: string; input_schema: Record<string, unknown> }>,\n options?: ProviderOptions\n ): Promise<RawGenerationResult> {\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n system: systemPrompt,\n messages,\n tools,\n }\n\n if (options?.temperature !== undefined) {\n body.temperature = options.temperature\n }\n\n const response = await this.callApi(body)\n\n // Map response content blocks to our ContentBlock type\n const content: ContentBlock[] = response.content.map((block) => {\n if (block.type === \"text\") {\n return { type: \"text\" as const, text: block.text || \"\" }\n }\n if (block.type === \"tool_use\") {\n return {\n type: \"tool_use\" as const,\n id: block.id || \"\",\n name: block.name || \"\",\n input: block.input || {},\n }\n }\n return { type: \"text\" as const, text: \"\" }\n })\n\n return {\n content,\n stop_reason: response.stop_reason as RawGenerationResult[\"stop_reason\"],\n usage: response.usage,\n }\n }\n\n async *stream(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): AsyncIterable<StreamEvent> {\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n const systemMsg = messages.find((m) => m.role === \"system\")\n const conversationMsgs = messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({\n role: m.role as \"user\" | \"assistant\",\n content: m.content,\n }))\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n messages: conversationMsgs,\n stream: true,\n tools: getLegacyTools(),\n }\n\n if (systemMsg) {\n body.system = systemMsg.content\n }\n\n const headers = this.buildHeaders()\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n })\n\n if (!res.ok) {\n const errorText = await res.text()\n yield { type: \"error\", error: `Anthropic API error (${res.status}): ${errorText}` }\n return\n }\n\n const reader = res.body?.getReader()\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" }\n return\n }\n\n const decoder = new TextDecoder()\n let buffer = \"\"\n const files: GeneratedFile[] = []\n let content = \"\"\n let followUp: string | undefined\n let tokensUsed = 0\n let activeTool: { name: string; id: string; json: string } | null = null\n\n const inferFollowUpFromText = (text: string): string | undefined => {\n const cleaned = (text || \"\").trim()\n if (!cleaned) return undefined\n if (cleaned.includes(\"```\")) return undefined\n\n const lines = cleaned.replace(/\\r\\n/g, \"\\n\").split(\"\\n\")\n const tail = lines.slice(Math.max(0, lines.length - 20))\n const tailText = tail.join(\"\\n\")\n\n const looksLikePlanApproval =\n /\\b(plan|proposal)\\b/i.test(tailText) &&\n /(ready for your review|review (the )?plan|requesting plan approval|awaiting approval|waiting for (your )?approval|approve (the )?plan|approval to proceed)/i.test(\n tailText\n )\n\n if (looksLikePlanApproval) {\n return (\n \"The provider is requesting plan approval.\\n\" +\n \"Reply with:\\n\" +\n \"- approve\\n\" +\n \"- revise: <what to change>\\n\" +\n \"- cancel\"\n )\n }\n\n const isIntro = (l: string) =>\n /^(question|clarification|clarify|i need|need more|before i proceed|to proceed|please (confirm|clarify)|which|what|where|when|how|do you)/i.test(\n l.trim()\n )\n\n let startIdx = -1\n for (let i = tail.length - 1; i >= 0; i--) {\n const l = tail[i].trim()\n if (!l) continue\n if (isIntro(l) || l.includes(\"?\")) {\n startIdx = i\n break\n }\n }\n if (startIdx === -1) return undefined\n\n const out: string[] = []\n for (let i = startIdx; i < tail.length && out.length < 8; i++) {\n const l = tail[i]\n const t = l.trim()\n if (out.length > 0 && !t) break\n if (\n out.length > 0 &&\n !/^(options?:|[-*]\\s|\\d+[\\).]\\s)/i.test(t) &&\n !t.includes(\"?\")\n ) {\n break\n }\n out.push(l.trimEnd())\n }\n\n const candidate = out.join(\"\\n\").trim()\n if (candidate.length < 5) return undefined\n if (candidate.length > 800) return candidate.slice(0, 800).trimEnd()\n return candidate\n }\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split(\"\\n\")\n buffer = lines.pop() || \"\"\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue\n const data = line.slice(6).trim()\n if (data === \"[DONE]\") continue\n\n try {\n const event = JSON.parse(data)\n\n if (event.type === \"content_block_start\") {\n if (event.content_block?.type === \"tool_use\") {\n // Finalize any previous tool block if the stream didn't send a stop.\n if (activeTool) {\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore invalid tool JSON\n } finally {\n activeTool = null\n }\n }\n\n activeTool = {\n name: event.content_block.name,\n id: event.content_block.id,\n json: \"\",\n }\n yield {\n type: \"tool_use_start\",\n name: event.content_block.name,\n id: event.content_block.id,\n }\n }\n }\n\n if (event.type === \"content_block_delta\") {\n if (event.delta?.type === \"text_delta\") {\n content += event.delta.text\n yield { type: \"text_delta\", text: event.delta.text }\n }\n if (event.delta?.type === \"input_json_delta\") {\n if (activeTool) activeTool.json += event.delta.partial_json || \"\"\n yield { type: \"tool_use_delta\", json: event.delta.partial_json }\n }\n }\n\n if (event.type === \"content_block_stop\") {\n // Tool use blocks are complete\n if (activeTool) {\n // Manually inline finalize to avoid generator gymnastics.\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore invalid tool JSON\n } finally {\n activeTool = null\n }\n }\n }\n\n if (event.type === \"message_delta\") {\n if (event.usage) {\n tokensUsed = (event.usage.input_tokens || 0) + (event.usage.output_tokens || 0)\n }\n }\n\n if (event.type === \"message_stop\") {\n // Message complete\n }\n } catch {\n // Skip unparseable lines\n }\n }\n }\n } finally {\n reader.releaseLock()\n }\n\n // Flush any trailing tool input.\n if (activeTool) {\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore\n }\n activeTool = null\n }\n\n if (!followUp && files.length === 0) {\n followUp = inferFollowUpFromText(content)\n }\n\n yield {\n type: \"done\",\n result: { content, files, followUp, tokensUsed },\n }\n }\n\n private buildHeaders(): Record<string, string> {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"anthropic-version\": \"2023-06-01\",\n }\n\n if (this.authType === \"oauth\") {\n headers[\"Authorization\"] = `Bearer ${this.apiKey}`\n headers[\"anthropic-beta\"] = \"claude-code-20250219,oauth-2025-04-20\"\n headers[\"user-agent\"] = \"claude-cli/2.1.2 (external, cli)\"\n headers[\"x-app\"] = \"cli\"\n headers[\"anthropic-dangerous-direct-browser-access\"] = \"true\"\n } else {\n headers[\"x-api-key\"] = this.apiKey\n }\n\n return headers\n }\n\n private async callApi(body: Record<string, unknown>): Promise<AnthropicResponse> {\n const headers = this.buildHeaders()\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n })\n\n if (!res.ok) {\n const errorText = await res.text()\n throw new Error(`Anthropic API error (${res.status}): ${errorText}`)\n }\n\n return (await res.json()) as AnthropicResponse\n }\n\n private parseResponse(response: AnthropicResponse): GenerationResult {\n const files: GeneratedFile[] = []\n let content = \"\"\n let followUp: string | undefined\n\n for (const block of response.content) {\n if (block.type === \"text\") {\n content += block.text || \"\"\n }\n\n if (block.type === \"tool_use\") {\n if (block.name === \"create_files\" && block.input) {\n const input = block.input as {\n files: GeneratedFile[]\n summary?: string\n }\n files.push(...(input.files || []))\n if (input.summary) {\n content += `\\n${input.summary}`\n }\n }\n\n if (block.name === \"ask_user\" && block.input) {\n const input = block.input as { question: string; options?: string[] }\n followUp = input.question\n if (input.options?.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n }\n\n return {\n content,\n files,\n followUp,\n tokensUsed: response.usage.input_tokens + response.usage.output_tokens,\n }\n }\n}\n","import type {\n AgentProvider,\n GenerationMessage,\n GenerationResult,\n GeneratedFile,\n ProviderOptions,\n StreamEvent,\n AnthropicMessage,\n RawGenerationResult,\n ContentBlock,\n} from \"./types\"\nimport { resolveToken, loadAuthConfig } from \"@/utils/auth-store\"\nimport { execa } from \"execa\"\nimport { getLegacyTools } from \"../tools/definitions\"\n\n// --- Claude Code provider: uses Claude CLI (subscription) or direct API (API key) ---\n\nconst DEFAULT_MODEL = \"claude-sonnet-4-20250514\"\nconst DEFAULT_MAX_TOKENS = 8192\n\n// Model ID → claude CLI alias\nconst CLI_MODEL_ALIASES: Record<string, string> = {\n \"claude-sonnet-4-20250514\": \"sonnet\",\n \"claude-opus-4-20250514\": \"opus\",\n \"claude-haiku-4-20250514\": \"haiku\",\n}\n\ntype AuthCredential = { type: \"oauth\"; token: string } | { type: \"api-key\"; token: string }\n\ninterface AnthropicResponse {\n id: string\n content: Array<{\n type: \"text\" | \"tool_use\" | \"tool_result\"\n text?: string\n id?: string\n name?: string\n input?: Record<string, unknown>\n }>\n model: string\n stop_reason: string\n usage: { input_tokens: number; output_tokens: number }\n}\n\nexport class ClaudeCodeProvider implements AgentProvider {\n name = \"claude-code\"\n private credential: AuthCredential\n\n constructor() {\n // Stored config takes priority — if user ran `agentx model` and chose OAuth,\n // we use that regardless of ANTHROPIC_API_KEY env var (same as OpenClaw's clearEnv).\n const stored = loadAuthConfig()\n if (stored) {\n this.credential = { type: stored.authType, token: stored.token }\n return\n }\n\n const resolved = resolveToken()\n if (!resolved) {\n throw new Error(\n \"No Claude credentials found.\\n\" +\n \"Options:\\n\" +\n \" 1. Run `agentx model` to configure credentials\\n\" +\n \" 2. Set ANTHROPIC_API_KEY environment variable\\n\" +\n \" 3. Set ANTHROPIC_OAUTH_TOKEN environment variable\"\n )\n }\n this.credential = { type: resolved.authType, token: resolved.token }\n }\n\n async generate(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): Promise<GenerationResult> {\n // OAuth tokens → use claude CLI (subscription billing)\n // API keys → call API directly\n if (this.credential.type === \"oauth\") {\n return this.generateViaCli(messages, options)\n }\n return this.generateViaApi(messages, options)\n }\n\n /**\n * generateRaw() for the agentic tool_result loop.\n * Only available for API key auth — the CLI binary has its own agent loop.\n */\n async generateRaw(\n messages: AnthropicMessage[],\n systemPrompt: string,\n tools: Array<{ name: string; description: string; input_schema: Record<string, unknown> }>,\n options?: ProviderOptions\n ): Promise<RawGenerationResult> {\n // OAuth path: not supported — the claude CLI has its own built-in tools\n if (this.credential.type === \"oauth\") {\n throw new Error(\"generateRaw() not available for OAuth/CLI mode\")\n }\n\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n system: systemPrompt,\n messages,\n tools,\n }\n\n if (options?.temperature !== undefined) {\n body.temperature = options.temperature\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"anthropic-version\": \"2023-06-01\",\n \"x-api-key\": this.credential.token,\n }\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n })\n\n if (!res.ok) {\n const errorText = await res.text()\n throw new Error(`Anthropic API error (${res.status}): ${errorText}`)\n }\n\n const response = (await res.json()) as AnthropicResponse\n\n const content: ContentBlock[] = response.content.map((block) => {\n if (block.type === \"text\") {\n return { type: \"text\" as const, text: block.text || \"\" }\n }\n if (block.type === \"tool_use\") {\n return {\n type: \"tool_use\" as const,\n id: block.id || \"\",\n name: block.name || \"\",\n input: block.input || {},\n }\n }\n return { type: \"text\" as const, text: \"\" }\n })\n\n return {\n content,\n stop_reason: response.stop_reason as RawGenerationResult[\"stop_reason\"],\n usage: response.usage,\n }\n }\n\n /**\n * Returns true if this provider can use the agentic tool loop.\n * Only available for API key auth (CLI mode falls back to legacy loop).\n */\n get supportsAgenticLoop(): boolean {\n return this.credential.type === \"api-key\"\n }\n\n /**\n * Generate via the `claude` CLI binary.\n * This is how subscription billing works — the CLI handles auth internally.\n */\n private async generateViaCli(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): Promise<GenerationResult> {\n const model = options?.model || loadAuthConfig()?.model || DEFAULT_MODEL\n const cliModel = CLI_MODEL_ALIASES[model] || model\n\n const systemMsg = messages.find((m) => m.role === \"system\")\n const userMsgs = messages.filter((m) => m.role === \"user\")\n const prompt = userMsgs.map((m) => m.content).join(\"\\n\\n\")\n\n const args = [\n \"-p\",\n \"--output-format\", \"json\",\n \"--model\", cliModel,\n \"--dangerously-skip-permissions\",\n ]\n\n if (systemMsg) {\n args.push(\"--append-system-prompt\", systemMsg.content)\n }\n\n // Prompt goes as the last positional argument\n args.push(prompt)\n\n // Clear ANTHROPIC_API_KEY to force CLI to use subscription auth\n const env = { ...process.env }\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_API_KEY_OLD\n\n const result = await execa(\"claude\", args, {\n env,\n extendEnv: false,\n reject: false,\n timeout: 300_000,\n stdin: \"ignore\",\n })\n\n if (result.exitCode !== 0) {\n const err = result.stderr || result.stdout || \"Claude CLI failed\"\n throw new Error(`Claude CLI error: ${err}`)\n }\n\n // Claude CLI may return success exit code but with is_error in JSON\n const output = result.stdout.trim()\n try {\n const json = JSON.parse(output)\n if (json.is_error && json.result) {\n throw new Error(json.result)\n }\n } catch (e: any) {\n if (e.message && !e.message.includes(\"JSON\")) throw e\n // Not JSON — that's fine, parseCliOutput will handle it\n }\n\n return this.parseCliOutput(output)\n }\n\n /**\n * Generate via direct Anthropic API call (for API key auth).\n */\n private async generateViaApi(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): Promise<GenerationResult> {\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n const systemMsg = messages.find((m) => m.role === \"system\")\n const conversationMsgs = messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({\n role: m.role as \"user\" | \"assistant\",\n content: m.content,\n }))\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n messages: conversationMsgs,\n tools: getLegacyTools(),\n }\n\n if (systemMsg) {\n body.system = systemMsg.content\n }\n\n if (options?.temperature !== undefined) {\n body.temperature = options.temperature\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"anthropic-version\": \"2023-06-01\",\n \"x-api-key\": this.credential.token,\n }\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n })\n\n if (!res.ok) {\n const errorText = await res.text()\n throw new Error(`Anthropic API error (${res.status}): ${errorText}`)\n }\n\n const response = (await res.json()) as AnthropicResponse\n return this.parseApiResponse(response)\n }\n\n /**\n * Stream responses. For OAuth, uses CLI with --output-format stream-json.\n * For API keys, uses SSE streaming.\n */\n async *stream(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): AsyncIterable<StreamEvent> {\n if (this.credential.type === \"oauth\") {\n // CLI streaming via --output-format stream-json\n yield* this.streamViaCli(messages, options)\n } else {\n // API streaming via SSE (same as ClaudeProvider.stream)\n yield* this.streamViaApi(messages, options)\n }\n }\n\n private async *streamViaCli(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): AsyncIterable<StreamEvent> {\n const model = options?.model || loadAuthConfig()?.model || DEFAULT_MODEL\n const cliModel = CLI_MODEL_ALIASES[model] || model\n\n const systemMsg = messages.find((m) => m.role === \"system\")\n const userMsgs = messages.filter((m) => m.role === \"user\")\n const prompt = userMsgs.map((m) => m.content).join(\"\\n\\n\")\n\n const args = [\n \"-p\",\n \"--output-format\", \"stream-json\",\n \"--model\", cliModel,\n \"--dangerously-skip-permissions\",\n ]\n\n if (systemMsg) {\n args.push(\"--append-system-prompt\", systemMsg.content)\n }\n\n args.push(prompt)\n\n const env = { ...process.env }\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_API_KEY_OLD\n\n const child = execa(\"claude\", args, {\n env,\n extendEnv: false,\n reject: false,\n timeout: 300_000,\n stdin: \"ignore\",\n })\n\n let fullContent = \"\"\n let stderr = \"\"\n let fatalError: string | undefined\n\n if (child.stderr) {\n child.stderr.on(\"data\", (chunk: any) => {\n stderr += Buffer.isBuffer(chunk) ? chunk.toString(\"utf8\") : String(chunk)\n })\n }\n\n if (child.stdout) {\n const decoder = new TextDecoder()\n const readable = child.stdout as unknown as AsyncIterable<Uint8Array>\n\n for await (const chunk of readable) {\n const text = typeof chunk === \"string\" ? chunk : decoder.decode(chunk, { stream: true })\n // Stream JSON format: each line is a JSON object\n const lines = text.split(\"\\n\").filter(Boolean)\n for (const line of lines) {\n try {\n const event = JSON.parse(line)\n // Some claude stream-json builds emit error events.\n if (event.type === \"error\") {\n fatalError = String(event.error || event.message || \"Claude CLI error\")\n continue\n }\n if (event.is_error && (event.result || event.message)) {\n fatalError = String(event.result || event.message)\n continue\n }\n if (event.type === \"assistant\" && event.message) {\n fullContent += event.message\n yield { type: \"text_delta\", text: event.message }\n } else if (event.type === \"result\") {\n fullContent = event.result || fullContent\n }\n } catch {\n // Not JSON, treat as raw text\n fullContent += line\n yield { type: \"text_delta\", text: line }\n }\n }\n }\n }\n\n const res = await child\n if (res.exitCode !== 0 && !fatalError) {\n fatalError = (stderr || res.stderr || res.stdout || \"Claude CLI failed\").toString().trim()\n }\n\n if (fatalError) {\n yield { type: \"error\", error: `Claude CLI error: ${fatalError}` }\n return\n }\n\n const files = this.extractFilesFromText(fullContent)\n const followUp =\n files.length === 0 ? this.inferFollowUpFromText(fullContent) : undefined\n yield {\n type: \"done\",\n result: { content: fullContent, files, followUp, tokensUsed: 0 },\n }\n }\n\n private async *streamViaApi(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): AsyncIterable<StreamEvent> {\n const model = options?.model || DEFAULT_MODEL\n const maxTokens = options?.maxTokens || DEFAULT_MAX_TOKENS\n\n const systemMsg = messages.find((m) => m.role === \"system\")\n const conversationMsgs = messages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({ role: m.role as \"user\" | \"assistant\", content: m.content }))\n\n const body: Record<string, unknown> = {\n model,\n max_tokens: maxTokens,\n messages: conversationMsgs,\n tools: getLegacyTools(),\n stream: true,\n }\n\n if (systemMsg) body.system = systemMsg.content\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"anthropic-version\": \"2023-06-01\",\n \"x-api-key\": this.credential.token,\n }\n\n const res = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers,\n body: JSON.stringify(body),\n })\n\n if (!res.ok) {\n const errorText = await res.text()\n yield { type: \"error\", error: `Anthropic API error (${res.status}): ${errorText}` }\n return\n }\n\n const reader = res.body?.getReader()\n if (!reader) {\n yield { type: \"error\", error: \"No response body\" }\n return\n }\n\n const decoder = new TextDecoder()\n let buffer = \"\"\n let content = \"\"\n let tokensUsed = 0\n const files: GeneratedFile[] = []\n let followUp: string | undefined\n let activeTool: { name: string; id: string; json: string } | null = null\n\n try {\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split(\"\\n\")\n buffer = lines.pop() || \"\"\n\n for (const line of lines) {\n if (!line.startsWith(\"data: \")) continue\n const data = line.slice(6).trim()\n if (data === \"[DONE]\") continue\n\n try {\n const event = JSON.parse(data)\n if (event.type === \"content_block_start\") {\n if (event.content_block?.type === \"tool_use\") {\n // Finalize any previous tool block if the stream didn't send a stop.\n if (activeTool) {\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore invalid tool JSON\n } finally {\n activeTool = null\n }\n }\n\n activeTool = {\n name: event.content_block.name,\n id: event.content_block.id,\n json: \"\",\n }\n yield { type: \"tool_use_start\", name: activeTool.name, id: activeTool.id }\n }\n }\n\n if (event.type === \"content_block_delta\" && event.delta?.type === \"text_delta\") {\n content += event.delta.text\n yield { type: \"text_delta\", text: event.delta.text }\n }\n if (event.type === \"content_block_delta\" && event.delta?.type === \"input_json_delta\") {\n if (activeTool) activeTool.json += event.delta.partial_json || \"\"\n yield { type: \"tool_use_delta\", json: event.delta.partial_json }\n }\n if (event.type === \"content_block_stop\") {\n if (activeTool) {\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore invalid tool JSON\n } finally {\n activeTool = null\n }\n }\n }\n if (event.type === \"message_delta\" && event.usage) {\n tokensUsed = (event.usage.input_tokens || 0) + (event.usage.output_tokens || 0)\n }\n } catch {\n // Skip\n }\n }\n }\n } finally {\n reader.releaseLock()\n }\n\n // Flush any trailing tool input.\n if (activeTool) {\n yield { type: \"tool_use_end\", name: activeTool.name }\n try {\n const input = JSON.parse(activeTool.json || \"{}\") as any\n if (activeTool.name === \"create_files\" && input) {\n if (Array.isArray(input.files)) {\n files.push(...(input.files as GeneratedFile[]))\n }\n if (typeof input.summary === \"string\" && input.summary.trim()) {\n content += `\\n${input.summary}`\n }\n }\n if (activeTool.name === \"ask_user\" && input) {\n if (typeof input.question === \"string\" && input.question.trim()) {\n followUp = input.question\n if (Array.isArray(input.options) && input.options.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n } catch {\n // Ignore\n }\n activeTool = null\n }\n\n // If the model didn't use tools (or we couldn't parse them), fall back to fenced-code extraction.\n if (files.length === 0) {\n files.push(...this.extractFilesFromText(content))\n }\n if (!followUp && files.length === 0) {\n followUp = this.inferFollowUpFromText(content)\n }\n yield {\n type: \"done\",\n result: { content, files, followUp, tokensUsed },\n }\n }\n\n /**\n * Parse JSON output from the `claude` CLI.\n */\n private parseCliOutput(stdout: string): GenerationResult {\n let parsed: any\n try {\n parsed = JSON.parse(stdout)\n } catch {\n // CLI returned plain text\n const inferred = this.inferFollowUpFromText(stdout.trim())\n return {\n content: stdout.trim(),\n files: [],\n followUp: inferred,\n tokensUsed: 0,\n }\n }\n\n // Claude CLI JSON format: { result: \"...\", session_id: \"...\", ... }\n const text = parsed.result || parsed.text || parsed.content || \"\"\n\n // Extract files from the text if it contains code blocks with file paths\n const files = this.extractFilesFromText(text)\n const followUp = files.length === 0 ? this.inferFollowUpFromText(text) : undefined\n\n return {\n content: text,\n files,\n followUp,\n tokensUsed: parsed.usage\n ? (parsed.usage.input_tokens || 0) + (parsed.usage.output_tokens || 0)\n : 0,\n }\n }\n\n /**\n * Extract file blocks from CLI text output.\n * Looks for patterns like: ```path/to/file.ts ... ```\n */\n private extractFilesFromText(text: string): GeneratedFile[] {\n const files: GeneratedFile[] = []\n // Match fenced code blocks with a file path hint on the opening line\n const pattern = /```[\\w]*\\s*([\\w/._-]+\\.\\w+)\\n([\\s\\S]*?)```/g\n let match: RegExpExecArray | null\n while ((match = pattern.exec(text)) !== null) {\n const filePath = match[1]\n const content = match[2]\n if (filePath && content) {\n files.push({ path: filePath, content: content.trimEnd() })\n }\n }\n return files\n }\n\n /**\n * Claude CLI (OAuth/subscription) doesn't always emit structured ask_user tool blocks.\n * When it's obviously asking for clarification, infer a follow-up question from the tail.\n */\n private inferFollowUpFromText(text: string): string | undefined {\n const cleaned = (text || \"\").trim()\n if (!cleaned) return undefined\n\n // If it looks like it produced file blocks, don't treat it as a follow-up.\n if (cleaned.includes(\"```\")) return undefined\n\n const lines = cleaned.replace(/\\r\\n/g, \"\\n\").split(\"\\n\")\n const tail = lines.slice(Math.max(0, lines.length - 20))\n\n const tailText = tail.join(\"\\n\")\n const looksLikePlanApproval =\n /\\b(plan|proposal)\\b/i.test(tailText) &&\n /(ready for your review|review (the )?plan|requesting plan approval|awaiting approval|waiting for (your )?approval|approve (the )?plan|approval to proceed)/i.test(\n tailText\n )\n\n if (looksLikePlanApproval) {\n return (\n \"The provider is requesting plan approval.\\n\" +\n \"Reply with:\\n\" +\n \"- approve\\n\" +\n \"- revise: <what to change>\\n\" +\n \"- cancel\"\n )\n }\n\n const isIntro = (l: string) =>\n /^(question|clarification|clarify|i need|need more|before i proceed|to proceed|please (confirm|clarify)|which|what|where|when|how|do you)/i.test(\n l.trim()\n )\n\n // Find the last strong candidate line.\n let startIdx = -1\n for (let i = tail.length - 1; i >= 0; i--) {\n const l = tail[i].trim()\n if (!l) continue\n if (isIntro(l) || l.includes(\"?\")) {\n startIdx = i\n break\n }\n }\n if (startIdx === -1) return undefined\n\n // Collect the question + a small option/list block that follows it.\n const out: string[] = []\n for (let i = startIdx; i < tail.length && out.length < 8; i++) {\n const l = tail[i]\n const t = l.trim()\n if (out.length > 0 && !t) break\n\n if (\n out.length > 0 &&\n !/^(options?:|[-*]\\s|\\d+[\\).]\\s)/i.test(t) &&\n !t.includes(\"?\")\n ) {\n break\n }\n\n out.push(l.trimEnd())\n }\n\n const candidate = out.join(\"\\n\").trim()\n if (candidate.length < 5) return undefined\n if (candidate.length > 800) return candidate.slice(0, 800).trimEnd()\n return candidate\n }\n\n /**\n * Parse Anthropic API response (tool-use format).\n */\n private parseApiResponse(response: AnthropicResponse): GenerationResult {\n const files: GeneratedFile[] = []\n let content = \"\"\n let followUp: string | undefined\n\n for (const block of response.content) {\n if (block.type === \"text\") {\n content += block.text || \"\"\n }\n\n if (block.type === \"tool_use\") {\n if (block.name === \"create_files\" && block.input) {\n const input = block.input as {\n files: GeneratedFile[]\n summary?: string\n }\n files.push(...(input.files || []))\n if (input.summary) {\n content += `\\n${input.summary}`\n }\n }\n\n if (block.name === \"ask_user\" && block.input) {\n const input = block.input as { question: string; options?: string[] }\n followUp = input.question\n if (input.options?.length) {\n followUp += `\\nOptions: ${input.options.join(\", \")}`\n }\n }\n }\n }\n\n return {\n content,\n files,\n followUp,\n tokensUsed: response.usage.input_tokens + response.usage.output_tokens,\n }\n }\n}\n","import type { AgentProvider } from \"./types\"\nimport { ClaudeProvider } from \"./claude\"\nimport { ClaudeCodeProvider } from \"./claude-code\"\nimport { loadAuthConfig } from \"@/utils/auth-store\"\n\nexport type ProviderName = \"claude-code\" | \"claude\" | \"openai\" | \"ollama\" | \"custom\"\n\nexport function createProvider(\n name: ProviderName = \"claude-code\",\n apiKey?: string\n): AgentProvider {\n // Auto-detect provider from stored config when using the default\n let resolvedName = name\n if (name === \"claude-code\" && !apiKey) {\n const stored = loadAuthConfig()\n if (stored) {\n resolvedName = stored.provider\n }\n }\n\n switch (resolvedName) {\n case \"claude-code\":\n return new ClaudeCodeProvider()\n case \"claude\":\n return new ClaudeProvider(apiKey)\n case \"openai\":\n throw new Error(\n \"OpenAI provider coming soon. Set provider to 'claude-code' or contribute at github.com/anis-marrouchi/agentx\"\n )\n case \"ollama\":\n throw new Error(\n \"Ollama provider coming soon. Set provider to 'claude-code' or contribute at github.com/anis-marrouchi/agentx\"\n )\n default:\n throw new Error(`Unknown provider: ${resolvedName}. Supported: claude-code, claude`)\n }\n}\n\nexport { ClaudeProvider } from \"./claude\"\nexport { ClaudeCodeProvider } from \"./claude-code\"\nexport type {\n AgentProvider,\n GenerationMessage,\n GenerationResult,\n GeneratedFile,\n ProviderOptions,\n StreamEvent,\n AnthropicMessage,\n ContentBlock,\n RawGenerationResult,\n} from \"./types\"\n"],"mappings":"+CASA,IAAMA,EAAqC,CACzC,CACE,KAAM,eACN,YACE,6HACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,MAAO,CACL,KAAM,QACN,MAAO,CACL,KAAM,SACN,WAAY,CACV,KAAM,CACJ,KAAM,SACN,YACE,wEACJ,EACA,QAAS,CACP,KAAM,SACN,YAAa,8BACf,EACA,SAAU,CACR,KAAM,SACN,YAAa,mCACf,EACA,YAAa,CACX,KAAM,SACN,YAAa,0CACf,CACF,EACA,SAAU,CAAC,OAAQ,SAAS,CAC9B,CACF,EACA,QAAS,CACP,KAAM,SACN,YAAa,sCACf,CACF,EACA,SAAU,CAAC,OAAO,CACpB,EACA,WAAY,YACd,EACA,CACE,KAAM,WACN,YACE,mKACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,SAAU,CACR,KAAM,SACN,YAAa,8BACf,EACA,QAAS,CACP,KAAM,QACN,MAAO,CAAE,KAAM,QAAS,EACxB,YAAa,uCACf,CACF,EACA,SAAU,CAAC,UAAU,CACvB,EACA,WAAY,MACd,EACA,CACE,KAAM,YACN,YACE,wJACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,KAAM,CACJ,KAAM,SACN,YAAa,sCACf,EACA,UAAW,CACT,KAAM,SACN,YACE,wEACJ,CACF,EACA,SAAU,CAAC,MAAM,CACnB,EACA,WAAY,WACd,EACA,CACE,KAAM,eACN,YACE,mLACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,QAAS,CACP,KAAM,SACN,YACE,6DACJ,EACA,cAAe,CACb,KAAM,SACN,YACE,wEACJ,EACA,YAAa,CACX,KAAM,SACN,YAAa,mDACf,CACF,EACA,SAAU,CAAC,SAAS,CACtB,EACA,WAAY,MACd,EACA,CACE,KAAM,iBACN,YACE,qFACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,KAAM,CACJ,KAAM,SACN,YACE,oEACJ,EACA,UAAW,CACT,KAAM,UACN,YAAa,mCACf,EACA,UAAW,CACT,KAAM,SACN,YAAa,kDACf,CACF,CACF,EACA,WAAY,MACd,EACA,CACE,KAAM,cACN,YACE,wJACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,QAAS,CACP,KAAM,SACN,YAAa,8BACf,EACA,QAAS,CACP,KAAM,SACN,YACE,uDACJ,CACF,EACA,SAAU,CAAC,SAAS,CACtB,EACA,WAAY,SACd,EACA,CACE,KAAM,YACN,YACE,+IACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,KAAM,CACJ,KAAM,SACN,YAAa,sCACf,EACA,MAAO,CACL,KAAM,QACN,MAAO,CACL,KAAM,SACN,WAAY,CACV,SAAU,CACR,KAAM,SACN,YAAa,oCACf,EACA,SAAU,CACR,KAAM,SACN,YAAa,sBACf,CACF,EACA,SAAU,CAAC,WAAY,UAAU,CACnC,EACA,YAAa,gDACf,CACF,EACA,SAAU,CAAC,OAAQ,OAAO,CAC5B,EACA,WAAY,YACd,EACA,CACE,KAAM,cACN,YACE,kNACF,aAAc,CACZ,KAAM,SACN,WAAY,CACV,SAAU,CACR,KAAM,SACN,YAAa,2DACf,EACA,OAAQ,CACN,KAAM,SACN,YAAa,wCACf,EACA,gBAAiB,CACf,KAAM,SACN,YAAa,2EACf,CACF,EACA,SAAU,CAAC,WAAY,QAAQ,CACjC,EAC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ACb,IAAK,SACH,OAAO,IAAIC,EAAeL,CAAM,EAClC,IAAK,SACH,MAAM,IAAI,MACR,8GACF,EACF,IAAK,SACH,MAAM,IAAI,MACR,8GACF,EACF,QACE,MAAM,IAAI,MAAM,qBAAqBC,mCAA8C,CACvF,CACF","names":["TOOL_DEFINITIONS","getAnthropicTools","enabledTools","t","name","description","input_schema","getLegacyTools","formatToolsForSystemPrompt","agenticTools","lines","tool","ALL_TOOL_NAMES","DEFAULT_MODEL","DEFAULT_MAX_TOKENS","ClaudeProvider","apiKey","resolved","resolveToken","messages","options","model","maxTokens","systemMsg","m","conversationMsgs","body","getLegacyTools","response","systemPrompt","tools","block","headers","res","errorText","reader","decoder","buffer","files","content","followUp","tokensUsed","activeTool","inferFollowUpFromText","text","cleaned","lines","tail","tailText","isIntro","l","startIdx","i","out","t","candidate","done","value","line","data","event","input","execa","DEFAULT_MODEL","DEFAULT_MAX_TOKENS","CLI_MODEL_ALIASES","ClaudeCodeProvider","stored","loadAuthConfig","resolved","resolveToken","messages","options","systemPrompt","tools","model","maxTokens","body","headers","res","errorText","response","block","cliModel","systemMsg","m","prompt","args","env","result","execa","err","output","json","e","conversationMsgs","getLegacyTools","child","fullContent","stderr","fatalError","chunk","decoder","readable","lines","line","event","files","followUp","reader","buffer","content","tokensUsed","activeTool","done","value","data","input","stdout","parsed","inferred","text","pattern","match","filePath","cleaned","tail","tailText","isIntro","l","startIdx","i","out","t","candidate","createProvider","name","apiKey","resolvedName","stored","loadAuthConfig","ClaudeCodeProvider","ClaudeProvider"]}
@@ -0,0 +1,108 @@
1
+ import{a as Ce,b as Se,c as ge}from"./chunk-SFQUP3BP.js";import{d as X,h as p}from"./chunk-CJ45Y2IR.js";import{a as he,b as ye}from"./chunk-X32247GM.js";import{a as de,c as ue,g as me}from"./chunk-KXZMYLHQ.js";import{a as F,b as ce,f as pe}from"./chunk-M7HKBG3V.js";import{a as Te,d as fe}from"./chunk-FRFR27IN.js";import{e as v}from"./chunk-DSYKYZMT.js";import{z as R}from"zod";var Re=R.object({provider:R.enum(["claude-code","claude","openai","ollama","custom"]).default("claude-code"),model:R.string().optional(),apiKey:R.string().optional(),skills:R.array(R.string()).default([]),output:R.object({dir:R.string().default("./generated")}).default({}),context7:R.object({enabled:R.boolean().default(!0),apiKey:R.string().optional()}).default({}),agentic:R.object({maxIterations:R.number().default(20),enabledTools:R.array(R.string()).default(["create_files","ask_user","read_file","search_files","list_directory","run_command","edit_file"]),disabledTools:R.array(R.string()).default([])}).default({})}),dt=["component","page","api","website","document","script","config","skill","media","report","test","workflow","schema","email","diagram","auto"],ut={component:"UI component (any framework)",page:"Full page or screen",api:"API endpoint, route handler, or service",website:"Multi-page website or app",document:"Markdown, documentation, or specification",script:"Standalone script or utility",config:"Configuration file or setup",skill:"Agent skill (SKILL.md format for skills.sh)",media:"Media generation prompt (image/audio/video description)",report:"Analysis report or audit",test:"Test suite, test fixtures, or test data",workflow:"CI/CD pipeline, GitHub Actions, or automation",schema:"Database schema, Zod validators, or GraphQL types",email:"Email template (React Email, MJML, HTML)",diagram:"Mermaid, D2, or PlantUML diagram",auto:"Auto-detect the best output type"};import{existsSync as Ye,promises as Je}from"fs";import B from"path";import Qe from"fast-glob";var Ae={"prisma/schema.prisma":{type:"prisma",category:"database"},"drizzle/schema.ts":{type:"drizzle",category:"database"},"schema.graphql":{type:"graphql",category:"api"},"schema.gql":{type:"graphql",category:"api"},"openapi.yaml":{type:"openapi",category:"api"},"openapi.json":{type:"openapi",category:"api"},"swagger.yaml":{type:"openapi",category:"api"},"swagger.json":{type:"openapi",category:"api"}};async function Me(o){let e={},t=await Qe.glob("**/*",{cwd:o,deep:4,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/.next/**","**/target/**","**/__pycache__/**","**/vendor/**","**/.git/**"],onlyFiles:!0});for(let[s,i]of Object.entries(Ae)){let l=t.find(a=>a.endsWith(s)||a===s);if(l&&i.category==="database"){let a=await K(B.resolve(o,l));if(a){e.database={type:i.type,content:Z(a,3e3),tables:Ve(a,i.type)};break}}}for(let[s,i]of Object.entries(Ae)){let l=t.find(a=>a.endsWith(s)||a===s);if(l&&i.category==="api"){let a=await K(B.resolve(o,l));if(a){e.api={type:i.type,content:Z(a,3e3)};break}}}if(!e.api){let s=t.find(i=>i.includes("trpc")&&(i.endsWith("router.ts")||i.endsWith("router.js")));if(s){let i=await K(B.resolve(o,s));i&&(e.api={type:"trpc",content:Z(i,3e3)})}}let n=t.find(s=>s===".env.example"||s===".env.local.example"||s===".env.template");if(n){let s=await K(B.resolve(o,n));s&&(e.env=Xe(s))}let r=t.filter(s=>(s.includes("models")||s.includes("types")||s.includes("schemas"))&&(s.endsWith(".ts")||s.endsWith(".py")||s.endsWith(".rs")||s.endsWith(".go")));if(r.length){e.models=[];for(let s of r.slice(0,5)){let i=await K(B.resolve(o,s));i&&e.models.push({path:s,content:Z(i,2e3),type:B.extname(s).slice(1)})}}return e}function Ve(o,e){if(e==="prisma"){let t=o.match(/model\s+(\w+)\s*\{/g);return t?t.map(n=>n.replace(/model\s+/,"").replace(/\s*\{/,"")):[]}return[]}function Xe(o){return{variables:o.split(`
2
+ `).filter(n=>n.trim()&&!n.trim().startsWith("#")).map(n=>{let[r]=n.split("="),s=r.trim(),i=n.includes("=")&&n.split("=")[1]?.trim().length>0;return{key:s,required:!i}})}}async function K(o){try{return Ye(o)?await Je.readFile(o,"utf8"):null}catch{return null}}function Z(o,e){return o.length<=e?o:o.slice(0,e)+`
3
+ ... (truncated)`}function Ie(o){let e=[];if(o.database&&e.push(`## Database Schema (${o.database.type})
4
+ `+(o.database.tables?.length?`Tables: ${o.database.tables.join(", ")}
5
+ `:"")+"```\n"+o.database.content+"\n```"),o.api&&e.push(`## API Schema (${o.api.type})
6
+ \`\`\`
7
+ `+o.api.content+"\n```"),o.env&&e.push(`## Environment Variables
8
+ `+o.env.variables.map(t=>`- ${t.key}${t.required?" (required)":""}`).join(`
9
+ `)),o.models?.length)for(let t of o.models)e.push(`## Model: ${t.path}
10
+ \`\`\``+t.type+`
11
+ `+t.content+"\n```");return e.join(`
12
+
13
+ `)}import $e from"node-fetch";var je="https://api.context7.com/v1";async function Ze(o,e){try{let t={"Content-Type":"application/json"};e&&(t.Authorization=`Bearer ${e}`);let n=await $e(`${je}/libraries/resolve`,{method:"POST",headers:t,body:JSON.stringify({name:o})});if(!n.ok)return null;let r=await n.json();return r?.libraries?.length?r.libraries[0]:null}catch{return null}}async function et(o,e,t=5e3,n){try{let r={"Content-Type":"application/json"};n&&(r.Authorization=`Bearer ${n}`);let s=await $e(`${je}/libraries/${encodeURIComponent(o)}/docs`,{method:"POST",headers:r,body:JSON.stringify({topic:e,maxTokens:t})});return s.ok&&(await s.json())?.content||null}catch{return null}}async function Oe(o,e,t){let n=[];for(let i of o.frameworks.slice(0,3))n.push(i.name);let r=["react","vue","svelte","angular","next","nuxt","express","fastify","hono","prisma","drizzle-orm","tailwindcss","shadcn","@tanstack/react-query","zod","trpc"];for(let i of r)(o.dependencies[i]||o.devDependencies[i])&&(n.includes(i)||n.push(i));let s=[];for(let i of n.slice(0,5)){let l=await Ze(i,t);if(l){let a=await et(l.id,e,3e3,t);a&&s.push(`## ${l.name} Documentation
14
+ ${a}`)}}return s.length?`# Relevant Library Documentation (via Context7)
15
+
16
+ ${s.join(`
17
+
18
+ ---
19
+
20
+ `)}`:""}var Ue={component:{type:"component",baseDir:"src/components",filePatterns:["*.tsx","*.vue","*.svelte","*.jsx","*.ts"],description:"UI component"},page:{type:"page",baseDir:"src/app",filePatterns:["*.tsx","*.vue","*.svelte","*.jsx","*.astro"],description:"Page or screen"},api:{type:"api",baseDir:"src/api",filePatterns:["*.ts","*.js","*.py","*.go","*.rs"],description:"API route or endpoint"},website:{type:"website",baseDir:".",filePatterns:["*"],description:"Multi-file website"},document:{type:"document",baseDir:"docs",filePatterns:["*.md","*.mdx","*.txt","*.rst"],description:"Documentation"},script:{type:"script",baseDir:"scripts",filePatterns:["*.ts","*.js","*.py","*.sh","*.go"],description:"Standalone script"},config:{type:"config",baseDir:".",filePatterns:["*.json","*.yaml","*.yml","*.toml","*.env"],description:"Configuration file"},skill:{type:"skill",baseDir:".skills",filePatterns:["SKILL.md"],description:"Agent skill (SKILL.md)"},media:{type:"media",baseDir:"media",filePatterns:["*.md","*.json","*.txt"],description:"Media generation prompt/description"},report:{type:"report",baseDir:"reports",filePatterns:["*.md","*.html","*.json"],description:"Analysis report"},test:{type:"test",baseDir:"src",filePatterns:["*.test.ts","*.test.tsx","*.spec.ts","*.test.js","*.test.py","*.test.go"],description:"Test suite or fixture"},workflow:{type:"workflow",baseDir:".github/workflows",filePatterns:["*.yml","*.yaml"],description:"CI/CD pipeline or automation"},schema:{type:"schema",baseDir:"src",filePatterns:["*.ts","*.prisma","*.graphql","*.gql","*.py"],description:"Database schema, validators, or types"},email:{type:"email",baseDir:"src/emails",filePatterns:["*.tsx","*.jsx","*.html","*.mjml"],description:"Email template"},diagram:{type:"diagram",baseDir:"docs",filePatterns:["*.md","*.mmd","*.d2","*.puml"],description:"Architecture or data diagram"}};function we(o,e){if(o&&o!=="auto")return o;let t=e.toLowerCase(),n=[[/\b(component|button|card|modal|dialog|form|input|dropdown|nav|sidebar|header|footer|widget|ui)\b/i,"component"],[/\b(page|screen|view|route|layout|dashboard|landing)\b/i,"page"],[/\b(api|endpoint|route handler|rest|graphql|webhook|middleware|server)\b/i,"api"],[/\b(website|site|web app|landing page|portfolio|blog)\b/i,"website"],[/\b(document|doc|readme|guide|tutorial|specification|spec|changelog)\b/i,"document"],[/\b(script|cli|command|tool|utility|migration|seed|cron)\b/i,"script"],[/\b(config|configuration|setup|env|settings)\b/i,"config"],[/\b(skill|agent skill|skill\.md)\b/i,"skill"],[/\b(video|audio|image|media|animation|thumbnail|podcast)\b/i,"media"],[/\b(report|audit|analysis|review|assessment|benchmark)\b/i,"report"],[/\b(test|spec|unit test|integration test|e2e|coverage|fixture|mock)\b/i,"test"],[/\b(workflow|ci|cd|pipeline|github action|deploy|automation|ci\/cd)\b/i,"workflow"],[/\b(schema|model|migration|prisma|drizzle|zod|validator|graphql type)\b/i,"schema"],[/\b(email|newsletter|transactional|invite|welcome email|notification email)\b/i,"email"],[/\b(diagram|erd|flowchart|architecture diagram|sequence diagram|mermaid|plantuml|d2)\b/i,"diagram"]];for(let[r,s]of n)if(r.test(t))return s;return"component"}import{existsSync as rt,promises as Ge}from"fs";import te from"path";import tt from"prompts";import ot from"chalk";import{z as D}from"zod";var Ee=["default","acceptEdits","plan","yolo"],De=D.enum(Ee),be=D.object({mode:De.default("default"),allow:D.array(D.string()).default([]),deny:D.array(D.string()).default([]),confirm:D.array(D.string()).default([])});function nt(o,e){let t=e.replace(/\./g,"\\.").replace(/\*\*/g,"{{GLOBSTAR}}").replace(/\*/g,"[^/]*").replace(/\{\{GLOBSTAR\}\}/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${t}$`).test(o)}var ee=class{mode;allowPatterns;denyPatterns;confirmPatterns;autoAllowAll=!1;constructor(e){let t=be.parse(e||{});this.mode=t.mode,this.allowPatterns=t.allow,this.denyPatterns=t.deny,this.confirmPatterns=t.confirm}getMode(){return this.mode}setMode(e){this.mode=e,this.autoAllowAll=!1,v.context("permissions",`mode set to ${e}`)}async checkFileWrite(e){if(v.context("permissions",`checking write: ${e} (mode: ${this.mode})`),this.matchesAny(e,this.denyPatterns))return v.context("permissions",`denied by pattern: ${e}`),"deny";switch(this.mode){case"yolo":return"allow";case"plan":return"skip";case"acceptEdits":return"allow";case"default":return this.autoAllowAll||this.matchesAny(e,this.allowPatterns)?"allow":this.promptUser(e);default:return"allow"}}async checkCommand(e){return this.mode==="yolo"?"allow":this.mode==="plan"?"deny":"allow"}matchesAny(e,t){return t.some(n=>nt(e,n))}async promptUser(e){let{action:t}=await tt({type:"select",name:"action",message:`Write file ${ot.cyan(e)}?`,choices:[{title:"Yes",value:"allow"},{title:"No",value:"deny"},{title:"All (allow remaining)",value:"all"},{title:"Skip",value:"skip"}],initial:0});return t==="all"?(this.autoAllowAll=!0,"allow"):t||"deny"}},N=new ee;async function oe(o,e){let t={written:[],skipped:[],errors:[]};for(let n of o){let r=te.isAbsolute(n.path)?n.path:te.resolve(e.cwd,e.outputDir||"",n.path);try{let s=n.content;if(p.has("pre:file-write")){let h=await p.execute("pre:file-write",{event:"pre:file-write",file:r,fileContent:s,cwd:e.cwd});if(h.blocked){t.skipped.push(r);continue}h.modified?.fileContent&&(s=String(h.modified.fileContent))}let i=te.relative(e.cwd,r),l=await N.checkFileWrite(i);if(l==="deny"){t.skipped.push(r);continue}if(l==="skip"){t.written.push(r);continue}if(rt(r)&&!e.overwrite){t.skipped.push(r);continue}if(e.dryRun){t.written.push(r);continue}let a=te.dirname(r);await Ge.mkdir(a,{recursive:!0}),await Ge.writeFile(r,s,"utf8"),t.written.push(r),p.has("post:file-write")&&await p.execute("post:file-write",{event:"post:file-write",file:r,fileContent:s,cwd:e.cwd})}catch(s){t.errors.push(`${r}: ${s.message}`)}}return t}function ne(o,e,t){if(t)return t;let n=Ue[o];if(!n)return"generated";let r=n.baseDir;return o==="component"&&(e.srcDir?r=`${e.srcDir}/components`:r="components"),o==="page"&&e.frameworks.find(i=>i.name==="nextjs")&&e.srcDir&&(r=`${e.srcDir}/app`),o==="api"&&e.frameworks.find(i=>i.name==="nextjs")&&(r=e.srcDir?`${e.srcDir}/app/api`:"app/api"),o==="test"&&(e.testing.includes("vitest")||e.testing.includes("jest"))&&(r=e.srcDir||"src"),o==="workflow"&&(r=".github/workflows"),o==="schema"&&(e.databases.includes("prisma")?r="prisma":e.srcDir&&(r=`${e.srcDir}/schemas`)),o==="email"&&(r=e.srcDir?`${e.srcDir}/emails`:"emails"),r}import st from"os";var it=st.homedir(),Y=class{constructor(e){this.cwd=e;this.userMemory=new ge(it),this.projectMemory=new ge(e)}userMemory;projectMemory;async load(){await Promise.all([this.userMemory.load(),this.projectMemory.load()])}async save(){await Promise.all([this.userMemory.save(),this.projectMemory.save()])}buildMemoryContext(e){let t=this.userMemory.buildMemoryContext(e),n=this.projectMemory.buildMemoryContext(e);if(!t&&!n)return"";let r=[];return n&&r.push(n),t&&r.push(t.replace("# Memory (learned from past interactions)","# Global Memory (cross-project patterns)")),r.join(`
21
+
22
+ `)}async learnPreference(e,t,n){await this.userMemory.learnPreference(e,t,n)}async recordGeneration(e){return this.projectMemory.recordGeneration(e)}getPreferences(){let e=this.userMemory.getPreferences(),t=this.projectMemory.getPreferences(),n=new Map;for(let r of e)n.set(r.key,r);for(let r of t)n.set(r.key,r);return Array.from(n.values())}getPatterns(){let e=this.userMemory.getPatterns();return[...this.projectMemory.getPatterns(),...e]}getStats(){return{user:this.userMemory.getStats(),project:this.projectMemory.getStats()}}getRecentGenerations(e=10){return this.projectMemory.getRecentGenerations(e)}};import{existsSync as Fe,readFileSync as Ne}from"fs";import Le from"path";function qe(o,e){return o.replace(/@([\w./-]+)/g,(t,n)=>{let r=Le.resolve(e,n);if(Fe(r))try{return Ne(r,"utf8")}catch{return t}return t})}function ke(o){let e=["SHADXN.md","CLAUDE.md"];for(let t of e){let n=Le.join(o,t);if(Fe(n))try{let r=Ne(n,"utf8");return r=qe(r,o),r}catch{}}return""}function at(o){return Math.ceil(o.length/4)}var xe=class{sections=[];addSection(e,t,n=50){t.trim()&&this.sections.push({label:e,content:t,priority:n})}buildContext(e,t=12e3){if(this.sections.length===0)return"";let n=this.sections.map(c=>c.content),r=he(n),s=ye(e,r),i=new Map(s.map(c=>[c.docIndex,c.score])),l=this.sections.map((c,f)=>({...c,relevance:i.get(f)??0,tokens:at(c.content)}));l.sort((c,f)=>f.priority+f.relevance*100-(c.priority+c.relevance*100));let a=[],h=0;for(let c of l)h+c.tokens>t&&a.length>0||(a.push(c),h+=c.tokens);return a.map(c=>c.content).join(`
23
+
24
+ `)}};import{promises as J}from"fs";import re from"path";import{execa as lt}from"execa";import Be from"fast-glob";var Q=class{cwd;options;constructor(e,t={}){this.cwd=e,this.options=t}async execute(e){if(v.context("tool-executor",`executing: ${e.name}`),p.has("pre:tool-call")){let n=await p.execute("pre:tool-call",{event:"pre:tool-call",toolName:e.name,toolInput:e.input,cwd:this.cwd});if(n.blocked)return{tool_use_id:e.id,content:n.message||`Tool ${e.name} blocked by pre:tool-call hook`,is_error:!0}}let t;try{switch(e.name){case"read_file":t=await this.readFile(e);break;case"search_files":t=await this.searchFiles(e);break;case"list_directory":t=await this.listDirectory(e);break;case"run_command":t=await this.runCommand(e);break;case"edit_file":t=await this.editFile(e);break;case"create_files":t=await this.createFiles(e);break;case"ask_user":t=await this.askUser(e);break;case"spawn_agent":t=await this.spawnAgent(e);break;default:t={tool_use_id:e.id,content:`Unknown tool: ${e.name}`,is_error:!0}}}catch(n){t={tool_use_id:e.id,content:`Error executing ${e.name}: ${n.message}`,is_error:!0}}return p.has("post:tool-call")&&await p.execute("post:tool-call",{event:"post:tool-call",toolName:e.name,toolInput:e.input,toolResult:t.content,cwd:this.cwd}),t}async readFile(e){let t=String(e.input.path||""),n=Number(e.input.max_lines)||500,r=re.resolve(this.cwd,t),s=await J.readFile(r,"utf8"),i=s.split(`
25
+ `),a=i.length>n?i.slice(0,n).join(`
26
+ `)+`
27
+
28
+ ... (truncated, ${i.length-n} more lines)`:s;return{tool_use_id:e.id,content:a}}async searchFiles(e){let t=String(e.input.pattern||"**/*"),n=e.input.content_regex?String(e.input.content_regex):void 0,r=Number(e.input.max_results)||50,s=await Be(t,{cwd:this.cwd,ignore:["node_modules/**",".git/**","dist/**",".next/**"],dot:!1});if(!n){let a=s.slice(0,r);return{tool_use_id:e.id,content:a.length?a.join(`
29
+ `)+(s.length>r?`
30
+
31
+ ... (${s.length-r} more files)`:""):"No files matched the pattern."}}let i=new RegExp(n,"gm"),l=[];for(let a of s){if(l.length>=r)break;try{let c=(await J.readFile(re.resolve(this.cwd,a),"utf8")).split(`
32
+ `);for(let f=0;f<c.length&&!(l.length>=r);f++)i.test(c[f])&&l.push(`${a}:${f+1}: ${c[f]}`),i.lastIndex=0}catch{}}return{tool_use_id:e.id,content:l.length?l.join(`
33
+ `):"No matches found."}}async listDirectory(e){let t=String(e.input.path||"."),n=!!e.input.recursive,r=Number(e.input.max_depth)||3,s=re.resolve(this.cwd,t);if(n){let h=await Be("**/*",{cwd:s,onlyFiles:!1,markDirectories:!0,deep:r,ignore:["node_modules/**",".git/**","dist/**",".next/**"]});return{tool_use_id:e.id,content:h.length?h.join(`
34
+ `):"Empty directory."}}let l=(await J.readdir(s,{withFileTypes:!0})).map(a=>a.isDirectory()?`${a.name}/`:a.name);return{tool_use_id:e.id,content:l.length?l.join(`
35
+ `):"Empty directory."}}async runCommand(e){let t=String(e.input.command||""),n=Number(e.input.timeout)||3e4;if(await N.checkCommand(t)==="deny")return{tool_use_id:e.id,content:`Command blocked by permissions (mode: ${N.getMode()}): ${t}`,is_error:!0};if(p.has("pre:command")){let a=await p.execute("pre:command",{event:"pre:command",command:t,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`Command blocked by pre:command hook: ${t}`,is_error:!0}}let s=await lt("sh",["-c",t],{cwd:this.cwd,timeout:n,reject:!1,stdin:"ignore"}),i=[s.stdout,s.stderr].filter(Boolean).join(`
36
+ `),l=i.length>1e4?i.slice(0,1e4)+`
37
+
38
+ ... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
39
+ ${l}`,is_error:!0}:{tool_use_id:e.id,content:l||"(no output)"}}async editFile(e){let t=String(e.input.path||""),n=e.input.edits,r=re.resolve(this.cwd,t);if(!n||n.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await N.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(p.has("pre:file-write")){let a=await p.execute("pre:file-write",{event:"pre:file-write",file:r,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await J.readFile(r,"utf8"),l=[];for(let a of n)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),l.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):l.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await J.writeFile(r,i,"utf8"),p.has("post:file-write")&&await p.execute("post:file-write",{event:"post:file-write",file:r,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
40
+ ${l.join(`
41
+ `)}`}}async createFiles(e){let t=e.input,n=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${n.length} file(s) for creation.`,files:n}}async spawnAgent(e){let t=String(e.input.agent_id||""),n=String(e.input.prompt||""),r=Number(e.input.timeout_seconds)||300;if(!t||!n)return{tool_use_id:e.id,content:"agent_id and prompt are required.",is_error:!0};try{let{SubAgentManager:s}=await import("./subagent-WV7QKQ3L.js"),{getGlobalRegistry:i}=await import("./registry-FP6FUOXF.js"),l=i();if(!l)return{tool_use_id:e.id,content:"Sub-agent spawning requires the daemon to be running.",is_error:!0};let h=await new s(l).spawn({targetAgentId:t,prompt:n,parentAgentId:"orchestrator",timeout:r*1e3});return h.success?{tool_use_id:e.id,content:`Sub-agent "${t}" completed (${Math.round(h.duration/1e3)}s):
42
+
43
+ ${h.content}`}:{tool_use_id:e.id,content:`Sub-agent "${t}" failed: ${h.error}`,is_error:!0}}catch(s){return{tool_use_id:e.id,content:`Failed to spawn sub-agent: ${s.message}`,is_error:!0}}}async askUser(e){let t=String(e.input.question||""),n=e.input.options,r=t;return n?.length&&(r+=`
44
+ Options: ${n.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:r}}};async function ve(o){let{provider:e,systemPrompt:t,messages:n,providerOptions:r,cwd:s,maxIterations:i=20,enabledTools:l,interactive:a=!0,overwrite:h=!1,dryRun:c=!1,onProgress:f}=o;if(!e.generateRaw)return We(o);let x=new Q(s,{interactive:a,overwrite:h,dryRun:c}),b=de(l),$=n.filter(k=>k.role!=="system").map(k=>({role:k.role,content:k.content})),G=[],C=0,S="",O,M=0;for(;M<i;){M++,f?.({type:"iteration_start",iteration:M}),v.step(M,`Agentic loop iteration (${b.length} tools available)`);let k;try{k=await e.generateRaw($,t,b,r)}catch(y){if(y.message?.includes("not available"))return We(o);throw y}C+=k.usage.input_tokens+k.usage.output_tokens;for(let y of k.content)y.type==="text"&&(S+=y.text,f?.({type:"text_delta",text:y.text}));if(k.stop_reason==="end_turn"||k.stop_reason==="max_tokens")break;if(k.stop_reason==="tool_use"){let y=k.content.filter(_=>_.type==="tool_use");if(y.length===0)break;$.push({role:"assistant",content:k.content});let I=[];for(let _ of y){f?.({type:"tool_call",name:_.name,id:_.id,input:_.input}),v.step(M,`Tool call: ${_.name}`);let w=await x.execute({name:_.name,id:_.id,input:_.input});f?.({type:"tool_result",name:_.name,id:_.id,content:w.content.slice(0,200),is_error:w.is_error}),w.files?.length&&(G.push(...w.files),f?.({type:"files_created",files:w.files})),w.followUp&&(O=w.followUp),I.push({type:"tool_result",tool_use_id:w.tool_use_id,content:w.content,is_error:w.is_error})}if($.push({role:"user",content:I}),O)break;continue}break}return f?.({type:"complete",iterations:M,totalTokens:C}),{files:G,content:S,followUp:O,tokensUsed:C,iterations:M}}async function We(o){let{provider:e,systemPrompt:t,messages:n,providerOptions:r,maxIterations:s=5}=o,l=[{role:"system",content:t+`
45
+
46
+ `+ue()},...n.filter(b=>b.role!=="system")],a=[],h=0,c="",f,x=0;for(;x<s;){x++,v.step(x,`Legacy loop step (model: ${r.model||"default"})`);let b=await e.generate(l,r);if(h+=b.tokensUsed||0,c=b.content,b.files.length&&a.push(...b.files),b.followUp){f=b.followUp;break}if(b.files.length===0&&x>1||!(b.content.includes("[CONTINUE]")||b.content.includes("Next, I'll")||b.content.includes("Now let me")||b.content.includes("I'll also generate")))break;let G=b.files.map(C=>`Created: ${C.path}${C.description?` \u2014 ${C.description}`:""}`).join(`
47
+ `);l.push({role:"assistant",content:b.content+(G?`
48
+
49
+ Files created:
50
+ ${G}`:"")}),l.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."})}return{files:a,content:c,followUp:f,tokensUsed:h,iterations:x}}function _e(o){return typeof o.generateRaw=="function"}var se=class{queue=[];resolvers=[];closed=!1;push(e){if(this.closed)return;let t=this.resolvers.shift();if(t){t({value:e,done:!1});return}this.queue.push(e)}close(){if(!this.closed){this.closed=!0;for(let e of this.resolvers.splice(0))e({value:void 0,done:!0})}}async next(){return this.queue.length?{value:this.queue.shift(),done:!1}:this.closed?{value:void 0,done:!0}:new Promise(e=>{this.resolvers.push(e)})}async*[Symbol.asyncIterator](){for(;;){let{value:e,done:t}=await this.next();if(t)return;yield e}}};async function ze(o,e,t){let n=Re.parse(t||{}),r=new Y(o);await r.load();let[s,i,l]=await Promise.all([Ce(o),Me(o),Te(o)]),a="";if(n.context7.enabled)try{a=await Oe(s,e,n.context7.apiKey)}catch{}let h=r.buildMemoryContext(e),c=ke(o);return v.context("memory",h?"loaded":"empty"),v.context("instructions",c?"loaded from project":"none"),{techStack:s,schemas:i,skills:l,docs:a,config:n,memoryContext:h,projectInstructions:c}}async function Oo(o){let{task:e,cwd:t,overwrite:n=!1,dryRun:r=!1,provider:s="claude-code",model:i,apiKey:l,context7:a=!0,interactive:h=!0}=o,c=e;if(p.has("pre:prompt")){let u=await p.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by pre:prompt hook");u.modified?.task&&(c=String(u.modified.task))}if(p.has("pre:generate")){let u=await p.execute("pre:generate",{event:"pre:generate",task:c,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by pre:generate hook")}F.info("Analyzing project...");let f=await ze(t,c,{provider:s,context7:{enabled:a,apiKey:l}}),x=we(o.outputType,c);F.info(`Output type: ${x}`);let b=fe(f.skills,c,x);b.length&&F.info(`Loaded ${b.length} relevant skill(s): ${b.map(u=>u.skill.frontmatter.name).join(", ")}`);let $=He(f,x,b.map(u=>u.skill));if(!await pe(l))throw new Error("No credentials configured. Run `agentx model` to set up.");let C=me(s,l),S=i||ce()?.model,O=[...o.sessionMessages||[],{role:"user",content:c}];F.info("Generating...");let M=_e(C),k=o.maxSteps??(M?20:5),y=await ve({provider:C,systemPrompt:$,messages:[{role:"system",content:$},...O],providerOptions:{model:S,maxTokens:8192},cwd:t,maxIterations:k,enabledTools:f.config.agentic.enabledTools.filter(u=>!f.config.agentic.disabledTools.includes(u)),interactive:h,overwrite:n,dryRun:r,onProgress:u=>{u.type==="iteration_start"&&u.iteration>1&&F.info(`Step ${u.iteration}/${k}...`),u.type==="tool_call"&&v.step(0,`Tool: ${u.name}`)}});if(y.tokensUsed){let u=S||"claude-sonnet-4-20250514",L=Math.round(y.tokensUsed*.3),ie=y.tokensUsed-L;X.recordStep(1,u,L,ie)}let{content:I}=y,{followUp:_,tokensUsed:w}=y;if(y.iterations>1&&F.info(`Completed in ${y.iterations} step(s)`),p.has("post:response")){let u=await p.execute("post:response",{event:"post:response",content:I,task:c,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by post:response hook");u.modified?.content&&(I=String(u.modified.content))}if(_&&h)return{files:{written:[],skipped:[],errors:[]},content:I,outputType:x,followUp:_,tokensUsed:w};let U=new Map;for(let u of y.files)U.set(u.path,u);let A=ne(x,f.techStack,o.outputDir),T=await oe(Array.from(U.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:A}),j;if(o.heal!==!1&&!r&&T.written.length>0){let{HealEngine:u}=await import("./heal-OTGT5HHJ.js");j=await new u(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(T.written,c),!j.healed&&j.error&&await p.execute("on:error",{event:"on:error",error:new Error(j.error),task:c,cwd:t})}return p.has("post:generate")&&await p.execute("post:generate",{event:"post:generate",task:c,content:I,cwd:t}),{files:T,content:I,outputType:x,tokensUsed:w,healResult:j}}async function*Uo(o){let{task:e,cwd:t,overwrite:n=!1,dryRun:r=!1,provider:s="claude-code",model:i,apiKey:l,context7:a=!0,interactive:h=!0}=o,c=e;if(p.has("pre:prompt")){let d=await p.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by pre:prompt hook"};return}d.modified?.task&&(c=String(d.modified.task))}if(p.has("pre:generate")){let d=await p.execute("pre:generate",{event:"pre:generate",task:c,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by pre:generate hook"};return}}let f=await ze(t,c,{provider:s,context7:{enabled:a,apiKey:l}}),x=we(o.outputType,c);yield{type:"context_ready",outputType:x};let b=fe(f.skills,c,x),$=He(f,x,b.map(d=>d.skill));if(!await pe(l)){yield{type:"error",error:"No credentials configured. Run `agentx model` to set up."};return}let C=me(s,l),S=i||ce()?.model,O=_e(C),M=o.maxSteps??(O?20:5),k=[...o.sessionMessages||[],{role:"user",content:c}];if(O){let d=new se,P,g,q=(async()=>{try{P=await ve({provider:C,systemPrompt:$,messages:[{role:"system",content:$},...k],providerOptions:{model:S,maxTokens:8192},cwd:t,maxIterations:M,enabledTools:f.config.agentic.enabledTools.filter(m=>!f.config.agentic.disabledTools.includes(m)),interactive:h,overwrite:n,dryRun:r,onProgress:m=>{m.type==="text_delta"&&d.push({type:"text_delta",text:m.text}),m.type==="iteration_start"&&d.push({type:"iteration",iteration:m.iteration}),m.type==="tool_call"&&d.push({type:"tool_call",name:m.name,id:m.id}),m.type==="tool_result"&&d.push({type:"tool_result",name:m.name,id:m.id,is_error:m.is_error}),m.type==="files_created"&&d.push({type:"step_complete",step:0,filesCount:m.files.length})}})}catch(m){g=m}finally{d.close()}})();for await(let m of d)yield m;if(await q,g){yield{type:"error",error:g instanceof Error?g.message:String(g)};return}if(!P){yield{type:"error",error:"Agentic loop failed without a result"};return}yield{type:"done",result:{content:P.content,files:P.files,tokensUsed:P.tokensUsed,followUp:P.followUp}};let{content:E}=P;if(p.has("post:response")){let m=await p.execute("post:response",{event:"post:response",content:E,task:c,cwd:t});if(m.blocked){yield{type:"error",error:m.message||"Blocked by post:response hook"};return}m.modified?.content&&(E=String(m.modified.content))}if(P.followUp&&h){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:E,outputType:x,followUp:P.followUp,tokensUsed:P.tokensUsed}};return}let z=new Map;for(let m of P.files)z.set(m.path,m);let le=ne(x,f.techStack,o.outputDir),V=await oe(Array.from(z.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:le}),H;if(o.heal!==!1&&!r&&V.written.length>0){let{HealEngine:m}=await import("./heal-OTGT5HHJ.js");H=await new m(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(V.written,c)}p.has("post:generate")&&await p.execute("post:generate",{event:"post:generate",task:c,content:E,cwd:t}),yield{type:"generate_result",result:{files:V,content:E,outputType:x,tokensUsed:P.tokensUsed,healResult:H}};return}let y=[{role:"system",content:$},...k],I=[],_=0,w="",U,A=0;A++,v.step(A,`Starting generation (model: ${S||"default"})`);let T;if(C.stream){let d="",P;for await(let g of C.stream(y,{model:S,maxTokens:8192}))yield g,g.type==="text_delta"&&(d+=g.text),g.type==="done"&&(P=g.result);T=P||{content:d,files:[],tokensUsed:0}}else{let d=await C.generate(y,{model:S,maxTokens:8192});d.content&&(yield{type:"text_delta",text:d.content}),yield{type:"done",result:d},T=d}_+=T.tokensUsed||0,w=T.content;let j=T.tokensUsed||0,u=S||"claude-sonnet-4-20250514",L=Math.round(j*.3),ie=j-L;if(X.recordStep(A,u,L,ie),v.api("generate",u,j),v.step(A,`Generated ${T.files.length} file(s), ${j} tokens`),T.files.length&&I.push(...T.files),T.followUp&&(U=T.followUp),yield{type:"step_complete",step:A,filesCount:T.files.length},!U&&(w.includes("[CONTINUE]")||w.includes("Next, I'll")||w.includes("Now let me")||w.includes("I'll also generate"))&&T.files.length>0){let P=T.files.map(g=>`Created: ${g.path}${g.description?` \u2014 ${g.description}`:""}`).join(`
51
+ `);for(y.push({role:"assistant",content:w+(P?`
52
+
53
+ Files created:
54
+ ${P}`:"")}),y.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."});A<M;){A++,v.step(A,`Starting generation (model: ${S||"default"})`);let g=await C.generate(y,{model:S,maxTokens:8192});_+=g.tokensUsed||0,w=g.content;let q=g.tokensUsed||0,E=S||"claude-sonnet-4-20250514",z=Math.round(q*.3),le=q-z;if(X.recordStep(A,E,z,le),v.api("generate",E,q),v.step(A,`Generated ${g.files.length} file(s), ${q} tokens`),g.files.length&&I.push(...g.files),yield{type:"step_complete",step:A,filesCount:g.files.length},g.followUp){U=g.followUp;break}if(g.files.length===0&&A>1||!(g.content.includes("[CONTINUE]")||g.content.includes("Next, I'll")||g.content.includes("Now let me")||g.content.includes("I'll also generate")))break;let H=g.files.map(m=>`Created: ${m.path}${m.description?` \u2014 ${m.description}`:""}`).join(`
55
+ `);y.push({role:"assistant",content:g.content+(H?`
56
+
57
+ Files created:
58
+ ${H}`:"")}),y.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."})}}if(p.has("post:response")){let d=await p.execute("post:response",{event:"post:response",content:w,task:c,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by post:response hook"};return}d.modified?.content&&(w=String(d.modified.content))}if(U&&h){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:w,outputType:x,followUp:U,tokensUsed:_}};return}let Pe=new Map;for(let d of I)Pe.set(d.path,d);let Ke=ne(x,f.techStack,o.outputDir),ae=await oe(Array.from(Pe.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:Ke}),W;if(o.heal!==!1&&!r&&ae.written.length>0){let{HealEngine:d}=await import("./heal-OTGT5HHJ.js");W=await new d(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(ae.written,c),!W.healed&&W.error&&await p.execute("on:error",{event:"on:error",error:new Error(W.error),task:c,cwd:t})}p.has("post:generate")&&await p.execute("post:generate",{event:"post:generate",task:c,content:w,cwd:t}),yield{type:"generate_result",result:{files:ae,content:w,outputType:x,tokensUsed:_,healResult:W}}}function He(o,e,t){let n=[];n.push(`You are agentx, an agentic code generation tool. You generate high-quality, production-ready output for any tech stack.
59
+
60
+ Your primary tool is \`create_files\` \u2014 use it to output all generated code, documents, and configs as files.
61
+ If the request is ambiguous or you need critical information to proceed correctly, use \`ask_user\` to ask a clarifying question.
62
+
63
+ You also have tools to inspect the codebase before generating code:
64
+ - \`read_file\` \u2014 read existing files to understand patterns, styles, and implementations
65
+ - \`search_files\` \u2014 search for files by glob pattern, optionally grep content with regex
66
+ - \`list_directory\` \u2014 explore the project structure
67
+ - \`run_command\` \u2014 run shell commands (build, test, lint, etc.)
68
+ - \`edit_file\` \u2014 apply targeted search/replace edits to existing files
69
+
70
+ AGENTIC WORKFLOW:
71
+ - Before generating code, use \`read_file\` and \`search_files\` to understand the existing codebase
72
+ - Match the project's existing patterns, naming conventions, and code style
73
+ - After creating files, consider running tests or build commands to verify correctness
74
+ - Use \`edit_file\` for small, targeted changes instead of rewriting entire files
75
+
76
+ IMPORTANT RULES:
77
+ - Generate complete, working code \u2014 not stubs or placeholders
78
+ - Follow the project's existing patterns and conventions
79
+ - Use the detected tech stack to choose the right language, framework, and patterns
80
+ - File paths should be relative to the project root
81
+ - Include all necessary imports
82
+ - Do NOT add unnecessary dependencies
83
+
84
+ MULTI-STEP GENERATION:
85
+ For complex tasks that require multiple related files (e.g., schema + API + UI + tests), you can chain steps:
86
+ - Generate the foundational files first (schemas, types, configs)
87
+ - Include "[CONTINUE]" in your response text when there are more files to generate
88
+ - In subsequent steps, you'll see what was already created \u2014 build on it
89
+ - When all files are generated, do NOT include "[CONTINUE]"
90
+ - This enables you to generate a schema first, then an API that references it, then a UI that calls the API`),n.push(`# Project Tech Stack
91
+ ${Se(o.techStack)}`);let r=Object.keys(o.techStack.dependencies).slice(0,30);r.length&&n.push(`# Key Dependencies
92
+ ${r.join(", ")}`);let s=Ie(o.schemas);return s&&n.push(`# Project Schemas
93
+ ${s}`),t.length&&n.push(`# Active Skills
94
+ Follow these skill instructions when applicable:
95
+
96
+ `+t.map(i=>`## Skill: ${i.frontmatter.name}
97
+ ${i.frontmatter.description}
98
+
99
+ ${i.instructions}`).join(`
100
+
101
+ ---
102
+
103
+ `)),o.docs&&n.push(o.docs),o.projectInstructions&&n.push(`# Project Instructions
104
+ ${o.projectInstructions}`),o.memoryContext&&n.push(o.memoryContext),n.push(`# Output Type: ${e}
105
+ Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),n.join(`
106
+
107
+ `)}export{Re as a,dt as b,ut as c,Me as d,Ie as e,Oe as f,Ue as g,we as h,Ee as i,De as j,be as k,ee as l,N as m,Y as n,qe as o,ke as p,xe as q,Q as r,ze as s,Oo as t,Uo as u};
108
+ //# sourceMappingURL=chunk-SBUX74OU.js.map