#!/usr/bin/env node
import {a}from'./chunk-EKZDFEJW.js';import'./chunk-5TAVYPOV.js';var w={opus:"claude-opus-4-5-20251101",sonnet:"claude-sonnet-4-20250514",haiku:"claude-haiku-4-20250514"},_=class{name="claude";apiKey=null;baseUrl="https://api.anthropic.com/v1";constructor(){this.apiKey=process.env.ANTHROPIC_API_KEY||null;}listModels(){return ["opus","sonnet","haiku"]}supportsParallel(){return  true}supportsMcp(){return  true}getTokenCost(n){return a[n]}async isAvailable(){return !!this.apiKey}async*spawn(n,t){if(!this.apiKey){yield {type:"error",content:"ANTHROPIC_API_KEY not set",timestamp:new Date().toISOString()};return}let e=t.model||"sonnet",o=w[e],l=this.buildSystemPrompt(n,t),a=[{role:"user",content:t.task}],r={input:0,output:0,total:0},p=true,i=0,u=50;for(;p&&i<u;){i++;try{let d=await this.streamRequest(o,l,a,t),m=[],c=null;for await(let s of d)if(s.type==="content_block_start"&&s.content_block)s.content_block.type==="tool_use"&&(c={id:s.content_block.id||"",name:s.content_block.name||"",input:""});else if(s.type==="content_block_delta"&&s.delta)s.delta.type==="text_delta"&&s.delta.text?yield {type:"text",content:s.delta.text,timestamp:new Date().toISOString()}:s.delta.type==="input_json_delta"&&c&&(c.input+=s.delta.partial_json||"");else if(s.type==="content_block_stop"){if(c){let h=JSON.parse(c.input||"{}");m.push({type:"tool_use",id:c.id,name:c.name,input:h}),yield {type:"tool_use",content:`Using tool: ${c.name}`,toolName:c.name,toolInput:h,timestamp:new Date().toISOString()},c=null;}}else if(s.type==="message_delta"&&s.usage)r.input+=s.usage.input_tokens||0,r.output+=s.usage.output_tokens||0,r.total=r.input+r.output;else if(s.type==="message_stop")if(m.some(y=>y.type==="tool_use")){a.push({role:"assistant",content:m});let y=await this.executeTools(m,t);a.push({role:"user",content:y});for(let g of y)g.type==="tool_result"&&(yield {type:"tool_result",content:typeof g.content=="string"?g.content:JSON.stringify(g.content),toolName:g.tool_use_id,toolResult:g.content,timestamp:new Date().toISOString()});m=[];}else p=!1;t.budget?.maxTokens&&r.total>t.budget.maxTokens&&(yield {type:"error",content:`Token budget exceeded: ${r.total} > ${t.budget.maxTokens}`,usage:r,timestamp:new Date().toISOString()},p=!1);}catch(d){yield {type:"error",content:d instanceof Error?d.message:String(d),timestamp:new Date().toISOString()},p=false;}}yield {type:"done",content:"Agent completed",usage:r,timestamp:new Date().toISOString()};}buildSystemPrompt(n,t){let e=[];return e.push(t.context.systemPrompt),e.push(`
## Your Role: ${n.name.toUpperCase()}
`),e.push(n.role),n.focus&&(e.push(`
### Focus Areas
`),n.focus.reads.length>0&&e.push(`**Read**: ${n.focus.reads.join(", ")}`),n.focus.writes.length>0&&e.push(`**Write**: ${n.focus.writes.join(", ")}`)),t.context.handoffContext&&(e.push(`
### Context from Previous Agent
`),e.push(t.context.handoffContext)),t.context.symbols.length>0&&(e.push(`
### Symbols in Scope
`),e.push(t.context.symbols.join(", "))),e.join(`
`)}async*streamRequest(n,t,e,o){let l=await fetch(`${this.baseUrl}/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:n,max_tokens:o.budget?.maxTokens||4096,system:t,messages:e,stream:true,tools:this.getAvailableTools(o)})});if(!l.ok){let i=await l.text();throw new Error(`API error: ${l.status} - ${i}`)}if(!l.body)throw new Error("No response body");let a=l.body.getReader(),r=new TextDecoder,p="";for(;;){let{done:i,value:u}=await a.read();if(i)break;p+=r.decode(u,{stream:true});let d=p.split(`
`);p=d.pop()||"";for(let m of d)if(m.startsWith("data: ")){let c=m.slice(6).trim();if(c&&c!=="[DONE]")try{yield JSON.parse(c);}catch{}}}}getAvailableTools(n){let t=[{name:"read_file",description:"Read a file from the filesystem",input_schema:{type:"object",properties:{path:{type:"string",description:"Path to the file"}},required:["path"]}},{name:"write_file",description:"Write content to a file",input_schema:{type:"object",properties:{path:{type:"string",description:"Path to the file"},content:{type:"string",description:"Content to write"}},required:["path","content"]}},{name:"search_files",description:"Search for files matching a pattern",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern"},path:{type:"string",description:"Directory to search in"}},required:["pattern"]}},{name:"run_command",description:"Run a shell command",input_schema:{type:"object",properties:{command:{type:"string",description:"Command to run"},cwd:{type:"string",description:"Working directory"}},required:["command"]}}];return n.mcpServerPath&&t.push({name:"mcp_call",description:"Call an MCP tool",input_schema:{type:"object",properties:{tool:{type:"string",description:"MCP tool name"},args:{type:"object",description:"Tool arguments"}},required:["tool"]}}),t}async executeTools(n,t){let e=[];for(let o of n)if(o.type==="tool_use"&&o.id&&o.name){let l;try{l=await this.executeTool(o.name,o.input||{},t);}catch(a){l=`Error: ${a instanceof Error?a.message:String(a)}`;}e.push({type:"tool_result",tool_use_id:o.id,content:l});}return e}async executeTool(n,t,e){let o=e.workingDirectory||process.cwd(),{execSync:l}=await import('child_process'),a=await import('fs'),r=await import('path'),{glob:p}=await import('glob');switch(n){case "read_file":{let i=r.resolve(o,t.path);return a.readFileSync(i,"utf-8")}case "write_file":{let i=r.resolve(o,t.path),u=r.dirname(i);return a.existsSync(u)||a.mkdirSync(u,{recursive:true}),a.writeFileSync(i,t.content),`Written to ${i}`}case "search_files":{let i=t.path?r.resolve(o,t.path):o;return (await p(t.pattern,{cwd:i})).join(`
`)}case "run_command":{let i=t.cwd?r.resolve(o,t.cwd):o;return l(t.command,{cwd:i,encoding:"utf-8",timeout:e.timeout||3e4})}case "mcp_call":return `MCP tool ${t.tool} called with ${JSON.stringify(t.args)}`;default:return `Unknown tool: ${n}`}}};export{_ as ClaudeAgentProvider};