agentix-cli 0.8.0 → 0.13.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 (71) hide show
  1. package/README.md +387 -116
  2. package/dist/agent-5KIMJI3F.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-CJ45Y2IR.js +12 -0
  7. package/dist/chunk-CJ45Y2IR.js.map +1 -0
  8. package/dist/chunk-D6EDMQRV.js +108 -0
  9. package/dist/chunk-D6EDMQRV.js.map +1 -0
  10. package/dist/chunk-DSYKYZMT.js +2 -0
  11. package/dist/chunk-DSYKYZMT.js.map +1 -0
  12. package/dist/chunk-HI24KAEY.js +54 -0
  13. package/dist/chunk-HI24KAEY.js.map +1 -0
  14. package/dist/{chunk-MGMZNJCE.js → chunk-KXZMYLHQ.js} +27 -27
  15. package/dist/chunk-KXZMYLHQ.js.map +1 -0
  16. package/dist/chunk-MCJUAE6V.js +6 -0
  17. package/dist/chunk-MCJUAE6V.js.map +1 -0
  18. package/dist/chunk-QOYAX2FT.js +2 -0
  19. package/dist/chunk-QOYAX2FT.js.map +1 -0
  20. package/dist/chunk-QZP65I2H.js +45 -0
  21. package/dist/chunk-QZP65I2H.js.map +1 -0
  22. package/dist/chunk-T25UEXVK.js +126 -0
  23. package/dist/chunk-T25UEXVK.js.map +1 -0
  24. package/dist/chunk-VH23CDHL.js +157 -0
  25. package/dist/chunk-VH23CDHL.js.map +1 -0
  26. package/dist/chunk-WJ6ZF6EZ.js +6 -0
  27. package/dist/chunk-WJ6ZF6EZ.js.map +1 -0
  28. package/dist/chunk-ZRYBSI5G.js +23 -0
  29. package/dist/chunk-ZRYBSI5G.js.map +1 -0
  30. package/dist/cli.js +277 -36
  31. package/dist/cli.js.map +1 -1
  32. package/dist/compaction-7I3E5QUO.js +28 -0
  33. package/dist/compaction-7I3E5QUO.js.map +1 -0
  34. package/dist/config-HAD5E4YX.js +2 -0
  35. package/dist/debug-N3B5NVJU.js +2 -0
  36. package/dist/heal-OTGT5HHJ.js +2 -0
  37. package/dist/index.d.ts +1849 -368
  38. package/dist/index.js +39 -35
  39. package/dist/index.js.map +1 -1
  40. package/dist/loader-YQE6XJBT.js +2 -0
  41. package/dist/loader-YQE6XJBT.js.map +1 -0
  42. package/dist/memory-extract-RGPUPMKU.js +2 -0
  43. package/dist/memory-extract-RGPUPMKU.js.map +1 -0
  44. package/dist/{providers-AVYG63KK.js → providers-G3WZ4RVJ.js} +2 -2
  45. package/dist/providers-G3WZ4RVJ.js.map +1 -0
  46. package/dist/registry-CDWY7CLL.js +2 -0
  47. package/dist/registry-CDWY7CLL.js.map +1 -0
  48. package/dist/subagent-WV7QKQ3L.js +3 -0
  49. package/dist/subagent-WV7QKQ3L.js.map +1 -0
  50. package/dist/usage-dashboard-2TJQBFSH.js +404 -0
  51. package/dist/usage-dashboard-2TJQBFSH.js.map +1 -0
  52. package/dist/workspace-setup-QQTCJY4B.js +2 -0
  53. package/dist/workspace-setup-QQTCJY4B.js.map +1 -0
  54. package/package.json +4 -1
  55. package/dist/agent-K2YOEOJ5.js +0 -2
  56. package/dist/chunk-F73GPYCO.js +0 -106
  57. package/dist/chunk-F73GPYCO.js.map +0 -1
  58. package/dist/chunk-FRFR27IN.js +0 -3
  59. package/dist/chunk-FRFR27IN.js.map +0 -1
  60. package/dist/chunk-MGMZNJCE.js.map +0 -1
  61. package/dist/chunk-NGKOM4ZZ.js +0 -137
  62. package/dist/chunk-NGKOM4ZZ.js.map +0 -1
  63. package/dist/chunk-Z4GC5D6D.js +0 -12
  64. package/dist/chunk-Z4GC5D6D.js.map +0 -1
  65. package/dist/heal-UV5A6B5T.js +0 -2
  66. package/dist/loader-6VSM6FSY.js +0 -2
  67. /package/dist/{agent-K2YOEOJ5.js.map → agent-5KIMJI3F.js.map} +0 -0
  68. /package/dist/{chunk-X7UN6JAA.js.map → chunk-6MKAXEE5.js.map} +0 -0
  69. /package/dist/{heal-UV5A6B5T.js.map → config-HAD5E4YX.js.map} +0 -0
  70. /package/dist/{loader-6VSM6FSY.js.map → debug-N3B5NVJU.js.map} +0 -0
  71. /package/dist/{providers-AVYG63KK.js.map → heal-OTGT5HHJ.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent/providers/types.ts","../src/agent/context/schema.ts","../src/agent/context/context7.ts","../src/agent/outputs/types.ts","../src/agent/outputs/handlers.ts","../src/permissions/manager.ts","../src/permissions/types.ts","../src/memory/hierarchy.ts","../src/memory/context-builder.ts","../src/agent/tools/executor.ts","../src/agent/orchestrator.ts","../src/utils/async-queue.ts","../src/agent/index.ts"],"sourcesContent":["import { z } from \"zod\"\n\n// --- Provider abstraction ---\n\nexport interface GenerationMessage {\n role: \"user\" | \"assistant\" | \"system\"\n content: string\n}\n\nexport interface GenerationResult {\n content: string\n files: GeneratedFile[]\n followUp?: string // Agent may ask for more info\n tokensUsed?: number\n}\n\nexport interface GeneratedFile {\n path: string\n content: string\n language?: string\n description?: string\n}\n\nexport interface ProviderOptions {\n model?: string\n maxTokens?: number\n temperature?: number\n apiKey?: string\n}\n\nexport type StreamEvent =\n | { type: \"text_delta\"; text: string }\n | { type: \"tool_use_start\"; name: string; id: string }\n | { type: \"tool_use_delta\"; json: string }\n | { type: \"tool_use_end\"; name: string }\n | { type: \"done\"; result: GenerationResult }\n | { type: \"error\"; error: string }\n\n// --- Raw (agentic) API types ---\n\nexport interface AnthropicMessage {\n role: \"user\" | \"assistant\"\n content: string | ContentBlock[]\n}\n\nexport type ContentBlock =\n | { type: \"text\"; text: string }\n | { type: \"tool_use\"; id: string; name: string; input: Record<string, unknown> }\n | { type: \"tool_result\"; tool_use_id: string; content: string; is_error?: boolean }\n\nexport interface RawGenerationResult {\n content: ContentBlock[]\n stop_reason: \"end_turn\" | \"tool_use\" | \"max_tokens\" | \"stop_sequence\"\n usage: { input_tokens: number; output_tokens: number }\n}\n\nexport interface AgentProvider {\n name: string\n generate(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): Promise<GenerationResult>\n stream?(\n messages: GenerationMessage[],\n options?: ProviderOptions\n ): AsyncIterable<StreamEvent>\n /** Low-level method returning raw content blocks for the agentic tool_result loop */\n 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}\n\n// --- Agent configuration ---\n\nexport const agentConfigSchema = z.object({\n provider: z.enum([\"claude-code\", \"claude\", \"openai\", \"ollama\", \"custom\"]).default(\"claude-code\"),\n model: z.string().optional(),\n apiKey: z.string().optional(),\n skills: z.array(z.string()).default([]),\n output: z\n .object({\n dir: z.string().default(\"./generated\"),\n })\n .default({}),\n context7: z\n .object({\n enabled: z.boolean().default(true),\n apiKey: z.string().optional(),\n })\n .default({}),\n agentic: z\n .object({\n maxIterations: z.number().default(20),\n enabledTools: z.array(z.string()).default([\n \"create_files\", \"ask_user\", \"read_file\",\n \"search_files\", \"list_directory\", \"run_command\", \"edit_file\",\n ]),\n disabledTools: z.array(z.string()).default([]),\n })\n .default({}),\n})\n\nexport type AgentConfig = z.infer<typeof agentConfigSchema>\n\n// --- Output types ---\n\nexport const OUTPUT_TYPES = [\n \"component\",\n \"page\",\n \"api\",\n \"website\",\n \"document\",\n \"script\",\n \"config\",\n \"skill\",\n \"media\",\n \"report\",\n \"test\",\n \"workflow\",\n \"schema\",\n \"email\",\n \"diagram\",\n \"auto\",\n] as const\n\nexport type OutputType = (typeof OUTPUT_TYPES)[number]\n\nexport const outputTypeDescriptions: Record<OutputType, string> = {\n component: \"UI component (any framework)\",\n page: \"Full page or screen\",\n api: \"API endpoint, route handler, or service\",\n website: \"Multi-page website or app\",\n document: \"Markdown, documentation, or specification\",\n script: \"Standalone script or utility\",\n config: \"Configuration file or setup\",\n skill: \"Agent skill (SKILL.md format for skills.sh)\",\n media: \"Media generation prompt (image/audio/video description)\",\n report: \"Analysis report or audit\",\n test: \"Test suite, test fixtures, or test data\",\n workflow: \"CI/CD pipeline, GitHub Actions, or automation\",\n schema: \"Database schema, Zod validators, or GraphQL types\",\n email: \"Email template (React Email, MJML, HTML)\",\n diagram: \"Mermaid, D2, or PlantUML diagram\",\n auto: \"Auto-detect the best output type\",\n}\n","import { existsSync, promises as fs } from \"fs\"\nimport path from \"path\"\nimport fg from \"fast-glob\"\n\n// --- Schema awareness: detect DB schemas, API specs, env vars, configs ---\n\nexport interface ProjectSchemas {\n database?: DatabaseSchema\n api?: ApiSchema\n env?: EnvSchema\n models?: ModelFile[]\n}\n\nexport interface DatabaseSchema {\n type: string // prisma, drizzle, typeorm, etc.\n content: string\n tables?: string[]\n}\n\nexport interface ApiSchema {\n type: string // openapi, graphql, trpc, etc.\n content: string\n endpoints?: string[]\n}\n\nexport interface EnvSchema {\n variables: { key: string; description?: string; required: boolean }[]\n}\n\nexport interface ModelFile {\n path: string\n content: string\n type: string\n}\n\nconst SCHEMA_FILES: Record<string, { type: string; category: \"database\" | \"api\" | \"model\" }> = {\n \"prisma/schema.prisma\": { type: \"prisma\", category: \"database\" },\n \"drizzle/schema.ts\": { type: \"drizzle\", category: \"database\" },\n \"schema.graphql\": { type: \"graphql\", category: \"api\" },\n \"schema.gql\": { type: \"graphql\", category: \"api\" },\n \"openapi.yaml\": { type: \"openapi\", category: \"api\" },\n \"openapi.json\": { type: \"openapi\", category: \"api\" },\n \"swagger.yaml\": { type: \"openapi\", category: \"api\" },\n \"swagger.json\": { type: \"openapi\", category: \"api\" },\n}\n\nexport async function detectSchemas(cwd: string): Promise<ProjectSchemas> {\n const schemas: ProjectSchemas = {}\n\n // Find schema files\n const files = await fg.glob(\"**/*\", {\n cwd,\n deep: 4,\n ignore: [\n \"**/node_modules/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/.next/**\",\n \"**/target/**\",\n \"**/__pycache__/**\",\n \"**/vendor/**\",\n \"**/.git/**\",\n ],\n onlyFiles: true,\n })\n\n // Detect database schemas\n for (const [schemaFile, info] of Object.entries(SCHEMA_FILES)) {\n const match = files.find((f) => f.endsWith(schemaFile) || f === schemaFile)\n if (match && info.category === \"database\") {\n const content = await safeReadFile(path.resolve(cwd, match))\n if (content) {\n schemas.database = {\n type: info.type,\n content: truncate(content, 3000),\n tables: extractTableNames(content, info.type),\n }\n break\n }\n }\n }\n\n // Detect API schemas\n for (const [schemaFile, info] of Object.entries(SCHEMA_FILES)) {\n const match = files.find((f) => f.endsWith(schemaFile) || f === schemaFile)\n if (match && info.category === \"api\") {\n const content = await safeReadFile(path.resolve(cwd, match))\n if (content) {\n schemas.api = {\n type: info.type,\n content: truncate(content, 3000),\n }\n break\n }\n }\n }\n\n // Detect tRPC router\n if (!schemas.api) {\n const trpcRouter = files.find(\n (f) => f.includes(\"trpc\") && (f.endsWith(\"router.ts\") || f.endsWith(\"router.js\"))\n )\n if (trpcRouter) {\n const content = await safeReadFile(path.resolve(cwd, trpcRouter))\n if (content) {\n schemas.api = {\n type: \"trpc\",\n content: truncate(content, 3000),\n }\n }\n }\n }\n\n // Detect env variables\n const envExample = files.find(\n (f) => f === \".env.example\" || f === \".env.local.example\" || f === \".env.template\"\n )\n if (envExample) {\n const content = await safeReadFile(path.resolve(cwd, envExample))\n if (content) {\n schemas.env = parseEnvFile(content)\n }\n }\n\n // Detect model/type files\n const modelFiles = files.filter(\n (f) =>\n (f.includes(\"models\") || f.includes(\"types\") || f.includes(\"schemas\")) &&\n (f.endsWith(\".ts\") || f.endsWith(\".py\") || f.endsWith(\".rs\") || f.endsWith(\".go\"))\n )\n\n if (modelFiles.length) {\n schemas.models = []\n for (const mf of modelFiles.slice(0, 5)) {\n const content = await safeReadFile(path.resolve(cwd, mf))\n if (content) {\n schemas.models.push({\n path: mf,\n content: truncate(content, 2000),\n type: path.extname(mf).slice(1),\n })\n }\n }\n }\n\n return schemas\n}\n\nfunction extractTableNames(content: string, type: string): string[] {\n if (type === \"prisma\") {\n const matches = content.match(/model\\s+(\\w+)\\s*\\{/g)\n return matches ? matches.map((m) => m.replace(/model\\s+/, \"\").replace(/\\s*\\{/, \"\")) : []\n }\n return []\n}\n\nfunction parseEnvFile(content: string): EnvSchema {\n const lines = content.split(\"\\n\").filter((l) => l.trim() && !l.trim().startsWith(\"#\"))\n const variables = lines.map((line) => {\n const [keyPart] = line.split(\"=\")\n const key = keyPart.trim()\n const hasValue = line.includes(\"=\") && line.split(\"=\")[1]?.trim().length > 0\n return {\n key,\n required: !hasValue,\n }\n })\n return { variables }\n}\n\nasync function safeReadFile(filePath: string): Promise<string | null> {\n try {\n if (!existsSync(filePath)) return null\n return await fs.readFile(filePath, \"utf8\")\n } catch {\n return null\n }\n}\n\nfunction truncate(str: string, maxLen: number): string {\n if (str.length <= maxLen) return str\n return str.slice(0, maxLen) + \"\\n... (truncated)\"\n}\n\nexport function formatSchemas(schemas: ProjectSchemas): string {\n const sections: string[] = []\n\n if (schemas.database) {\n sections.push(\n `## Database Schema (${schemas.database.type})\\n` +\n (schemas.database.tables?.length\n ? `Tables: ${schemas.database.tables.join(\", \")}\\n`\n : \"\") +\n \"```\\n\" +\n schemas.database.content +\n \"\\n```\"\n )\n }\n\n if (schemas.api) {\n sections.push(\n `## API Schema (${schemas.api.type})\\n` + \"```\\n\" + schemas.api.content + \"\\n```\"\n )\n }\n\n if (schemas.env) {\n sections.push(\n `## Environment Variables\\n` +\n schemas.env.variables.map((v) => `- ${v.key}${v.required ? \" (required)\" : \"\"}`).join(\"\\n\")\n )\n }\n\n if (schemas.models?.length) {\n for (const model of schemas.models) {\n sections.push(\n `## Model: ${model.path}\\n` + \"```\" + model.type + \"\\n\" + model.content + \"\\n```\"\n )\n }\n }\n\n return sections.join(\"\\n\\n\")\n}\n","import fetch from \"node-fetch\"\nimport { logger } from \"@/utils/logger\"\nimport type { TechStack } from \"./tech-stack\"\n\n// --- Context7 integration: fetch up-to-date library documentation ---\n\nconst CONTEXT7_API = \"https://api.context7.com/v1\"\n\ninterface Context7Library {\n id: string\n name: string\n description?: string\n}\n\ninterface Context7Docs {\n libraryId: string\n content: string\n tokens: number\n}\n\nexport async function resolveLibraryId(\n libraryName: string,\n apiKey?: string\n): Promise<Context7Library | null> {\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n }\n if (apiKey) headers[\"Authorization\"] = `Bearer ${apiKey}`\n\n const response = await fetch(`${CONTEXT7_API}/libraries/resolve`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ name: libraryName }),\n })\n\n if (!response.ok) return null\n\n const data = (await response.json()) as any\n if (data?.libraries?.length) {\n return data.libraries[0]\n }\n return null\n } catch {\n return null\n }\n}\n\nexport async function getLibraryDocs(\n libraryId: string,\n topic?: string,\n maxTokens: number = 5000,\n apiKey?: string\n): Promise<string | null> {\n try {\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n }\n if (apiKey) headers[\"Authorization\"] = `Bearer ${apiKey}`\n\n const response = await fetch(`${CONTEXT7_API}/libraries/${encodeURIComponent(libraryId)}/docs`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ topic, maxTokens }),\n })\n\n if (!response.ok) return null\n\n const data = (await response.json()) as any\n return data?.content || null\n } catch {\n return null\n }\n}\n\nexport async function gatherContext7Docs(\n stack: TechStack,\n topic: string,\n apiKey?: string\n): Promise<string> {\n const relevantLibraries: string[] = []\n\n // Gather the most important frameworks and libraries\n for (const fw of stack.frameworks.slice(0, 3)) {\n relevantLibraries.push(fw.name)\n }\n\n // Add key dependencies\n const priorityDeps = [\n \"react\",\n \"vue\",\n \"svelte\",\n \"angular\",\n \"next\",\n \"nuxt\",\n \"express\",\n \"fastify\",\n \"hono\",\n \"prisma\",\n \"drizzle-orm\",\n \"tailwindcss\",\n \"shadcn\",\n \"@tanstack/react-query\",\n \"zod\",\n \"trpc\",\n ]\n\n for (const dep of priorityDeps) {\n if (stack.dependencies[dep] || stack.devDependencies[dep]) {\n if (!relevantLibraries.includes(dep)) {\n relevantLibraries.push(dep)\n }\n }\n }\n\n const docs: string[] = []\n\n for (const lib of relevantLibraries.slice(0, 5)) {\n const library = await resolveLibraryId(lib, apiKey)\n if (library) {\n const content = await getLibraryDocs(library.id, topic, 3000, apiKey)\n if (content) {\n docs.push(`## ${library.name} Documentation\\n${content}`)\n }\n }\n }\n\n if (!docs.length) {\n return \"\"\n }\n\n return `# Relevant Library Documentation (via Context7)\\n\\n${docs.join(\"\\n\\n---\\n\\n\")}`\n}\n","import type { OutputType } from \"../providers/types\"\n\n// --- Output type resolution and file path mapping ---\n\nexport interface OutputConfig {\n type: OutputType\n baseDir: string\n filePatterns: string[]\n description: string\n}\n\nexport const OUTPUT_CONFIGS: Record<string, OutputConfig> = {\n component: {\n type: \"component\",\n baseDir: \"src/components\",\n filePatterns: [\"*.tsx\", \"*.vue\", \"*.svelte\", \"*.jsx\", \"*.ts\"],\n description: \"UI component\",\n },\n page: {\n type: \"page\",\n baseDir: \"src/app\",\n filePatterns: [\"*.tsx\", \"*.vue\", \"*.svelte\", \"*.jsx\", \"*.astro\"],\n description: \"Page or screen\",\n },\n api: {\n type: \"api\",\n baseDir: \"src/api\",\n filePatterns: [\"*.ts\", \"*.js\", \"*.py\", \"*.go\", \"*.rs\"],\n description: \"API route or endpoint\",\n },\n website: {\n type: \"website\",\n baseDir: \".\",\n filePatterns: [\"*\"],\n description: \"Multi-file website\",\n },\n document: {\n type: \"document\",\n baseDir: \"docs\",\n filePatterns: [\"*.md\", \"*.mdx\", \"*.txt\", \"*.rst\"],\n description: \"Documentation\",\n },\n script: {\n type: \"script\",\n baseDir: \"scripts\",\n filePatterns: [\"*.ts\", \"*.js\", \"*.py\", \"*.sh\", \"*.go\"],\n description: \"Standalone script\",\n },\n config: {\n type: \"config\",\n baseDir: \".\",\n filePatterns: [\"*.json\", \"*.yaml\", \"*.yml\", \"*.toml\", \"*.env\"],\n description: \"Configuration file\",\n },\n skill: {\n type: \"skill\",\n baseDir: \".skills\",\n filePatterns: [\"SKILL.md\"],\n description: \"Agent skill (SKILL.md)\",\n },\n media: {\n type: \"media\",\n baseDir: \"media\",\n filePatterns: [\"*.md\", \"*.json\", \"*.txt\"],\n description: \"Media generation prompt/description\",\n },\n report: {\n type: \"report\",\n baseDir: \"reports\",\n filePatterns: [\"*.md\", \"*.html\", \"*.json\"],\n description: \"Analysis report\",\n },\n test: {\n type: \"test\",\n baseDir: \"src\",\n filePatterns: [\"*.test.ts\", \"*.test.tsx\", \"*.spec.ts\", \"*.test.js\", \"*.test.py\", \"*.test.go\"],\n description: \"Test suite or fixture\",\n },\n workflow: {\n type: \"workflow\",\n baseDir: \".github/workflows\",\n filePatterns: [\"*.yml\", \"*.yaml\"],\n description: \"CI/CD pipeline or automation\",\n },\n schema: {\n type: \"schema\",\n baseDir: \"src\",\n filePatterns: [\"*.ts\", \"*.prisma\", \"*.graphql\", \"*.gql\", \"*.py\"],\n description: \"Database schema, validators, or types\",\n },\n email: {\n type: \"email\",\n baseDir: \"src/emails\",\n filePatterns: [\"*.tsx\", \"*.jsx\", \"*.html\", \"*.mjml\"],\n description: \"Email template\",\n },\n diagram: {\n type: \"diagram\",\n baseDir: \"docs\",\n filePatterns: [\"*.md\", \"*.mmd\", \"*.d2\", \"*.puml\"],\n description: \"Architecture or data diagram\",\n },\n}\n\nexport function resolveOutputType(\n userHint: string | undefined,\n taskDescription: string\n): OutputType {\n if (userHint && userHint !== \"auto\") {\n return userHint as OutputType\n }\n\n const lower = taskDescription.toLowerCase()\n\n // Pattern matching for output type detection\n const patterns: [RegExp, OutputType][] = [\n [/\\b(component|button|card|modal|dialog|form|input|dropdown|nav|sidebar|header|footer|widget|ui)\\b/i, \"component\"],\n [/\\b(page|screen|view|route|layout|dashboard|landing)\\b/i, \"page\"],\n [/\\b(api|endpoint|route handler|rest|graphql|webhook|middleware|server)\\b/i, \"api\"],\n [/\\b(website|site|web app|landing page|portfolio|blog)\\b/i, \"website\"],\n [/\\b(document|doc|readme|guide|tutorial|specification|spec|changelog)\\b/i, \"document\"],\n [/\\b(script|cli|command|tool|utility|migration|seed|cron)\\b/i, \"script\"],\n [/\\b(config|configuration|setup|env|settings)\\b/i, \"config\"],\n [/\\b(skill|agent skill|skill\\.md)\\b/i, \"skill\"],\n [/\\b(video|audio|image|media|animation|thumbnail|podcast)\\b/i, \"media\"],\n [/\\b(report|audit|analysis|review|assessment|benchmark)\\b/i, \"report\"],\n [/\\b(test|spec|unit test|integration test|e2e|coverage|fixture|mock)\\b/i, \"test\"],\n [/\\b(workflow|ci|cd|pipeline|github action|deploy|automation|ci\\/cd)\\b/i, \"workflow\"],\n [/\\b(schema|model|migration|prisma|drizzle|zod|validator|graphql type)\\b/i, \"schema\"],\n [/\\b(email|newsletter|transactional|invite|welcome email|notification email)\\b/i, \"email\"],\n [/\\b(diagram|erd|flowchart|architecture diagram|sequence diagram|mermaid|plantuml|d2)\\b/i, \"diagram\"],\n ]\n\n for (const [pattern, type] of patterns) {\n if (pattern.test(lower)) {\n return type\n }\n }\n\n return \"component\" // Default fallback\n}\n","import { existsSync, promises as fs } from \"fs\"\nimport path from \"path\"\nimport type { GeneratedFile } from \"../providers/types\"\nimport type { TechStack } from \"../context/tech-stack\"\nimport { OUTPUT_CONFIGS } from \"./types\"\nimport { logger } from \"@/utils/logger\"\nimport { globalHooks } from \"@/hooks\"\nimport { globalPermissions } from \"@/permissions\"\n\n// --- Write generated files to disk ---\n\nexport interface WriteOptions {\n cwd: string\n overwrite: boolean\n dryRun: boolean\n outputDir?: string\n}\n\nexport interface WriteResult {\n written: string[]\n skipped: string[]\n errors: string[]\n}\n\nexport async function writeGeneratedFiles(\n files: GeneratedFile[],\n options: WriteOptions\n): Promise<WriteResult> {\n const result: WriteResult = { written: [], skipped: [], errors: [] }\n\n for (const file of files) {\n const filePath = path.isAbsolute(file.path)\n ? file.path\n : path.resolve(options.cwd, options.outputDir || \"\", file.path)\n\n try {\n // pre:file-write hook — can block or modify file content\n let fileContent = file.content\n if (globalHooks.has(\"pre:file-write\")) {\n const hookResult = await globalHooks.execute(\"pre:file-write\", {\n event: \"pre:file-write\",\n file: filePath,\n fileContent,\n cwd: options.cwd,\n })\n if (hookResult.blocked) {\n result.skipped.push(filePath)\n continue\n }\n if (hookResult.modified?.fileContent) {\n fileContent = String(hookResult.modified.fileContent)\n }\n }\n\n // Permissions check — can allow, deny, or skip (plan mode)\n const relativePath = path.relative(options.cwd, filePath)\n const permission = await globalPermissions.checkFileWrite(relativePath)\n if (permission === \"deny\") {\n result.skipped.push(filePath)\n continue\n }\n if (permission === \"skip\") {\n // Plan mode: record what would be written but don't write\n result.written.push(filePath)\n continue\n }\n\n if (existsSync(filePath) && !options.overwrite) {\n result.skipped.push(filePath)\n continue\n }\n\n if (options.dryRun) {\n result.written.push(filePath)\n continue\n }\n\n // Create directory structure\n const dir = path.dirname(filePath)\n await fs.mkdir(dir, { recursive: true })\n\n // Write file\n await fs.writeFile(filePath, fileContent, \"utf8\")\n result.written.push(filePath)\n\n // post:file-write hook — post-processing (format, git add, etc.)\n if (globalHooks.has(\"post:file-write\")) {\n await globalHooks.execute(\"post:file-write\", {\n event: \"post:file-write\",\n file: filePath,\n fileContent,\n cwd: options.cwd,\n })\n }\n } catch (error: any) {\n result.errors.push(`${filePath}: ${error.message}`)\n }\n }\n\n return result\n}\n\nexport function resolveOutputDir(\n outputType: string,\n stack: TechStack,\n customDir?: string\n): string {\n if (customDir) return customDir\n\n const config = OUTPUT_CONFIGS[outputType]\n if (!config) return \"generated\"\n\n // Adjust base dir based on project structure\n let baseDir = config.baseDir\n\n if (outputType === \"component\") {\n // Detect existing component directory\n if (stack.srcDir) {\n baseDir = `${stack.srcDir}/components`\n } else {\n baseDir = \"components\"\n }\n }\n\n if (outputType === \"page\") {\n // Detect app dir structure\n const hasAppDir =\n stack.frameworks.find((f) => f.name === \"nextjs\") && stack.srcDir\n if (hasAppDir) {\n baseDir = `${stack.srcDir}/app`\n }\n }\n\n if (outputType === \"api\") {\n const isNextJs = stack.frameworks.find((f) => f.name === \"nextjs\")\n if (isNextJs) {\n baseDir = stack.srcDir ? `${stack.srcDir}/app/api` : \"app/api\"\n }\n }\n\n if (outputType === \"test\") {\n if (stack.testing.includes(\"vitest\") || stack.testing.includes(\"jest\")) {\n baseDir = stack.srcDir || \"src\"\n }\n }\n\n if (outputType === \"workflow\") {\n baseDir = \".github/workflows\"\n }\n\n if (outputType === \"schema\") {\n if (stack.databases.includes(\"prisma\")) {\n baseDir = \"prisma\"\n } else if (stack.srcDir) {\n baseDir = `${stack.srcDir}/schemas`\n }\n }\n\n if (outputType === \"email\") {\n baseDir = stack.srcDir ? `${stack.srcDir}/emails` : \"emails\"\n }\n\n return baseDir\n}\n","// --- Permission Manager: checking and inline prompts for file writes ---\n\nimport prompts from \"prompts\"\nimport chalk from \"chalk\"\nimport type { PermissionMode, PermissionConfig } from \"./types\"\nimport { permissionConfigSchema } from \"./types\"\nimport { debug } from \"@/observability\"\n\nexport type PermissionAction = \"allow\" | \"deny\" | \"skip\"\n\n/**\n * Simple glob matching: supports *, **, and ? wildcards.\n */\nfunction matchGlob(filePath: string, pattern: string): boolean {\n // Convert glob pattern to regex\n let regex = pattern\n .replace(/\\./g, \"\\\\.\")\n .replace(/\\*\\*/g, \"{{GLOBSTAR}}\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, \".*\")\n .replace(/\\?/g, \"[^/]\")\n return new RegExp(`^${regex}$`).test(filePath)\n}\n\nexport class PermissionManager {\n private mode: PermissionMode\n private allowPatterns: string[]\n private denyPatterns: string[]\n private confirmPatterns: string[]\n private autoAllowAll = false // set when user picks \"all\" in interactive prompt\n\n constructor(config?: Partial<PermissionConfig>) {\n const parsed = permissionConfigSchema.parse(config || {})\n this.mode = parsed.mode\n this.allowPatterns = parsed.allow\n this.denyPatterns = parsed.deny\n this.confirmPatterns = parsed.confirm\n }\n\n getMode(): PermissionMode {\n return this.mode\n }\n\n setMode(mode: PermissionMode): void {\n this.mode = mode\n this.autoAllowAll = false // reset on mode change\n debug.context(\"permissions\", `mode set to ${mode}`)\n }\n\n /**\n * Check whether a file write should proceed.\n */\n async checkFileWrite(filePath: string): Promise<PermissionAction> {\n debug.context(\"permissions\", `checking write: ${filePath} (mode: ${this.mode})`)\n\n // Always deny files matching deny patterns\n if (this.matchesAny(filePath, this.denyPatterns)) {\n debug.context(\"permissions\", `denied by pattern: ${filePath}`)\n return \"deny\"\n }\n\n switch (this.mode) {\n case \"yolo\":\n return \"allow\"\n\n case \"plan\":\n return \"skip\"\n\n case \"acceptEdits\":\n return \"allow\"\n\n case \"default\":\n // If user already chose \"all\", auto-allow\n if (this.autoAllowAll) return \"allow\"\n\n // Auto-allow if matches allow patterns\n if (this.matchesAny(filePath, this.allowPatterns)) {\n return \"allow\"\n }\n\n // Must confirm if matches confirm patterns or no patterns match\n return this.promptUser(filePath)\n\n default:\n return \"allow\"\n }\n }\n\n /**\n * Check whether a command should proceed (for pre:command hook).\n */\n async checkCommand(command: string): Promise<\"allow\" | \"deny\"> {\n if (this.mode === \"yolo\") return \"allow\"\n if (this.mode === \"plan\") return \"deny\"\n // For default and acceptEdits, commands are allowed\n return \"allow\"\n }\n\n private matchesAny(filePath: string, patterns: string[]): boolean {\n return patterns.some((p) => matchGlob(filePath, p))\n }\n\n private async promptUser(filePath: string): Promise<PermissionAction> {\n const { action } = await prompts({\n type: \"select\",\n name: \"action\",\n message: `Write file ${chalk.cyan(filePath)}?`,\n choices: [\n { title: \"Yes\", value: \"allow\" },\n { title: \"No\", value: \"deny\" },\n { title: \"All (allow remaining)\", value: \"all\" },\n { title: \"Skip\", value: \"skip\" },\n ],\n initial: 0,\n })\n\n if (action === \"all\") {\n this.autoAllowAll = true\n return \"allow\"\n }\n\n return action || \"deny\"\n }\n}\n\nexport const globalPermissions = new PermissionManager()\n","// --- Permission mode definitions and config schema ---\n\nimport { z } from \"zod\"\n\nexport const PERMISSION_MODES = [\"default\", \"acceptEdits\", \"plan\", \"yolo\"] as const\nexport type PermissionMode = (typeof PERMISSION_MODES)[number]\n\nexport const permissionModeSchema = z.enum(PERMISSION_MODES)\n\nexport interface PermissionRule {\n pattern: string\n action: \"allow\" | \"deny\" | \"confirm\"\n}\n\nexport const permissionConfigSchema = z.object({\n mode: permissionModeSchema.default(\"default\"),\n allow: z.array(z.string()).default([]),\n deny: z.array(z.string()).default([]),\n confirm: z.array(z.string()).default([]),\n})\n\nexport type PermissionConfig = z.infer<typeof permissionConfigSchema>\n","// --- Memory Hierarchy: user-level + project-level layered memory ---\n\nimport os from \"os\"\nimport { Memory, type UserPreference, type MemoryEntry, type LearnedPattern, type MemoryStore } from \"@/runtime/memory\"\n\nconst USER_MEMORY_DIR = os.homedir()\n\nexport class MemoryHierarchy {\n private userMemory: Memory\n private projectMemory: Memory\n\n constructor(private cwd: string) {\n // User-level memory at ~/.agentx/memory.json\n this.userMemory = new Memory(USER_MEMORY_DIR)\n // Project-level memory at <cwd>/.agentx/memory.json\n this.projectMemory = new Memory(cwd)\n }\n\n async load(): Promise<void> {\n await Promise.all([this.userMemory.load(), this.projectMemory.load()])\n }\n\n async save(): Promise<void> {\n await Promise.all([this.userMemory.save(), this.projectMemory.save()])\n }\n\n /**\n * Build merged memory context for the agent. Project overrides user.\n */\n buildMemoryContext(task: string): string {\n const userCtx = this.userMemory.buildMemoryContext(task)\n const projectCtx = this.projectMemory.buildMemoryContext(task)\n\n if (!userCtx && !projectCtx) return \"\"\n\n const sections: string[] = []\n if (projectCtx) {\n sections.push(projectCtx)\n }\n if (userCtx) {\n // Prefix user-level context to distinguish it\n sections.push(\n userCtx.replace(\n \"# Memory (learned from past interactions)\",\n \"# Global Memory (cross-project patterns)\"\n )\n )\n }\n\n return sections.join(\"\\n\\n\")\n }\n\n /**\n * Learn a preference at user level (global).\n */\n async learnPreference(key: string, value: string, source: string): Promise<void> {\n await this.userMemory.learnPreference(key, value, source)\n }\n\n /**\n * Record a generation at project level (task-specific).\n */\n async recordGeneration(\n entry: Omit<MemoryEntry, \"id\" | \"timestamp\" | \"type\"> & { type?: MemoryEntry[\"type\"] }\n ): Promise<string> {\n return this.projectMemory.recordGeneration(entry)\n }\n\n /**\n * Get combined preferences (project overrides user for same keys).\n */\n getPreferences(): UserPreference[] {\n const userPrefs = this.userMemory.getPreferences()\n const projectPrefs = this.projectMemory.getPreferences()\n\n const merged = new Map<string, UserPreference>()\n for (const p of userPrefs) {\n merged.set(p.key, p)\n }\n for (const p of projectPrefs) {\n merged.set(p.key, p) // project overrides\n }\n return Array.from(merged.values())\n }\n\n /**\n * Get combined patterns from both levels.\n */\n getPatterns(): LearnedPattern[] {\n const userPatterns = this.userMemory.getPatterns()\n const projectPatterns = this.projectMemory.getPatterns()\n return [...projectPatterns, ...userPatterns]\n }\n\n /**\n * Get stats from both levels.\n */\n getStats(): { user: MemoryStore[\"stats\"]; project: MemoryStore[\"stats\"] } {\n return {\n user: this.userMemory.getStats(),\n project: this.projectMemory.getStats(),\n }\n }\n\n /**\n * Get recent generations from project level.\n */\n getRecentGenerations(limit = 10): MemoryEntry[] {\n return this.projectMemory.getRecentGenerations(limit)\n }\n}\n","// --- Context Builder: smart assembly with @-import resolution and relevance trimming ---\n\nimport { existsSync, readFileSync } from \"fs\"\nimport path from \"path\"\nimport { buildIndex, scoreAll } from \"./bm25\"\n\ninterface ContextSection {\n label: string\n content: string\n priority: number // higher = more important\n}\n\n/**\n * Resolve @-imports in content: replace @path/to/file with file contents.\n */\nexport function resolveAtImports(content: string, basedir: string): string {\n return content.replace(/@([\\w./-]+)/g, (match, filePath: string) => {\n const resolved = path.resolve(basedir, filePath)\n if (existsSync(resolved)) {\n try {\n return readFileSync(resolved, \"utf8\")\n } catch {\n return match // keep original if read fails\n }\n }\n return match // keep original if file doesn't exist\n })\n}\n\n/**\n * Load project instructions from SHADXN.md or CLAUDE.md.\n */\nexport function loadProjectInstructions(cwd: string): string {\n const candidates = [\"SHADXN.md\", \"CLAUDE.md\"]\n for (const name of candidates) {\n const filePath = path.join(cwd, name)\n if (existsSync(filePath)) {\n try {\n let content = readFileSync(filePath, \"utf8\")\n content = resolveAtImports(content, cwd)\n return content\n } catch {\n // skip if unreadable\n }\n }\n }\n return \"\"\n}\n\n/**\n * Estimate token count from content (rough chars-to-tokens).\n */\nfunction estimateTokens(content: string): number {\n return Math.ceil(content.length / 4)\n}\n\nexport class ContextBuilder {\n private sections: ContextSection[] = []\n\n addSection(label: string, content: string, priority = 50): void {\n if (!content.trim()) return\n this.sections.push({ label, content, priority })\n }\n\n /**\n * Build final context, trimming lowest-relevance sections if over budget.\n */\n buildContext(task: string, maxTokens = 12000): string {\n if (this.sections.length === 0) return \"\"\n\n // Score each section via BM25\n const docs = this.sections.map((s) => s.content)\n const index = buildIndex(docs)\n const bm25Results = scoreAll(task, index)\n const scoreMap = new Map(bm25Results.map((r) => [r.docIndex, r.score]))\n\n const scored = this.sections.map((s, i) => ({\n ...s,\n relevance: scoreMap.get(i) ?? 0,\n tokens: estimateTokens(s.content),\n }))\n\n // Sort by combined score (priority weight + relevance)\n scored.sort(\n (a, b) => b.priority + b.relevance * 100 - (a.priority + a.relevance * 100)\n )\n\n // Include sections until budget is exceeded\n const included: typeof scored = []\n let totalTokens = 0\n\n for (const section of scored) {\n if (totalTokens + section.tokens > maxTokens && included.length > 0) {\n // Skip this section — over budget\n continue\n }\n included.push(section)\n totalTokens += section.tokens\n }\n\n return included.map((s) => s.content).join(\"\\n\\n\")\n }\n}\n","// --- Tool Executor: runs tool calls with permission and hook integration ---\n\nimport { promises as fs } from \"fs\"\nimport path from \"path\"\nimport { execa } from \"execa\"\nimport fg from \"fast-glob\"\nimport { globalPermissions } from \"@/permissions\"\nimport { globalHooks } from \"@/hooks\"\nimport { debug } from \"@/observability\"\nimport type { GeneratedFile } from \"../providers/types\"\n\nexport interface ToolCallInput {\n name: string\n id: string\n input: Record<string, unknown>\n}\n\nexport interface ToolResult {\n tool_use_id: string\n content: string\n is_error?: boolean\n /** Files collected from create_files calls */\n files?: GeneratedFile[]\n /** Question from ask_user calls */\n followUp?: string\n}\n\nexport interface ToolExecutorOptions {\n interactive?: boolean\n overwrite?: boolean\n dryRun?: boolean\n}\n\nexport class ToolExecutor {\n private cwd: string\n private options: ToolExecutorOptions\n\n constructor(cwd: string, options: ToolExecutorOptions = {}) {\n this.cwd = cwd\n this.options = options\n }\n\n async execute(call: ToolCallInput): Promise<ToolResult> {\n debug.context(\"tool-executor\", `executing: ${call.name}`)\n\n // pre:tool-call hook\n if (globalHooks.has(\"pre:tool-call\")) {\n const hookResult = await globalHooks.execute(\"pre:tool-call\", {\n event: \"pre:tool-call\" as any,\n toolName: call.name,\n toolInput: call.input,\n cwd: this.cwd,\n })\n if (hookResult.blocked) {\n return {\n tool_use_id: call.id,\n content: hookResult.message || `Tool ${call.name} blocked by pre:tool-call hook`,\n is_error: true,\n }\n }\n }\n\n let result: ToolResult\n\n try {\n switch (call.name) {\n case \"read_file\":\n result = await this.readFile(call)\n break\n case \"search_files\":\n result = await this.searchFiles(call)\n break\n case \"list_directory\":\n result = await this.listDirectory(call)\n break\n case \"run_command\":\n result = await this.runCommand(call)\n break\n case \"edit_file\":\n result = await this.editFile(call)\n break\n case \"create_files\":\n result = await this.createFiles(call)\n break\n case \"ask_user\":\n result = await this.askUser(call)\n break\n case \"spawn_agent\":\n result = await this.spawnAgent(call)\n break\n default:\n result = {\n tool_use_id: call.id,\n content: `Unknown tool: ${call.name}`,\n is_error: true,\n }\n }\n } catch (error: any) {\n result = {\n tool_use_id: call.id,\n content: `Error executing ${call.name}: ${error.message}`,\n is_error: true,\n }\n }\n\n // post:tool-call hook\n if (globalHooks.has(\"post:tool-call\")) {\n await globalHooks.execute(\"post:tool-call\", {\n event: \"post:tool-call\" as any,\n toolName: call.name,\n toolInput: call.input,\n toolResult: result.content,\n cwd: this.cwd,\n })\n }\n\n return result\n }\n\n private async readFile(call: ToolCallInput): Promise<ToolResult> {\n const filePath = String(call.input.path || \"\")\n const maxLines = Number(call.input.max_lines) || 500\n const absPath = path.resolve(this.cwd, filePath)\n\n const content = await fs.readFile(absPath, \"utf8\")\n const lines = content.split(\"\\n\")\n const truncated = lines.length > maxLines\n const output = truncated\n ? lines.slice(0, maxLines).join(\"\\n\") + `\\n\\n... (truncated, ${lines.length - maxLines} more lines)`\n : content\n\n return {\n tool_use_id: call.id,\n content: output,\n }\n }\n\n private async searchFiles(call: ToolCallInput): Promise<ToolResult> {\n const pattern = String(call.input.pattern || \"**/*\")\n const contentRegex = call.input.content_regex ? String(call.input.content_regex) : undefined\n const maxResults = Number(call.input.max_results) || 50\n\n const files = await fg(pattern, {\n cwd: this.cwd,\n ignore: [\"node_modules/**\", \".git/**\", \"dist/**\", \".next/**\"],\n dot: false,\n })\n\n if (!contentRegex) {\n const limited = files.slice(0, maxResults)\n return {\n tool_use_id: call.id,\n content: limited.length\n ? limited.join(\"\\n\") + (files.length > maxResults ? `\\n\\n... (${files.length - maxResults} more files)` : \"\")\n : \"No files matched the pattern.\",\n }\n }\n\n // Search content within matched files\n const regex = new RegExp(contentRegex, \"gm\")\n const results: string[] = []\n\n for (const file of files) {\n if (results.length >= maxResults) break\n try {\n const content = await fs.readFile(path.resolve(this.cwd, file), \"utf8\")\n const lines = content.split(\"\\n\")\n for (let i = 0; i < lines.length; i++) {\n if (results.length >= maxResults) break\n if (regex.test(lines[i])) {\n results.push(`${file}:${i + 1}: ${lines[i]}`)\n }\n regex.lastIndex = 0\n }\n } catch {\n // Skip unreadable files\n }\n }\n\n return {\n tool_use_id: call.id,\n content: results.length\n ? results.join(\"\\n\")\n : \"No matches found.\",\n }\n }\n\n private async listDirectory(call: ToolCallInput): Promise<ToolResult> {\n const dirPath = String(call.input.path || \".\")\n const recursive = Boolean(call.input.recursive)\n const maxDepth = Number(call.input.max_depth) || 3\n const absPath = path.resolve(this.cwd, dirPath)\n\n if (recursive) {\n const pattern = \"**/*\"\n const entries = await fg(pattern, {\n cwd: absPath,\n onlyFiles: false,\n markDirectories: true,\n deep: maxDepth,\n ignore: [\"node_modules/**\", \".git/**\", \"dist/**\", \".next/**\"],\n })\n return {\n tool_use_id: call.id,\n content: entries.length ? entries.join(\"\\n\") : \"Empty directory.\",\n }\n }\n\n const entries = await fs.readdir(absPath, { withFileTypes: true })\n const formatted = entries.map((e) =>\n e.isDirectory() ? `${e.name}/` : e.name\n )\n\n return {\n tool_use_id: call.id,\n content: formatted.length ? formatted.join(\"\\n\") : \"Empty directory.\",\n }\n }\n\n private async runCommand(call: ToolCallInput): Promise<ToolResult> {\n const command = String(call.input.command || \"\")\n const timeout = Number(call.input.timeout) || 30_000\n\n // Check permissions\n const permission = await globalPermissions.checkCommand(command)\n if (permission === \"deny\") {\n return {\n tool_use_id: call.id,\n content: `Command blocked by permissions (mode: ${globalPermissions.getMode()}): ${command}`,\n is_error: true,\n }\n }\n\n // pre:command hook\n if (globalHooks.has(\"pre:command\")) {\n const hookResult = await globalHooks.execute(\"pre:command\", {\n event: \"pre:command\",\n command,\n cwd: this.cwd,\n })\n if (hookResult.blocked) {\n return {\n tool_use_id: call.id,\n content: hookResult.message || `Command blocked by pre:command hook: ${command}`,\n is_error: true,\n }\n }\n }\n\n const result = await execa(\"sh\", [\"-c\", command], {\n cwd: this.cwd,\n timeout,\n reject: false,\n stdin: \"ignore\",\n })\n\n const output = [result.stdout, result.stderr].filter(Boolean).join(\"\\n\")\n const truncated = output.length > 10_000\n ? output.slice(0, 10_000) + \"\\n\\n... (output truncated)\"\n : output\n\n if (result.exitCode !== 0) {\n return {\n tool_use_id: call.id,\n content: `Command exited with code ${result.exitCode}:\\n${truncated}`,\n is_error: true,\n }\n }\n\n return {\n tool_use_id: call.id,\n content: truncated || \"(no output)\",\n }\n }\n\n private async editFile(call: ToolCallInput): Promise<ToolResult> {\n const filePath = String(call.input.path || \"\")\n const edits = call.input.edits as Array<{ old_text: string; new_text: string }> | undefined\n const absPath = path.resolve(this.cwd, filePath)\n\n if (!edits || edits.length === 0) {\n return {\n tool_use_id: call.id,\n content: \"No edits provided.\",\n is_error: true,\n }\n }\n\n // Check write permission\n const permission = await globalPermissions.checkFileWrite(filePath)\n if (permission === \"deny\") {\n return {\n tool_use_id: call.id,\n content: `File write blocked by permissions: ${filePath}`,\n is_error: true,\n }\n }\n if (permission === \"skip\") {\n return {\n tool_use_id: call.id,\n content: `File write skipped (plan mode): ${filePath}`,\n }\n }\n\n // pre:file-write hook\n if (globalHooks.has(\"pre:file-write\")) {\n const hookResult = await globalHooks.execute(\"pre:file-write\", {\n event: \"pre:file-write\",\n file: absPath,\n cwd: this.cwd,\n })\n if (hookResult.blocked) {\n return {\n tool_use_id: call.id,\n content: hookResult.message || `File edit blocked by pre:file-write hook: ${filePath}`,\n is_error: true,\n }\n }\n }\n\n let content = await fs.readFile(absPath, \"utf8\")\n const applied: string[] = []\n\n for (const edit of edits) {\n if (content.includes(edit.old_text)) {\n content = content.replace(edit.old_text, edit.new_text)\n applied.push(`Replaced: \"${edit.old_text.slice(0, 40)}...\"`)\n } else {\n applied.push(`Not found: \"${edit.old_text.slice(0, 40)}...\"`)\n }\n }\n\n if (!this.options.dryRun) {\n await fs.writeFile(absPath, content, \"utf8\")\n }\n\n // post:file-write hook\n if (globalHooks.has(\"post:file-write\")) {\n await globalHooks.execute(\"post:file-write\", {\n event: \"post:file-write\",\n file: absPath,\n fileContent: content,\n cwd: this.cwd,\n })\n }\n\n return {\n tool_use_id: call.id,\n content: `Edited ${filePath}:\\n${applied.join(\"\\n\")}`,\n }\n }\n\n private async createFiles(call: ToolCallInput): Promise<ToolResult> {\n const input = call.input as {\n files?: GeneratedFile[]\n summary?: string\n }\n\n const files = input.files || []\n\n return {\n tool_use_id: call.id,\n content: input.summary || `Queued ${files.length} file(s) for creation.`,\n files,\n }\n }\n\n private async spawnAgent(call: ToolCallInput): Promise<ToolResult> {\n const agentId = String(call.input.agent_id || \"\")\n const prompt = String(call.input.prompt || \"\")\n const timeoutSeconds = Number(call.input.timeout_seconds) || 300\n\n if (!agentId || !prompt) {\n return {\n tool_use_id: call.id,\n content: \"agent_id and prompt are required.\",\n is_error: true,\n }\n }\n\n try {\n // Dynamically import to avoid circular dependency\n const { SubAgentManager } = await import(\"@/agents/subagent\")\n\n // Get the global registry from the daemon (if running)\n const { getGlobalRegistry } = await import(\"@/agents/registry\")\n const registry = getGlobalRegistry()\n\n if (!registry) {\n return {\n tool_use_id: call.id,\n content: \"Sub-agent spawning requires the daemon to be running.\",\n is_error: true,\n }\n }\n\n const manager = new SubAgentManager(registry)\n const result = await manager.spawn({\n targetAgentId: agentId,\n prompt,\n parentAgentId: \"orchestrator\",\n timeout: timeoutSeconds * 1000,\n })\n\n if (result.success) {\n return {\n tool_use_id: call.id,\n content: `Sub-agent \"${agentId}\" completed (${Math.round(result.duration / 1000)}s):\\n\\n${result.content}`,\n }\n } else {\n return {\n tool_use_id: call.id,\n content: `Sub-agent \"${agentId}\" failed: ${result.error}`,\n is_error: true,\n }\n }\n } catch (error: any) {\n return {\n tool_use_id: call.id,\n content: `Failed to spawn sub-agent: ${error.message}`,\n is_error: true,\n }\n }\n }\n\n private async askUser(call: ToolCallInput): Promise<ToolResult> {\n const question = String(call.input.question || \"\")\n const options = call.input.options as string[] | undefined\n\n let followUp = question\n if (options?.length) {\n followUp += `\\nOptions: ${options.join(\", \")}`\n }\n\n return {\n tool_use_id: call.id,\n content: \"Question sent to user.\",\n followUp,\n }\n }\n}\n","// --- Agentic Orchestrator: tool_result feedback loop ---\n\nimport type {\n AgentProvider,\n GenerationMessage,\n GeneratedFile,\n ProviderOptions,\n AnthropicMessage,\n ContentBlock,\n RawGenerationResult,\n} from \"./providers/types\"\nimport { ToolExecutor, type ToolResult } from \"./tools\"\nimport { getAnthropicTools, formatToolsForSystemPrompt } from \"./tools\"\nimport { debug } from \"@/observability\"\n\nexport interface AgenticLoopOptions {\n provider: AgentProvider\n systemPrompt: string\n messages: GenerationMessage[]\n providerOptions: ProviderOptions\n cwd: string\n maxIterations?: number\n enabledTools?: string[]\n interactive?: boolean\n overwrite?: boolean\n dryRun?: boolean\n onProgress?: (event: AgenticProgressEvent) => void\n}\n\nexport type AgenticProgressEvent =\n | { type: \"iteration_start\"; iteration: number }\n | { type: \"tool_call\"; name: string; id: string; input: Record<string, unknown> }\n | { type: \"tool_result\"; name: string; id: string; content: string; is_error?: boolean }\n | { type: \"text_delta\"; text: string }\n | { type: \"files_created\"; files: GeneratedFile[] }\n | { type: \"complete\"; iterations: number; totalTokens: number }\n\nexport interface AgenticResult {\n files: GeneratedFile[]\n content: string\n followUp?: string\n tokensUsed: number\n iterations: number\n}\n\n/**\n * Run the agentic tool_result loop.\n * The LLM decides what tools to call (read files, search, edit, etc.)\n * and we feed results back until it signals completion.\n */\nexport async function runAgenticLoop(options: AgenticLoopOptions): Promise<AgenticResult> {\n const {\n provider,\n systemPrompt,\n messages: inputMessages,\n providerOptions,\n cwd,\n maxIterations = 20,\n enabledTools,\n interactive = true,\n overwrite = false,\n dryRun = false,\n onProgress,\n } = options\n\n // Check if provider supports generateRaw\n if (!provider.generateRaw) {\n return runLegacyLoop(options)\n }\n\n const executor = new ToolExecutor(cwd, { interactive, overwrite, dryRun })\n const tools = getAnthropicTools(enabledTools)\n\n // Convert GenerationMessage[] to AnthropicMessage[] (strip system messages)\n const anthropicMessages: AnthropicMessage[] = inputMessages\n .filter((m) => m.role !== \"system\")\n .map((m) => ({\n role: m.role as \"user\" | \"assistant\",\n content: m.content,\n }))\n\n const allFiles: GeneratedFile[] = []\n let totalTokens = 0\n let textContent = \"\"\n let followUp: string | undefined\n let iteration = 0\n\n while (iteration < maxIterations) {\n iteration++\n onProgress?.({ type: \"iteration_start\", iteration })\n debug.step(iteration, `Agentic loop iteration (${tools.length} tools available)`)\n\n let result: RawGenerationResult\n try {\n result = await provider.generateRaw(\n anthropicMessages,\n systemPrompt,\n tools,\n providerOptions\n )\n } catch (error: any) {\n // If generateRaw fails (e.g., OAuth mode), fall back to legacy\n if (error.message?.includes(\"not available\")) {\n return runLegacyLoop(options)\n }\n throw error\n }\n\n totalTokens += result.usage.input_tokens + result.usage.output_tokens\n\n // Collect text from response\n for (const block of result.content) {\n if (block.type === \"text\") {\n textContent += block.text\n onProgress?.({ type: \"text_delta\", text: block.text })\n }\n }\n\n // If stop_reason is end_turn or max_tokens, we're done\n if (result.stop_reason === \"end_turn\" || result.stop_reason === \"max_tokens\") {\n break\n }\n\n // If stop_reason is tool_use, execute the tools\n if (result.stop_reason === \"tool_use\") {\n const toolUseBlocks = result.content.filter(\n (b): b is Extract<ContentBlock, { type: \"tool_use\" }> => b.type === \"tool_use\"\n )\n\n if (toolUseBlocks.length === 0) break\n\n // Append assistant message with the tool_use blocks\n anthropicMessages.push({\n role: \"assistant\",\n content: result.content,\n })\n\n // Execute each tool and collect results\n const toolResults: ContentBlock[] = []\n\n for (const toolBlock of toolUseBlocks) {\n onProgress?.({\n type: \"tool_call\",\n name: toolBlock.name,\n id: toolBlock.id,\n input: toolBlock.input,\n })\n\n debug.step(iteration, `Tool call: ${toolBlock.name}`)\n\n const toolResult = await executor.execute({\n name: toolBlock.name,\n id: toolBlock.id,\n input: toolBlock.input,\n })\n\n onProgress?.({\n type: \"tool_result\",\n name: toolBlock.name,\n id: toolBlock.id,\n content: toolResult.content.slice(0, 200),\n is_error: toolResult.is_error,\n })\n\n // Collect files from create_files calls\n if (toolResult.files?.length) {\n allFiles.push(...toolResult.files)\n onProgress?.({ type: \"files_created\", files: toolResult.files })\n }\n\n // Handle ask_user — surface the question to caller\n if (toolResult.followUp) {\n followUp = toolResult.followUp\n }\n\n toolResults.push({\n type: \"tool_result\",\n tool_use_id: toolResult.tool_use_id,\n content: toolResult.content,\n is_error: toolResult.is_error,\n })\n }\n\n // Append user message with tool_result blocks\n anthropicMessages.push({\n role: \"user\",\n content: toolResults,\n })\n\n // If we got a follow-up question, break the loop to surface it\n if (followUp) break\n\n continue\n }\n\n // Unknown stop_reason — break\n break\n }\n\n onProgress?.({ type: \"complete\", iterations: iteration, totalTokens })\n\n return {\n files: allFiles,\n content: textContent,\n followUp,\n tokensUsed: totalTokens,\n iterations: iteration,\n }\n}\n\n/**\n * Fallback to the legacy [CONTINUE]-based multi-step loop.\n * Used when provider doesn't support generateRaw() (CLI/OAuth mode).\n * For CLI mode, we include tool descriptions in the system prompt so the\n * `claude` binary uses its own built-in tools (read, write, bash, etc.).\n */\nasync function runLegacyLoop(options: AgenticLoopOptions): Promise<AgenticResult> {\n const {\n provider,\n systemPrompt,\n messages: inputMessages,\n providerOptions,\n maxIterations = 5,\n } = options\n\n // Enhance system prompt with tool descriptions for CLI mode\n const enhancedSystemPrompt = systemPrompt + \"\\n\\n\" + formatToolsForSystemPrompt()\n\n const messages: GenerationMessage[] = [\n { role: \"system\", content: enhancedSystemPrompt },\n ...inputMessages.filter((m) => m.role !== \"system\"),\n ]\n\n const allFiles: GeneratedFile[] = []\n let totalTokens = 0\n let content = \"\"\n let followUp: string | undefined\n let step = 0\n\n while (step < maxIterations) {\n step++\n debug.step(step, `Legacy loop step (model: ${providerOptions.model || \"default\"})`)\n\n const result = await provider.generate(messages, providerOptions)\n\n totalTokens += result.tokensUsed || 0\n content = result.content\n\n if (result.files.length) {\n allFiles.push(...result.files)\n }\n\n if (result.followUp) {\n followUp = result.followUp\n break\n }\n\n if (result.files.length === 0 && step > 1) break\n\n const wantsContinuation =\n result.content.includes(\"[CONTINUE]\") ||\n result.content.includes(\"Next, I'll\") ||\n result.content.includes(\"Now let me\") ||\n result.content.includes(\"I'll also generate\")\n\n if (!wantsContinuation) break\n\n const filesSummary = result.files\n .map((f) => `Created: ${f.path}${f.description ? ` — ${f.description}` : \"\"}`)\n .join(\"\\n\")\n\n messages.push({\n role: \"assistant\",\n content: result.content + (filesSummary ? `\\n\\nFiles created:\\n${filesSummary}` : \"\"),\n })\n\n messages.push({\n role: \"user\",\n content:\n \"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response.\",\n })\n }\n\n return {\n files: allFiles,\n content,\n followUp,\n tokensUsed: totalTokens,\n iterations: step,\n }\n}\n\n/**\n * Check if a provider supports the agentic loop (has generateRaw).\n */\nexport function supportsAgenticLoop(provider: AgentProvider): boolean {\n return typeof provider.generateRaw === \"function\"\n}\n","export class AsyncQueue<T> {\n private queue: T[] = []\n private resolvers: Array<(value: IteratorResult<T>) => void> = []\n private closed = false\n\n push(item: T): void {\n if (this.closed) return\n\n const resolver = this.resolvers.shift()\n if (resolver) {\n resolver({ value: item, done: false })\n return\n }\n this.queue.push(item)\n }\n\n close(): void {\n if (this.closed) return\n this.closed = true\n for (const resolve of this.resolvers.splice(0)) {\n resolve({ value: undefined as any, done: true })\n }\n }\n\n async next(): Promise<IteratorResult<T>> {\n if (this.queue.length) {\n return { value: this.queue.shift() as T, done: false }\n }\n if (this.closed) {\n return { value: undefined as any, done: true }\n }\n return new Promise<IteratorResult<T>>((resolve) => {\n this.resolvers.push(resolve)\n })\n }\n\n async *[Symbol.asyncIterator](): AsyncGenerator<T> {\n while (true) {\n const { value, done } = await this.next()\n if (done) return\n yield value\n }\n }\n}\n\n","import type { AgentProvider, GenerationMessage, GenerationResult, OutputType, StreamEvent } from \"./providers/types\"\nimport { agentConfigSchema, type AgentConfig } from \"./providers/types\"\nimport { createProvider, type ProviderName } from \"./providers\"\nimport { loadAuthConfig } from \"@/utils/auth-store\"\nimport { ensureCredentials } from \"@/utils/auth-store\"\nimport { detectTechStack, formatTechStack, type TechStack } from \"./context/tech-stack\"\nimport { detectSchemas, formatSchemas, type ProjectSchemas } from \"./context/schema\"\nimport { gatherContext7Docs } from \"./context/context7\"\nimport { loadLocalSkills, matchSkillsToTask } from \"./skills/loader\"\nimport { resolveOutputType } from \"./outputs/types\"\nimport { writeGeneratedFiles, resolveOutputDir, type WriteOptions, type WriteResult } from \"./outputs/handlers\"\nimport { logger } from \"@/utils/logger\"\nimport { globalHooks } from \"@/hooks\"\nimport { globalTracker } from \"@/observability\"\nimport { debug } from \"@/observability\"\nimport { MemoryHierarchy, ContextBuilder, loadProjectInstructions } from \"@/memory\"\nimport type { Skill } from \"./skills/types\"\nimport { runAgenticLoop, supportsAgenticLoop, type AgenticProgressEvent } from \"./orchestrator\"\nimport { AsyncQueue } from \"@/utils/async-queue\"\n\n// --- Agent Orchestrator: the brain that coordinates everything ---\n\nexport interface AgentContext {\n techStack: TechStack\n schemas: ProjectSchemas\n skills: Skill[]\n docs: string\n config: AgentConfig\n memoryContext: string\n projectInstructions: string\n}\n\nexport interface GenerateOptions {\n task: string\n outputType?: OutputType\n outputDir?: string\n overwrite?: boolean\n dryRun?: boolean\n provider?: ProviderName\n model?: string\n apiKey?: string\n cwd: string\n context7?: boolean\n interactive?: boolean\n skills?: string[] // Additional skill packages to load\n maxSteps?: number // Max agentic loop iterations (default 20 for agentic, 5 for legacy)\n sessionMessages?: GenerationMessage[] // Multi-turn context from REPL sessions\n heal?: boolean // undefined = auto (heal if files written), false = skip\n healConfig?: {\n testCommand?: string\n buildCommand?: string\n lintCommand?: string\n maxAttempts?: number\n }\n}\n\nexport interface GenerateResult {\n files: WriteResult\n content: string\n outputType: OutputType\n followUp?: string\n tokensUsed?: number\n healResult?: import(\"@/runtime/heal\").HealResult\n}\n\nexport async function createAgentContext(\n cwd: string,\n task: string,\n config?: Partial<AgentConfig>\n): Promise<AgentContext> {\n const agentConfig = agentConfigSchema.parse(config || {})\n\n // Load memory hierarchy\n const memory = new MemoryHierarchy(cwd)\n await memory.load()\n\n // Gather all context in parallel\n const [techStack, schemas, skills] = await Promise.all([\n detectTechStack(cwd),\n detectSchemas(cwd),\n loadLocalSkills(cwd),\n ])\n\n // Context7 docs (optional, can fail gracefully)\n let docs = \"\"\n if (agentConfig.context7.enabled) {\n try {\n docs = await gatherContext7Docs(techStack, task, agentConfig.context7.apiKey)\n } catch {\n // Context7 is optional, don't fail the whole flow\n }\n }\n\n // Build memory context from both user and project levels\n const memoryContext = memory.buildMemoryContext(task)\n\n // Load project instructions (SHADXN.md or CLAUDE.md) with @-import resolution\n const projectInstructions = loadProjectInstructions(cwd)\n\n debug.context(\"memory\", memoryContext ? \"loaded\" : \"empty\")\n debug.context(\"instructions\", projectInstructions ? \"loaded from project\" : \"none\")\n\n return {\n techStack,\n schemas,\n skills,\n docs,\n config: agentConfig,\n memoryContext,\n projectInstructions,\n }\n}\n\nexport async function generate(options: GenerateOptions): Promise<GenerateResult> {\n const {\n task,\n cwd,\n overwrite = false,\n dryRun = false,\n provider: providerName = \"claude-code\",\n model,\n apiKey,\n context7 = true,\n interactive = true,\n } = options\n\n // 0. pre:prompt hook — can modify or block the task prompt\n let effectiveTask = task\n if (globalHooks.has(\"pre:prompt\")) {\n const promptResult = await globalHooks.execute(\"pre:prompt\", {\n event: \"pre:prompt\",\n task,\n cwd,\n })\n if (promptResult.blocked) {\n throw new Error(promptResult.message || \"Blocked by pre:prompt hook\")\n }\n if (promptResult.modified?.task) {\n effectiveTask = String(promptResult.modified.task)\n }\n }\n\n // 0b. pre:generate hook — can block the entire generation\n if (globalHooks.has(\"pre:generate\")) {\n const genResult = await globalHooks.execute(\"pre:generate\", {\n event: \"pre:generate\",\n task: effectiveTask,\n cwd,\n })\n if (genResult.blocked) {\n throw new Error(genResult.message || \"Blocked by pre:generate hook\")\n }\n }\n\n // 1. Gather context\n logger.info(\"Analyzing project...\")\n const context = await createAgentContext(cwd, effectiveTask, {\n provider: providerName,\n context7: { enabled: context7, apiKey },\n })\n\n // 2. Resolve output type\n const outputType = resolveOutputType(options.outputType, effectiveTask)\n logger.info(`Output type: ${outputType}`)\n\n // 3. Match relevant skills\n const matchedSkills = matchSkillsToTask(context.skills, effectiveTask, outputType)\n if (matchedSkills.length) {\n logger.info(\n `Loaded ${matchedSkills.length} relevant skill(s): ${matchedSkills.map((m) => m.skill.frontmatter.name).join(\", \")}`\n )\n }\n\n // 4. Build system prompt\n const systemPrompt = buildSystemPrompt(context, outputType, matchedSkills.map((m) => m.skill))\n\n // 5. Ensure credentials exist (auto-prompt if missing)\n const hasCredentials = await ensureCredentials(apiKey)\n if (!hasCredentials) {\n throw new Error(\"No credentials configured. Run `agentx model` to set up.\")\n }\n\n // 6. Create provider\n const provider = createProvider(providerName, apiKey)\n const resolvedModel = model || loadAuthConfig()?.model\n\n // Build initial messages (without system — orchestrator handles it)\n const sessionMessages: GenerationMessage[] = [\n ...(options.sessionMessages || []),\n { role: \"user\", content: effectiveTask },\n ]\n\n logger.info(\"Generating...\")\n\n // Determine if we should use the agentic loop\n const useAgentic = supportsAgenticLoop(provider)\n const maxSteps = options.maxSteps ?? (useAgentic ? 20 : 5)\n\n // 7. Run orchestrator (agentic or legacy)\n const agenticResult = await runAgenticLoop({\n provider,\n systemPrompt,\n messages: [\n { role: \"system\", content: systemPrompt },\n ...sessionMessages,\n ],\n providerOptions: { model: resolvedModel, maxTokens: 8192 },\n cwd,\n maxIterations: maxSteps,\n enabledTools: context.config.agentic.enabledTools.filter(\n (t) => !context.config.agentic.disabledTools.includes(t)\n ),\n interactive,\n overwrite,\n dryRun,\n onProgress: (event) => {\n if (event.type === \"iteration_start\" && event.iteration > 1) {\n logger.info(`Step ${event.iteration}/${maxSteps}...`)\n }\n if (event.type === \"tool_call\") {\n debug.step(0, `Tool: ${event.name}`)\n }\n },\n })\n\n // Track token usage\n if (agenticResult.tokensUsed) {\n const stepModel = resolvedModel || \"claude-sonnet-4-20250514\"\n const estInput = Math.round(agenticResult.tokensUsed * 0.3)\n const estOutput = agenticResult.tokensUsed - estInput\n globalTracker.recordStep(1, stepModel, estInput, estOutput)\n }\n\n let { content } = agenticResult\n const { followUp, tokensUsed: totalTokens } = agenticResult\n\n if (agenticResult.iterations > 1) {\n logger.info(`Completed in ${agenticResult.iterations} step(s)`)\n }\n\n // post:response hook — can modify or block the AI response\n if (globalHooks.has(\"post:response\")) {\n const responseResult = await globalHooks.execute(\"post:response\", {\n event: \"post:response\",\n content,\n task: effectiveTask,\n cwd,\n })\n if (responseResult.blocked) {\n throw new Error(responseResult.message || \"Blocked by post:response hook\")\n }\n if (responseResult.modified?.content) {\n content = String(responseResult.modified.content)\n }\n }\n\n // Handle follow-up questions (interactive mode)\n if (followUp && interactive) {\n return {\n files: { written: [], skipped: [], errors: [] },\n content,\n outputType,\n followUp,\n tokensUsed: totalTokens,\n }\n }\n\n // Deduplicate files (later versions override earlier ones)\n const deduped = new Map<string, import(\"./providers/types\").GeneratedFile>()\n for (const file of agenticResult.files) {\n deduped.set(file.path, file)\n }\n\n // Write files\n const outputDir = resolveOutputDir(outputType, context.techStack, options.outputDir)\n\n const writeResult = await writeGeneratedFiles(Array.from(deduped.values()), {\n cwd,\n overwrite,\n dryRun,\n outputDir,\n })\n\n // Heal loop — verify generated code and auto-fix if needed\n let healResult: import(\"@/runtime/heal\").HealResult | undefined\n if (options.heal !== false && !dryRun && writeResult.written.length > 0) {\n const { HealEngine } = await import(\"@/runtime/heal\")\n const healEngine = new HealEngine(cwd, {\n enabled: true,\n testCommand: options.healConfig?.testCommand,\n buildCommand: options.healConfig?.buildCommand,\n lintCommand: options.healConfig?.lintCommand,\n maxAttempts: options.healConfig?.maxAttempts ?? 3,\n provider: providerName,\n model: resolvedModel,\n apiKey,\n })\n healResult = await healEngine.detectAndHeal(writeResult.written, effectiveTask)\n\n if (!healResult.healed && healResult.error) {\n await globalHooks.execute(\"on:error\", {\n event: \"on:error\",\n error: new Error(healResult.error),\n task: effectiveTask,\n cwd,\n })\n }\n }\n\n // post:generate hook — post-processing (format, lint, etc.)\n if (globalHooks.has(\"post:generate\")) {\n await globalHooks.execute(\"post:generate\", {\n event: \"post:generate\",\n task: effectiveTask,\n content,\n cwd,\n })\n }\n\n return {\n files: writeResult,\n content,\n outputType,\n tokensUsed: totalTokens,\n healResult,\n }\n}\n\n// --- Streaming generation ---\n\nexport type GenerateStreamEvent =\n | StreamEvent\n | { type: \"context_ready\"; outputType: OutputType }\n | { type: \"step_complete\"; step: number; filesCount: number }\n | { type: \"tool_call\"; name: string; id: string }\n | { type: \"tool_result\"; name: string; id: string; is_error?: boolean }\n | { type: \"iteration\"; iteration: number }\n | { type: \"generate_result\"; result: GenerateResult }\n\nexport async function* generateStream(\n options: GenerateOptions\n): AsyncGenerator<GenerateStreamEvent> {\n const {\n task,\n cwd,\n overwrite = false,\n dryRun = false,\n provider: providerName = \"claude-code\",\n model,\n apiKey,\n context7 = true,\n interactive = true,\n } = options\n\n // 0. pre:prompt hook\n let effectiveTask = task\n if (globalHooks.has(\"pre:prompt\")) {\n const promptResult = await globalHooks.execute(\"pre:prompt\", {\n event: \"pre:prompt\",\n task,\n cwd,\n })\n if (promptResult.blocked) {\n yield { type: \"error\", error: promptResult.message || \"Blocked by pre:prompt hook\" }\n return\n }\n if (promptResult.modified?.task) {\n effectiveTask = String(promptResult.modified.task)\n }\n }\n\n // 0b. pre:generate hook\n if (globalHooks.has(\"pre:generate\")) {\n const genResult = await globalHooks.execute(\"pre:generate\", {\n event: \"pre:generate\",\n task: effectiveTask,\n cwd,\n })\n if (genResult.blocked) {\n yield { type: \"error\", error: genResult.message || \"Blocked by pre:generate hook\" }\n return\n }\n }\n\n // 1. Gather context\n const context = await createAgentContext(cwd, effectiveTask, {\n provider: providerName,\n context7: { enabled: context7, apiKey },\n })\n\n // 2. Resolve output type\n const outputType = resolveOutputType(options.outputType, effectiveTask)\n\n // Signal context ready so UI can stop spinner\n yield { type: \"context_ready\", outputType }\n\n // 3. Match relevant skills\n const matchedSkills = matchSkillsToTask(context.skills, effectiveTask, outputType)\n\n // 4. Build system prompt\n const systemPrompt = buildSystemPrompt(context, outputType, matchedSkills.map((m) => m.skill))\n\n // 5. Ensure credentials\n const hasCredentials = await ensureCredentials(apiKey)\n if (!hasCredentials) {\n yield { type: \"error\", error: \"No credentials configured. Run `agentx model` to set up.\" }\n return\n }\n\n // 6. Create provider\n const provider = createProvider(providerName, apiKey)\n const resolvedModel = model || loadAuthConfig()?.model\n const useAgentic = supportsAgenticLoop(provider)\n const maxSteps = options.maxSteps ?? (useAgentic ? 20 : 5)\n\n const sessionMessages: GenerationMessage[] = [\n ...(options.sessionMessages || []),\n { role: \"user\", content: effectiveTask },\n ]\n\n // For agentic mode, use the orchestrator with progress events\n if (useAgentic) {\n const q = new AsyncQueue<GenerateStreamEvent>()\n let agenticResult: Awaited<ReturnType<typeof runAgenticLoop>> | undefined\n let agenticError: unknown\n\n const agenticPromise = (async () => {\n try {\n agenticResult = await runAgenticLoop({\n provider,\n systemPrompt,\n messages: [\n { role: \"system\", content: systemPrompt },\n ...sessionMessages,\n ],\n providerOptions: { model: resolvedModel, maxTokens: 8192 },\n cwd,\n maxIterations: maxSteps,\n enabledTools: context.config.agentic.enabledTools.filter(\n (t) => !context.config.agentic.disabledTools.includes(t)\n ),\n interactive,\n overwrite,\n dryRun,\n onProgress: (event) => {\n if (event.type === \"text_delta\") {\n q.push({ type: \"text_delta\", text: event.text })\n }\n if (event.type === \"iteration_start\") {\n q.push({ type: \"iteration\", iteration: event.iteration })\n }\n if (event.type === \"tool_call\") {\n q.push({ type: \"tool_call\", name: event.name, id: event.id })\n }\n if (event.type === \"tool_result\") {\n q.push({ type: \"tool_result\", name: event.name, id: event.id, is_error: event.is_error })\n }\n if (event.type === \"files_created\") {\n q.push({ type: \"step_complete\", step: 0, filesCount: event.files.length })\n }\n },\n })\n } catch (err) {\n agenticError = err\n } finally {\n q.close()\n }\n })()\n\n for await (const evt of q) {\n yield evt\n }\n\n await agenticPromise\n if (agenticError) {\n const msg = agenticError instanceof Error ? agenticError.message : String(agenticError)\n yield { type: \"error\", error: msg }\n return\n }\n if (!agenticResult) {\n yield { type: \"error\", error: \"Agentic loop failed without a result\" }\n return\n }\n\n yield {\n type: \"done\",\n result: {\n content: agenticResult.content,\n files: agenticResult.files,\n tokensUsed: agenticResult.tokensUsed,\n followUp: agenticResult.followUp,\n },\n }\n\n // Write files and heal\n let { content } = agenticResult\n\n // post:response hook\n if (globalHooks.has(\"post:response\")) {\n const responseResult = await globalHooks.execute(\"post:response\", {\n event: \"post:response\",\n content,\n task: effectiveTask,\n cwd,\n })\n if (responseResult.blocked) {\n yield { type: \"error\", error: responseResult.message || \"Blocked by post:response hook\" }\n return\n }\n if (responseResult.modified?.content) {\n content = String(responseResult.modified.content)\n }\n }\n\n if (agenticResult.followUp && interactive) {\n yield {\n type: \"generate_result\",\n result: {\n files: { written: [], skipped: [], errors: [] },\n content,\n outputType,\n followUp: agenticResult.followUp,\n tokensUsed: agenticResult.tokensUsed,\n },\n }\n return\n }\n\n const deduped = new Map<string, import(\"./providers/types\").GeneratedFile>()\n for (const file of agenticResult.files) {\n deduped.set(file.path, file)\n }\n\n const outputDir = resolveOutputDir(outputType, context.techStack, options.outputDir)\n const writeResult = await writeGeneratedFiles(Array.from(deduped.values()), {\n cwd,\n overwrite,\n dryRun,\n outputDir,\n })\n\n let healResult: import(\"@/runtime/heal\").HealResult | undefined\n if (options.heal !== false && !dryRun && writeResult.written.length > 0) {\n const { HealEngine } = await import(\"@/runtime/heal\")\n const healEngine = new HealEngine(cwd, {\n enabled: true,\n testCommand: options.healConfig?.testCommand,\n buildCommand: options.healConfig?.buildCommand,\n lintCommand: options.healConfig?.lintCommand,\n maxAttempts: options.healConfig?.maxAttempts ?? 3,\n provider: providerName,\n model: resolvedModel,\n apiKey,\n })\n healResult = await healEngine.detectAndHeal(writeResult.written, effectiveTask)\n }\n\n if (globalHooks.has(\"post:generate\")) {\n await globalHooks.execute(\"post:generate\", {\n event: \"post:generate\",\n task: effectiveTask,\n content,\n cwd,\n })\n }\n\n yield {\n type: \"generate_result\",\n result: {\n files: writeResult,\n content,\n outputType,\n tokensUsed: agenticResult.tokensUsed,\n healResult,\n },\n }\n return\n }\n\n // --- Legacy streaming path (no generateRaw) ---\n\n const messages: GenerationMessage[] = [\n { role: \"system\", content: systemPrompt },\n ...sessionMessages,\n ]\n\n const allFiles: import(\"./providers/types\").GeneratedFile[] = []\n let totalTokens = 0\n let content = \"\"\n let followUp: string | undefined\n let step = 0\n\n // --- Step 1: streamed ---\n step++\n debug.step(step, `Starting generation (model: ${resolvedModel || \"default\"})`)\n\n let step1Result: GenerationResult\n\n if (provider.stream) {\n let accumulated = \"\"\n let streamResult: GenerationResult | undefined\n\n for await (const event of provider.stream(messages, {\n model: resolvedModel,\n maxTokens: 8192,\n })) {\n yield event\n\n if (event.type === \"text_delta\") {\n accumulated += event.text\n }\n if (event.type === \"done\") {\n streamResult = event.result\n }\n }\n\n step1Result = streamResult || {\n content: accumulated,\n files: [],\n tokensUsed: 0,\n }\n } else {\n const result = await provider.generate(messages, {\n model: resolvedModel,\n maxTokens: 8192,\n })\n\n if (result.content) {\n yield { type: \"text_delta\", text: result.content }\n }\n yield { type: \"done\", result }\n step1Result = result\n }\n\n totalTokens += step1Result.tokensUsed || 0\n content = step1Result.content\n\n const step1Tokens = step1Result.tokensUsed || 0\n const step1Model = resolvedModel || \"claude-sonnet-4-20250514\"\n const estInput1 = Math.round(step1Tokens * 0.3)\n const estOutput1 = step1Tokens - estInput1\n globalTracker.recordStep(step, step1Model, estInput1, estOutput1)\n debug.api(\"generate\", step1Model, step1Tokens)\n debug.step(step, `Generated ${step1Result.files.length} file(s), ${step1Tokens} tokens`)\n\n if (step1Result.files.length) {\n allFiles.push(...step1Result.files)\n }\n\n if (step1Result.followUp) {\n followUp = step1Result.followUp\n }\n\n yield { type: \"step_complete\", step, filesCount: step1Result.files.length }\n\n // --- Steps 2-N: non-streaming continuation loop ---\n if (!followUp) {\n const wantsContinuation1 =\n content.includes(\"[CONTINUE]\") ||\n content.includes(\"Next, I'll\") ||\n content.includes(\"Now let me\") ||\n content.includes(\"I'll also generate\")\n\n if (wantsContinuation1 && step1Result.files.length > 0) {\n const filesSummary = step1Result.files\n .map((f) => `Created: ${f.path}${f.description ? ` — ${f.description}` : \"\"}`)\n .join(\"\\n\")\n messages.push({\n role: \"assistant\",\n content: content + (filesSummary ? `\\n\\nFiles created:\\n${filesSummary}` : \"\"),\n })\n messages.push({\n role: \"user\",\n content:\n \"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response.\",\n })\n\n while (step < maxSteps) {\n step++\n debug.step(step, `Starting generation (model: ${resolvedModel || \"default\"})`)\n\n const result = await provider.generate(messages, {\n model: resolvedModel,\n maxTokens: 8192,\n })\n\n totalTokens += result.tokensUsed || 0\n content = result.content\n\n const stepTokens = result.tokensUsed || 0\n const stepModel = resolvedModel || \"claude-sonnet-4-20250514\"\n const estInput = Math.round(stepTokens * 0.3)\n const estOutput = stepTokens - estInput\n globalTracker.recordStep(step, stepModel, estInput, estOutput)\n debug.api(\"generate\", stepModel, stepTokens)\n debug.step(step, `Generated ${result.files.length} file(s), ${stepTokens} tokens`)\n\n if (result.files.length) {\n allFiles.push(...result.files)\n }\n\n yield { type: \"step_complete\", step, filesCount: result.files.length }\n\n if (result.followUp) {\n followUp = result.followUp\n break\n }\n if (result.files.length === 0 && step > 1) break\n\n const wantsContinuation =\n result.content.includes(\"[CONTINUE]\") ||\n result.content.includes(\"Next, I'll\") ||\n result.content.includes(\"Now let me\") ||\n result.content.includes(\"I'll also generate\")\n\n if (!wantsContinuation) break\n\n const filesSummary2 = result.files\n .map((f) => `Created: ${f.path}${f.description ? ` — ${f.description}` : \"\"}`)\n .join(\"\\n\")\n messages.push({\n role: \"assistant\",\n content: result.content + (filesSummary2 ? `\\n\\nFiles created:\\n${filesSummary2}` : \"\"),\n })\n messages.push({\n role: \"user\",\n content:\n \"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response.\",\n })\n }\n }\n }\n\n // post:response hook\n if (globalHooks.has(\"post:response\")) {\n const responseResult = await globalHooks.execute(\"post:response\", {\n event: \"post:response\",\n content,\n task: effectiveTask,\n cwd,\n })\n if (responseResult.blocked) {\n yield { type: \"error\", error: responseResult.message || \"Blocked by post:response hook\" }\n return\n }\n if (responseResult.modified?.content) {\n content = String(responseResult.modified.content)\n }\n }\n\n if (followUp && interactive) {\n yield {\n type: \"generate_result\",\n result: {\n files: { written: [], skipped: [], errors: [] },\n content,\n outputType,\n followUp,\n tokensUsed: totalTokens,\n },\n }\n return\n }\n\n const deduped = new Map<import(\"./providers/types\").GeneratedFile[\"path\"], import(\"./providers/types\").GeneratedFile>()\n for (const file of allFiles) {\n deduped.set(file.path, file)\n }\n\n const outputDir = resolveOutputDir(outputType, context.techStack, options.outputDir)\n const writeResult = await writeGeneratedFiles(Array.from(deduped.values()), {\n cwd,\n overwrite,\n dryRun,\n outputDir,\n })\n\n let healResult: import(\"@/runtime/heal\").HealResult | undefined\n if (options.heal !== false && !dryRun && writeResult.written.length > 0) {\n const { HealEngine } = await import(\"@/runtime/heal\")\n const healEngine = new HealEngine(cwd, {\n enabled: true,\n testCommand: options.healConfig?.testCommand,\n buildCommand: options.healConfig?.buildCommand,\n lintCommand: options.healConfig?.lintCommand,\n maxAttempts: options.healConfig?.maxAttempts ?? 3,\n provider: providerName,\n model: resolvedModel,\n apiKey,\n })\n healResult = await healEngine.detectAndHeal(writeResult.written, effectiveTask)\n\n if (!healResult.healed && healResult.error) {\n await globalHooks.execute(\"on:error\", {\n event: \"on:error\",\n error: new Error(healResult.error),\n task: effectiveTask,\n cwd,\n })\n }\n }\n\n if (globalHooks.has(\"post:generate\")) {\n await globalHooks.execute(\"post:generate\", {\n event: \"post:generate\",\n task: effectiveTask,\n content,\n cwd,\n })\n }\n\n yield {\n type: \"generate_result\",\n result: {\n files: writeResult,\n content,\n outputType,\n tokensUsed: totalTokens,\n healResult,\n },\n }\n}\n\nfunction buildSystemPrompt(\n context: AgentContext,\n outputType: string,\n skills: Skill[]\n): string {\n const sections: string[] = []\n\n // Identity — updated for agentic capabilities\n sections.push(`You are agentx, an agentic code generation tool. You generate high-quality, production-ready output for any tech stack.\n\nYour primary tool is \\`create_files\\` — use it to output all generated code, documents, and configs as files.\nIf the request is ambiguous or you need critical information to proceed correctly, use \\`ask_user\\` to ask a clarifying question.\n\nYou also have tools to inspect the codebase before generating code:\n- \\`read_file\\` — read existing files to understand patterns, styles, and implementations\n- \\`search_files\\` — search for files by glob pattern, optionally grep content with regex\n- \\`list_directory\\` — explore the project structure\n- \\`run_command\\` — run shell commands (build, test, lint, etc.)\n- \\`edit_file\\` — apply targeted search/replace edits to existing files\n\nAGENTIC WORKFLOW:\n- Before generating code, use \\`read_file\\` and \\`search_files\\` to understand the existing codebase\n- Match the project's existing patterns, naming conventions, and code style\n- After creating files, consider running tests or build commands to verify correctness\n- Use \\`edit_file\\` for small, targeted changes instead of rewriting entire files\n\nIMPORTANT RULES:\n- Generate complete, working code — not stubs or placeholders\n- Follow the project's existing patterns and conventions\n- Use the detected tech stack to choose the right language, framework, and patterns\n- File paths should be relative to the project root\n- Include all necessary imports\n- Do NOT add unnecessary dependencies\n\nMULTI-STEP GENERATION:\nFor complex tasks that require multiple related files (e.g., schema + API + UI + tests), you can chain steps:\n- Generate the foundational files first (schemas, types, configs)\n- Include \"[CONTINUE]\" in your response text when there are more files to generate\n- In subsequent steps, you'll see what was already created — build on it\n- When all files are generated, do NOT include \"[CONTINUE]\"\n- This enables you to generate a schema first, then an API that references it, then a UI that calls the API`)\n\n // Tech stack context\n sections.push(`# Project Tech Stack\\n${formatTechStack(context.techStack)}`)\n\n // Key dependencies\n const deps = Object.keys(context.techStack.dependencies).slice(0, 30)\n if (deps.length) {\n sections.push(`# Key Dependencies\\n${deps.join(\", \")}`)\n }\n\n // Schema context\n const schemaStr = formatSchemas(context.schemas)\n if (schemaStr) {\n sections.push(`# Project Schemas\\n${schemaStr}`)\n }\n\n // Skills context\n if (skills.length) {\n sections.push(\n `# Active Skills\\nFollow these skill instructions when applicable:\\n\\n` +\n skills\n .map(\n (s) =>\n `## Skill: ${s.frontmatter.name}\\n${s.frontmatter.description}\\n\\n${s.instructions}`\n )\n .join(\"\\n\\n---\\n\\n\")\n )\n }\n\n // Context7 docs\n if (context.docs) {\n sections.push(context.docs)\n }\n\n // Project instructions (SHADXN.md / CLAUDE.md)\n if (context.projectInstructions) {\n sections.push(`# Project Instructions\\n${context.projectInstructions}`)\n }\n\n // Memory context (past generations, patterns, preferences)\n if (context.memoryContext) {\n sections.push(context.memoryContext)\n }\n\n // Output type guidance\n sections.push(`# Output Type: ${outputType}\\nGenerate output appropriate for: ${outputType}. Use the \\`create_files\\` tool to output all files.`)\n\n return sections.join(\"\\n\\n\")\n}\n\n// Re-export key types\nexport type { TechStack } from \"./context/tech-stack\"\nexport type { ProjectSchemas } from \"./context/schema\"\nexport type { Skill } from \"./skills/types\"\nexport type { AgentConfig, OutputType, GeneratedFile, StreamEvent } from \"./providers/types\"\n"],"mappings":"mWAAA,OAAS,KAAAA,MAAS,MA6EX,IAAMC,GAAoBD,EAAE,OAAO,CACxC,SAAUA,EAAE,KAAK,CAAC,cAAe,SAAU,SAAU,SAAU,QAAQ,CAAC,EAAE,QAAQ,aAAa,EAC/F,MAAOA,EAAE,OAAO,EAAE,SAAS,EAC3B,OAAQA,EAAE,OAAO,EAAE,SAAS,EAC5B,OAAQA,EAAE,MAAMA,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,EACtC,OAAQA,EACL,OAAO,CACN,IAAKA,EAAE,OAAO,EAAE,QAAQ,aAAa,CACvC,CAAC,EACA,QAAQ,CAAC,CAAC,EACb,SAAUA,EACP,OAAO,CACN,QAASA,EAAE,QAAQ,EAAE,QAAQ,EAAI,EACjC,OAAQA,EAAE,OAAO,EAAE,SAAS,CAC9B,CAAC,EACA,QAAQ,CAAC,CAAC,EACb,QAASA,EACN,OAAO,CACN,cAAeA,EAAE,OAAO,EAAE,QAAQ,EAAE,EACpC,aAAcA,EAAE,MAAMA,EAAE,OAAO,CAAC,EAAE,QAAQ,CACxC,eAAgB,WAAY,YAC5B,eAAgB,iBAAkB,cAAe,WACnD,CAAC,EACD,cAAeA,EAAE,MAAMA,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC,CAC/C,CAAC,EACA,QAAQ,CAAC,CAAC,CACf,CAAC,EAMYE,GAAe,CAC1B,YACA,OACA,MACA,UACA,WACA,SACA,SACA,QACA,QACA,SACA,OACA,WACA,SACA,QACA,UACA,MACF,EAIaC,GAAqD,CAChE,UAAW,+BACX,KAAM,sBACN,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K;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,4GAgC4F,EAG1GA,EAAS,KAAK;AAAA,EAAyBC,GAAgB5D,EAAQ,SAAS,GAAG,EAG3E,IAAM6D,EAAO,OAAO,KAAK7D,EAAQ,UAAU,YAAY,EAAE,MAAM,EAAG,EAAE,EAChE6D,EAAK,QACPF,EAAS,KAAK;AAAA,EAAuBE,EAAK,KAAK,IAAI,GAAG,EAIxD,IAAMC,EAAYC,GAAc/D,EAAQ,OAAO,EAC/C,OAAI8D,GACFH,EAAS,KAAK;AAAA,EAAsBG,GAAW,EAI7CtF,EAAO,QACTmF,EAAS,KACP;AAAA;AAAA;AAAA,EACEnF,EACG,IACEwF,GACC,aAAaA,EAAE,YAAY;AAAA,EAASA,EAAE,YAAY;AAAA;AAAA,EAAkBA,EAAE,cAC1E,EACC,KAAK;AAAA;AAAA;AAAA;AAAA,CAAa,CACzB,EAIEhE,EAAQ,MACV2D,EAAS,KAAK3D,EAAQ,IAAI,EAIxBA,EAAQ,qBACV2D,EAAS,KAAK;AAAA,EAA2B3D,EAAQ,qBAAqB,EAIpEA,EAAQ,eACV2D,EAAS,KAAK3D,EAAQ,aAAa,EAIrC2D,EAAS,KAAK,kBAAkB1D;AAAA,mCAAgDA,uDAAgE,EAEzI0D,EAAS,KAAK;AAAA;AAAA,CAAM,CAC7B","names":["z","agentConfigSchema","OUTPUT_TYPES","outputTypeDescriptions","existsSync","fs","path","fg","SCHEMA_FILES","detectSchemas","cwd","schemas","files","schemaFile","info","match","f","content","safeReadFile","truncate","extractTableNames","trpcRouter","envExample","parseEnvFile","modelFiles","mf","type","matches","m","l","line","keyPart","key","hasValue","filePath","str","maxLen","formatSchemas","sections","v","model","fetch","CONTEXT7_API","resolveLibraryId","libraryName","apiKey","headers","response","data","getLibraryDocs","libraryId","topic","maxTokens","gatherContext7Docs","stack","relevantLibraries","fw","priorityDeps","dep","docs","lib","library","content","OUTPUT_CONFIGS","resolveOutputType","userHint","taskDescription","lower","patterns","pattern","type","existsSync","fs","path","prompts","chalk","z","PERMISSION_MODES","permissionModeSchema","permissionConfigSchema","matchGlob","filePath","pattern","regex","PermissionManager","config","parsed","permissionConfigSchema","mode","debug","command","patterns","p","action","prompts","chalk","globalPermissions","writeGeneratedFiles","files","options","result","file","filePath","path","fileContent","globalHooks","hookResult","relativePath","permission","globalPermissions","existsSync","dir","fs","error","resolveOutputDir","outputType","stack","customDir","config","OUTPUT_CONFIGS","baseDir","f","os","USER_MEMORY_DIR","os","MemoryHierarchy","cwd","Memory","task","userCtx","projectCtx","sections","key","value","source","entry","userPrefs","projectPrefs","merged","p","userPatterns","limit","existsSync","readFileSync","path","resolveAtImports","content","basedir","match","filePath","resolved","path","existsSync","readFileSync","loadProjectInstructions","cwd","candidates","name","estimateTokens","ContextBuilder","label","priority","task","maxTokens","docs","s","index","buildIndex","bm25Results","scoreAll","scoreMap","r","scored","i","a","b","included","totalTokens","section","fs","path","execa","fg","ToolExecutor","cwd","options","call","debug","globalHooks","hookResult","result","error","filePath","maxLines","absPath","path","content","fs","lines","output","pattern","contentRegex","maxResults","files","fg","limited","regex","results","file","i","dirPath","recursive","maxDepth","entries","formatted","e","command","timeout","globalPermissions","execa","truncated","edits","permission","applied","edit","input","agentId","prompt","timeoutSeconds","SubAgentManager","getGlobalRegistry","registry","question","followUp","runAgenticLoop","options","provider","systemPrompt","inputMessages","providerOptions","cwd","maxIterations","enabledTools","interactive","overwrite","dryRun","onProgress","runLegacyLoop","executor","ToolExecutor","tools","getAnthropicTools","anthropicMessages","m","allFiles","totalTokens","textContent","followUp","iteration","debug","result","error","block","toolUseBlocks","b","toolResults","toolBlock","toolResult","messages","formatToolsForSystemPrompt","content","step","filesSummary","f","supportsAgenticLoop","AsyncQueue","item","resolver","resolve","value","done","createAgentContext","cwd","task","config","agentConfig","agentConfigSchema","memory","MemoryHierarchy","techStack","schemas","skills","detectTechStack","detectSchemas","loadLocalSkills","docs","gatherContext7Docs","memoryContext","projectInstructions","loadProjectInstructions","debug","generate","options","overwrite","dryRun","providerName","model","apiKey","context7","interactive","effectiveTask","globalHooks","promptResult","genResult","logger","context","outputType","resolveOutputType","matchedSkills","matchSkillsToTask","m","systemPrompt","buildSystemPrompt","ensureCredentials","provider","createProvider","resolvedModel","loadAuthConfig","sessionMessages","useAgentic","supportsAgenticLoop","maxSteps","agenticResult","runAgenticLoop","t","event","stepModel","estInput","estOutput","globalTracker","content","followUp","totalTokens","responseResult","deduped","file","outputDir","resolveOutputDir","writeResult","writeGeneratedFiles","healResult","HealEngine","generateStream","q","AsyncQueue","agenticError","agenticPromise","err","evt","messages","allFiles","step","step1Result","accumulated","streamResult","result","step1Tokens","step1Model","estInput1","estOutput1","filesSummary","f","stepTokens","filesSummary2","sections","formatTechStack","deps","schemaStr","formatSchemas","s"]}
