@crewx/sdk 0.9.0-rc.0 → 0.9.0-rc.1
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/dist/esm/index.js +1 -1
- package/dist/index.js +1 -1
- package/dist/types/task-log.types.d.ts +1 -1
- package/package.json +1 -1
package/dist/esm/index.js
CHANGED
|
@@ -26,7 +26,7 @@ import*as X from'path';import X__default,{join,resolve,dirname,isAbsolute,basena
|
|
|
26
26
|
|
|
27
27
|
---
|
|
28
28
|
|
|
29
|
-
${e}`:e}async runProcess(e,t,r){try{return await On(this.adapter.command,e,this.providerStr,this.providerId,t,r,this.adapter)}catch(o){if(Us(this.providerId,o)){let s=e[0]==="copilot"?e:["copilot",...e];return On("gh",s,this.providerStr,this.providerId,t,r,this.adapter)}throw o}}handleResultMeta(e,t){if(!this.adapter.parseResultMeta){let i=$s(e);i&&t?.onUsage&&t.onUsage(i);return}let{usage:r,model:o}=this.adapter.parseResultMeta(e);r&&t?.onUsage&&t.onUsage(r);let s=o??(this.providerId==="opencode"?t?.model??null:null);s&&t?.onModel&&t.onModel(s);}};});function Mr(n){let e=n.update;if(e.sessionUpdate==="agent_message_chunk"){let t=e.content;if(t.type==="text"&&typeof t.text=="string")return t.text}return null}function ce(n,e){try{let t=JSON.parse(n);if(t!=null&&typeof t=="object"&&typeof t.type=="string"&&Ei.has(t.type)){let r=e??new Date().toISOString();return [{...t,timestamp:t.timestamp||r}]}}catch{}return []}var Ei,Ce=D(()=>{c();Ei=new Set(["text","tool_use","tool_result","error","agent_call"]);});var po,go,wt,Fr=D(()=>{c();ge();po=10,go=50,wt=class{config;constructor(e){this.config=e;}async query(e,t){return this._run(e,"query",t)}async execute(e,t){return this._run(e,"execute",t)}async _run(e,t,r){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(r?.tools??[],s),a=this.createModel(r?.model),d=Math.min(r?.maxSteps??this.config.maxSteps??po,go);try{let l=0,u=await o({model:a,system:r?.systemPrompt??void 0,prompt:e,tools:i,maxSteps:d,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens},onStepFinish:y=>{if(l++,!!r?.onOutput){if(y.toolCalls&&y.toolCalls.length>0)for(let g of y.toolCalls)r.onOutput(JSON.stringify({type:"assistant",message:{content:[{type:"tool_use",id:g.toolCallId,name:g.toolName,input:g.args}]}}),"stdout");if(y.toolResults&&y.toolResults.length>0)for(let g of y.toolResults){let w=typeof g.result=="string"?g.result:JSON.stringify(g.result);r.onOutput(JSON.stringify({type:"user",message:{content:[{type:"tool_result",tool_use_id:g.toolCallId,output:w,is_error:!1}]}}),"stdout");}}}}),p=new Set((r?.tools??[]).filter(y=>!y.execute).map(y=>y.name));if(u.finishReason==="tool-calls"&&Array.isArray(u.toolCalls)&&u.toolCalls.length>0){let y=u.toolCalls.filter(g=>p.has(g.toolName));if(y.length>0){let g=y[0];throw new le({toolCallId:g.toolCallId,toolName:g.toolName,args:g.args},{userMessage:e,responseMessages:u.response?.messages??[],toolDefinitions:r?.tools??[],maxSteps:d,systemPrompt:r?.systemPrompt,modelOverride:r?.model})}}if(r?.onUsage&&u.usage){let y={inputTokens:u.usage.promptTokens??0,outputTokens:u.usage.completionTokens??0,cachedInputTokens:0,costUsd:0};r.onUsage(y);}return r?.onModel&&r.onModel(r.model??this.config.model),u.text??""}catch(l){throw l instanceof le?l:l.status===401?new T(`Authentication failed for ${this.config.provider}. Check your API key.`,this.config.provider):l.status===429?new T(`Rate limit exceeded for ${this.config.provider}.`,this.config.provider):new T(`Provider error: ${l.message}`,this.config.provider)}}async continueWithToolResults(e,t,r){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(e.toolDefinitions,s),a=this.createModel(e.modelOverride),d=Math.min(e.maxSteps??this.config.maxSteps??po,go),l=[{role:"user",content:e.userMessage},...e.responseMessages,{role:"tool",content:t.map(u=>({type:"tool-result",toolCallId:u.toolCallId,toolName:u.toolName,result:typeof u.result=="string"?u.result:JSON.stringify(u.result)}))}];try{let u=await o({model:a,system:e.systemPrompt??void 0,messages:l,tools:i,maxSteps:d,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens}}),p=new Set(e.toolDefinitions.filter(y=>!y.execute).map(y=>y.name));if(u.finishReason==="tool-calls"&&Array.isArray(u.toolCalls)&&u.toolCalls.length>0){let y=u.toolCalls.filter(g=>p.has(g.toolName));if(y.length>0){let g=y[0];throw new le({toolCallId:g.toolCallId,toolName:g.toolName,args:g.args},{userMessage:e.userMessage,responseMessages:[...e.responseMessages,{role:"tool",content:t.map(w=>({type:"tool-result",toolCallId:w.toolCallId,toolName:w.toolName,result:typeof w.result=="string"?w.result:JSON.stringify(w.result)}))},...u.response?.messages??[]],toolDefinitions:e.toolDefinitions,maxSteps:e.maxSteps,systemPrompt:e.systemPrompt,modelOverride:e.modelOverride})}}return r?.onUsage&&u.usage&&r.onUsage({inputTokens:u.usage.promptTokens??0,outputTokens:u.usage.completionTokens??0,cachedInputTokens:0,costUsd:0}),r?.onModel&&r.onModel(e.modelOverride??this.config.model),u.text??""}catch(u){throw u instanceof le?u:new T(`Provider error: ${u.message}`,this.config.provider)}}convertTools(e,t){let{z:r}=Y("zod"),o={};for(let s of e){let i=this.jsonSchemaToZod(s.parameters??{},r);s.execute?o[s.name]=t({description:s.description,parameters:i,execute:async a=>s.execute(a)}):o[s.name]=t({description:s.description,parameters:i});}return o}jsonSchemaToZod(e,t){if(!e||!e.properties)return t.object({});let r={},o=e.properties,s=e.required??[];for(let[i,a]of Object.entries(o)){let d;switch(a.type){case "string":d=t.string();break;case "number":d=t.number();break;case "integer":d=t.number().int();break;case "boolean":d=t.boolean();break;case "array":d=t.array(t.any());break;default:d=t.any();}a.description&&(d=d.describe(a.description)),s.includes(i)||(d=d.optional()),r[i]=d;}return t.object(r)}createModel(e){let{provider:t,apiKey:r,baseURL:o}=this.config,s=e||this.config.model;switch(t){case "api/openrouter":{let{createOpenAI:i}=Y("@ai-sdk/openai");return i({apiKey:r||process.env.OPENROUTER_API_KEY,baseURL:o||"https://openrouter.ai/api/v1"})(s)}case "api/openai":{let{createOpenAI:i}=Y("@ai-sdk/openai");return i({apiKey:r||process.env.OPENAI_API_KEY,...o&&{baseURL:o}})(s)}case "api/anthropic":{let{createAnthropic:i}=Y("@ai-sdk/anthropic");return i({apiKey:r||process.env.ANTHROPIC_API_KEY,...o&&{baseURL:o}})(s)}case "api/google":{let{createGoogleGenerativeAI:i}=Y("@ai-sdk/google");return i({apiKey:r||process.env.GOOGLE_API_KEY})(s)}default:throw new T(`Unsupported API provider: ${t}`,t)}}};});var fo={};Pt(fo,{registerApiProviders:()=>mo});function mo(n){we("api",(e,t)=>{let r=n?.apiKeys?.[e];return new wt({provider:t,model:"",apiKey:r,maxSteps:n?.defaults?.maxSteps,temperature:n?.defaults?.temperature})});}var qr=D(()=>{c();ge();Fr();});var Re,Br=D(()=>{c();Re=class extends Error{constructor(t,r,o){super(t);this.code=r;this.data=o;}code;data;name="AcpProtocolError"};});var xa,ka,yo,ho,_a,We,Jt=D(()=>{c();Br();ge();xa=-32e3,ka=2e3,yo=3e4,ho=1e4,_a=8*36e5,We=class{constructor(e){this.options=e;}options;proc=null;sdkConnection=null;disposed=false;stderrBuffer="";collectedStderr="";pendingUpdateCallback=null;authMethods=[];_initResponse=null;get initResponse(){return this._initResponse}async connect(e){if(this.disposed)throw new T("AcpConnection has been disposed","acp");let t=this.options.spawn,r=process.platform==="win32"&&(t.shellOnWindows??true),o=spawn(t.command,t.args,{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.options.env??{}},cwd:this.options.cwd,shell:r,windowsHide:true,detached:process.platform!=="win32"});o.pid!==void 0&&this.options.onPid?.(o.pid),o.stderr.on("data",g=>{let w=g.toString();this.collectedStderr+=w,this.stderrBuffer+=w;let k=this.stderrBuffer.split(`
|
|
29
|
+
${e}`:e}async runProcess(e,t,r){try{return await On(this.adapter.command,e,this.providerStr,this.providerId,t,r,this.adapter)}catch(o){if(Us(this.providerId,o)){let s=e[0]==="copilot"?e:["copilot",...e];return On("gh",s,this.providerStr,this.providerId,t,r,this.adapter)}throw o}}handleResultMeta(e,t){if(!this.adapter.parseResultMeta){let i=$s(e);i&&t?.onUsage&&t.onUsage(i);return}let{usage:r,model:o}=this.adapter.parseResultMeta(e);r&&t?.onUsage&&t.onUsage(r);let s=o??(this.providerId==="opencode"?t?.model??null:null);s&&t?.onModel&&t.onModel(s);}};});function Mr(n){let e=n.update;if(e.sessionUpdate==="agent_message_chunk"){let t=e.content;if(t.type==="text"&&typeof t.text=="string")return t.text}return null}function ce(n,e){try{let t=JSON.parse(n);if(t!=null&&typeof t=="object"&&typeof t.type=="string"&&Ei.has(t.type)){let r=e??new Date().toISOString();return [{...t,timestamp:t.timestamp||r}]}}catch{}return []}var Ei,Ce=D(()=>{c();Ei=new Set(["text","tool_use","tool_result","error","running_instruction","agent_call"]);});var po,go,wt,Fr=D(()=>{c();ge();po=10,go=50,wt=class{config;constructor(e){this.config=e;}async query(e,t){return this._run(e,"query",t)}async execute(e,t){return this._run(e,"execute",t)}async _run(e,t,r){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(r?.tools??[],s),a=this.createModel(r?.model),d=Math.min(r?.maxSteps??this.config.maxSteps??po,go);try{let l=0,u=await o({model:a,system:r?.systemPrompt??void 0,prompt:e,tools:i,maxSteps:d,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens},onStepFinish:y=>{if(l++,!!r?.onOutput){if(y.toolCalls&&y.toolCalls.length>0)for(let g of y.toolCalls)r.onOutput(JSON.stringify({type:"assistant",message:{content:[{type:"tool_use",id:g.toolCallId,name:g.toolName,input:g.args}]}}),"stdout");if(y.toolResults&&y.toolResults.length>0)for(let g of y.toolResults){let w=typeof g.result=="string"?g.result:JSON.stringify(g.result);r.onOutput(JSON.stringify({type:"user",message:{content:[{type:"tool_result",tool_use_id:g.toolCallId,output:w,is_error:!1}]}}),"stdout");}}}}),p=new Set((r?.tools??[]).filter(y=>!y.execute).map(y=>y.name));if(u.finishReason==="tool-calls"&&Array.isArray(u.toolCalls)&&u.toolCalls.length>0){let y=u.toolCalls.filter(g=>p.has(g.toolName));if(y.length>0){let g=y[0];throw new le({toolCallId:g.toolCallId,toolName:g.toolName,args:g.args},{userMessage:e,responseMessages:u.response?.messages??[],toolDefinitions:r?.tools??[],maxSteps:d,systemPrompt:r?.systemPrompt,modelOverride:r?.model})}}if(r?.onUsage&&u.usage){let y={inputTokens:u.usage.promptTokens??0,outputTokens:u.usage.completionTokens??0,cachedInputTokens:0,costUsd:0};r.onUsage(y);}return r?.onModel&&r.onModel(r.model??this.config.model),u.text??""}catch(l){throw l instanceof le?l:l.status===401?new T(`Authentication failed for ${this.config.provider}. Check your API key.`,this.config.provider):l.status===429?new T(`Rate limit exceeded for ${this.config.provider}.`,this.config.provider):new T(`Provider error: ${l.message}`,this.config.provider)}}async continueWithToolResults(e,t,r){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(e.toolDefinitions,s),a=this.createModel(e.modelOverride),d=Math.min(e.maxSteps??this.config.maxSteps??po,go),l=[{role:"user",content:e.userMessage},...e.responseMessages,{role:"tool",content:t.map(u=>({type:"tool-result",toolCallId:u.toolCallId,toolName:u.toolName,result:typeof u.result=="string"?u.result:JSON.stringify(u.result)}))}];try{let u=await o({model:a,system:e.systemPrompt??void 0,messages:l,tools:i,maxSteps:d,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens}}),p=new Set(e.toolDefinitions.filter(y=>!y.execute).map(y=>y.name));if(u.finishReason==="tool-calls"&&Array.isArray(u.toolCalls)&&u.toolCalls.length>0){let y=u.toolCalls.filter(g=>p.has(g.toolName));if(y.length>0){let g=y[0];throw new le({toolCallId:g.toolCallId,toolName:g.toolName,args:g.args},{userMessage:e.userMessage,responseMessages:[...e.responseMessages,{role:"tool",content:t.map(w=>({type:"tool-result",toolCallId:w.toolCallId,toolName:w.toolName,result:typeof w.result=="string"?w.result:JSON.stringify(w.result)}))},...u.response?.messages??[]],toolDefinitions:e.toolDefinitions,maxSteps:e.maxSteps,systemPrompt:e.systemPrompt,modelOverride:e.modelOverride})}}return r?.onUsage&&u.usage&&r.onUsage({inputTokens:u.usage.promptTokens??0,outputTokens:u.usage.completionTokens??0,cachedInputTokens:0,costUsd:0}),r?.onModel&&r.onModel(e.modelOverride??this.config.model),u.text??""}catch(u){throw u instanceof le?u:new T(`Provider error: ${u.message}`,this.config.provider)}}convertTools(e,t){let{z:r}=Y("zod"),o={};for(let s of e){let i=this.jsonSchemaToZod(s.parameters??{},r);s.execute?o[s.name]=t({description:s.description,parameters:i,execute:async a=>s.execute(a)}):o[s.name]=t({description:s.description,parameters:i});}return o}jsonSchemaToZod(e,t){if(!e||!e.properties)return t.object({});let r={},o=e.properties,s=e.required??[];for(let[i,a]of Object.entries(o)){let d;switch(a.type){case "string":d=t.string();break;case "number":d=t.number();break;case "integer":d=t.number().int();break;case "boolean":d=t.boolean();break;case "array":d=t.array(t.any());break;default:d=t.any();}a.description&&(d=d.describe(a.description)),s.includes(i)||(d=d.optional()),r[i]=d;}return t.object(r)}createModel(e){let{provider:t,apiKey:r,baseURL:o}=this.config,s=e||this.config.model;switch(t){case "api/openrouter":{let{createOpenAI:i}=Y("@ai-sdk/openai");return i({apiKey:r||process.env.OPENROUTER_API_KEY,baseURL:o||"https://openrouter.ai/api/v1"})(s)}case "api/openai":{let{createOpenAI:i}=Y("@ai-sdk/openai");return i({apiKey:r||process.env.OPENAI_API_KEY,...o&&{baseURL:o}})(s)}case "api/anthropic":{let{createAnthropic:i}=Y("@ai-sdk/anthropic");return i({apiKey:r||process.env.ANTHROPIC_API_KEY,...o&&{baseURL:o}})(s)}case "api/google":{let{createGoogleGenerativeAI:i}=Y("@ai-sdk/google");return i({apiKey:r||process.env.GOOGLE_API_KEY})(s)}default:throw new T(`Unsupported API provider: ${t}`,t)}}};});var fo={};Pt(fo,{registerApiProviders:()=>mo});function mo(n){we("api",(e,t)=>{let r=n?.apiKeys?.[e];return new wt({provider:t,model:"",apiKey:r,maxSteps:n?.defaults?.maxSteps,temperature:n?.defaults?.temperature})});}var qr=D(()=>{c();ge();Fr();});var Re,Br=D(()=>{c();Re=class extends Error{constructor(t,r,o){super(t);this.code=r;this.data=o;}code;data;name="AcpProtocolError"};});var xa,ka,yo,ho,_a,We,Jt=D(()=>{c();Br();ge();xa=-32e3,ka=2e3,yo=3e4,ho=1e4,_a=8*36e5,We=class{constructor(e){this.options=e;}options;proc=null;sdkConnection=null;disposed=false;stderrBuffer="";collectedStderr="";pendingUpdateCallback=null;authMethods=[];_initResponse=null;get initResponse(){return this._initResponse}async connect(e){if(this.disposed)throw new T("AcpConnection has been disposed","acp");let t=this.options.spawn,r=process.platform==="win32"&&(t.shellOnWindows??true),o=spawn(t.command,t.args,{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.options.env??{}},cwd:this.options.cwd,shell:r,windowsHide:true,detached:process.platform!=="win32"});o.pid!==void 0&&this.options.onPid?.(o.pid),o.stderr.on("data",g=>{let w=g.toString();this.collectedStderr+=w,this.stderrBuffer+=w;let k=this.stderrBuffer.split(`
|
|
30
30
|
`);this.stderrBuffer=k.pop()??"";for(let A of k)A.trim()&&this.options.onStderr?.(A);}),this.proc=o;let s=new WritableStream({write:g=>new Promise((w,k)=>{o.stdin.write(g,A=>{A?k(A):w();});}),close:()=>{o.stdin.end();}}),i=new ReadableStream({start:g=>{o.stdout.on("data",w=>{g.enqueue(new Uint8Array(w));}),o.stdout.on("end",()=>{g.close();}),o.stdout.on("error",w=>{g.error(w);});}}),a=ndJsonStream(s,i),d=this,l=new ClientSideConnection(g=>({requestPermission:async w=>{if(d.options.configOptions?.allow_all!==void 0){let k=w.options;if(Array.isArray(k)&&k.length>0)return {outcome:{outcome:"selected",optionId:(k.find(x=>x.kind==="allow_once")??k.find(x=>x.kind?.startsWith("allow_"))??k[0]).optionId}}}return {outcome:{outcome:"cancelled"}}},sessionUpdate:async w=>{d.pendingUpdateCallback?.(w);}}),a);this.sdkConnection=l;let u=new Promise((g,w)=>{o.on("error",k=>{if(k.code==="ENOENT"){let x=t.command==="npx"&&t.args.length>0?`@agentclientprotocol/${t.args[0]}`:t.command;w(new T(`ACP command "${t.command}" not found. Is the ACP adapter installed? Try: npm install -g ${x}`,"acp"));}else w(new T(`ACP spawn error: ${k.message}`,"acp"));});}),p=this.doInitialize(l,e),y=new Promise((g,w)=>{setTimeout(()=>{w(new Re(`ACP connect timeout after ${yo}ms. The ACP adapter may not be installed or may require interactive setup.`));},yo).unref();});await Promise.race([p,y,u]);}async doInitialize(e,t){let r=await e.initialize({protocolVersion:1,clientCapabilities:{auth:{}},clientInfo:{name:t?.name??"crewx-sdk",version:t?.version??"0.8.4"}});this._initResponse=r,this.authMethods=r.authMethods??[];}async newSession(e){if(!this.sdkConnection)throw new T("AcpConnection not connected. Call connect() first.","acp");try{return await this.newSessionWithTimeout(e)}catch(t){if(!this.isAuthError(t))throw t;return await this.tryAuthenticate(),this.newSessionWithTimeout(e)}}async newSessionWithTimeout(e){return (await this.newSessionRawTimeout(e)).sessionId}async newSessionRaw(e){if(!this.sdkConnection)throw new T("AcpConnection not connected. Call connect() first.","acp");try{return await this.newSessionRawTimeout(e)}catch(t){if(!this.isAuthError(t))throw t;return await this.tryAuthenticate(),this.newSessionRawTimeout(e)}}async newSessionRawTimeout(e){let t=this.sdkConnection.newSession(e),r=new Promise((o,s)=>{setTimeout(()=>{s(new Re(`ACP session/new timeout after ${ho}ms`));},ho).unref();});return Promise.race([t,r])}isAuthError(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code===xa}async tryAuthenticate(){if(!this.sdkConnection)throw new T("AcpConnection not connected.","acp");let e=this.authMethods.find(r=>r.type==="env_var"&&this.hasEnvVarsFor(r));if(e){await this.sdkConnection.authenticate({methodId:e.id});return}let t=this.authMethods.map(r=>`${r.id} (${r.type??"agent"})`).join(", ");if(this.authMethods.length>0){let r=this.authMethods.filter(o=>o.type==="env_var");if(r.length>0){let o=r.flatMap(s=>(s.vars??[]).filter(i=>!i.optional&&!process.env[i.name]).map(i=>i.name));throw new Re(`ACP authentication required. Missing environment variables: ${o.join(", ")}. Set them in your shell or crewx.yaml env block.`)}throw new Re(`ACP authentication required but no supported method found. Available methods: ${t}. CrewX currently supports env_var authentication only.`)}throw new Re("ACP agent requires authentication but advertised no auth methods.")}hasEnvVarsFor(e){return !e.vars||e.vars.length===0?true:e.vars.filter(t=>!t.optional).every(t=>!!process.env[t.name])}async setModel(e,t){if(!this.sdkConnection)throw new T("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.unstable_setSessionModel({sessionId:e,modelId:t});}async setMode(e,t){if(!this.sdkConnection)throw new T("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.setSessionMode({sessionId:e,modeId:t});}async setConfigOption(e,t,r){if(!this.sdkConnection)throw new T("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.setSessionConfigOption({sessionId:e,configId:t,value:r});}async prompt(e,t,r,o){if(!this.sdkConnection||!this.proc)throw new T("AcpConnection not connected. Call connect() first.","acp");this.pendingUpdateCallback=r??null;let s=this.sdkConnection,i=this.proc,a=o??_a,d=false,l=s.prompt({sessionId:e,prompt:t}).finally(()=>{d=true;}),u=new Promise((y,g)=>{setTimeout(()=>{s.cancel({sessionId:e}).catch(()=>{}),g(new Ie(`ACP prompt timeout after ${a}ms`,"acp"));},a).unref();}),p=new Promise((y,g)=>{let w=(v,_,I)=>{if(d)return;let b=_!=null?`signal=${_}`:`code=${String(v)}`;g(new T(`ACP process terminated unexpectedly (${b}) [${I}]: ${this.collectedStderr.slice(-500)}`,"acp"));},k=(v,_)=>w(v,_,"exit"),A=(v,_)=>w(v,_,"close");i.once("exit",k),i.once("close",A);let x=()=>{i.off("exit",k),i.off("close",A);};l.then(x,x);});try{return await Promise.race([l,u,p])}finally{this.pendingUpdateCallback=null;}}async dispose(){if(this.disposed)return;this.disposed=true,this.pendingUpdateCallback=null,this.sdkConnection=null;let e=this.proc;if(!e)return;this.proc=null,this.stderrBuffer.trim()&&(this.options.onStderr?.(this.stderrBuffer),this.stderrBuffer="");let t=e.pid,r=o=>{if(t!==void 0&&process.platform!=="win32")try{process.kill(-t,o);}catch{}else try{e.kill(o);}catch{}};await new Promise(o=>{let s=()=>{clearTimeout(i),o();};e.once("close",s),e.once("error",s);try{r("SIGTERM");}catch{s();return}let i=setTimeout(()=>{r("SIGKILL");},ka);});}get isConnected(){return !this.disposed&&this.sdkConnection!==null&&this.proc!==null}};});function wo(n,e){if(n!=null&&typeof n=="object"){let t=n;if(typeof t.command=="string")return t.command;if(typeof t.file_path=="string")return t.file_path;if(typeof t.filePath=="string")return t.filePath;if(typeof t.path=="string")return t.path;if(typeof t.query=="string")return t.query;if(typeof t.pattern=="string")return t.pattern;if(typeof t.url=="string")return t.url;if(Object.keys(t).length>0)return JSON.stringify(t)}if(e&&e.length>0)return e.map(t=>t.path).join(", ")}var va,xt,Wr=D(()=>{c();Ce();Jt();va={read:"Read",edit:"Edit",delete:"Delete",move:"Move",search:"Search",execute:"Bash",think:"Think",fetch:"WebFetch",switch_mode:"SwitchMode"};xt=class{constructor(e,t,r){this.adapter=t;}adapter;async query(e,t){return this.runPrompt(e,t)}async execute(e,t){return this.runPrompt(e,t)}async dispose(){}async runPrompt(e,t){let{command:r,args:o}=this.adapter.spawn;t?.onCommand?.(`${r} ${o.join(" ")}`);let s=this.adapter.buildSpawnEnv?.(t?.model??""),i=s?{...t?.env,...s}:t?.env,a=new We({spawn:this.adapter.spawn,env:i,cwd:t?.cwd,timeoutMs:t?.timeoutMs,onPid:t?.onPid,onStderr:d=>t?.onOutput?.(d,"stderr"),configOptions:t?.configOptions});try{await a.connect(this.adapter.clientInfo);let d=this.adapter.buildSessionParams({cwd:t?.cwd,env:t?.env,model:t?.model,systemPrompt:t?.systemPrompt}),l=await a.newSession(d);await this.applySessionOptions(a,l,t);let u=this.composePrompt(e,t),p=[],y=await a.prompt(l,u,g=>this.handleUpdate(g,t,p),t?.timeoutMs);return this.handleUsage(y,t),p.join("")}finally{await a.dispose().catch(()=>{});}}async applySessionOptions(e,t,r){if(r?.model&&r.model!=="default"&&!this.adapter.buildSpawnEnv){let o=this.adapter.buildEffortAction?.(r.effort??"",r.model);try{o?.type==="set_model"?await e.setModel(t,o.modelId):await e.setModel(t,r.model);}catch(s){console.warn(`[acp] setModel(${r.model}) failed: ${s instanceof Error?s.message:String(s)}`);}}if(r?.mode){let o=this.adapter.resolveMode?.(r.mode)??r.mode;if(o)try{await e.setMode(t,o);}catch(s){console.warn(`[acp] setMode(${o}) failed: ${s instanceof Error?s.message:String(s)}`);}}if(r?.effort){let o=this.adapter.buildEffortAction?.(r.effort,r.model);if(o&&o.type==="set_config_option")try{await e.setConfigOption(t,o.configId,o.value);}catch(s){console.warn(`[acp] setConfigOption(${o.configId}) effort failed: ${s instanceof Error?s.message:String(s)}`);}}if(r?.configOptions)for(let[o,s]of Object.entries(r.configOptions))try{await e.setConfigOption(t,o,s);}catch(i){console.warn(`[acp] setConfigOption(${o}) failed, retrying: ${i instanceof Error?i.message:String(i)}`);try{await new Promise(a=>setTimeout(a,500)),await e.setConfigOption(t,o,s);}catch(a){console.warn(`[acp] setConfigOption(${o}) retry failed: ${a instanceof Error?a.message:String(a)}`);}}}composePrompt(e,t){let r=[];return t?.systemPrompt?.trim()&&(r.push(t.systemPrompt),r.push("---")),t?.context&&(r.push(t.context),r.push("---")),r.push(e),[{type:"text",text:r.join(`
|
|
31
31
|
|
|
32
32
|
`)}]}handleUpdate(e,t,r){let o=e.update;if(o.sessionUpdate==="agent_message_chunk"){let s=null;this.adapter.extractTextFromUpdate?s=this.adapter.extractTextFromUpdate(e):s=Mr(e),s!==null&&(r.push(s),t?.onOutput?.(s,"stdout"));}else if(o.sessionUpdate==="tool_call"){this.pushBlockBoundary(r);let s=new Date().toISOString(),i=o,a={title:i.title??"",kind:i.kind,rawInput:i.rawInput,rawOutput:i.rawOutput,locations:i.locations,_meta:i._meta},d=this.resolveToolCall(a),l={timestamp:s,type:"tool_use",toolUseId:i.toolCallId,toolName:d.toolName,toolInput:d.toolInput};t?.onTaskLog?.([l]);}else if(o.sessionUpdate==="tool_call_update"){let s=new Date().toISOString(),i=o;if(i.status==="completed"||i.status==="failed"){let d=this.extractResultPreview(i.rawOutput),l={timestamp:s,type:"tool_result",toolUseId:i.toolCallId,resultPreview:d,isError:i.status==="failed"};t?.onTaskLog?.([l]);}else if(i.rawInput!=null&&typeof i.rawInput=="object"&&Object.keys(i.rawInput).length>0){this.pushBlockBoundary(r);let d={title:i.title??"",kind:i.kind,rawInput:i.rawInput,rawOutput:i.rawOutput,locations:i.locations,_meta:i._meta},l=this.resolveToolCall(d),u={timestamp:s,type:"tool_use",toolUseId:i.toolCallId,toolName:l.toolName,toolInput:l.toolInput};t?.onTaskLog?.([u]);}}else o.sessionUpdate;}pushBlockBoundary(e){e.length===0||e[e.length-1].endsWith(`
|
package/dist/index.js
CHANGED
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
|
|
27
27
|
---
|
|
28
28
|
|
|
29
|
-
${e}`:e}async runProcess(e,t,r){try{return await Sn(this.adapter.command,e,this.providerStr,this.providerId,t,r,this.adapter)}catch(o){if(Ms(this.providerId,o)){let s=e[0]==="copilot"?e:["copilot",...e];return Sn("gh",s,this.providerStr,this.providerId,t,r,this.adapter)}throw o}}handleResultMeta(e,t){if(!this.adapter.parseResultMeta){let i=Os(e);i&&t?.onUsage&&t.onUsage(i);return}let{usage:r,model:o}=this.adapter.parseResultMeta(e);r&&t?.onUsage&&t.onUsage(r);let s=o??(this.providerId==="opencode"?t?.model??null:null);s&&t?.onModel&&t.onModel(s);}};});function Or(n){let e=n.update;if(e.sessionUpdate==="agent_message_chunk"){let t=e.content;if(t.type==="text"&&typeof t.text=="string")return t.text}return null}function le(n,e){try{let t=JSON.parse(n);if(t!=null&&typeof t=="object"&&typeof t.type=="string"&&ki.has(t.type)){let r=e??new Date().toISOString();return [{...t,timestamp:t.timestamp||r}]}}catch{}return []}var ki,Ee=N(()=>{c();ki=new Set(["text","tool_use","tool_result","error","agent_call"]);});var co,uo;exports.VercelProviderRuntime=void 0;var Hr=N(()=>{c();pe();co=10,uo=50,exports.VercelProviderRuntime=class{config;constructor(e){this.config=e;}async query(e,t){return this._run(e,"query",t)}async execute(e,t){return this._run(e,"execute",t)}async _run(e,t,r){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(r?.tools??[],s),a=this.createModel(r?.model),d=Math.min(r?.maxSteps??this.config.maxSteps??co,uo);try{let l=0,u=await o({model:a,system:r?.systemPrompt??void 0,prompt:e,tools:i,maxSteps:d,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens},onStepFinish:f=>{if(l++,!!r?.onOutput){if(f.toolCalls&&f.toolCalls.length>0)for(let g of f.toolCalls)r.onOutput(JSON.stringify({type:"assistant",message:{content:[{type:"tool_use",id:g.toolCallId,name:g.toolName,input:g.args}]}}),"stdout");if(f.toolResults&&f.toolResults.length>0)for(let g of f.toolResults){let h=typeof g.result=="string"?g.result:JSON.stringify(g.result);r.onOutput(JSON.stringify({type:"user",message:{content:[{type:"tool_result",tool_use_id:g.toolCallId,output:h,is_error:!1}]}}),"stdout");}}}}),p=new Set((r?.tools??[]).filter(f=>!f.execute).map(f=>f.name));if(u.finishReason==="tool-calls"&&Array.isArray(u.toolCalls)&&u.toolCalls.length>0){let f=u.toolCalls.filter(g=>p.has(g.toolName));if(f.length>0){let g=f[0];throw new exports.ClientToolCallRequiredError({toolCallId:g.toolCallId,toolName:g.toolName,args:g.args},{userMessage:e,responseMessages:u.response?.messages??[],toolDefinitions:r?.tools??[],maxSteps:d,systemPrompt:r?.systemPrompt,modelOverride:r?.model})}}if(r?.onUsage&&u.usage){let f={inputTokens:u.usage.promptTokens??0,outputTokens:u.usage.completionTokens??0,cachedInputTokens:0,costUsd:0};r.onUsage(f);}return r?.onModel&&r.onModel(r.model??this.config.model),u.text??""}catch(l){throw l instanceof exports.ClientToolCallRequiredError?l:l.status===401?new exports.ProviderError(`Authentication failed for ${this.config.provider}. Check your API key.`,this.config.provider):l.status===429?new exports.ProviderError(`Rate limit exceeded for ${this.config.provider}.`,this.config.provider):new exports.ProviderError(`Provider error: ${l.message}`,this.config.provider)}}async continueWithToolResults(e,t,r){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(e.toolDefinitions,s),a=this.createModel(e.modelOverride),d=Math.min(e.maxSteps??this.config.maxSteps??co,uo),l=[{role:"user",content:e.userMessage},...e.responseMessages,{role:"tool",content:t.map(u=>({type:"tool-result",toolCallId:u.toolCallId,toolName:u.toolName,result:typeof u.result=="string"?u.result:JSON.stringify(u.result)}))}];try{let u=await o({model:a,system:e.systemPrompt??void 0,messages:l,tools:i,maxSteps:d,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens}}),p=new Set(e.toolDefinitions.filter(f=>!f.execute).map(f=>f.name));if(u.finishReason==="tool-calls"&&Array.isArray(u.toolCalls)&&u.toolCalls.length>0){let f=u.toolCalls.filter(g=>p.has(g.toolName));if(f.length>0){let g=f[0];throw new exports.ClientToolCallRequiredError({toolCallId:g.toolCallId,toolName:g.toolName,args:g.args},{userMessage:e.userMessage,responseMessages:[...e.responseMessages,{role:"tool",content:t.map(h=>({type:"tool-result",toolCallId:h.toolCallId,toolName:h.toolName,result:typeof h.result=="string"?h.result:JSON.stringify(h.result)}))},...u.response?.messages??[]],toolDefinitions:e.toolDefinitions,maxSteps:e.maxSteps,systemPrompt:e.systemPrompt,modelOverride:e.modelOverride})}}return r?.onUsage&&u.usage&&r.onUsage({inputTokens:u.usage.promptTokens??0,outputTokens:u.usage.completionTokens??0,cachedInputTokens:0,costUsd:0}),r?.onModel&&r.onModel(e.modelOverride??this.config.model),u.text??""}catch(u){throw u instanceof exports.ClientToolCallRequiredError?u:new exports.ProviderError(`Provider error: ${u.message}`,this.config.provider)}}convertTools(e,t){let{z:r}=J("zod"),o={};for(let s of e){let i=this.jsonSchemaToZod(s.parameters??{},r);s.execute?o[s.name]=t({description:s.description,parameters:i,execute:async a=>s.execute(a)}):o[s.name]=t({description:s.description,parameters:i});}return o}jsonSchemaToZod(e,t){if(!e||!e.properties)return t.object({});let r={},o=e.properties,s=e.required??[];for(let[i,a]of Object.entries(o)){let d;switch(a.type){case "string":d=t.string();break;case "number":d=t.number();break;case "integer":d=t.number().int();break;case "boolean":d=t.boolean();break;case "array":d=t.array(t.any());break;default:d=t.any();}a.description&&(d=d.describe(a.description)),s.includes(i)||(d=d.optional()),r[i]=d;}return t.object(r)}createModel(e){let{provider:t,apiKey:r,baseURL:o}=this.config,s=e||this.config.model;switch(t){case "api/openrouter":{let{createOpenAI:i}=J("@ai-sdk/openai");return i({apiKey:r||process.env.OPENROUTER_API_KEY,baseURL:o||"https://openrouter.ai/api/v1"})(s)}case "api/openai":{let{createOpenAI:i}=J("@ai-sdk/openai");return i({apiKey:r||process.env.OPENAI_API_KEY,...o&&{baseURL:o}})(s)}case "api/anthropic":{let{createAnthropic:i}=J("@ai-sdk/anthropic");return i({apiKey:r||process.env.ANTHROPIC_API_KEY,...o&&{baseURL:o}})(s)}case "api/google":{let{createGoogleGenerativeAI:i}=J("@ai-sdk/google");return i({apiKey:r||process.env.GOOGLE_API_KEY})(s)}default:throw new exports.ProviderError(`Unsupported API provider: ${t}`,t)}}};});var go={};Tt(go,{registerApiProviders:()=>po});function po(n){he("api",(e,t)=>{let r=n?.apiKeys?.[e];return new exports.VercelProviderRuntime({provider:t,model:"",apiKey:r,maxSteps:n?.defaults?.maxSteps,temperature:n?.defaults?.temperature})});}var Fr=N(()=>{c();pe();Hr();});exports.AcpProtocolError=void 0;var qr=N(()=>{c();exports.AcpProtocolError=class extends Error{constructor(t,r,o){super(t);this.code=r;this.data=o;}code;data;name="AcpProtocolError"};});var ma,fa,mo,fo,ya;exports.AcpConnection=void 0;var Xt=N(()=>{c();qr();pe();ma=-32e3,fa=2e3,mo=3e4,fo=1e4,ya=8*36e5,exports.AcpConnection=class{constructor(e){this.options=e;}options;proc=null;sdkConnection=null;disposed=false;stderrBuffer="";collectedStderr="";pendingUpdateCallback=null;authMethods=[];_initResponse=null;get initResponse(){return this._initResponse}async connect(e){if(this.disposed)throw new exports.ProviderError("AcpConnection has been disposed","acp");let t=this.options.spawn,r=process.platform==="win32"&&(t.shellOnWindows??true),o=child_process.spawn(t.command,t.args,{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.options.env??{}},cwd:this.options.cwd,shell:r,windowsHide:true,detached:process.platform!=="win32"});o.pid!==void 0&&this.options.onPid?.(o.pid),o.stderr.on("data",g=>{let h=g.toString();this.collectedStderr+=h,this.stderrBuffer+=h;let x=this.stderrBuffer.split(`
|
|
29
|
+
${e}`:e}async runProcess(e,t,r){try{return await Sn(this.adapter.command,e,this.providerStr,this.providerId,t,r,this.adapter)}catch(o){if(Ms(this.providerId,o)){let s=e[0]==="copilot"?e:["copilot",...e];return Sn("gh",s,this.providerStr,this.providerId,t,r,this.adapter)}throw o}}handleResultMeta(e,t){if(!this.adapter.parseResultMeta){let i=Os(e);i&&t?.onUsage&&t.onUsage(i);return}let{usage:r,model:o}=this.adapter.parseResultMeta(e);r&&t?.onUsage&&t.onUsage(r);let s=o??(this.providerId==="opencode"?t?.model??null:null);s&&t?.onModel&&t.onModel(s);}};});function Or(n){let e=n.update;if(e.sessionUpdate==="agent_message_chunk"){let t=e.content;if(t.type==="text"&&typeof t.text=="string")return t.text}return null}function le(n,e){try{let t=JSON.parse(n);if(t!=null&&typeof t=="object"&&typeof t.type=="string"&&ki.has(t.type)){let r=e??new Date().toISOString();return [{...t,timestamp:t.timestamp||r}]}}catch{}return []}var ki,Ee=N(()=>{c();ki=new Set(["text","tool_use","tool_result","error","running_instruction","agent_call"]);});var co,uo;exports.VercelProviderRuntime=void 0;var Hr=N(()=>{c();pe();co=10,uo=50,exports.VercelProviderRuntime=class{config;constructor(e){this.config=e;}async query(e,t){return this._run(e,"query",t)}async execute(e,t){return this._run(e,"execute",t)}async _run(e,t,r){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(r?.tools??[],s),a=this.createModel(r?.model),d=Math.min(r?.maxSteps??this.config.maxSteps??co,uo);try{let l=0,u=await o({model:a,system:r?.systemPrompt??void 0,prompt:e,tools:i,maxSteps:d,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens},onStepFinish:f=>{if(l++,!!r?.onOutput){if(f.toolCalls&&f.toolCalls.length>0)for(let g of f.toolCalls)r.onOutput(JSON.stringify({type:"assistant",message:{content:[{type:"tool_use",id:g.toolCallId,name:g.toolName,input:g.args}]}}),"stdout");if(f.toolResults&&f.toolResults.length>0)for(let g of f.toolResults){let h=typeof g.result=="string"?g.result:JSON.stringify(g.result);r.onOutput(JSON.stringify({type:"user",message:{content:[{type:"tool_result",tool_use_id:g.toolCallId,output:h,is_error:!1}]}}),"stdout");}}}}),p=new Set((r?.tools??[]).filter(f=>!f.execute).map(f=>f.name));if(u.finishReason==="tool-calls"&&Array.isArray(u.toolCalls)&&u.toolCalls.length>0){let f=u.toolCalls.filter(g=>p.has(g.toolName));if(f.length>0){let g=f[0];throw new exports.ClientToolCallRequiredError({toolCallId:g.toolCallId,toolName:g.toolName,args:g.args},{userMessage:e,responseMessages:u.response?.messages??[],toolDefinitions:r?.tools??[],maxSteps:d,systemPrompt:r?.systemPrompt,modelOverride:r?.model})}}if(r?.onUsage&&u.usage){let f={inputTokens:u.usage.promptTokens??0,outputTokens:u.usage.completionTokens??0,cachedInputTokens:0,costUsd:0};r.onUsage(f);}return r?.onModel&&r.onModel(r.model??this.config.model),u.text??""}catch(l){throw l instanceof exports.ClientToolCallRequiredError?l:l.status===401?new exports.ProviderError(`Authentication failed for ${this.config.provider}. Check your API key.`,this.config.provider):l.status===429?new exports.ProviderError(`Rate limit exceeded for ${this.config.provider}.`,this.config.provider):new exports.ProviderError(`Provider error: ${l.message}`,this.config.provider)}}async continueWithToolResults(e,t,r){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(e.toolDefinitions,s),a=this.createModel(e.modelOverride),d=Math.min(e.maxSteps??this.config.maxSteps??co,uo),l=[{role:"user",content:e.userMessage},...e.responseMessages,{role:"tool",content:t.map(u=>({type:"tool-result",toolCallId:u.toolCallId,toolName:u.toolName,result:typeof u.result=="string"?u.result:JSON.stringify(u.result)}))}];try{let u=await o({model:a,system:e.systemPrompt??void 0,messages:l,tools:i,maxSteps:d,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens}}),p=new Set(e.toolDefinitions.filter(f=>!f.execute).map(f=>f.name));if(u.finishReason==="tool-calls"&&Array.isArray(u.toolCalls)&&u.toolCalls.length>0){let f=u.toolCalls.filter(g=>p.has(g.toolName));if(f.length>0){let g=f[0];throw new exports.ClientToolCallRequiredError({toolCallId:g.toolCallId,toolName:g.toolName,args:g.args},{userMessage:e.userMessage,responseMessages:[...e.responseMessages,{role:"tool",content:t.map(h=>({type:"tool-result",toolCallId:h.toolCallId,toolName:h.toolName,result:typeof h.result=="string"?h.result:JSON.stringify(h.result)}))},...u.response?.messages??[]],toolDefinitions:e.toolDefinitions,maxSteps:e.maxSteps,systemPrompt:e.systemPrompt,modelOverride:e.modelOverride})}}return r?.onUsage&&u.usage&&r.onUsage({inputTokens:u.usage.promptTokens??0,outputTokens:u.usage.completionTokens??0,cachedInputTokens:0,costUsd:0}),r?.onModel&&r.onModel(e.modelOverride??this.config.model),u.text??""}catch(u){throw u instanceof exports.ClientToolCallRequiredError?u:new exports.ProviderError(`Provider error: ${u.message}`,this.config.provider)}}convertTools(e,t){let{z:r}=J("zod"),o={};for(let s of e){let i=this.jsonSchemaToZod(s.parameters??{},r);s.execute?o[s.name]=t({description:s.description,parameters:i,execute:async a=>s.execute(a)}):o[s.name]=t({description:s.description,parameters:i});}return o}jsonSchemaToZod(e,t){if(!e||!e.properties)return t.object({});let r={},o=e.properties,s=e.required??[];for(let[i,a]of Object.entries(o)){let d;switch(a.type){case "string":d=t.string();break;case "number":d=t.number();break;case "integer":d=t.number().int();break;case "boolean":d=t.boolean();break;case "array":d=t.array(t.any());break;default:d=t.any();}a.description&&(d=d.describe(a.description)),s.includes(i)||(d=d.optional()),r[i]=d;}return t.object(r)}createModel(e){let{provider:t,apiKey:r,baseURL:o}=this.config,s=e||this.config.model;switch(t){case "api/openrouter":{let{createOpenAI:i}=J("@ai-sdk/openai");return i({apiKey:r||process.env.OPENROUTER_API_KEY,baseURL:o||"https://openrouter.ai/api/v1"})(s)}case "api/openai":{let{createOpenAI:i}=J("@ai-sdk/openai");return i({apiKey:r||process.env.OPENAI_API_KEY,...o&&{baseURL:o}})(s)}case "api/anthropic":{let{createAnthropic:i}=J("@ai-sdk/anthropic");return i({apiKey:r||process.env.ANTHROPIC_API_KEY,...o&&{baseURL:o}})(s)}case "api/google":{let{createGoogleGenerativeAI:i}=J("@ai-sdk/google");return i({apiKey:r||process.env.GOOGLE_API_KEY})(s)}default:throw new exports.ProviderError(`Unsupported API provider: ${t}`,t)}}};});var go={};Tt(go,{registerApiProviders:()=>po});function po(n){he("api",(e,t)=>{let r=n?.apiKeys?.[e];return new exports.VercelProviderRuntime({provider:t,model:"",apiKey:r,maxSteps:n?.defaults?.maxSteps,temperature:n?.defaults?.temperature})});}var Fr=N(()=>{c();pe();Hr();});exports.AcpProtocolError=void 0;var qr=N(()=>{c();exports.AcpProtocolError=class extends Error{constructor(t,r,o){super(t);this.code=r;this.data=o;}code;data;name="AcpProtocolError"};});var ma,fa,mo,fo,ya;exports.AcpConnection=void 0;var Xt=N(()=>{c();qr();pe();ma=-32e3,fa=2e3,mo=3e4,fo=1e4,ya=8*36e5,exports.AcpConnection=class{constructor(e){this.options=e;}options;proc=null;sdkConnection=null;disposed=false;stderrBuffer="";collectedStderr="";pendingUpdateCallback=null;authMethods=[];_initResponse=null;get initResponse(){return this._initResponse}async connect(e){if(this.disposed)throw new exports.ProviderError("AcpConnection has been disposed","acp");let t=this.options.spawn,r=process.platform==="win32"&&(t.shellOnWindows??true),o=child_process.spawn(t.command,t.args,{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.options.env??{}},cwd:this.options.cwd,shell:r,windowsHide:true,detached:process.platform!=="win32"});o.pid!==void 0&&this.options.onPid?.(o.pid),o.stderr.on("data",g=>{let h=g.toString();this.collectedStderr+=h,this.stderrBuffer+=h;let x=this.stderrBuffer.split(`
|
|
30
30
|
`);this.stderrBuffer=x.pop()??"";for(let v of x)v.trim()&&this.options.onStderr?.(v);}),this.proc=o;let s=new WritableStream({write:g=>new Promise((h,x)=>{o.stdin.write(g,v=>{v?x(v):h();});}),close:()=>{o.stdin.end();}}),i=new ReadableStream({start:g=>{o.stdout.on("data",h=>{g.enqueue(new Uint8Array(h));}),o.stdout.on("end",()=>{g.close();}),o.stdout.on("error",h=>{g.error(h);});}}),a=sdk.ndJsonStream(s,i),d=this,l=new sdk.ClientSideConnection(g=>({requestPermission:async h=>{if(d.options.configOptions?.allow_all!==void 0){let x=h.options;if(Array.isArray(x)&&x.length>0)return {outcome:{outcome:"selected",optionId:(x.find(w=>w.kind==="allow_once")??x.find(w=>w.kind?.startsWith("allow_"))??x[0]).optionId}}}return {outcome:{outcome:"cancelled"}}},sessionUpdate:async h=>{d.pendingUpdateCallback?.(h);}}),a);this.sdkConnection=l;let u=new Promise((g,h)=>{o.on("error",x=>{if(x.code==="ENOENT"){let w=t.command==="npx"&&t.args.length>0?`@agentclientprotocol/${t.args[0]}`:t.command;h(new exports.ProviderError(`ACP command "${t.command}" not found. Is the ACP adapter installed? Try: npm install -g ${w}`,"acp"));}else h(new exports.ProviderError(`ACP spawn error: ${x.message}`,"acp"));});}),p=this.doInitialize(l,e),f=new Promise((g,h)=>{setTimeout(()=>{h(new exports.AcpProtocolError(`ACP connect timeout after ${mo}ms. The ACP adapter may not be installed or may require interactive setup.`));},mo).unref();});await Promise.race([p,f,u]);}async doInitialize(e,t){let r=await e.initialize({protocolVersion:1,clientCapabilities:{auth:{}},clientInfo:{name:t?.name??"crewx-sdk",version:t?.version??"0.8.4"}});this._initResponse=r,this.authMethods=r.authMethods??[];}async newSession(e){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");try{return await this.newSessionWithTimeout(e)}catch(t){if(!this.isAuthError(t))throw t;return await this.tryAuthenticate(),this.newSessionWithTimeout(e)}}async newSessionWithTimeout(e){return (await this.newSessionRawTimeout(e)).sessionId}async newSessionRaw(e){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");try{return await this.newSessionRawTimeout(e)}catch(t){if(!this.isAuthError(t))throw t;return await this.tryAuthenticate(),this.newSessionRawTimeout(e)}}async newSessionRawTimeout(e){let t=this.sdkConnection.newSession(e),r=new Promise((o,s)=>{setTimeout(()=>{s(new exports.AcpProtocolError(`ACP session/new timeout after ${fo}ms`));},fo).unref();});return Promise.race([t,r])}isAuthError(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code===ma}async tryAuthenticate(){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected.","acp");let e=this.authMethods.find(r=>r.type==="env_var"&&this.hasEnvVarsFor(r));if(e){await this.sdkConnection.authenticate({methodId:e.id});return}let t=this.authMethods.map(r=>`${r.id} (${r.type??"agent"})`).join(", ");if(this.authMethods.length>0){let r=this.authMethods.filter(o=>o.type==="env_var");if(r.length>0){let o=r.flatMap(s=>(s.vars??[]).filter(i=>!i.optional&&!process.env[i.name]).map(i=>i.name));throw new exports.AcpProtocolError(`ACP authentication required. Missing environment variables: ${o.join(", ")}. Set them in your shell or crewx.yaml env block.`)}throw new exports.AcpProtocolError(`ACP authentication required but no supported method found. Available methods: ${t}. CrewX currently supports env_var authentication only.`)}throw new exports.AcpProtocolError("ACP agent requires authentication but advertised no auth methods.")}hasEnvVarsFor(e){return !e.vars||e.vars.length===0?true:e.vars.filter(t=>!t.optional).every(t=>!!process.env[t.name])}async setModel(e,t){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.unstable_setSessionModel({sessionId:e,modelId:t});}async setMode(e,t){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.setSessionMode({sessionId:e,modeId:t});}async setConfigOption(e,t,r){if(!this.sdkConnection)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.setSessionConfigOption({sessionId:e,configId:t,value:r});}async prompt(e,t,r,o){if(!this.sdkConnection||!this.proc)throw new exports.ProviderError("AcpConnection not connected. Call connect() first.","acp");this.pendingUpdateCallback=r??null;let s=this.sdkConnection,i=this.proc,a=o??ya,d=false,l=s.prompt({sessionId:e,prompt:t}).finally(()=>{d=true;}),u=new Promise((f,g)=>{setTimeout(()=>{s.cancel({sessionId:e}).catch(()=>{}),g(new Se(`ACP prompt timeout after ${a}ms`,"acp"));},a).unref();}),p=new Promise((f,g)=>{let h=(_,k,S)=>{if(d)return;let P=k!=null?`signal=${k}`:`code=${String(_)}`;g(new exports.ProviderError(`ACP process terminated unexpectedly (${P}) [${S}]: ${this.collectedStderr.slice(-500)}`,"acp"));},x=(_,k)=>h(_,k,"exit"),v=(_,k)=>h(_,k,"close");i.once("exit",x),i.once("close",v);let w=()=>{i.off("exit",x),i.off("close",v);};l.then(w,w);});try{return await Promise.race([l,u,p])}finally{this.pendingUpdateCallback=null;}}async dispose(){if(this.disposed)return;this.disposed=true,this.pendingUpdateCallback=null,this.sdkConnection=null;let e=this.proc;if(!e)return;this.proc=null,this.stderrBuffer.trim()&&(this.options.onStderr?.(this.stderrBuffer),this.stderrBuffer="");let t=e.pid,r=o=>{if(t!==void 0&&process.platform!=="win32")try{process.kill(-t,o);}catch{}else try{e.kill(o);}catch{}};await new Promise(o=>{let s=()=>{clearTimeout(i),o();};e.once("close",s),e.once("error",s);try{r("SIGTERM");}catch{s();return}let i=setTimeout(()=>{r("SIGKILL");},fa);});}get isConnected(){return !this.disposed&&this.sdkConnection!==null&&this.proc!==null}};});function yo(n,e){if(n!=null&&typeof n=="object"){let t=n;if(typeof t.command=="string")return t.command;if(typeof t.file_path=="string")return t.file_path;if(typeof t.filePath=="string")return t.filePath;if(typeof t.path=="string")return t.path;if(typeof t.query=="string")return t.query;if(typeof t.pattern=="string")return t.pattern;if(typeof t.url=="string")return t.url;if(Object.keys(t).length>0)return JSON.stringify(t)}if(e&&e.length>0)return e.map(t=>t.path).join(", ")}var ha;exports.AcpProviderRuntime=void 0;var Br=N(()=>{c();Ee();Xt();ha={read:"Read",edit:"Edit",delete:"Delete",move:"Move",search:"Search",execute:"Bash",think:"Think",fetch:"WebFetch",switch_mode:"SwitchMode"};exports.AcpProviderRuntime=class{constructor(e,t,r){this.adapter=t;}adapter;async query(e,t){return this.runPrompt(e,t)}async execute(e,t){return this.runPrompt(e,t)}async dispose(){}async runPrompt(e,t){let{command:r,args:o}=this.adapter.spawn;t?.onCommand?.(`${r} ${o.join(" ")}`);let s=this.adapter.buildSpawnEnv?.(t?.model??""),i=s?{...t?.env,...s}:t?.env,a=new exports.AcpConnection({spawn:this.adapter.spawn,env:i,cwd:t?.cwd,timeoutMs:t?.timeoutMs,onPid:t?.onPid,onStderr:d=>t?.onOutput?.(d,"stderr"),configOptions:t?.configOptions});try{await a.connect(this.adapter.clientInfo);let d=this.adapter.buildSessionParams({cwd:t?.cwd,env:t?.env,model:t?.model,systemPrompt:t?.systemPrompt}),l=await a.newSession(d);await this.applySessionOptions(a,l,t);let u=this.composePrompt(e,t),p=[],f=await a.prompt(l,u,g=>this.handleUpdate(g,t,p),t?.timeoutMs);return this.handleUsage(f,t),p.join("")}finally{await a.dispose().catch(()=>{});}}async applySessionOptions(e,t,r){if(r?.model&&r.model!=="default"&&!this.adapter.buildSpawnEnv){let o=this.adapter.buildEffortAction?.(r.effort??"",r.model);try{o?.type==="set_model"?await e.setModel(t,o.modelId):await e.setModel(t,r.model);}catch(s){console.warn(`[acp] setModel(${r.model}) failed: ${s instanceof Error?s.message:String(s)}`);}}if(r?.mode){let o=this.adapter.resolveMode?.(r.mode)??r.mode;if(o)try{await e.setMode(t,o);}catch(s){console.warn(`[acp] setMode(${o}) failed: ${s instanceof Error?s.message:String(s)}`);}}if(r?.effort){let o=this.adapter.buildEffortAction?.(r.effort,r.model);if(o&&o.type==="set_config_option")try{await e.setConfigOption(t,o.configId,o.value);}catch(s){console.warn(`[acp] setConfigOption(${o.configId}) effort failed: ${s instanceof Error?s.message:String(s)}`);}}if(r?.configOptions)for(let[o,s]of Object.entries(r.configOptions))try{await e.setConfigOption(t,o,s);}catch(i){console.warn(`[acp] setConfigOption(${o}) failed, retrying: ${i instanceof Error?i.message:String(i)}`);try{await new Promise(a=>setTimeout(a,500)),await e.setConfigOption(t,o,s);}catch(a){console.warn(`[acp] setConfigOption(${o}) retry failed: ${a instanceof Error?a.message:String(a)}`);}}}composePrompt(e,t){let r=[];return t?.systemPrompt?.trim()&&(r.push(t.systemPrompt),r.push("---")),t?.context&&(r.push(t.context),r.push("---")),r.push(e),[{type:"text",text:r.join(`
|
|
31
31
|
|
|
32
32
|
`)}]}handleUpdate(e,t,r){let o=e.update;if(o.sessionUpdate==="agent_message_chunk"){let s=null;this.adapter.extractTextFromUpdate?s=this.adapter.extractTextFromUpdate(e):s=Or(e),s!==null&&(r.push(s),t?.onOutput?.(s,"stdout"));}else if(o.sessionUpdate==="tool_call"){this.pushBlockBoundary(r);let s=new Date().toISOString(),i=o,a={title:i.title??"",kind:i.kind,rawInput:i.rawInput,rawOutput:i.rawOutput,locations:i.locations,_meta:i._meta},d=this.resolveToolCall(a),l={timestamp:s,type:"tool_use",toolUseId:i.toolCallId,toolName:d.toolName,toolInput:d.toolInput};t?.onTaskLog?.([l]);}else if(o.sessionUpdate==="tool_call_update"){let s=new Date().toISOString(),i=o;if(i.status==="completed"||i.status==="failed"){let d=this.extractResultPreview(i.rawOutput),l={timestamp:s,type:"tool_result",toolUseId:i.toolCallId,resultPreview:d,isError:i.status==="failed"};t?.onTaskLog?.([l]);}else if(i.rawInput!=null&&typeof i.rawInput=="object"&&Object.keys(i.rawInput).length>0){this.pushBlockBoundary(r);let d={title:i.title??"",kind:i.kind,rawInput:i.rawInput,rawOutput:i.rawOutput,locations:i.locations,_meta:i._meta},l=this.resolveToolCall(d),u={timestamp:s,type:"tool_use",toolUseId:i.toolCallId,toolName:l.toolName,toolInput:l.toolInput};t?.onTaskLog?.([u]);}}else o.sessionUpdate;}pushBlockBoundary(e){e.length===0||e[e.length-1].endsWith(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type TaskLogEntryType = 'text' | 'thinking' | 'tool_use' | 'tool_result' | 'error' | 'info' | 'agent_call';
|
|
1
|
+
export type TaskLogEntryType = 'text' | 'thinking' | 'tool_use' | 'tool_result' | 'error' | 'info' | 'running_instruction' | 'agent_call';
|
|
2
2
|
export interface TaskLogEntry {
|
|
3
3
|
timestamp: string;
|
|
4
4
|
type: TaskLogEntryType;
|