agentix-cli 0.2.0 → 0.3.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.
- package/README.md +192 -107
- package/dist/agent-CRA5PU6S.js +2 -0
- package/dist/chunk-KVWUPUR5.js +106 -0
- package/dist/chunk-KVWUPUR5.js.map +1 -0
- package/dist/chunk-M7HKBG3V.js +2 -0
- package/dist/chunk-M7HKBG3V.js.map +1 -0
- package/dist/chunk-MDR7SH7F.js +2 -0
- package/dist/chunk-MGMZNJCE.js +46 -0
- package/dist/chunk-MGMZNJCE.js.map +1 -0
- package/dist/chunk-PCAYW54Q.js +12 -0
- package/dist/chunk-PCAYW54Q.js.map +1 -0
- package/dist/chunk-S74N276K.js +35 -0
- package/dist/chunk-S74N276K.js.map +1 -0
- package/dist/{chunk-6PVFYFUE.js → chunk-X7UN6JAA.js} +2 -2
- package/dist/{chunk-6PVFYFUE.js.map → chunk-X7UN6JAA.js.map} +1 -1
- package/dist/cli.js +9 -155
- package/dist/cli.js.map +1 -1
- package/dist/heal-RDZZJXDZ.js +2 -0
- package/dist/index.d.ts +239 -8
- package/dist/index.js +85 -1
- package/dist/index.js.map +1 -1
- package/dist/loader-RL2LKXIF.js +2 -0
- package/dist/providers-Q3U3ONJO.js +2 -0
- package/dist/providers-Q3U3ONJO.js.map +1 -0
- package/package.json +3 -1
- package/dist/agent-AI6DUEPU.js +0 -2
- package/dist/chunk-FUYKPFUV.js +0 -46
- package/dist/chunk-FUYKPFUV.js.map +0 -1
- package/dist/chunk-NZ6W33BD.js +0 -116
- package/dist/chunk-NZ6W33BD.js.map +0 -1
- package/dist/chunk-THMHQELC.js +0 -106
- package/dist/chunk-THMHQELC.js.map +0 -1
- package/dist/heal-MJLBETRV.js +0 -2
- package/dist/loader-PHU6STSZ.js +0 -2
- package/dist/providers-MPYTYJVB.js +0 -2
- /package/dist/{agent-AI6DUEPU.js.map → agent-CRA5PU6S.js.map} +0 -0
- /package/dist/{heal-MJLBETRV.js.map → chunk-MDR7SH7F.js.map} +0 -0
- /package/dist/{loader-PHU6STSZ.js.map → heal-RDZZJXDZ.js.map} +0 -0
- /package/dist/{providers-MPYTYJVB.js.map → loader-RL2LKXIF.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\"\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\n/**\n * Score a section's relevance to a task via word overlap.\n */\nfunction scoreRelevance(section: string, task: string): number {\n const taskWords = new Set(\n task.toLowerCase().split(/\\s+/).filter((w) => w.length > 3)\n )\n if (taskWords.size === 0) return 0\n\n const sectionWords = new Set(\n section.toLowerCase().split(/\\s+/).filter((w) => w.length > 3)\n )\n let overlap = 0\n for (const w of taskWords) {\n if (sectionWords.has(w)) overlap++\n }\n return overlap / taskWords.size\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 by priority + relevance\n const scored = this.sections.map((s) => ({\n ...s,\n relevance: scoreRelevance(s.content, task),\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 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 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":"iRAAA,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,CA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AK;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","loadProjectInstructions","cwd","candidates","name","estimateTokens","scoreRelevance","section","task","taskWords","w","sectionWords","overlap","ContextBuilder","label","priority","maxTokens","scored","s","a","b","included","totalTokens","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","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","stepTokens","filesSummary2","f","sections","formatTechStack","deps","schemaStr","formatSchemas","s"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import l from"chalk";var s={error(...e){console.log(l.red(...e))},warn(...e){console.log(l.yellow(...e))},info(...e){console.log(l.cyan(...e))},success(...e){console.log(l.green(...e))},break(){console.log("")}};import{existsSync as f,readFileSync as g,writeFileSync as T,mkdirSync as w}from"fs";import i from"path";import A from"os";import c from"chalk";import a from"prompts";var h=i.join(A.homedir(),".agentx"),d=i.join(h,"auth.json");function m(){if(!f(d))return null;try{let e=JSON.parse(g(d,"utf8"));return e.provider&&e.authType&&e.token&&e.model?e:null}catch{return null}}function v(e){f(h)||w(h,{recursive:!0}),T(d,JSON.stringify(e,null,2),"utf8")}function P(e){if(e?.trim()){let p=e.startsWith("sk-ant-oat")?"oauth":"api-key";return{token:e.trim(),authType:p}}let t=process.env.ANTHROPIC_OAUTH_TOKEN;if(t?.trim())return{token:t.trim(),authType:"oauth"};let r=process.env.ANTHROPIC_API_KEY;if(r?.trim())return{token:r.trim(),authType:"api-key"};let n=m();if(n)return{token:n.token,authType:n.authType};let o=A.homedir(),u=[i.join(o,".openclaw","agents","main","agent","auth-profiles.json"),i.join(o,".openclaw","auth-profiles.json"),i.join(o,".openclaw","credentials","oauth.json"),i.join(o,".claude","oauth.json"),i.join(o,".config","claude","oauth.json"),i.join(o,".config","anthropic","oauth.json")];for(let p of u){let y=b(p);if(y)return{token:y,authType:"oauth"}}return null}function b(e){if(!f(e))return"";try{let t=JSON.parse(g(e,"utf8"));if(t.profiles){let r="";for(let[n,o]of Object.entries(t.profiles))if(n.startsWith("anthropic")){if(o.type==="oauth"&&o.access){if(o.expires&&Date.now()>o.expires)continue;return o.access}o.type==="token"&&o.token&&(r=o.token)}if(r)return r}return t.anthropic?.access?t.anthropic.access:t.anthropic?.token?t.anthropic.token:""}catch{return""}}var k=[{id:"claude-sonnet-4-20250514",label:"anthropic/claude-sonnet-4",hint:"Claude Sonnet 4 \xB7 ctx 200k \xB7 recommended"},{id:"claude-opus-4-20250514",label:"anthropic/claude-opus-4-5",hint:"Claude Opus 4.5 \xB7 ctx 200k \xB7 reasoning"},{id:"claude-haiku-4-20250514",label:"anthropic/claude-haiku-4",hint:"Claude Haiku 4 \xB7 ctx 200k \xB7 fast"}];async function x(){let e=process.env.ANTHROPIC_API_KEY;if(e?.trim()){let n=e.slice(0,10)+"..."+e.slice(-4),{useExisting:o}=await a({type:"confirm",name:"useExisting",message:`Use existing ANTHROPIC_API_KEY (env, ${n})?`,initial:!0});if(o)return{token:e.trim(),authType:"api-key"}}let t=m();if(t?.authType==="api-key"&&t.token){let n=t.token.slice(0,10)+"..."+t.token.slice(-4),{useExisting:o}=await a({type:"confirm",name:"useExisting",message:`Use stored API key (${n})?`,initial:!0});if(o)return{token:t.token,authType:"api-key"}}let{apiKey:r}=await a({type:"password",name:"apiKey",message:"Enter Anthropic API key",validate:n=>n.startsWith("sk-ant-api")?n.length<40?"API key seems too short":!0:"API key must start with sk-ant-api"});return r?{token:r,authType:"api-key"}:null}async function I(){s.break();let e=46,t="Run `claude setup-token` in your terminal.",r="Then paste the generated token below.";console.log(` ${c.cyan("Anthropic setup-token")} ${"\u2500".repeat(e-21-1)}\u256E`),console.log(` ${" ".repeat(e)}\u2502`),console.log(` ${t}${" ".repeat(e-t.length)}\u2502`),console.log(` ${r}${" ".repeat(e-r.length)}\u2502`),console.log(` ${" ".repeat(e)}\u2502`),console.log(` ${"\u2500".repeat(e)}\u256F`),s.break();let{token:n}=await a({type:"password",name:"token",message:"Paste Anthropic setup-token",validate:u=>u.trim()?u.length<40?"Token seems too short":!0:"Token is required"});if(!n)return null;let{tokenName:o}=await a({type:"text",name:"tokenName",message:"Token name (blank = default)"});return{token:n,authType:"oauth"}}async function C(){for(;;){let{provider:e}=await a({type:"select",name:"provider",message:"Model/auth provider",choices:[{title:"Anthropic",value:"anthropic",description:"setup-token + API key"}]});if(e===void 0)return null;let{method:t}=await a({type:"select",name:"method",message:"Anthropic auth method",choices:[{title:"Anthropic token (paste setup-token)",value:"setup-token",description:"run `claude setup-token` elsewhere, then paste the token here"},{title:"Anthropic API key",value:"api-key"},{title:c.dim("Back"),value:"back"}]});if(t===void 0)return null;if(t!=="back")return t==="api-key"?x():t==="setup-token"?I():null}}async function j(){let e=m(),t=k.map(n=>({title:n.label,value:n.id,description:n.hint+(e?.model===n.id?" \xB7 current":"")}));if(e?.model){let n=k.find(u=>u.id===e.model),o=n?n.label:e.model;t.unshift({title:`Keep current (${o})`,value:e.model,description:"no change"})}let{modelId:r}=await a({type:"select",name:"modelId",message:"Default model",choices:t});return r||null}async function $(){let e=await C();if(!e)return null;let t=await j();if(!t)return null;let r={provider:e.authType==="oauth"?"claude-code":"claude",authType:e.authType,token:e.token,model:t};return v(r),s.break(),s.success("Configuration saved to ~/.agentx/auth.json"),console.log(` Provider: ${c.bold("anthropic")} (${r.authType})`),console.log(` Model: ${c.bold(k.find(n=>n.id===r.model)?.label||r.model)}`),r}async function M(e){return P(e)?!0:(s.warn("No AI credentials configured."),s.break(),await $()!==null)}export{s as a,m as b,v as c,P as d,$ as e,M as f};
|
|
2
|
+
//# sourceMappingURL=chunk-M7HKBG3V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/logger.ts","../src/utils/auth-store.ts"],"sourcesContent":["import chalk from \"chalk\"\n\nexport const logger = {\n error(...args: unknown[]) {\n console.log(chalk.red(...args))\n },\n warn(...args: unknown[]) {\n console.log(chalk.yellow(...args))\n },\n info(...args: unknown[]) {\n console.log(chalk.cyan(...args))\n },\n success(...args: unknown[]) {\n console.log(chalk.green(...args))\n },\n break() {\n console.log(\"\")\n },\n}\n","import { existsSync, readFileSync, writeFileSync, mkdirSync } from \"fs\"\nimport path from \"path\"\nimport os from \"os\"\nimport chalk from \"chalk\"\nimport prompts from \"prompts\"\nimport { logger } from \"@/utils/logger\"\n\n// --- Auth config stored at ~/.agentx/auth.json ---\n\nexport interface AuthConfig {\n provider: \"claude\" | \"claude-code\"\n authType: \"api-key\" | \"oauth\"\n token: string\n model: string\n}\n\nconst AUTH_DIR = path.join(os.homedir(), \".agentx\")\nconst AUTH_FILE = path.join(AUTH_DIR, \"auth.json\")\n\nexport function loadAuthConfig(): AuthConfig | null {\n if (!existsSync(AUTH_FILE)) return null\n try {\n const data = JSON.parse(readFileSync(AUTH_FILE, \"utf8\"))\n if (data.provider && data.authType && data.token && data.model) {\n return data as AuthConfig\n }\n return null\n } catch {\n return null\n }\n}\n\nexport function saveAuthConfig(config: AuthConfig): void {\n if (!existsSync(AUTH_DIR)) {\n mkdirSync(AUTH_DIR, { recursive: true })\n }\n writeFileSync(AUTH_FILE, JSON.stringify(config, null, 2), \"utf8\")\n}\n\n/**\n * Resolve a token for the Anthropic API.\n * Priority: (1) explicit token, (2) env vars, (3) ~/.agentx/auth.json, (4) OpenClaw auth stores\n */\nexport function resolveToken(explicitKey?: string): {\n token: string\n authType: \"api-key\" | \"oauth\"\n} | null {\n // 1. Explicit CLI flag\n if (explicitKey?.trim()) {\n const type = explicitKey.startsWith(\"sk-ant-oat\") ? \"oauth\" : \"api-key\"\n return { token: explicitKey.trim(), authType: type }\n }\n\n // 2. Environment variables\n const envOAuth = process.env.ANTHROPIC_OAUTH_TOKEN\n if (envOAuth?.trim()) {\n return { token: envOAuth.trim(), authType: \"oauth\" }\n }\n\n const envApiKey = process.env.ANTHROPIC_API_KEY\n if (envApiKey?.trim()) {\n return { token: envApiKey.trim(), authType: \"api-key\" }\n }\n\n // 3. Stored config\n const stored = loadAuthConfig()\n if (stored) {\n return { token: stored.token, authType: stored.authType }\n }\n\n // 4. OpenClaw auth-profiles store (legacy fallback)\n const homeDir = os.homedir()\n const storePaths = [\n path.join(homeDir, \".openclaw\", \"agents\", \"main\", \"agent\", \"auth-profiles.json\"),\n path.join(homeDir, \".openclaw\", \"auth-profiles.json\"),\n path.join(homeDir, \".openclaw\", \"credentials\", \"oauth.json\"),\n path.join(homeDir, \".claude\", \"oauth.json\"),\n path.join(homeDir, \".config\", \"claude\", \"oauth.json\"),\n path.join(homeDir, \".config\", \"anthropic\", \"oauth.json\"),\n ]\n\n for (const p of storePaths) {\n const t = readTokenFromAuthProfiles(p)\n if (t) {\n return { token: t, authType: \"oauth\" }\n }\n }\n\n return null\n}\n\n/**\n * Read an Anthropic OAuth/token credential from an auth-profiles or oauth JSON file.\n */\nfunction readTokenFromAuthProfiles(filePath: string): string {\n if (!existsSync(filePath)) return \"\"\n\n try {\n const data = JSON.parse(readFileSync(filePath, \"utf8\"))\n\n // Modern auth-profiles format: { profiles: { \"anthropic:xxx\": { type, access/token } } }\n if (data.profiles) {\n let fallbackToken = \"\"\n for (const [id, cred] of Object.entries(data.profiles) as [string, any][]) {\n if (!id.startsWith(\"anthropic\")) continue\n if (cred.type === \"oauth\" && cred.access) {\n if (cred.expires && Date.now() > cred.expires) {\n continue\n }\n return cred.access\n }\n if (cred.type === \"token\" && cred.token) {\n fallbackToken = cred.token\n }\n }\n if (fallbackToken) return fallbackToken\n }\n\n // Legacy oauth.json format: { anthropic: { access: \"...\" } }\n if (data.anthropic?.access) return data.anthropic.access\n if (data.anthropic?.token) return data.anthropic.token\n\n return \"\"\n } catch {\n return \"\"\n }\n}\n\n// --- Model setup & credentials ---\n\nconst ANTHROPIC_MODELS = [\n { id: \"claude-sonnet-4-20250514\", label: \"anthropic/claude-sonnet-4\", hint: \"Claude Sonnet 4 · ctx 200k · recommended\" },\n { id: \"claude-opus-4-20250514\", label: \"anthropic/claude-opus-4-5\", hint: \"Claude Opus 4.5 · ctx 200k · reasoning\" },\n { id: \"claude-haiku-4-20250514\", label: \"anthropic/claude-haiku-4\", hint: \"Claude Haiku 4 · ctx 200k · fast\" },\n]\n\nasync function handleApiKey(): Promise<{ token: string; authType: \"api-key\" } | null> {\n const envKey = process.env.ANTHROPIC_API_KEY\n if (envKey?.trim()) {\n const preview = envKey.slice(0, 10) + \"...\" + envKey.slice(-4)\n const { useExisting } = await prompts({\n type: \"confirm\",\n name: \"useExisting\",\n message: `Use existing ANTHROPIC_API_KEY (env, ${preview})?`,\n initial: true,\n })\n\n if (useExisting) {\n return { token: envKey.trim(), authType: \"api-key\" }\n }\n }\n\n const stored = loadAuthConfig()\n if (stored?.authType === \"api-key\" && stored.token) {\n const preview = stored.token.slice(0, 10) + \"...\" + stored.token.slice(-4)\n const { useExisting } = await prompts({\n type: \"confirm\",\n name: \"useExisting\",\n message: `Use stored API key (${preview})?`,\n initial: true,\n })\n\n if (useExisting) {\n return { token: stored.token, authType: \"api-key\" }\n }\n }\n\n const { apiKey } = await prompts({\n type: \"password\",\n name: \"apiKey\",\n message: \"Enter Anthropic API key\",\n validate: (v: string) => {\n if (!v.startsWith(\"sk-ant-api\")) return \"API key must start with sk-ant-api\"\n if (v.length < 40) return \"API key seems too short\"\n return true\n },\n })\n\n if (!apiKey) return null\n return { token: apiKey, authType: \"api-key\" }\n}\n\nasync function handleSetupToken(): Promise<{ token: string; authType: \"oauth\" } | null> {\n logger.break()\n const boxWidth = 46\n const line1 = \"Run `claude setup-token` in your terminal.\"\n const line2 = \"Then paste the generated token below.\"\n console.log(` ${chalk.cyan(\"Anthropic setup-token\")} ${\"─\".repeat(boxWidth - \"Anthropic setup-token\".length - 1)}╮`)\n console.log(` ${\" \".repeat(boxWidth)}│`)\n console.log(` ${line1}${\" \".repeat(boxWidth - line1.length)}│`)\n console.log(` ${line2}${\" \".repeat(boxWidth - line2.length)}│`)\n console.log(` ${\" \".repeat(boxWidth)}│`)\n console.log(` ${\"─\".repeat(boxWidth)}╯`)\n logger.break()\n\n const { token } = await prompts({\n type: \"password\",\n name: \"token\",\n message: \"Paste Anthropic setup-token\",\n validate: (v: string) => {\n if (!v.trim()) return \"Token is required\"\n if (v.length < 40) return \"Token seems too short\"\n return true\n },\n })\n\n if (!token) return null\n\n const { tokenName } = await prompts({\n type: \"text\",\n name: \"tokenName\",\n message: \"Token name (blank = default)\",\n })\n\n return { token, authType: \"oauth\" }\n}\n\ntype AuthResult = { token: string; authType: \"api-key\" | \"oauth\" } | null\n\nasync function selectAuthMethod(): Promise<AuthResult> {\n while (true) {\n const { provider } = await prompts({\n type: \"select\",\n name: \"provider\",\n message: \"Model/auth provider\",\n choices: [\n { title: \"Anthropic\", value: \"anthropic\", description: \"setup-token + API key\" },\n ],\n })\n\n if (provider === undefined) return null\n\n const { method } = await prompts({\n type: \"select\",\n name: \"method\",\n message: \"Anthropic auth method\",\n choices: [\n { title: \"Anthropic token (paste setup-token)\", value: \"setup-token\", description: \"run `claude setup-token` elsewhere, then paste the token here\" },\n { title: \"Anthropic API key\", value: \"api-key\" },\n { title: chalk.dim(\"Back\"), value: \"back\" },\n ],\n })\n\n if (method === undefined) return null\n if (method === \"back\") continue\n\n if (method === \"api-key\") return handleApiKey()\n if (method === \"setup-token\") return handleSetupToken()\n\n return null\n }\n}\n\nasync function selectModel(): Promise<string | null> {\n const stored = loadAuthConfig()\n\n const choices = ANTHROPIC_MODELS.map((m) => ({\n title: m.label,\n value: m.id,\n description: m.hint + (stored?.model === m.id ? \" · current\" : \"\"),\n }))\n\n if (stored?.model) {\n const current = ANTHROPIC_MODELS.find((m) => m.id === stored.model)\n const label = current ? current.label : stored.model\n choices.unshift({\n title: `Keep current (${label})`,\n value: stored.model,\n description: \"no change\",\n })\n }\n\n const { modelId } = await prompts({\n type: \"select\",\n name: \"modelId\",\n message: \"Default model\",\n choices,\n })\n\n return modelId || null\n}\n\n/**\n * Reusable interactive setup flow. Returns the saved config, or null if the user cancelled.\n */\nexport async function runModelSetup(): Promise<AuthConfig | null> {\n const auth = await selectAuthMethod()\n if (!auth) return null\n\n const modelId = await selectModel()\n if (!modelId) return null\n\n const config: AuthConfig = {\n provider: auth.authType === \"oauth\" ? \"claude-code\" : \"claude\",\n authType: auth.authType,\n token: auth.token,\n model: modelId,\n }\n\n saveAuthConfig(config)\n\n logger.break()\n logger.success(\"Configuration saved to ~/.agentx/auth.json\")\n console.log(` Provider: ${chalk.bold(\"anthropic\")} (${config.authType})`)\n console.log(` Model: ${chalk.bold(ANTHROPIC_MODELS.find((m) => m.id === config.model)?.label || config.model)}`)\n\n return config\n}\n\n/**\n * Ensure credentials are available. If not, auto-prompt the interactive setup.\n * Returns true if credentials are ready, false if user cancelled.\n */\nexport async function ensureCredentials(explicitKey?: string): Promise<boolean> {\n const resolved = resolveToken(explicitKey)\n if (resolved) return true\n\n logger.warn(\"No AI credentials configured.\")\n logger.break()\n\n const result = await runModelSetup()\n return result !== null\n}\n"],"mappings":"AAAA,OAAOA,MAAW,QAEX,IAAMC,EAAS,CACpB,SAASC,EAAiB,CACxB,QAAQ,IAAIF,EAAM,IAAI,GAAGE,CAAI,CAAC,CAChC,EACA,QAAQA,EAAiB,CACvB,QAAQ,IAAIF,EAAM,OAAO,GAAGE,CAAI,CAAC,CACnC,EACA,QAAQA,EAAiB,CACvB,QAAQ,IAAIF,EAAM,KAAK,GAAGE,CAAI,CAAC,CACjC,EACA,WAAWA,EAAiB,CAC1B,QAAQ,IAAIF,EAAM,MAAM,GAAGE,CAAI,CAAC,CAClC,EACA,OAAQ,CACN,QAAQ,IAAI,EAAE,CAChB,CACF,EClBA,OAAS,cAAAC,EAAY,gBAAAC,EAAc,iBAAAC,EAAe,aAAAC,MAAiB,KACnE,OAAOC,MAAU,OACjB,OAAOC,MAAQ,KACf,OAAOC,MAAW,QAClB,OAAOC,MAAa,UAYpB,IAAMC,EAAWC,EAAK,KAAKC,EAAG,QAAQ,EAAG,SAAS,EAC5CC,EAAYF,EAAK,KAAKD,EAAU,WAAW,EAE1C,SAASI,GAAoC,CAClD,GAAI,CAACC,EAAWF,CAAS,EAAG,OAAO,KACnC,GAAI,CACF,IAAMG,EAAO,KAAK,MAAMC,EAAaJ,EAAW,MAA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AAMnB,EAAQ,CAChC,KAAM,SACN,KAAM,UACN,QAAS,gBACT,QAAAe,CACF,CAAC,EAED,OAAOI,GAAW,IACpB,CAKA,eAAsBC,GAA4C,CAChE,IAAMC,EAAO,MAAMV,EAAiB,EACpC,GAAI,CAACU,EAAM,OAAO,KAElB,IAAMF,EAAU,MAAML,EAAY,EAClC,GAAI,CAACK,EAAS,OAAO,KAErB,IAAMzC,EAAqB,CACzB,SAAU2C,EAAK,WAAa,QAAU,cAAgB,SACtD,SAAUA,EAAK,SACf,MAAOA,EAAK,MACZ,MAAOF,CACT,EAEA,OAAA1C,EAAeC,CAAM,EAErB0B,EAAO,MAAM,EACbA,EAAO,QAAQ,4CAA4C,EAC3D,QAAQ,IAAI,gBAAgBI,EAAM,KAAK,WAAW,MAAM9B,EAAO,WAAW,EAC1E,QAAQ,IAAI,gBAAgB8B,EAAM,KAAKb,EAAiB,KAAMqB,GAAMA,EAAE,KAAOtC,EAAO,KAAK,GAAG,OAASA,EAAO,KAAK,GAAG,EAE7GA,CACT,CAMA,eAAsB4C,EAAkBxC,EAAwC,CAE9E,OADiBD,EAAaC,CAAW,EACpB,IAErBsB,EAAO,KAAK,+BAA+B,EAC3CA,EAAO,MAAM,EAEE,MAAMgB,EAAc,IACjB,KACpB","names":["chalk","logger","args","existsSync","readFileSync","writeFileSync","mkdirSync","path","os","chalk","prompts","AUTH_DIR","path","os","AUTH_FILE","loadAuthConfig","existsSync","data","readFileSync","saveAuthConfig","config","mkdirSync","writeFileSync","resolveToken","explicitKey","type","envOAuth","envApiKey","stored","homeDir","storePaths","t","readTokenFromAuthProfiles","filePath","fallbackToken","id","cred","ANTHROPIC_MODELS","handleApiKey","envKey","preview","useExisting","prompts","apiKey","v","handleSetupToken","logger","boxWidth","line1","line2","chalk","token","tokenName","selectAuthMethod","provider","method","selectModel","choices","m","current","label","modelId","runModelSetup","auth","ensureCredentials"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var d=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+a+'" is not supported')});export{d as a};
|
|
2
|
+
//# sourceMappingURL=chunk-MDR7SH7F.js.map
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import{b as P,d as I}from"./chunk-M7HKBG3V.js";var M=[{name:"create_files",description:"Create one or more files as output. Use this when you need to generate code, documents, configs, or any file-based output.",input_schema:{type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string",description:"Relative file path from project root (e.g., src/components/Button.tsx)"},content:{type:"string",description:"The full content of the file"},language:{type:"string",description:"Programming language or file type"},description:{type:"string",description:"Brief description of what this file does"}},required:["path","content"]}},summary:{type:"string",description:"Brief summary of all generated files"}},required:["files"]},permission:"file-write"},{name:"ask_user",description:"Ask the user a clarifying question when you need more information to proceed. Use this when the request is ambiguous or you need to confirm important decisions.",input_schema:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"},options:{type:"array",items:{type:"string"},description:"Optional list of choices for the user"}},required:["question"]},permission:"none"},{name:"read_file",description:"Read the contents of a file. Use this to inspect existing code, understand patterns, check implementations, or gather context before generating code.",input_schema:{type:"object",properties:{path:{type:"string",description:"Relative file path from project root"},max_lines:{type:"number",description:"Maximum number of lines to read. Defaults to 500. Use for large files."}},required:["path"]},permission:"file-read"},{name:"search_files",description:"Search for files matching a pattern and optionally search their content with a regex. Use this to find relevant code, understand project structure, or locate specific patterns.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern to match files (e.g., 'src/**/*.ts', '*.json')"},content_regex:{type:"string",description:"Optional regex to search within matched files. Returns matching lines."},max_results:{type:"number",description:"Maximum number of results to return. Default: 50."}},required:["pattern"]},permission:"none"},{name:"list_directory",description:"List files and directories at a given path. Use this to explore project structure.",input_schema:{type:"object",properties:{path:{type:"string",description:"Relative directory path from project root. Defaults to '.' (root)."},recursive:{type:"boolean",description:"List recursively. Default: false."},max_depth:{type:"number",description:"Maximum depth for recursive listing. Default: 3."}}},permission:"none"},{name:"run_command",description:"Execute a shell command. Use this to run build tools, test commands, linters, or inspect the environment. Commands run in the project root directory.",input_schema:{type:"object",properties:{command:{type:"string",description:"The shell command to execute"},timeout:{type:"number",description:"Timeout in milliseconds. Default: 30000 (30 seconds)."}},required:["command"]},permission:"command"},{name:"edit_file",description:"Apply search-and-replace edits to an existing file. Use this for targeted modifications to existing code rather than rewriting entire files.",input_schema:{type:"object",properties:{path:{type:"string",description:"Relative file path from project root"},edits:{type:"array",items:{type:"object",properties:{old_text:{type:"string",description:"The exact text to find in the file"},new_text:{type:"string",description:"The replacement text"}},required:["old_text","new_text"]},description:"List of search/replace pairs to apply in order"}},required:["path","edits"]},permission:"file-write"}];function K(A){return(A?M.filter(e=>A.includes(e.name)):M).map(({name:e,description:i,input_schema:s})=>({name:e,description:i,input_schema:s}))}function j(){return K(["create_files","ask_user"])}function B(){let A=M.filter(e=>e.name!=="create_files"&&e.name!=="ask_user");if(A.length===0)return"";let t=["# Available Capabilities","In addition to generating files, you have the following capabilities:",""];for(let e of A)t.push(`## ${e.name}`),t.push(e.description),t.push("");return t.join(`
|
|
2
|
+
`)}var H=M.map(A=>A.name);var U="claude-sonnet-4-20250514",L=8192,C=class{name="claude";apiKey;authType="api-key";constructor(t){if(this.apiKey=t||process.env.ANTHROPIC_API_KEY||"",!this.apiKey){let e=I();e&&(this.apiKey=e.token,this.authType=e.authType)}if(!this.apiKey)throw new Error("Anthropic API key required. Run `agentx model` to configure, set ANTHROPIC_API_KEY, or pass --api-key.")}async generate(t,e){let i=e?.model||U,s=e?.maxTokens||L,r=t.find(p=>p.role==="system"),u=t.filter(p=>p.role!=="system").map(p=>({role:p.role,content:p.content})),g={model:i,max_tokens:s,messages:u,tools:j()};r&&(g.system=r.content),e?.temperature!==void 0&&(g.temperature=e.temperature);let h=await this.callApi(g);return this.parseResponse(h)}async generateRaw(t,e,i,s){let r=s?.model||U,u=s?.maxTokens||L,g={model:r,max_tokens:u,system:e,messages:t,tools:i};s?.temperature!==void 0&&(g.temperature=s.temperature);let h=await this.callApi(g);return{content:h.content.map(c=>c.type==="text"?{type:"text",text:c.text||""}:c.type==="tool_use"?{type:"tool_use",id:c.id||"",name:c.name||"",input:c.input||{}}:{type:"text",text:""}),stop_reason:h.stop_reason,usage:h.usage}}async*stream(t,e){let i=e?.model||U,s=e?.maxTokens||L,r=t.find(m=>m.role==="system"),u=t.filter(m=>m.role!=="system").map(m=>({role:m.role,content:m.content})),g={model:i,max_tokens:s,messages:u,stream:!0,tools:j()};r&&(g.system=r.content);let h=this.buildHeaders(),p=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:h,body:JSON.stringify(g)});if(!p.ok){let m=await p.text();yield{type:"error",error:`Anthropic API error (${p.status}): ${m}`};return}let c=p.body?.getReader();if(!c){yield{type:"error",error:"No response body"};return}let d=new TextDecoder,a="",_=[],v="",x,k=0,n=null,y=m=>{let R=(m||"").trim();if(!R||R.includes("```"))return;let T=R.replace(/\r\n/g,`
|
|
3
|
+
`).split(`
|
|
4
|
+
`),w=T.slice(Math.max(0,T.length-20)),l=w.join(`
|
|
5
|
+
`);if(/\b(plan|proposal)\b/i.test(l)&&/(ready for your review|review (the )?plan|requesting plan approval|awaiting approval|waiting for (your )?approval|approve (the )?plan|approval to proceed)/i.test(l))return`The provider is requesting plan approval.
|
|
6
|
+
Reply with:
|
|
7
|
+
- approve
|
|
8
|
+
- revise: <what to change>
|
|
9
|
+
- cancel`;let f=b=>/^(question|clarification|clarify|i need|need more|before i proceed|to proceed|please (confirm|clarify)|which|what|where|when|how|do you)/i.test(b.trim()),q=-1;for(let b=w.length-1;b>=0;b--){let O=w[b].trim();if(O&&(f(O)||O.includes("?"))){q=b;break}}if(q===-1)return;let E=[];for(let b=q;b<w.length&&E.length<8;b++){let O=w[b],N=O.trim();if(E.length>0&&!N||E.length>0&&!/^(options?:|[-*]\s|\d+[\).]\s)/i.test(N)&&!N.includes("?"))break;E.push(O.trimEnd())}let F=E.join(`
|
|
10
|
+
`).trim();if(!(F.length<5))return F.length>800?F.slice(0,800).trimEnd():F};try{for(;;){let{done:m,value:R}=await c.read();if(m)break;a+=d.decode(R,{stream:!0});let T=a.split(`
|
|
11
|
+
`);a=T.pop()||"";for(let w of T){if(!w.startsWith("data: "))continue;let l=w.slice(6).trim();if(l!=="[DONE]")try{let o=JSON.parse(l);if(o.type==="content_block_start"&&o.content_block?.type==="tool_use"){if(n){yield{type:"tool_use_end",name:n.name};try{let f=JSON.parse(n.json||"{}");n.name==="create_files"&&f&&(Array.isArray(f.files)&&_.push(...f.files),typeof f.summary=="string"&&f.summary.trim()&&(v+=`
|
|
12
|
+
${f.summary}`)),n.name==="ask_user"&&f&&typeof f.question=="string"&&f.question.trim()&&(x=f.question,Array.isArray(f.options)&&f.options.length&&(x+=`
|
|
13
|
+
Options: ${f.options.join(", ")}`))}catch{}finally{n=null}}n={name:o.content_block.name,id:o.content_block.id,json:""},yield{type:"tool_use_start",name:o.content_block.name,id:o.content_block.id}}if(o.type==="content_block_delta"&&(o.delta?.type==="text_delta"&&(v+=o.delta.text,yield{type:"text_delta",text:o.delta.text}),o.delta?.type==="input_json_delta"&&(n&&(n.json+=o.delta.partial_json||""),yield{type:"tool_use_delta",json:o.delta.partial_json})),o.type==="content_block_stop"&&n){yield{type:"tool_use_end",name:n.name};try{let f=JSON.parse(n.json||"{}");n.name==="create_files"&&f&&(Array.isArray(f.files)&&_.push(...f.files),typeof f.summary=="string"&&f.summary.trim()&&(v+=`
|
|
14
|
+
${f.summary}`)),n.name==="ask_user"&&f&&typeof f.question=="string"&&f.question.trim()&&(x=f.question,Array.isArray(f.options)&&f.options.length&&(x+=`
|
|
15
|
+
Options: ${f.options.join(", ")}`))}catch{}finally{n=null}}o.type==="message_delta"&&o.usage&&(k=(o.usage.input_tokens||0)+(o.usage.output_tokens||0)),o.type}catch{}}}}finally{c.releaseLock()}if(n){yield{type:"tool_use_end",name:n.name};try{let m=JSON.parse(n.json||"{}");n.name==="create_files"&&m&&(Array.isArray(m.files)&&_.push(...m.files),typeof m.summary=="string"&&m.summary.trim()&&(v+=`
|
|
16
|
+
${m.summary}`)),n.name==="ask_user"&&m&&typeof m.question=="string"&&m.question.trim()&&(x=m.question,Array.isArray(m.options)&&m.options.length&&(x+=`
|
|
17
|
+
Options: ${m.options.join(", ")}`))}catch{}n=null}!x&&_.length===0&&(x=y(v)),yield{type:"done",result:{content:v,files:_,followUp:x,tokensUsed:k}}}buildHeaders(){let t={"Content-Type":"application/json","anthropic-version":"2023-06-01"};return this.authType==="oauth"?(t.Authorization=`Bearer ${this.apiKey}`,t["anthropic-beta"]="claude-code-20250219,oauth-2025-04-20",t["user-agent"]="claude-cli/2.1.2 (external, cli)",t["x-app"]="cli",t["anthropic-dangerous-direct-browser-access"]="true"):t["x-api-key"]=this.apiKey,t}async callApi(t){let e=this.buildHeaders(),i=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:e,body:JSON.stringify(t)});if(!i.ok){let s=await i.text();throw new Error(`Anthropic API error (${i.status}): ${s}`)}return await i.json()}parseResponse(t){let e=[],i="",s;for(let r of t.content)if(r.type==="text"&&(i+=r.text||""),r.type==="tool_use"){if(r.name==="create_files"&&r.input){let u=r.input;e.push(...u.files||[]),u.summary&&(i+=`
|
|
18
|
+
${u.summary}`)}if(r.name==="ask_user"&&r.input){let u=r.input;s=u.question,u.options?.length&&(s+=`
|
|
19
|
+
Options: ${u.options.join(", ")}`)}}return{content:i,files:e,followUp:s,tokensUsed:t.usage.input_tokens+t.usage.output_tokens}}};import{execa as D}from"execa";var S="claude-sonnet-4-20250514",$=8192,J={"claude-sonnet-4-20250514":"sonnet","claude-opus-4-20250514":"opus","claude-haiku-4-20250514":"haiku"},G=class{name="claude-code";credential;constructor(){let t=P();if(t){this.credential={type:t.authType,token:t.token};return}let e=I();if(!e)throw new Error(`No Claude credentials found.
|
|
20
|
+
Options:
|
|
21
|
+
1. Run \`agentx model\` to configure credentials
|
|
22
|
+
2. Set ANTHROPIC_API_KEY environment variable
|
|
23
|
+
3. Set ANTHROPIC_OAUTH_TOKEN environment variable`);this.credential={type:e.authType,token:e.token}}async generate(t,e){return this.credential.type==="oauth"?this.generateViaCli(t,e):this.generateViaApi(t,e)}async generateRaw(t,e,i,s){if(this.credential.type==="oauth")throw new Error("generateRaw() not available for OAuth/CLI mode");let r=s?.model||S,u=s?.maxTokens||$,g={model:r,max_tokens:u,system:e,messages:t,tools:i};s?.temperature!==void 0&&(g.temperature=s.temperature);let h={"Content-Type":"application/json","anthropic-version":"2023-06-01","x-api-key":this.credential.token},p=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:h,body:JSON.stringify(g)});if(!p.ok){let a=await p.text();throw new Error(`Anthropic API error (${p.status}): ${a}`)}let c=await p.json();return{content:c.content.map(a=>a.type==="text"?{type:"text",text:a.text||""}:a.type==="tool_use"?{type:"tool_use",id:a.id||"",name:a.name||"",input:a.input||{}}:{type:"text",text:""}),stop_reason:c.stop_reason,usage:c.usage}}get supportsAgenticLoop(){return this.credential.type==="api-key"}async generateViaCli(t,e){let i=e?.model||P()?.model||S,s=J[i]||i,r=t.find(a=>a.role==="system"),g=t.filter(a=>a.role==="user").map(a=>a.content).join(`
|
|
24
|
+
|
|
25
|
+
`),h=["-p","--output-format","json","--model",s,"--dangerously-skip-permissions"];r&&h.push("--append-system-prompt",r.content),h.push(g);let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD;let c=await D("claude",h,{env:p,extendEnv:!1,reject:!1,timeout:3e5,stdin:"ignore"});if(c.exitCode!==0){let a=c.stderr||c.stdout||"Claude CLI failed";throw new Error(`Claude CLI error: ${a}`)}let d=c.stdout.trim();try{let a=JSON.parse(d);if(a.is_error&&a.result)throw new Error(a.result)}catch(a){if(a.message&&!a.message.includes("JSON"))throw a}return this.parseCliOutput(d)}async generateViaApi(t,e){let i=e?.model||S,s=e?.maxTokens||$,r=t.find(d=>d.role==="system"),u=t.filter(d=>d.role!=="system").map(d=>({role:d.role,content:d.content})),g={model:i,max_tokens:s,messages:u,tools:j()};r&&(g.system=r.content),e?.temperature!==void 0&&(g.temperature=e.temperature);let h={"Content-Type":"application/json","anthropic-version":"2023-06-01","x-api-key":this.credential.token},p=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:h,body:JSON.stringify(g)});if(!p.ok){let d=await p.text();throw new Error(`Anthropic API error (${p.status}): ${d}`)}let c=await p.json();return this.parseApiResponse(c)}async*stream(t,e){this.credential.type==="oauth"?yield*this.streamViaCli(t,e):yield*this.streamViaApi(t,e)}async*streamViaCli(t,e){let i=e?.model||P()?.model||S,s=J[i]||i,r=t.find(n=>n.role==="system"),g=t.filter(n=>n.role==="user").map(n=>n.content).join(`
|
|
26
|
+
|
|
27
|
+
`),h=["-p","--output-format","stream-json","--model",s,"--dangerously-skip-permissions"];r&&h.push("--append-system-prompt",r.content),h.push(g);let p={...process.env};delete p.ANTHROPIC_API_KEY,delete p.ANTHROPIC_API_KEY_OLD;let c=D("claude",h,{env:p,extendEnv:!1,reject:!1,timeout:3e5,stdin:"ignore"}),d="",a="",_;if(c.stderr&&c.stderr.on("data",n=>{a+=Buffer.isBuffer(n)?n.toString("utf8"):String(n)}),c.stdout){let n=new TextDecoder,y=c.stdout;for await(let m of y){let T=(typeof m=="string"?m:n.decode(m,{stream:!0})).split(`
|
|
28
|
+
`).filter(Boolean);for(let w of T)try{let l=JSON.parse(w);if(l.type==="error"){_=String(l.error||l.message||"Claude CLI error");continue}if(l.is_error&&(l.result||l.message)){_=String(l.result||l.message);continue}l.type==="assistant"&&l.message?(d+=l.message,yield{type:"text_delta",text:l.message}):l.type==="result"&&(d=l.result||d)}catch{d+=w,yield{type:"text_delta",text:w}}}}let v=await c;if(v.exitCode!==0&&!_&&(_=(a||v.stderr||v.stdout||"Claude CLI failed").toString().trim()),_){yield{type:"error",error:`Claude CLI error: ${_}`};return}let x=this.extractFilesFromText(d),k=x.length===0?this.inferFollowUpFromText(d):void 0;yield{type:"done",result:{content:d,files:x,followUp:k,tokensUsed:0}}}async*streamViaApi(t,e){let i=e?.model||S,s=e?.maxTokens||$,r=t.find(y=>y.role==="system"),u=t.filter(y=>y.role!=="system").map(y=>({role:y.role,content:y.content})),g={model:i,max_tokens:s,messages:u,tools:j(),stream:!0};r&&(g.system=r.content);let h={"Content-Type":"application/json","anthropic-version":"2023-06-01","x-api-key":this.credential.token},p=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:h,body:JSON.stringify(g)});if(!p.ok){let y=await p.text();yield{type:"error",error:`Anthropic API error (${p.status}): ${y}`};return}let c=p.body?.getReader();if(!c){yield{type:"error",error:"No response body"};return}let d=new TextDecoder,a="",_="",v=0,x=[],k,n=null;try{for(;;){let{done:y,value:m}=await c.read();if(y)break;a+=d.decode(m,{stream:!0});let R=a.split(`
|
|
29
|
+
`);a=R.pop()||"";for(let T of R){if(!T.startsWith("data: "))continue;let w=T.slice(6).trim();if(w!=="[DONE]")try{let l=JSON.parse(w);if(l.type==="content_block_start"&&l.content_block?.type==="tool_use"){if(n){yield{type:"tool_use_end",name:n.name};try{let o=JSON.parse(n.json||"{}");n.name==="create_files"&&o&&(Array.isArray(o.files)&&x.push(...o.files),typeof o.summary=="string"&&o.summary.trim()&&(_+=`
|
|
30
|
+
${o.summary}`)),n.name==="ask_user"&&o&&typeof o.question=="string"&&o.question.trim()&&(k=o.question,Array.isArray(o.options)&&o.options.length&&(k+=`
|
|
31
|
+
Options: ${o.options.join(", ")}`))}catch{}finally{n=null}}n={name:l.content_block.name,id:l.content_block.id,json:""},yield{type:"tool_use_start",name:n.name,id:n.id}}if(l.type==="content_block_delta"&&l.delta?.type==="text_delta"&&(_+=l.delta.text,yield{type:"text_delta",text:l.delta.text}),l.type==="content_block_delta"&&l.delta?.type==="input_json_delta"&&(n&&(n.json+=l.delta.partial_json||""),yield{type:"tool_use_delta",json:l.delta.partial_json}),l.type==="content_block_stop"&&n){yield{type:"tool_use_end",name:n.name};try{let o=JSON.parse(n.json||"{}");n.name==="create_files"&&o&&(Array.isArray(o.files)&&x.push(...o.files),typeof o.summary=="string"&&o.summary.trim()&&(_+=`
|
|
32
|
+
${o.summary}`)),n.name==="ask_user"&&o&&typeof o.question=="string"&&o.question.trim()&&(k=o.question,Array.isArray(o.options)&&o.options.length&&(k+=`
|
|
33
|
+
Options: ${o.options.join(", ")}`))}catch{}finally{n=null}}l.type==="message_delta"&&l.usage&&(v=(l.usage.input_tokens||0)+(l.usage.output_tokens||0))}catch{}}}}finally{c.releaseLock()}if(n){yield{type:"tool_use_end",name:n.name};try{let y=JSON.parse(n.json||"{}");n.name==="create_files"&&y&&(Array.isArray(y.files)&&x.push(...y.files),typeof y.summary=="string"&&y.summary.trim()&&(_+=`
|
|
34
|
+
${y.summary}`)),n.name==="ask_user"&&y&&typeof y.question=="string"&&y.question.trim()&&(k=y.question,Array.isArray(y.options)&&y.options.length&&(k+=`
|
|
35
|
+
Options: ${y.options.join(", ")}`))}catch{}n=null}x.length===0&&x.push(...this.extractFilesFromText(_)),!k&&x.length===0&&(k=this.inferFollowUpFromText(_)),yield{type:"done",result:{content:_,files:x,followUp:k,tokensUsed:v}}}parseCliOutput(t){let e;try{e=JSON.parse(t)}catch{let u=this.inferFollowUpFromText(t.trim());return{content:t.trim(),files:[],followUp:u,tokensUsed:0}}let i=e.result||e.text||e.content||"",s=this.extractFilesFromText(i),r=s.length===0?this.inferFollowUpFromText(i):void 0;return{content:i,files:s,followUp:r,tokensUsed:e.usage?(e.usage.input_tokens||0)+(e.usage.output_tokens||0):0}}extractFilesFromText(t){let e=[],i=/```[\w]*\s*([\w/._-]+\.\w+)\n([\s\S]*?)```/g,s;for(;(s=i.exec(t))!==null;){let r=s[1],u=s[2];r&&u&&e.push({path:r,content:u.trimEnd()})}return e}inferFollowUpFromText(t){let e=(t||"").trim();if(!e||e.includes("```"))return;let i=e.replace(/\r\n/g,`
|
|
36
|
+
`).split(`
|
|
37
|
+
`),s=i.slice(Math.max(0,i.length-20)),r=s.join(`
|
|
38
|
+
`);if(/\b(plan|proposal)\b/i.test(r)&&/(ready for your review|review (the )?plan|requesting plan approval|awaiting approval|waiting for (your )?approval|approve (the )?plan|approval to proceed)/i.test(r))return`The provider is requesting plan approval.
|
|
39
|
+
Reply with:
|
|
40
|
+
- approve
|
|
41
|
+
- revise: <what to change>
|
|
42
|
+
- cancel`;let g=d=>/^(question|clarification|clarify|i need|need more|before i proceed|to proceed|please (confirm|clarify)|which|what|where|when|how|do you)/i.test(d.trim()),h=-1;for(let d=s.length-1;d>=0;d--){let a=s[d].trim();if(a&&(g(a)||a.includes("?"))){h=d;break}}if(h===-1)return;let p=[];for(let d=h;d<s.length&&p.length<8;d++){let a=s[d],_=a.trim();if(p.length>0&&!_||p.length>0&&!/^(options?:|[-*]\s|\d+[\).]\s)/i.test(_)&&!_.includes("?"))break;p.push(a.trimEnd())}let c=p.join(`
|
|
43
|
+
`).trim();if(!(c.length<5))return c.length>800?c.slice(0,800).trimEnd():c}parseApiResponse(t){let e=[],i="",s;for(let r of t.content)if(r.type==="text"&&(i+=r.text||""),r.type==="tool_use"){if(r.name==="create_files"&&r.input){let u=r.input;e.push(...u.files||[]),u.summary&&(i+=`
|
|
44
|
+
${u.summary}`)}if(r.name==="ask_user"&&r.input){let u=r.input;s=u.question,u.options?.length&&(s+=`
|
|
45
|
+
Options: ${u.options.join(", ")}`)}}return{content:i,files:e,followUp:s,tokensUsed:t.usage.input_tokens+t.usage.output_tokens}}};function oe(A="claude-code",t){let e=A;if(A==="claude-code"&&!t){let i=P();i&&(e=i.provider)}switch(e){case"claude-code":return new G;case"claude":return new C(t);case"openai":throw new Error("OpenAI provider coming soon. Set provider to 'claude-code' or contribute at github.com/anis-marrouchi/agentx");case"ollama":throw new Error("Ollama provider coming soon. Set provider to 'claude-code' or contribute at github.com/anis-marrouchi/agentx");default:throw new Error(`Unknown provider: ${e}. Supported: claude-code, claude`)}}export{K as a,j as b,B as c,H as d,C as e,G as f,oe as g};
|
|
46
|
+
//# sourceMappingURL=chunk-MGMZNJCE.js.map
|