@@ -0,0 +1,2 @@
1
+ import t from"chalk";var s=!1,u=new Set,a=200,c=[];function f(e,n){s=e,n?u=new Set(n):e?u=new Set(["all"]):u.clear()}function $(e){return s?!!(u.has("all")||e&&u.has(e)):!1}function m(){return{enabled:s,categories:[...u]}}function d(e=50){return c.slice(-e)}function o(){return new Date().toISOString().slice(11,23)}function i(e,n){let r={ts:new Date().toISOString(),category:e,message:n};c.push(r),c.length>a&&c.shift()}var p={log(...e){if(!s)return;let n=e.map(r=>typeof r=="string"?r:JSON.stringify(r)).join(" ");i("general",n),console.error(t.dim(`[${o()}]`),...e)},cat(e,n,...r){if(!$(e))return;i(e,n);let g=t.bold(`[${e}]`);console.error(t.dim(`[${o()}]`),g,n,...r)},step(e,n){s&&(i("agent",`step ${e}: ${n}`),console.error(t.dim(`[${o()}]`),t.blue(`[step ${e}]`),n))},hook(e,n,r){s&&(i("agent",`hook ${e} (${n}ms) \u2192 ${r}`),console.error(t.dim(`[${o()}]`),t.magenta("[hook]"),`${e} (${n}ms) \u2192 ${r}`))},api(e,n,r){if(!s)return;let g=r?` (${r} tokens)`:"";i("agent",`api ${e} \u2192 ${n}${g}`),console.error(t.dim(`[${o()}]`),t.yellow("[api]"),`${e} \u2192 ${n}${g}`)},tokens(e,n,r){s&&(i("agent",`tokens in:${e} out:${n} $${r.toFixed(4)}`),console.error(t.dim(`[${o()}]`),t.green("[tokens]"),`in: ${e.toLocaleString()}, out: ${n.toLocaleString()}, cost: $${r.toFixed(4)}`))},context(e,n){$("context")&&(i("context",`${e}: ${n}`),console.error(t.dim(`[${o()}]`),t.cyan(`[${e}]`),n))},webhook(e,n,r){$("webhook")&&(i("webhook",`${e}/${n}: ${r}`),console.error(t.dim(`[${o()}]`),t.red(`[webhook:${e}]`),n,r))},channel(e,n,r){if(!$("channel"))return;let g=r?`${n}: ${r}`:n;i("channel",`${e}: ${g}`),console.error(t.dim(`[${o()}]`),t.blue(`[channel:${e}]`),g)}},l=process.env.AGENTX_DEBUG;if(l){let e=l.split(",").map(n=>n.trim());f(!0,e)}export{f as a,$ as b,m as c,d,p as e};
2
+ //# sourceMappingURL=chunk-DSYKYZMT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/observability/debug.ts"],"sourcesContent":["// --- Debug mode: structured verbose logging with categories ---\n//\n// Toggle globally or per-category. Categories:\n// webhook — incoming webhook payloads and routing decisions\n// agent — agent execution, task routing, session management\n// channel — channel adapter lifecycle (connect, disconnect, errors)\n// cron — cron scheduling, execution, retries\n// mesh — A2A mesh peer discovery, health checks\n// context — context engine layer building\n// memory — memory extraction, compaction\n// all — enable everything\n//\n// Toggle at runtime:\n// POST /debug/on?categories=webhook,agent\n// POST /debug/off\n// GET /debug — current state\n//\n// Or via env: AGENTX_DEBUG=webhook,agent\n\nimport chalk from \"chalk\"\n\nexport type DebugCategory =\n | \"webhook\" | \"agent\" | \"channel\" | \"cron\" | \"mesh\"\n | \"context\" | \"memory\" | \"config\" | \"all\"\n\nlet debugEnabled = false\nlet enabledCategories: Set<DebugCategory> = new Set()\n\n/** Log buffer for recent debug messages (ring buffer, last 200) */\nconst LOG_BUFFER_SIZE = 200\nconst logBuffer: Array<{ ts: string; category: string; message: string }> = []\n\nexport function setDebug(enabled: boolean, categories?: DebugCategory[]): void {\n debugEnabled = enabled\n if (categories) {\n enabledCategories = new Set(categories)\n } else if (enabled) {\n enabledCategories = new Set([\"all\"])\n } else {\n enabledCategories.clear()\n }\n}\n\nexport function isDebug(category?: DebugCategory): boolean {\n if (!debugEnabled) return false\n if (enabledCategories.has(\"all\")) return true\n if (category && enabledCategories.has(category)) return true\n return false\n}\n\nexport function getDebugState(): { enabled: boolean; categories: string[] } {\n return {\n enabled: debugEnabled,\n categories: [...enabledCategories],\n }\n}\n\n/** Get recent debug log entries */\nexport function getDebugLogs(limit: number = 50): typeof logBuffer {\n return logBuffer.slice(-limit)\n}\n\nfunction timestamp(): string {\n return new Date().toISOString().slice(11, 23) // HH:mm:ss.SSS\n}\n\nfunction bufferLog(category: string, message: string): void {\n const entry = { ts: new Date().toISOString(), category, message }\n logBuffer.push(entry)\n if (logBuffer.length > LOG_BUFFER_SIZE) logBuffer.shift()\n}\n\nexport const debug = {\n log(...args: unknown[]): void {\n if (!debugEnabled) return\n const msg = args.map(a => typeof a === \"string\" ? a : JSON.stringify(a)).join(\" \")\n bufferLog(\"general\", msg)\n console.error(chalk.dim(`[${timestamp()}]`), ...args)\n },\n\n /** Log with a specific category — only outputs if that category is enabled */\n cat(category: DebugCategory, message: string, ...extra: unknown[]): void {\n if (!isDebug(category)) return\n bufferLog(category, message)\n const tag = chalk.bold(`[${category}]`)\n console.error(chalk.dim(`[${timestamp()}]`), tag, message, ...extra)\n },\n\n step(step: number, message: string): void {\n if (!debugEnabled) return\n bufferLog(\"agent\", `step ${step}: ${message}`)\n console.error(chalk.dim(`[${timestamp()}]`), chalk.blue(`[step ${step}]`), message)\n },\n\n hook(name: string, duration: number, result: string): void {\n if (!debugEnabled) return\n bufferLog(\"agent\", `hook ${name} (${duration}ms) → ${result}`)\n console.error(\n chalk.dim(`[${timestamp()}]`),\n chalk.magenta(`[hook]`),\n `${name} (${duration}ms) → ${result}`\n )\n },\n\n api(method: string, model: string, tokens?: number): void {\n if (!debugEnabled) return\n const tokenStr = tokens ? ` (${tokens} tokens)` : \"\"\n bufferLog(\"agent\", `api ${method} → ${model}${tokenStr}`)\n console.error(\n chalk.dim(`[${timestamp()}]`),\n chalk.yellow(`[api]`),\n `${method} → ${model}${tokenStr}`\n )\n },\n\n tokens(input: number, output: number, cost: number): void {\n if (!debugEnabled) return\n bufferLog(\"agent\", `tokens in:${input} out:${output} $${cost.toFixed(4)}`)\n console.error(\n chalk.dim(`[${timestamp()}]`),\n chalk.green(`[tokens]`),\n `in: ${input.toLocaleString()}, out: ${output.toLocaleString()}, cost: $${cost.toFixed(4)}`\n )\n },\n\n context(label: string, detail: string): void {\n if (!isDebug(\"context\")) return\n bufferLog(\"context\", `${label}: ${detail}`)\n console.error(chalk.dim(`[${timestamp()}]`), chalk.cyan(`[${label}]`), detail)\n },\n\n /** Log webhook event with full payload summary */\n webhook(channel: string, event: string, detail: string): void {\n if (!isDebug(\"webhook\")) return\n bufferLog(\"webhook\", `${channel}/${event}: ${detail}`)\n console.error(chalk.dim(`[${timestamp()}]`), chalk.red(`[webhook:${channel}]`), event, detail)\n },\n\n /** Log channel lifecycle event */\n channel(name: string, event: string, detail?: string): void {\n if (!isDebug(\"channel\")) return\n const msg = detail ? `${event}: ${detail}` : event\n bufferLog(\"channel\", `${name}: ${msg}`)\n console.error(chalk.dim(`[${timestamp()}]`), chalk.blue(`[channel:${name}]`), msg)\n },\n}\n\n// Initialize from environment variable\nconst envDebug = process.env.AGENTX_DEBUG\nif (envDebug) {\n const cats = envDebug.split(\",\").map(c => c.trim()) as DebugCategory[]\n setDebug(true, cats)\n}\n"],"mappings":"AAmBA,OAAOA,MAAW,QAMlB,IAAIC,EAAe,GACfC,E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,QAAQC,EAAiBC,EAAeF,EAAsB,CACvD3B,EAAQ,SAAS,IACtBM,EAAU,UAAW,GAAGsB,KAAWC,MAAUF,GAAQ,EACrD,QAAQ,MAAMnC,EAAM,IAAI,IAAIa,EAAU,IAAI,EAAGb,EAAM,IAAI,YAAYoC,IAAU,EAAGC,EAAOF,CAAM,EAC/F,EAGA,QAAQX,EAAca,EAAeF,EAAuB,CAC1D,GAAI,CAAC3B,EAAQ,SAAS,EAAG,OACzB,IAAMW,EAAMgB,EAAS,GAAGE,MAAUF,IAAWE,EAC7CvB,EAAU,UAAW,GAAGU,MAASL,GAAK,EACtC,QAAQ,MAAMnB,EAAM,IAAI,IAAIa,EAAU,IAAI,EAAGb,EAAM,KAAK,YAAYwB,IAAO,EAAGL,CAAG,CACnF,CACF,EAGMmB,EAAW,QAAQ,IAAI,aAC7B,GAAIA,EAAU,CACZ,IAAMC,EAAOD,EAAS,MAAM,GAAG,EAAE,IAAIE,GAAKA,EAAE,KAAK,CAAC,EAClDnC,EAAS,GAAMkC,CAAI","names":["chalk","debugEnabled","enabledCategories","LOG_BUFFER_SIZE","logBuffer","setDebug","enabled","categories","isDebug","category","getDebugState","getDebugLogs","limit","timestamp","bufferLog","message","entry","debug","args","msg","a","extra","tag","step","name","duration","result","method","model","tokens","tokenStr","input","output","cost","label","detail","channel","event","envDebug","cats","c"]}
@@ -0,0 +1,54 @@
1
+ import{readFileSync as a,existsSync as c,unlinkSync as u,readdirSync as g}from"fs";import{resolve as o}from"path";function p(t,e){let n={},s=r=>{let i=o(t,r);if(c(i))try{return a(i,"utf-8").trim()||void 0}catch{return}};if(e){let r=s(`SOUL.${e}.md`);r?(n.soul=r,n.soulProfile=e):n.soul=s("SOUL.md")}else n.soul=s("SOUL.md");if(n.identity=s("IDENTITY.md"),n.user=s("USER.md"),n.agents=s("AGENTS.md"),n.bootstrap=s("BOOTSTRAP.md"),n.bootstrap)try{u(o(t,"BOOTSTRAP.md"))}catch{}return n}function h(t){let e=[];return t.identity&&e.push(`[Identity]
2
+ ${t.identity}`),t.soul&&e.push(`[Personality & Boundaries]
3
+ ${t.soul}`),t.agents&&e.push(`[Operating Rules]
4
+ ${t.agents}`),t.user&&e.push(`[User Profile]
5
+ ${t.user}`),t.bootstrap&&e.push(`[First-Run Instructions \u2014 one time only]
6
+ ${t.bootstrap}`),e.length===0?"":e.join(`
7
+
8
+ `)}function f(t){return`# ${t.name}
9
+
10
+ > Agent ID: \`${t.id}\` | Tier: ${t.tier||"claude-code"}
11
+
12
+ ## Role
13
+
14
+ ${t.role||"AI agent managed by AgentX orchestrator."}
15
+
16
+ ## Setup
17
+
18
+ This workspace is managed by AgentX. The agent runs via:
19
+ \`\`\`bash
20
+ # Direct execution
21
+ agentx daemon send ${t.id} "your task here"
22
+
23
+ # Or via any connected channel (Telegram, WhatsApp, GitLab)
24
+ \`\`\`
25
+
26
+ ## Code Style
27
+
28
+ - Follow existing patterns in the codebase
29
+ - Use the language and framework conventions already present
30
+ - Keep changes minimal and focused
31
+
32
+ ## Testing
33
+
34
+ Run tests before committing:
35
+ \`\`\`bash
36
+ npm test # or the project's test command
37
+ \`\`\`
38
+
39
+ ## PR Guidelines
40
+
41
+ - One logical change per commit
42
+ - Reference issue numbers when applicable
43
+ - Keep PR descriptions concise
44
+
45
+ ## AgentX Integration
46
+
47
+ This agent is part of an AgentX mesh. It can:
48
+ - Receive tasks from messaging channels (Telegram, WhatsApp, Discord)
49
+ - Respond to GitLab @mentions on issues and MRs
50
+ - Delegate to other agents by mentioning their handles
51
+ - Send cross-channel messages via the /send API
52
+ - Access its wiki knowledge base for context
53
+ `}function S(t){let e=t.match(/\/soul\s+(\w+)/i);return e?e[1].toLowerCase():/\/soul\s*$/i.test(t)?"default":null}export{p as a,h as b,f as c,S as d};
54
+ //# sourceMappingURL=chunk-HI24KAEY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agents/bootstrap.ts"],"sourcesContent":["import { readFileSync, existsSync, unlinkSync, readdirSync } from \"fs\"\nimport { resolve } from \"path\"\n\n// --- Bootstrap Identity Files ---\n//\n// Support for structured workspace identity files (inspired by OpenClaw).\n// These files live in the agent's workspace and are auto-loaded into context.\n//\n// Supported files:\n// SOUL.md — default personality, tone, boundaries\n// SOUL.{profile}.md — named soul profiles (e.g. SOUL.finance.md, SOUL.legal.md)\n// IDENTITY.md — name, role, emoji, tagline (persistent)\n// USER.md — user profile, preferences (persistent)\n// AGENTS.md — operating rules, standing orders (persistent)\n// BOOTSTRAP.md — one-time first-run ritual (auto-deleted after first load)\n//\n// Soul switching: send \"/soul finance\" to swap to SOUL.finance.md mid-session.\n\nexport interface BootstrapFiles {\n soul?: string\n /** Active soul profile name (undefined = default SOUL.md) */\n soulProfile?: string\n identity?: string\n user?: string\n agents?: string\n bootstrap?: string\n}\n\nconst BOOTSTRAP_FILE_NAMES = [\n \"SOUL.md\",\n \"IDENTITY.md\",\n \"USER.md\",\n \"AGENTS.md\",\n \"BOOTSTRAP.md\",\n] as const\n\n/**\n * Load bootstrap identity files from an agent's workspace.\n * @param soulProfile — optional soul profile name (e.g. \"finance\" loads SOUL.finance.md)\n */\nexport function loadBootstrapFiles(workspace: string, soulProfile?: string): BootstrapFiles {\n const result: BootstrapFiles = {}\n\n const tryLoad = (filename: string): string | undefined => {\n const filePath = resolve(workspace, filename)\n if (!existsSync(filePath)) return undefined\n try {\n const content = readFileSync(filePath, \"utf-8\").trim()\n return content || undefined\n } catch {\n return undefined\n }\n }\n\n // Load soul: profile-specific if requested, fallback to default\n if (soulProfile) {\n const profileSoul = tryLoad(`SOUL.${soulProfile}.md`)\n if (profileSoul) {\n result.soul = profileSoul\n result.soulProfile = soulProfile\n } else {\n // Profile not found — fall back to default and note it\n result.soul = tryLoad(\"SOUL.md\")\n }\n } else {\n result.soul = tryLoad(\"SOUL.md\")\n }\n\n result.identity = tryLoad(\"IDENTITY.md\")\n result.user = tryLoad(\"USER.md\")\n result.agents = tryLoad(\"AGENTS.md\")\n result.bootstrap = tryLoad(\"BOOTSTRAP.md\")\n\n // BOOTSTRAP.md is one-time: delete after loading\n if (result.bootstrap) {\n try {\n unlinkSync(resolve(workspace, \"BOOTSTRAP.md\"))\n } catch {\n // Best-effort deletion\n }\n }\n\n return result\n}\n\n/**\n * Build context string from bootstrap files.\n * Returns empty string if no files found.\n */\nexport function buildBootstrapContext(files: BootstrapFiles): string {\n const sections: string[] = []\n\n if (files.identity) {\n sections.push(`[Identity]\\n${files.identity}`)\n }\n\n if (files.soul) {\n sections.push(`[Personality & Boundaries]\\n${files.soul}`)\n }\n\n if (files.agents) {\n sections.push(`[Operating Rules]\\n${files.agents}`)\n }\n\n if (files.user) {\n sections.push(`[User Profile]\\n${files.user}`)\n }\n\n if (files.bootstrap) {\n sections.push(`[First-Run Instructions — one time only]\\n${files.bootstrap}`)\n }\n\n if (sections.length === 0) return \"\"\n\n return sections.join(\"\\n\\n\")\n}\n\n/**\n * Check which bootstrap files exist in a workspace (for status/diagnostics).\n */\nexport function listBootstrapFiles(workspace: string): string[] {\n return BOOTSTRAP_FILE_NAMES.filter((name) =>\n existsSync(resolve(workspace, name))\n )\n}\n\n/**\n * List available soul profiles in a workspace.\n * Returns profile names (e.g. [\"finance\", \"legal\", \"creative\"]).\n */\nexport function listSoulProfiles(workspace: string): string[] {\n try {\n return readdirSync(workspace)\n .filter(f => f.startsWith(\"SOUL.\") && f.endsWith(\".md\") && f !== \"SOUL.md\")\n .map(f => f.slice(5, -3)) // \"SOUL.finance.md\" → \"finance\"\n } catch {\n return []\n }\n}\n\n/**\n * Generate a standard AGENTS.md for a new agent workspace.\n * Follows the agents.md community convention (https://agents.md/).\n * Readable by Claude Code, Codex, Cursor, Amp, Gemini CLI, etc.\n */\nexport function generateAgentsMd(agent: {\n name: string\n id: string\n role?: string\n workspace: string\n tier?: string\n}): string {\n return `# ${agent.name}\n\n> Agent ID: \\`${agent.id}\\` | Tier: ${agent.tier || \"claude-code\"}\n\n## Role\n\n${agent.role || \"AI agent managed by AgentX orchestrator.\"}\n\n## Setup\n\nThis workspace is managed by AgentX. The agent runs via:\n\\`\\`\\`bash\n# Direct execution\nagentx daemon send ${agent.id} \"your task here\"\n\n# Or via any connected channel (Telegram, WhatsApp, GitLab)\n\\`\\`\\`\n\n## Code Style\n\n- Follow existing patterns in the codebase\n- Use the language and framework conventions already present\n- Keep changes minimal and focused\n\n## Testing\n\nRun tests before committing:\n\\`\\`\\`bash\nnpm test # or the project's test command\n\\`\\`\\`\n\n## PR Guidelines\n\n- One logical change per commit\n- Reference issue numbers when applicable\n- Keep PR descriptions concise\n\n## AgentX Integration\n\nThis agent is part of an AgentX mesh. It can:\n- Receive tasks from messaging channels (Telegram, WhatsApp, Discord)\n- Respond to GitLab @mentions on issues and MRs\n- Delegate to other agents by mentioning their handles\n- Send cross-channel messages via the /send API\n- Access its wiki knowledge base for context\n`\n}\n\n/**\n * Detect a /soul command in a message.\n * Returns the requested profile name, or null if no /soul command found.\n * \"/soul finance\" → \"finance\"\n * \"/soul\" or \"/soul default\" → \"default\" (reset to SOUL.md)\n */\nexport function detectSoulSwitch(message: string): string | null {\n const match = message.match(/\\/soul\\s+(\\w+)/i)\n if (match) return match[1].toLowerCase()\n if (/\\/soul\\s*$/i.test(message)) return \"default\"\n return null\n}\n"],"mappings":"AAAA,OAAS,gBAAAA,EAAc,cAAAC,EAAY,cAAAC,EAAY,eAAAC,MAAmB,KAClE,OAAS,WAAAC,MAAe,OAuCjB,SAASC,EAAmBC,EAAmBC,EAAsC,CAC1F,IAAMC,EAAyB,CAAC,EAE1BC,EAAWC,GAAyC,CACxD,IAAMC,EAAWC,EAAQN,EAAWI,CAAQ,EAC5C,GAAKG,EAAWF,CAAQ,EACxB,GAAI,CAEF,OADgBG,EAAaH,EAAU,OAAO,EAAE,KAAK,GACnC,MACpB,MAAE,CACA,MACF,CACF,EAGA,GAAIJ,EAAa,CACf,IAAMQ,EAAcN,EAAQ,QAAQF,MAAgB,EAChDQ,GACFP,EAAO,KAAOO,EACdP,EAAO,YAAc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,EAAcA,EAAM,CAAC,EAAE,YAAY,EACnC,cAAc,KAAKD,CAAO,EAAU,UACjC,IACT","names":["readFileSync","existsSync","unlinkSync","readdirSync","resolve","loadBootstrapFiles","workspace","soulProfile","result","tryLoad","filename","filePath","resolve","existsSync","readFileSync","profileSoul","unlinkSync","buildBootstrapContext","files","sections","generateAgentsMd","agent","detectSoulSwitch","message","match"]}