@fifthrevision/axle 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -185,23 +185,21 @@ const agent = new Agent({
185
185
  Axle includes several built-in tools: `braveSearchTool`, `calculatorTool`,
186
186
  `execTool`, `readFileTool`, `writeFileTool`, and `patchFileTool`.
187
187
 
188
- ### Server Tools
188
+ ### Provider Tools
189
189
 
190
- Server tools are provider-managed tools that execute on the provider's side
191
- (e.g. web search, code interpreter). Pass them alongside regular tools using
192
- `{ type: "server", name: "..." }`.
190
+ Provider tools are tools that execute on the LLM provider's side (e.g. web
191
+ search, code interpreter). Pass them via the `providerTools` option using
192
+ `{ type: "provider", name: "..." }`.
193
193
 
194
194
  ```typescript
195
- import { Agent } from "@fifthrevision/axle";
196
- import type { ServerTool } from "@fifthrevision/axle";
195
+ import { Agent, calculatorTool } from "@fifthrevision/axle";
196
+ import type { ProviderTool } from "@fifthrevision/axle";
197
197
 
198
198
  const agent = new Agent({
199
199
  provider,
200
200
  model,
201
- tools: [
202
- { type: "server", name: "web_search" },
203
- calculatorTool, // regular tools work alongside server tools
204
- ],
201
+ tools: [calculatorTool],
202
+ providerTools: [{ type: "provider", name: "web_search" }],
205
203
  });
206
204
  ```
207
205
 
@@ -216,10 +214,10 @@ You can also pass provider-specific names directly. Use the optional `config`
216
214
  field for provider-specific options:
217
215
 
218
216
  ```typescript
219
- { type: "server", name: "web_search", config: { max_results: 5 } }
217
+ { type: "provider", name: "web_search", config: { max_results: 5 } }
220
218
  ```
221
219
 
222
- Server tool events stream as `internal-tool:start` and `internal-tool:complete`.
220
+ Provider tool events stream as `provider-tool:start` and `provider-tool:complete`.
223
221
 
224
222
  ### MCP (Model Context Protocol)
225
223
 
@@ -288,8 +286,8 @@ const result = await handle.final;
288
286
  Event types include `turn:start`, `turn:complete`, `tool-results:start`,
289
287
  `tool-results:complete`, `text:start`, `text:delta`, `text:end`,
290
288
  `thinking:start`, `thinking:delta`, `thinking:end`, `tool:request`,
291
- `tool:exec-start`, `tool:exec-complete`, `internal-tool:start`,
292
- `internal-tool:complete`, and `error`. The `turn:*` and `tool-results:*`
289
+ `tool:exec-start`, `tool:exec-complete`, `provider-tool:start`,
290
+ `provider-tool:complete`, and `error`. The `turn:*` and `tool-results:*`
293
291
  events carry complete `AxleAssistantMessage` and `AxleToolCallMessage` objects
294
292
  for client-server architectures that need authoritative message boundaries.
295
293
 
@@ -343,7 +341,7 @@ task: |
343
341
  tools:
344
342
  - calculator
345
343
 
346
- server_tools:
344
+ provider_tools:
347
345
  - web_search
348
346
 
349
347
  files:
@@ -0,0 +1,45 @@
1
+ import{c as e}from"./models-DlE4tfcj.js";import t,{access as n,mkdir as r,readFile as i,stat as a,writeFile as o}from"node:fs/promises";import s,{dirname as c,extname as l,resolve as u}from"node:path";import*as d from"zod";import f,{z as p}from"zod";import m from"@anthropic-ai/sdk";import"glob";import h from"mime";import{FinishReason as g,GoogleGenAI as _}from"@google/genai";import v from"openai";import{spawn as y}from"node:child_process";import{Client as b}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as x}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as S}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import C from"chalk";import{marked as w}from"marked";import ee from"node:crypto";var T=class e extends Error{code;id;details;constructor(t,n){super(t,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||`AXLE_ERROR`,this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id?{id:this.id}:{},...this.details?{details:this.details}:{},...this.cause?{cause:E(this.cause)}:{}}}};function E(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:E(e.cause)}:{}}:e}function D(e){let{text:t,files:n}=e,r=[];if(t&&r.push({type:`text`,text:t}),n)for(let e of n)r.push({type:`file`,file:e});return r}function O(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
+
3
+ `)}function k(e){return e.filter(e=>e.type===`tool-call`)}var A=class{executableTools=new Map;providerTools=new Map;constructor(e){e?.tools&&this.add(e.tools),e?.providerTools&&this.addProvider(e.providerTools)}add(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new T(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.executableTools.set(e.name,e)}}addProvider(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new T(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.providerTools.set(e.name,e)}}remove(e){return this.executableTools.delete(e)||this.providerTools.delete(e)}has(e){return this.executableTools.has(e)||this.providerTools.has(e)}get(e){return this.executableTools.get(e)}getProvider(e){return this.providerTools.get(e)}executable(){return[...this.executableTools.values()]}provider(){return[...this.providerTools.values()]}get size(){return this.executableTools.size+this.providerTools.size}};function j(e,t){let n=t.usage??{in:0,out:0};e.in+=n.in??0,e.out+=n.out??0}function M(e){return JSON.stringify({error:e})}function N(e){let t=e.tools!==void 0||e.providerTools!==void 0;if(e.registry&&t)throw new T("Cannot specify both `registry` and `tools` / `providerTools`. Use one or the other.",{code:`TOOL_OPTIONS_CONFLICT`});return e.registry?e.registry:new A({tools:e.tools,providerTools:e.providerTools})}async function te(e,t=async()=>null,n,r,i){let a=[];for(let o of e){let e=i?.startSpan(o.name,{type:`tool`}),s={signal:n,tracer:e,registry:r,emit:()=>{}},c;try{c=await t(o.name,o.parameters,s)}catch(e){c={type:`error`,error:{type:`exception`,message:e instanceof Error?e.message:String(e)}}}if(c==null){let t=`Tool not found: ${o.name}`;e?.setResult({kind:`tool`,name:o.name,input:o.parameters,output:{type:`not-found`,message:t}}),e?.end(`error`),a.push({id:o.id,name:o.name,content:M({type:`not-found`,message:t}),isError:!0});continue}c.type===`success`?(e?.setResult({kind:`tool`,name:o.name,input:o.parameters,output:c.content}),e?.end(`ok`),a.push({id:o.id,name:o.name,content:c.content})):(e?.setResult({kind:`tool`,name:o.name,input:o.parameters,output:c.error}),e?.end(`error`),a.push({id:o.id,name:o.name,content:M(c.error),isError:!0}))}return{results:a}}let P=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function F(e,t){for(let n of e)n(t)}function ne(e){return{type:`error`,error:{type:`not-found`,message:`Tool not found: ${e}`}}}function re(e){return{name:e.name,description:e.description,schema:e.schema}}function I(e){let t=[],n=new AbortController,r=e.signal?AbortSignal.any([n.signal,e.signal]):n.signal,{promise:i,resolve:a,reject:o}=Promise.withResolvers();return Promise.resolve().then(()=>L(e,r,t).then(a,o)),{on(e){t.push(e)},cancel(){n.abort()},get final(){return i}}}async function L(e,t,n){let{provider:r,model:i,messages:a,system:o,onToolCall:s,maxIterations:c,tracer:l,fileResolver:u,options:d,reasoning:f}=e,p=N(e),m=[...a],h=[],g={in:0,out:0},_=0,v=0,y=e=>{m.push(e),h.push(e)},b=e=>{e.result===`error`&&F(n,{type:`error`,error:e.error});let t=e.result===`success`?e.final?.content:e.result===`cancelled`?e.partial?.content:null,r=e.result===`success`?e.final?.finishReason:e.result===`cancelled`?`cancelled`:void 0;return l?.setResult({kind:`llm`,model:i,request:{messages:a},response:{content:t??null},usage:e.usage?{inputTokens:e.usage.in,outputTokens:e.usage.out}:void 0,finishReason:r}),l?.end(e.result===`error`?`error`:`ok`),e},x=(e,t,n,r)=>{r();let i=e.length>0?{role:`assistant`,id:t,model:n,content:e,finishReason:`cancelled`}:void 0;return i&&y(i),l?.end(`ok`),{result:`cancelled`,messages:h,partial:i,usage:g}};for(;;){if(t.aborted)return x([],``,``,()=>{});if(c!==void 0&&v>=c)return b({result:`error`,messages:h,error:{type:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${c})`}}},usage:g});v+=1;let e=l?.startSpan(`turn-${v}`,{type:`llm`}),a=p?.executable()??[],S=a.length>0?a.map(re):void 0,C=p?.provider()??[],w=C.length>0?{...d,providerTools:C}:d,ee=r.createStreamingRequest(i,{messages:m,system:o,tools:S,context:{tracer:e,fileResolver:u},signal:t,options:w,reasoning:f}),T=[],E=``,D=``,O=null,k={in:0,out:0},A=-1,j=null,M=``,N=new Map,P=-1,I=()=>{j!==null&&A>=0&&(F(n,{type:j===`text`?`text:end`:`thinking:end`,index:A,final:M}),j=null,M=``,A=-1)};for await(let r of ee){switch(r.type){case`start`:E=r.id,D=r.data.model,F(n,{type:`turn:start`,id:E,model:D});break;case`text-start`:I(),T.push({type:`text`,text:``}),P=T.length-1,A=_++,j=`text`,M=``,F(n,{type:`text:start`,index:A});break;case`text-delta`:{let e=T[P];e.text+=r.data.text,M=e.text,F(n,{type:`text:delta`,index:A,delta:r.data.text,accumulated:M});break}case`text-complete`:I();break;case`thinking-start`:I(),T.push({type:`thinking`,text:``}),P=T.length-1,A=_++,j=`thinking`,M=``,F(n,{type:`thinking:start`,index:A});break;case`thinking-delta`:{let e=T[P];e.text+=r.data.text,M=e.text,F(n,{type:`thinking:delta`,index:A,delta:r.data.text,accumulated:M});break}case`thinking-summary-delta`:{let e=T[P];e.text+=r.data.text,M=e.text,F(n,{type:`thinking:delta`,index:A,delta:r.data.text,accumulated:M});break}case`thinking-complete`:I();break;case`tool-call-start`:{I();let e=_++;T.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),P=T.length-1,N.set(r.data.id,e),F(n,{type:`tool:request`,index:e,id:r.data.id,name:r.data.name});break}case`tool-call-args-delta`:F(n,{type:`tool:args-delta`,index:N.get(r.data.id)??-1,id:r.data.id,name:r.data.name,delta:r.data.delta,accumulated:r.data.accumulated});break;case`tool-call-complete`:{let e=T[P];r.data.id&&(e.id=r.data.id),r.data.name&&(e.name=r.data.name),e.parameters=r.data.arguments,r.data.providerMetadata&&(e.providerMetadata=r.data.providerMetadata);break}case`provider-tool-start`:{I();let e=_++;T.push({type:`provider-tool`,id:r.data.id,name:r.data.name}),P=T.length-1,F(n,{type:`provider-tool:start`,index:e,id:r.data.id,name:r.data.name});break}case`provider-tool-complete`:{let e=T[P];r.data.output!=null&&(e.output=r.data.output),F(n,{type:`provider-tool:complete`,index:r.data.index,id:r.data.id,name:r.data.name,output:r.data.output});break}case`complete`:I(),O=r.data.finishReason,k=r.data.usage;break;case`error`:{I();let t=r.data.usage??{in:0,out:0};return g.in+=t.in??0,g.out+=t.out??0,e?.end(`error`),b({result:`error`,messages:h,error:{type:`model`,error:{type:`error`,error:{type:r.data.type,message:r.data.message}}},usage:g})}default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.aborted)break}if(t.aborted)return e?.end(`ok`),x(T,E,D,I);if(O===null)return I(),e?.end(`error`),b({result:`error`,messages:h,error:{type:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:g});g.in+=k.in??0,g.out+=k.out??0;let L={kind:`llm`,model:D,request:{messages:m},response:{content:T},usage:{inputTokens:k.in,outputTokens:k.out},finishReason:O};e?.setResult(L),e?.end();let R={role:`assistant`,id:E,model:D,content:T,finishReason:O};if(y(R),F(n,{type:`turn:complete`,message:R,usage:k}),O!==`function_call`)return b({result:`success`,messages:h,final:R,usage:g});let z=T.filter(e=>e.type===`tool-call`);if(z.length===0)return b({result:`success`,messages:h,final:R,usage:g});if(t.aborted)return l?.end(`ok`),{result:`cancelled`,messages:h,usage:g};let B=crypto.randomUUID();F(n,{type:`tool-results:start`,id:B});let V=0,{results:H}=await te(z,async(e,t,r)=>{let i=z[V++],a=N.get(i.id)??-1;F(n,{type:`tool:exec-start`,index:a,id:i.id,name:e,parameters:t});let o={...r,emit:t=>{F(n,{type:`tool:exec-delta`,index:a,id:i.id,name:e,chunk:t})}},c=(s?await s(e,t,o):null)??ne(e);return F(n,{type:`tool:exec-complete`,index:a,id:i.id,name:e,result:c}),c},t,p,l);if(H.length>0){let e={role:`tool`,id:B,content:H};y(e),F(n,{type:`tool-results:complete`,message:e})}}}var R=class{rootPath;constructor(e){this.rootPath=e}async read(e){let n=s.join(this.rootPath,e);try{return await t.readFile(n,`utf-8`)}catch{return null}}async write(e,n){let r=s.join(this.rootPath,e);await t.mkdir(s.dirname(r),{recursive:!0}),await t.writeFile(r,n,`utf-8`)}};function z(e=new Date){return{start:e.toISOString()}}function B(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var V=class{currentTurn=null;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage={in:0,out:0};createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=B(z(r),r),a=()=>({...i});if(typeof e.content==`string`)n.push({id:crypto.randomUUID(),type:`text`,text:e.content,timing:a()});else for(let t of e.content)t.type===`text`?n.push({id:crypto.randomUUID(),type:`text`,text:t.text,timing:a()}):t.type===`file`&&n.push({id:crypto.randomUUID(),type:`file`,file:t.file,timing:a()});let o={id:t,owner:`user`,parts:n,status:`complete`,timing:i};return{turn:o,events:[{type:`turn:user`,turn:o}]}}startAgentTurn(){let e=crypto.randomUUID(),t={id:e,owner:`agent`,parts:[],status:`streaming`,timing:z()};return this.currentTurn=t,this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage={in:0,out:0},{turn:t,events:[{type:`turn:start`,turnId:e}]}}handleStreamEvent(e){let t=this.currentTurn;if(!t)return[];let n=[];switch(e.type){case`turn:start`:break;case`text:start`:{this.closeOpenParts(t,n);let e={id:crypto.randomUUID(),type:`text`,text:``,timing:z()};t.parts.push(e),this.currentTextPart=e,n.push({type:`part:start`,turnId:t.id,part:{...e}});break}case`text:delta`:this.currentTextPart&&(this.currentTextPart.text=e.accumulated,n.push({type:`text:delta`,turnId:t.id,partId:this.currentTextPart.id,delta:e.delta}));break;case`text:end`:this.currentTextPart&&=(this.currentTextPart.text=e.final,this.currentTextPart.timing=B(this.currentTextPart.timing),n.push({type:`part:end`,turnId:t.id,partId:this.currentTextPart.id,timing:this.currentTextPart.timing}),null);break;case`thinking:start`:{this.closeOpenParts(t,n);let e={id:crypto.randomUUID(),type:`thinking`,text:``,timing:z()};t.parts.push(e),this.currentThinkingPart=e,n.push({type:`part:start`,turnId:t.id,part:{...e}});break}case`thinking:delta`:this.currentThinkingPart&&(this.currentThinkingPart.text=e.accumulated,n.push({type:`thinking:delta`,turnId:t.id,partId:this.currentThinkingPart.id,delta:e.delta}));break;case`thinking:end`:this.currentThinkingPart&&=(this.currentThinkingPart.text=e.final,this.currentThinkingPart.timing=B(this.currentThinkingPart.timing),n.push({type:`part:end`,turnId:t.id,partId:this.currentThinkingPart.id,timing:this.currentThinkingPart.timing}),null);break;case`tool:request`:{this.closeOpenParts(t,n);let r=crypto.randomUUID(),i={id:r,type:`action`,kind:`tool`,status:`pending`,timing:z(),detail:{name:e.name,parameters:{}}};t.parts.push(i),this.toolIdMap.set(e.id,{partId:r,turnId:t.id}),n.push({type:`part:start`,turnId:t.id,part:{...i,detail:{...i.detail}}});break}case`tool:args-delta`:{let r=this.toolIdMap.get(e.id);if(r){let i=this.findActionPart(t,r.partId);i&&(i.detail.pendingArgs=e.accumulated),n.push({type:`action:args-delta`,turnId:t.id,partId:r.partId,delta:e.delta,accumulated:e.accumulated})}break}case`tool:exec-start`:{let r=this.toolIdMap.get(e.id);if(r){let i=this.findActionPart(t,r.partId);i&&(i.status=`running`,i.detail.parameters=e.parameters,delete i.detail.pendingArgs,n.push({type:`action:running`,turnId:t.id,partId:r.partId,parameters:e.parameters}))}break}case`tool:exec-delta`:{let r=this.toolIdMap.get(e.id);if(r){let i=this.findActionPart(t,r.partId);if(i){let t=i.detail.result?.type===`in-progress`?i.detail.result.content:``;i.detail.result={type:`in-progress`,content:t+e.chunk}}n.push({type:`action:progress`,turnId:t.id,partId:r.partId,chunk:e.chunk})}break}case`tool:exec-complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=this.findActionPart(t,r.partId);i&&(e.result.type===`success`?(i.status=`complete`,i.timing=B(i.timing),i.detail.result={type:`success`,content:e.result.content},n.push({type:`action:complete`,turnId:t.id,partId:r.partId,result:i.detail.result})):(i.status=`error`,i.timing=B(i.timing),i.detail.result={type:`error`,error:e.result.error},n.push({type:`action:error`,turnId:t.id,partId:r.partId,error:e.result.error})))}break}case`provider-tool:start`:{this.closeOpenParts(t,n);let r=crypto.randomUUID(),i={id:r,type:`action`,kind:`provider-tool`,status:`running`,timing:z(),detail:{name:e.name}};t.parts.push(i),this.toolIdMap.set(e.id,{partId:r,turnId:t.id}),n.push({type:`part:start`,turnId:t.id,part:{...i,detail:{...i.detail}}}),n.push({type:`action:running`,turnId:t.id,partId:r});break}case`provider-tool:complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=this.findActionPart(t,r.partId);i&&(i.status=`complete`,i.timing=B(i.timing),i.detail.result={type:`success`,content:e.output},n.push({type:`action:complete`,turnId:t.id,partId:r.partId,result:i.detail.result}))}break}case`turn:complete`:{this.closeOpenParts(t,n);let r=e.usage??{in:0,out:0};this.accumulatedUsage.in+=r.in,this.accumulatedUsage.out+=r.out;break}case`tool-results:start`:case`tool-results:complete`:break;case`error`:{let t=e.error,r=t.type===`model`?t.error.error.message:`Tool error (${t.error.name}): ${t.error.message}`;n.push({type:`error`,error:{type:t.type,message:r}});break}}return n}finalizeTurn(e=`complete`){let t=this.currentTurn;if(!t)return[];let n=[];return this.closeOpenParts(t,n),t.status=e,t.usage={...this.accumulatedUsage},t.timing=B(t.timing),n.push({type:`turn:end`,turnId:t.id,status:e,usage:t.usage,timing:t.timing}),this.currentTurn=null,n}closeOpenParts(e,t){this.currentTextPart&&=(this.currentTextPart.timing=B(this.currentTextPart.timing),t.push({type:`part:end`,turnId:e.id,partId:this.currentTextPart.id,timing:this.currentTextPart.timing}),null),this.currentThinkingPart&&=(this.currentThinkingPart.timing=B(this.currentThinkingPart.timing),t.push({type:`part:end`,turnId:e.id,partId:this.currentThinkingPart.id,timing:this.currentThinkingPart.timing}),null)}findActionPart(e,t){return e.parts.find(e=>e.id===t&&e.type===`action`)}};function H(e){return Array.isArray(e)?e:[e]}function ie(e){return new Promise(t=>setTimeout(t,e))}function ae(e){return e.then(()=>{},()=>{})}function oe(e,t,n){let r=new AbortController,i=n?AbortSignal.any([n,r.signal]):r.signal,a=e.then(()=>t(i));return{handle:{cancel:()=>r.abort(),get final(){return a}},settled:ae(a)}}function se(e,t,n={}){let{placeholderStyle:r=`{{}}`,strict:i=!1}=n,a=r===`{{}}`?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g,o=[];if(e=e.replace(a,(e,n)=>{if(n=n.trim(),Object.prototype.hasOwnProperty.call(t,n)){let e=t[n];return e==null?``:String(e)}return i&&o.push(n),e}),o.length>0){let e=[...new Set(o)];throw Error(`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}. Pass them as --args key=value or use --allow-missing-vars to suppress this error.`)}return e}function U(e){if(e instanceof d.ZodString)return[`string`,`Your answer`];if(e instanceof d.ZodNumber)return[`number`,42];if(e instanceof d.ZodBoolean)return[`boolean`,!0];if(e instanceof d.ZodArray){let t=e.element;if(t instanceof d.ZodString)return[`string array`,[`answer 1`,`answer 2`,`third answer`]];if(t instanceof d.ZodNumber)return[`number array`,[42,59,3.14]];if(t instanceof d.ZodBoolean)return[`boolean array`,[!0,!1,!1]];if(t instanceof d.ZodObject){let[,e]=U(t);return[`object array`,[e,e]]}return[`array`,[]]}if(e instanceof d.ZodObject){let t=e.shape,n={};for(let[e,r]of Object.entries(t)){let[,t]=U(r);n[e]=t}return[`JSON object`,n]}if(e instanceof d.ZodOptional){let[t,n]=U(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function ce(e,t){if(!t)return e;if(Object.keys(t).length===0){if(e.trim()===`{}`||e.trim()===``)return{};throw Error(`Schema is empty, but rawValue is not an empty object representation or empty string.`)}let n=ue(e),r={};for(let[e,i]of Object.entries(t)){let t=n.tags[e];if(t!==void 0)r[e]=le(i,t);else if(i.def.type!==`optional`)throw Error(`Expected results with tag ${e} but it does not exist`)}try{let e={};for(let[n,i]of Object.entries(t))n in r&&(e[n]=i.parse(r[n]));return e}catch(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Validation failed: ${t}`)}throw e}}function le(e,t){switch(t=t.trim(),e.def.type){case`string`:try{return JSON.parse(t)}catch{if(typeof t==`string`)return t;throw Error(`Cannot parse '${t}' as string. Ensure it is a valid JSON string or a plain string.`)}case`number`:{let e=parseFloat(t);if(isNaN(e))throw Error(`Cannot parse '${t}' as number`);return e}case`boolean`:{let e=t.toLowerCase();if(e===`true`)return!0;if(e===`false`)return!1;throw Error(`Cannot parse '${t}' as boolean. Expected 'true' or 'false'`)}case`array`:if(t===``)return[];try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}if(t.includes(`,`))return t.split(`,`).map(e=>{let t=e.trim();try{return JSON.parse(t)}catch{return t}}).filter(e=>e!==``);case`object`:t.includes("```json")&&(t=t.replace(/```json/g,``).replace(/```/g,``));try{return JSON.parse(t)}catch(e){throw Error(`Cannot parse object as JSON: ${e.message}`)}case`optional`:{let n=e.def.innerType;return le(n,t)}default:return t}}function ue(e){e.trim().startsWith("```json")&&e.trim().endsWith("```")&&(e=e.trim().slice(7,-3).trim());let t=/<(\w+)>(.*?)<\/\1>/gs,n={},r=e;return r=r.replace(t,(e,t,r)=>(n[t]=r,``)),r=r.replace(/<(\w+)>(.*?)(?:<\/?\w+>|$)/gs,(e,t,r)=>(n[t]=r,``)),{tags:n,remaining:r.trim()}}function de(e,t={},n={}){let r={...t,...e.inputs},i=se(e.prompt,r,{strict:n.strictVariables});if(e.textReferences.length>0)for(let[t,n]of e.textReferences.entries()){let e=n.name?`: ${n.name}`:``;i+=`\n\n## Reference ${t+1}${e}\n\n\`\`\`${n.content}'''`}if((e.schema?Object.keys(e.schema):[]).length===0)return i;let a=`# Output Format Instructions
4
+
5
+ Here is how you should format your output. Follow the instructions strictly.
6
+ `;for(let[t,n]of Object.entries(e.schema)){let[e,r]=U(n);a+=`\n- Use <${t}></${t}> tags to indicate the answer for ${t}. The answer must be a ${e}.\n Example: <${t}>${JSON.stringify(r)}</${t}>\n`}return a+i}var fe=class{_turns=[];_log=[];constructor(e){e?.turns&&(this._turns=e.turns),e?.log&&(this._log=e.log)}get turns(){return[...this._turns]}get log(){return[...this._log]}addTurn(e){this._turns.push(e)}appendToLog(e){Array.isArray(e)?this._log.push(...e):this._log.push(e)}latestTurn(){return this._turns[this._turns.length-1]}toString(){return JSON.stringify({turns:this._turns})}},pe=class{provider;model;history;tracer;name;scope;store;fileResolver;reasoning;registry;system;mcps=[];resolvedMcps=new WeakSet;memory;options;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e){if(this.provider=e.provider,this.model=e.model,this.history=new fe,this.tracer=e.tracer,this.system=e.system,this.name=e.name,this.scope=e.scope,this.store=new R(`.axle`),this.fileResolver=e.fileResolver,this.reasoning=e.reasoning,this.options=e.options??{},this.registry=new A({tools:e.tools,providerTools:e.providerTools}),e.mcps&&(this.mcps=[...e.mcps]),e.memory){if(!e.name)throw new T(`Agent requires a 'name' when memory is provided. The name is used to partition memory storage.`);this.memory=e.memory;let t=e.memory.tools?.();t&&this.registry.add(t)}}addMcp(e){this.mcps.push(e)}addMcps(e){this.mcps.push(...e)}hasTools(){return this.registry.size>0||this.mcps.length>0}on(e){this.eventCallbacks.push(e)}send(e,t){let n,r;if(typeof e==`string`)r={role:`user`,id:crypto.randomUUID(),content:[{type:`text`,text:e}]};else{let i=de(e,t?.variables,{strictVariables:this.options.strictVariables}),a=e.files;r={role:`user`,id:crypto.randomUUID(),content:D({text:i,files:a})},n=e.schema}let i=t?.reasoning??this.reasoning,{handle:a,settled:o}=oe(this.sendQueue,e=>this.run(r,n,e,t?.fileResolver,i),t?.signal);return this.sendQueue=o,a}async resolveMcpTools(){for(let e of this.mcps){if(this.resolvedMcps.has(e))continue;let t=await e.listTools({prefix:e.name,tracer:this.tracer});this.registry.add(t),this.resolvedMcps.add(e)}}emitEvent(e){for(let t of this.eventCallbacks)t(e)}async run(e,t,n,r,i){let a=new V;await this.resolveMcpTools();let o=this.system,s=[...this.history.log,e];if(this.memory){let e=await this.memory.recall({name:this.name,scope:this.scope,system:this.system,messages:s,store:this.store,tracer:this.tracer});e.systemSuffix&&(o=(o??``)+`
7
+
8
+ `+e.systemSuffix)}if(n.aborted)return{response:null,turn:void 0,usage:{in:0,out:0}};let{turn:c,events:l}=a.createUserTurn(e);this.history.addTurn(c),this.history.appendToLog(e);for(let e of l)this.emitEvent(e);let{turn:u,events:d}=a.startAgentTurn();this.history.addTurn(u);for(let e of d)this.emitEvent(e);let f=I({provider:this.provider,model:this.model,messages:s,system:o,registry:this.registry,tracer:this.tracer,fileResolver:r??this.fileResolver,reasoning:i,onToolCall:async(e,t,n)=>{let r=this.registry.get(e);if(!r)return null;try{return{type:`success`,content:await r.execute(t,n)}}catch(e){return{type:`error`,error:{type:`execution`,message:e instanceof Error?e.message:String(e)}}}},signal:n});f.on(e=>{let t=a.handleStreamEvent(e);for(let e of t)this.emitEvent(e)});let p=await f.final,m=p.result===`cancelled`?`cancelled`:p.result===`error`?`error`:`complete`;p.messages.length>0&&this.history.appendToLog(p.messages);let h=a.finalizeTurn(m);for(let e of h)this.emitEvent(e);if(p.result===`error`)throw new T(me(p.error),{code:p.error.type===`model`?`MODEL_ERROR`:`TOOL_ERROR`,details:{error:p.error}});let g=null;if(p.result===`success`&&(p.final&&(g=ce(O(p.final.content),t)),this.memory))try{await this.memory.record({name:this.name,scope:this.scope,system:this.system,messages:this.history.log,newMessages:p.messages,store:this.store,tracer:this.tracer})}catch(e){this.tracer?.warn(`memory record failed`,{error:e instanceof Error?e.message:String(e)})}let _=p.usage??{in:0,out:0};return{response:g,turn:u,usage:_}}};function me(e){return e.type===`model`?`Model error: ${e.error.error.message}`:`Tool error (${e.error.name}): ${e.error.message}`}var he=class{prompt;inputs={};files=[];textReferences=[];schema;constructor(e,t){this.prompt=e,this.schema=t}setInputs(e){this.inputs=e}addInput(e,t){this.inputs[e]=t}addFile(e,t){if(typeof e==`string`){this.textReferences.push({content:e,name:t?.name});return}if(e.kind===`text`&&e.source.type===`text`){this.textReferences.push({content:e.source.content,name:t?.name??e.name});return}this.files.push(t?.name?{...e,name:t.name}:e)}hasFiles(){return this.files.length>0}};function ge(e,t,n=`[redacted]`){return W(e,null,t,n)}function W(e,t,n,r){if(typeof e!=`object`||!e)return typeof e==`string`&&t&&n.has(t)?r:e;if(Array.isArray(e))return e.map(e=>W(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=W(a,t,n,r);return i}const _e=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function G(e){return ge(e,_e,`[redacted-file-value]`)}function K(e){if(e==null)return{type:`error`,error:{type:`Undetermined`,message:`Unknown error occurred`},usage:{in:0,out:0},raw:e};if(e instanceof Error)return{type:`error`,error:{type:e.name||`Error`,message:e.message||`Unexpected error`},usage:{in:0,out:0},raw:e};if(typeof e==`object`){let t=e,n=t?.error?.error?.type||t?.error?.type||t?.type||t?.code||t?.status||`Undetermined`,r=t?.error?.error?.message||t?.error?.message||t?.message||t?.error||`Unexpected error`;return{type:`error`,error:{type:String(n),message:String(r)},usage:{in:0,out:0},raw:e}}return{type:`error`,error:{type:`Undetermined`,message:String(e)},usage:{in:0,out:0},raw:e}}async function ve(e,t){let{defaults:n,tag:r}=t,a=null,o=``;if(e)try{o=u(e),a=await i(o,{encoding:`utf-8`})}catch{throw Error(`${r} not found, see --help for details`)}else{for(let e of n.formats)try{o=u(n.name+`.`+e),a=await i(o,{encoding:`utf-8`});break}catch{continue}if(a===null)throw Error(`${r} not found, see --help for details`)}return{content:a,format:o.split(`.`).pop()??``,path:o}}const q=20*1024*1024;async function J(e,t){if(t.signal?.aborted)throw new DOMException(`File resolution aborted`,`AbortError`);let{source:n}=e;if(n.type===`base64`)return Y({type:`base64`,data:n.data},e,t);if(n.type===`text`)return Y({type:`text`,content:n.content},e,t);if(n.type===`url`)return Y({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return Y(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function Y(e,t,n){if(n.accepted.includes(e.type))return{...e,mimeType:e.mimeType??t.mimeType,name:e.name??t.name};throw Error(`File source '${e.type}' is not supported for ${n.provider} ${t.kind} file '${t.name}'. Accepted: ${n.accepted.join(`, `)}`)}const ye=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function be(e){return e.startsWith(`text/`)||ye.has(e)}function xe(e){let t=h.getType(e);if(!t){let t=l(e).toLowerCase();throw Error(`Unsupported file type: ${t||`(no extension)`}`)}if(t.startsWith(`image/`))return{kind:`image`,mimeType:t};if(t===`application/pdf`)return{kind:`document`,mimeType:t};if(be(t))return{kind:`text`,mimeType:t};{let n=l(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function Se(e,t){let r=u(e);try{await n(r)}catch{throw Error(`File not found: ${e}`)}let o=await a(r);if(o.size>q)throw Error(`File too large: ${o.size} bytes. Maximum allowed: ${q} bytes`);let s=r.split(`/`).pop()||``,c=xe(r);if((t||(c.kind===`text`?`utf-8`:`base64`))===`utf-8`){if(c.kind!==`text`)throw Error(`Cannot read ${c.kind} file as text: ${e}`);let t=await i(r,`utf-8`);return{kind:`text`,mimeType:c.mimeType,size:o.size,name:s,source:{type:`text`,content:t}}}else{if(c.kind===`text`)throw Error(`Cannot read text file as binary: ${e}`);let t=(await i(r)).toString(`base64`);return{kind:c.kind,mimeType:c.mimeType,size:o.size,name:s,source:{type:`base64`,data:t}}}}async function Ce(e,t={model:``}){return Promise.all(e.map(e=>we(e,t)))}async function we(e,t){if(e.role===`assistant`){let t=[];for(let n of e.content)n.type===`text`?t.push({type:`text`,text:n.text}):n.type===`thinking`?n.redacted?t.push({type:`redacted_thinking`,data:n.text}):n.signature&&t.push({type:`thinking`,thinking:n.text,signature:n.signature}):n.type===`tool-call`?t.push({type:`tool_use`,id:n.id,name:n.name,input:n.parameters}):n.type===`provider-tool`&&(t.push({type:`server_tool_use`,id:n.id,name:n.name,input:n.input??{}}),n.output!=null&&t.push({type:`web_search_tool_result`,tool_use_id:n.id,content:n.output}));return{role:`assistant`,content:t}}if(e.role===`tool`)return{role:`user`,content:await Promise.all(e.content.map(async e=>({type:`tool_result`,tool_use_id:e.id,content:typeof e.content==`string`?e.content:await Pe(e.content,t),...e.isError?{is_error:!0}:{}})))};if(typeof e.content==`string`)return{role:`user`,content:e.content};{let n=[];for(let r of e.content)r.type===`text`?n.push({type:`text`,text:r.text}):r.type===`file`&&n.push(await Te(r.file,t,`user-message`));return{role:`user`,content:n}}}async function Te(e,t,n){if(e.kind===`image`)return{type:`image`,source:De(await J(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`Anthropic only supports PDF document files. Received ${e.mimeType}`);let r=await J(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`document`,source:Oe(r),title:r.name??e.name}}let r=await J(e,{provider:`anthropic`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Anthropic text source: ${r.type}`);return n===`tool-result`?{type:`text`,text:r.content}:{type:`document`,source:{type:`text`,media_type:`text/plain`,data:r.content},title:r.name??e.name}}function Ee(e){if(e===`image/jpeg`||e===`image/png`||e===`image/gif`||e===`image/webp`)return e;throw Error(`Anthropic does not support image MIME type: ${e}. Supported types: image/jpeg, image/png, image/gif, image/webp.`)}function De(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:Ee(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function Oe(e){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:`application/pdf`,data:e.data};throw Error(`Unsupported Anthropic PDF source: ${e.type}`)}function ke(e){return e===!0?{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function Ae(e){return e.map(e=>{let t=f.toJSONSchema(e.schema);if(!Ne(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}function je(e){let t=[];for(let n of e)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`thinking`)t.push({type:`thinking`,text:n.text||``,redacted:!1});else if(n.type===`redacted_thinking`)t.push({type:`thinking`,text:n.text||``,redacted:!0});else if(n.type===`tool_use`){if(typeof n.input!=`object`||n.input===null||Array.isArray(n.input))throw Error(`Invalid tool call input for ${n.name}: expected object, got ${typeof n.input}`);t.push({type:`tool-call`,id:n.id,name:n.name,parameters:n.input})}return t}function Me(e){switch(e){case`max_tokens`:return`length`;case`end_turn`:return`stop`;case`stop_sequence`:return`stop`;case`tool_use`:return`function_call`;default:return`error`}}function Ne(e){return e&&typeof e==`object`&&e.type===`object`}async function Pe(e,t){return Promise.all(e.map(async e=>e.type===`text`?{type:`text`,text:e.text}:Te(e.file,t,`tool-result`)))}async function Fe(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,options:s,reasoning:c}=e,l=o?.tracer,{stop:u,max_tokens:d,...f}=s??{},p;try{let e=await Ce(r,{model:n,fileResolver:o?.fileResolver}),s={model:n,max_tokens:d??16e3,messages:e,...i&&{system:i},...u&&{stop_sequences:H(u)},...a&&{tools:Ae(a)},...ke(c),...f};l?.debug(`Anthropic request`,{request:G(s)}),p=Ie(await t.messages.create(s))}catch(e){p=K(e)}return l?.debug(`Anthropic response`,{result:p}),p}function Ie(e){let t=Me(e.stop_reason);if(t===`error`)return{type:`error`,error:{type:`Uncaught error`,message:`Stop reason is not recognized or unhandled: ${e.stop_reason}`},usage:{in:e.usage.input_tokens,out:e.usage.output_tokens},raw:e};if(t===`function_call`){let t=je(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:O(t),usage:{in:e.usage.input_tokens,out:e.usage.output_tokens},raw:e}}if(e.type==`message`){let n=je(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:O(n),usage:{in:e.usage.input_tokens,out:e.usage.output_tokens},raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:{in:e.usage.input_tokens,out:e.usage.output_tokens},raw:e}}function Le(){let e=new Map,t=new Map,n=new Map;function r(r){let i=[];switch(r.type){case`message_start`:i.push({type:`start`,id:r.message.id,data:{model:r.message.model,timestamp:Date.now()}});break;case`message_delta`:r.delta.stop_reason&&i.push({type:`complete`,data:{finishReason:Me(r.delta.stop_reason),usage:{in:r.usage?.input_tokens||0,out:r.usage?.output_tokens||0}}});case`message_stop`:break;case`content_block_start`:if(r.content_block.type===`text`)e.set(r.index,`text`),i.push({type:`text-start`,data:{index:r.index}});else if(r.content_block.type===`tool_use`){e.set(r.index,`tool`);let t=r.content_block;n.set(r.index,{id:t.id,name:t.name,argumentsBuffer:``}),i.push({type:`tool-call-start`,data:{index:r.index,id:t.id,name:t.name}})}else if(r.content_block.type===`thinking`)e.set(r.index,`thinking`),i.push({type:`thinking-start`,data:{index:r.index,redacted:!1}});else if(r.content_block.type===`redacted_thinking`)e.set(r.index,`thinking`),i.push({type:`thinking-start`,data:{index:r.index,redacted:!0}});else if(r.content_block.type===`server_tool_use`){e.set(r.index,`provider-tool`);let n=r.content_block;t.set(n.id,{index:r.index,name:n.name}),i.push({type:`provider-tool-start`,data:{index:r.index,id:n.id,name:n.name}})}else if(r.content_block.type===`web_search_tool_result`){let e=r.content_block,n=t.get(e.tool_use_id);n&&(i.push({type:`provider-tool-complete`,data:{index:n.index,id:e.tool_use_id,name:n.name,output:e.content}}),t.delete(e.tool_use_id))}break;case`content_block_delta`:if(r.delta.type===`text_delta`)i.push({type:`text-delta`,data:{text:r.delta.text,index:r.index}});else if(r.delta.type===`input_json_delta`){let e=n.get(r.index);e&&(e.argumentsBuffer+=r.delta.partial_json,i.push({type:`tool-call-args-delta`,data:{index:r.index,id:e.id,name:e.name,delta:r.delta.partial_json,accumulated:e.argumentsBuffer}}))}else r.delta.type===`thinking_delta`?i.push({type:`thinking-delta`,data:{text:r.delta.thinking,index:r.index}}):r.delta.type===`signature_delta`||r.delta.type;break;case`content_block_stop`:{let t=e.get(r.index);if(t===`text`)i.push({type:`text-complete`,data:{index:r.index}});else if(t===`thinking`)i.push({type:`thinking-complete`,data:{index:r.index}});else if(t!==`provider-tool`&&t===`tool`){let e=n.get(r.index);if(e){try{let t=e.argumentsBuffer?JSON.parse(e.argumentsBuffer):{};i.push({type:`tool-call-complete`,data:{index:r.index,id:e.id,name:e.name,arguments:t}})}catch(t){throw Error(`Failed to parse tool call arguments for ${e.name}: ${t instanceof Error?t.message:String(t)}\nRaw buffer: ${e.argumentsBuffer}`)}n.delete(r.index)}}e.delete(r.index);break}}return i}return{handleEvent:r}}async function*Re(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,signal:s,options:c,reasoning:l}=e,u=o?.tracer,{stop:d,max_tokens:f,providerTools:p,...m}=c??{},h=a?Ae(a):[];if(p){let e={web_search:`web_search_20250305`};for(let t of p){let n=e[t.name]??t.name;h.push({type:n,name:t.name,...t.config})}}let g=Le();try{let e=await Ce(r,{model:n,fileResolver:o?.fileResolver,signal:s}),a={model:n,max_tokens:f??ze(n),messages:e,...i&&{system:i},...d&&{stop_sequences:H(d)},...h.length>0&&{tools:h},...ke(l),...m};u?.debug(`Anthropic streaming request`,{request:G(a)});let c=await t.messages.create({...a,stream:!0},{signal:s});for await(let e of c){let t=g.handleEvent(e);for(let e of t)yield e}}catch(e){if(s?.aborted)return;yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function ze(t){return t in e?e[t]:t.includes(`opus`)?t.match(/opus-4-[6-9]|opus-[5-9]/)?128e3:64e3:t.includes(`sonnet`)||t.includes(`haiku`)?t.match(/claude-3-[0-5]-/)?8192:64e3:16384}function Be(e){let t=new m({apiKey:e});return{name:`anthropic`,async createGenerationRequest(e,n){return await Fe({client:t,model:e,...n})},createStreamingRequest(e,n){return Re({client:t,model:e,...n})}}}async function Ve(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>We(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function He(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`minimal`}:{}}function Ue(e){if(e&&e.length>0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:f.toJSONSchema(e.schema)}}))}function X(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`function_call`;case`content_filter`:return`error`;default:return`stop`}}async function We(e,t){switch(e.role){case`tool`:return Ge(e,t);case`assistant`:return Ke(e);default:return qe(e,t)}}async function Ge(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await Ye(e.content,t),tool_call_id:e.id})))}function Ke(e){let t=e.content.filter(e=>e.type===`tool-call`),n=e.content.filter(e=>e.type===`text`),r=t.length>0?t.map(e=>({type:`function`,id:e.id,function:{name:e.name,arguments:JSON.stringify(e.parameters)}})):void 0;return{role:`assistant`,content:n.map(e=>e.text).join(``),...r&&{tool_calls:r}}}async function qe(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>Je(e,t)))).filter(e=>e!==null);return n.every(e=>e.type===`text`)?{role:`user`,content:n.map(e=>e.text).join(``)}:{role:`user`,content:n}}async function Je(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?Xe(e.file,t,`user-message`):null}async function Ye(e,t){let n=[];for(let r of e){if(r.type===`text`){n.push(r.text);continue}if(r.file.kind===`text`){let e=await J(r.file,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:`tool-result`,resolver:t.fileResolver,signal:t.signal});if(e.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${e.type}`);n.push($e(r.file,e.content,e.name,e.mimeType));continue}throw Error(`ChatCompletions tool results do not support file parts other than text`)}return n.join(`
9
+ `)}async function Xe(e,t,n){if(e.kind===`text`){let r=await J(e,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${r.type}`);return{type:`text`,text:$e(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`ChatCompletions document file inputs currently support PDF only. Received ${e.mimeType}`);let r=await J(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`file`,file:{filename:r.name??e.name,file_data:Qe(r,e)}}}return{type:`image_url`,image_url:{url:Ze(await J(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}}}function Ze(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions image source: ${e.type}`)}function Qe(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions file source: ${e.type}`)}function $e(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}async function et(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,context:o,apiKey:s,options:c,reasoning:l}=e,u=o?.tracer,d;try{let e=await Ve(r,i,{model:n,fileResolver:o?.fileResolver}),f=Ue(a),p={model:n,messages:e,...f&&{tools:f},...He(l)};c&&(c.temperature!==void 0&&(p.temperature=c.temperature),c.top_p!==void 0&&(p.top_p=c.top_p),c.max_tokens!==void 0&&(p.max_tokens=c.max_tokens),c.frequency_penalty!==void 0&&(p.frequency_penalty=c.frequency_penalty),c.presence_penalty!==void 0&&(p.presence_penalty=c.presence_penalty),c.stop!==void 0&&(p.stop=c.stop),c.reasoning_effort!==void 0&&(p.reasoning_effort=c.reasoning_effort)),u?.debug(`ChatCompletions request`,{request:G(p)});let m={"Content-Type":`application/json`};s&&(m.Authorization=`Bearer ${s}`);let h=await fetch(`${t}/chat/completions`,{method:`POST`,headers:m,body:JSON.stringify(p)});if(!h.ok){let e=await h.text().catch(()=>``);throw Error(`HTTP error! status: ${h.status}${e?` - ${e}`:``}`)}d=tt(await h.json())}catch(e){u?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),d=K(e)}return u?.debug(`ChatCompletions response`,{result:d}),d}function tt(e){let t=e.choices?.[0];if(!t)return{type:`error`,error:{type:`ChatCompletionsError`,message:`No choices in response`},usage:{in:0,out:0},raw:e};let n=[];if(t.message.reasoning_content&&n.push({type:`thinking`,text:t.message.reasoning_content}),t.message.content&&n.push({type:`text`,text:t.message.content}),t.message.tool_calls)for(let e of t.message.tool_calls){let t;try{t=JSON.parse(e.function.arguments)}catch(t){throw Error(`Invalid tool call arguments for ${e.function.name}: ${t instanceof Error?t.message:String(t)}`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Invalid tool call arguments for ${e.function.name}: expected object, got ${typeof t}`);n.push({type:`tool-call`,id:e.id,name:e.function.name,parameters:t})}let r=n.some(e=>e.type===`tool-call`)?X(`tool_calls`):X(t.finish_reason);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:r,content:n,text:O(n),usage:{in:e.usage?.prompt_tokens||0,out:e.usage?.completion_tokens||0},raw:e}}function nt(){let e=new Map,t=0,n=-1,r=``,i=``,a=null,o,s;function c(e){n<0||(a===`text`?e.push({type:`text-complete`,data:{index:n}}):a===`thinking`&&e.push({type:`thinking-complete`,data:{index:n}}),a=null,n=-1)}function l(l){let u=[];l.usage&&(s={in:l.usage.prompt_tokens,out:l.usage.completion_tokens});let d=l.choices?.[0];if(!d)return u;r||(r=l.id,i=l.model,u.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}}));let f=d.delta;if(f.reasoning_content&&(a!==`thinking`&&(c(u),n=t++,a=`thinking`,u.push({type:`thinking-start`,data:{index:n}})),u.push({type:`thinking-delta`,data:{index:n,text:f.reasoning_content}})),f.content&&(a!==`text`&&(c(u),n=t++,a=`text`,u.push({type:`text-start`,data:{index:n}})),u.push({type:`text-delta`,data:{text:f.content,index:n}})),f.tool_calls){c(u);for(let n of f.tool_calls){let r=n.index;if(!e.has(r)){let i=t++,a=n.id||`tool-${i}`;e.set(r,{id:a,name:n.function?.name||``,argumentsBuffer:``,partIdx:i}),u.push({type:`tool-call-start`,data:{index:i,id:a,name:n.function?.name||``}})}let i=e.get(r);n.id&&(i.id=n.id),n.function?.name&&(i.name=n.function.name),n.function?.arguments&&(i.argumentsBuffer+=n.function.arguments,u.push({type:`tool-call-args-delta`,data:{index:i.partIdx,id:i.id,name:i.name,delta:n.function.arguments,accumulated:i.argumentsBuffer}}))}}if(d.finish_reason){c(u);for(let[,t]of e)try{let e=t.argumentsBuffer?JSON.parse(t.argumentsBuffer):{};u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.id,name:t.name,arguments:e}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw buffer: ${t.argumentsBuffer}`)}o=X(d.finish_reason)}return u}function u(){return o===void 0?[]:[{type:`complete`,data:{finishReason:o,usage:s??{in:0,out:0}}}]}return{handleChunk:l,finalize:u}}async function*rt(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,context:o,signal:s,apiKey:c,options:l,reasoning:u}=e,d=o?.tracer;l?.providerTools&&d?.warn(`providerTools not supported by ChatCompletions provider`);let f=nt();try{let e=await Ve(r,i,{model:n,fileResolver:o?.fileResolver,signal:s}),p=Ue(a),m={model:n,messages:e,stream:!0,stream_options:{include_usage:!0},...p&&{tools:p},...He(u)};l&&(l.temperature!==void 0&&(m.temperature=l.temperature),l.top_p!==void 0&&(m.top_p=l.top_p),l.max_tokens!==void 0&&(m.max_tokens=l.max_tokens),l.frequency_penalty!==void 0&&(m.frequency_penalty=l.frequency_penalty),l.presence_penalty!==void 0&&(m.presence_penalty=l.presence_penalty),l.stop!==void 0&&(m.stop=l.stop),l.reasoning_effort!==void 0&&(m.reasoning_effort=l.reasoning_effort)),d?.debug(`ChatCompletions streaming request`,{request:G(m)});let h={"Content-Type":`application/json`};c&&(h.Authorization=`Bearer ${c}`);let g=await fetch(`${t}/chat/completions`,{method:`POST`,headers:h,body:JSON.stringify(m),signal:s});if(!g.ok){let e=await g.text().catch(()=>``);throw Error(`HTTP error! status: ${g.status}${e?` - ${e}`:``}`)}if(!g.body)throw Error(`Response body is null`);let _=g.body.getReader(),v=new TextDecoder,y=``;for(;;){let{done:e,value:t}=await _.read();if(e)break;y+=v.decode(t,{stream:!0});let n=y.split(`
10
+ `);y=n.pop()||``;for(let e of n){let t=e.trim();if(!t||t.startsWith(`:`)||!t.startsWith(`data: `))continue;let n=t.slice(6);if(n!==`[DONE]`)try{let e=JSON.parse(n),t=f.handleChunk(e);for(let e of t)yield e}catch(e){d?.error(`Error parsing ChatCompletions stream chunk`,{error:e instanceof Error?e.message:String(e),line:t})}}}for(let e of f.finalize())yield e}catch(e){if(s?.aborted)return;d?.error(`Error in ChatCompletions streaming request`,{error:e instanceof Error?e.message:String(e)}),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function it(e,t){return{name:`ChatCompletions`,async createGenerationRequest(n,r){return await et({baseUrl:e,model:n,apiKey:t,...r})},createStreamingRequest(n,r){return rt({baseUrl:e,model:n,apiKey:t,...r})}}}function at(e,t,n){let r={};return t&&(r.systemInstruction=t),e&&e.length>0&&(r.tools=e.map(e=>({functionDeclarations:[{name:e.name,description:e.description,parametersJsonSchema:f.toJSONSchema(e.schema)}]}))),n&&Object.assign(r,n),r}function ot(e){return e===!0?{thinkingConfig:{thinkingBudget:8192,includeThoughts:!0}}:e===!1?{thinkingConfig:{thinkingBudget:0}}:{}}async function st(e,t={model:``}){return(await Promise.all(e.map(e=>ct(e,t)))).filter(e=>e!==void 0)}async function ct(e,t){switch(e.role){case`tool`:return lt(e,t);case`assistant`:return ut(e);case`user`:return dt(e,t)}}async function lt(e,t){return{role:`user`,parts:(await Promise.all(e.content.map(async e=>{let n=typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
11
+ `),r={functionResponse:{id:e.id??void 0,name:e.name,response:{output:n}}};return typeof e.content==`string`?[r]:[r,...await Promise.all(e.content.filter(e=>e.type===`file`).map(e=>pt(e.file,t,`tool-result`)))]}))).flat(1)}}function ut(e){let t=[],n=e.content.filter(e=>e.type===`text`);if(n.length>0){let e=n.map(e=>e.text).join(``);e&&t.push({text:e})}let r=e.content.filter(e=>e.type===`tool-call`);return r.length>0&&t.push(...r.map(e=>{let t={functionCall:{id:e.id??void 0,name:e.name,args:e.parameters}};return e.providerMetadata?.thoughtSignature&&(t.thoughtSignature=e.providerMetadata.thoughtSignature),t})),{role:`model`,parts:t}}async function dt(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>ft(e,t)))).filter(e=>e!==null)}}async function ft(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?pt(e.file,t,`user-message`):null}async function pt(e,t,n){if(e.kind===`text`){let r=await J(e,{provider:`gemini`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Gemini text source: ${r.type}`);return{text:ht(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`&&e.mimeType!==`application/pdf`)throw Error(`Gemini document file support is limited to PDFs. Received ${e.mimeType}`);return mt(await J(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function mt(e,t){if(e.type===`base64`)return{inlineData:{mimeType:e.mimeType??t.mimeType,data:e.data}};if(e.type===`url`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.url}};if(e.type===`gemini-file-uri`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.uri}};throw Error(`Unsupported Gemini file source: ${e.type}`)}function ht(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function gt(e){switch(e){case g.STOP:return[!0,`stop`];case g.MAX_TOKENS:return[!0,`length`];case g.FINISH_REASON_UNSPECIFIED:case g.SAFETY:case g.RECITATION:case g.LANGUAGE:case g.OTHER:case g.BLOCKLIST:case g.PROHIBITED_CONTENT:case g.SPII:case g.MALFORMED_FUNCTION_CALL:case g.IMAGE_SAFETY:return[!1,`error`]}return[!1,`error`]}async function _t(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,options:s,reasoning:c}=e,l=o?.tracer,u={...ot(c),...s??{}};u.max_tokens&&(u.maxOutputTokens=u.max_tokens,delete u.max_tokens),u.stop&&(u.stopSequences=Array.isArray(u.stop)?u.stop:[u.stop],delete u.stop),u.top_p!==void 0&&(u.topP=u.top_p,delete u.top_p);let d;try{let e={contents:await st(r,{model:n,fileResolver:o?.fileResolver}),config:at(a,i,u)};l?.debug(`Gemini request`,{request:G(e)}),d=vt(await t.models.generateContent({model:n,...e}),{tracer:l})}catch(e){l?.error(e instanceof Error?e.message:String(e)),d=K(e)}return l?.debug(`Gemini response`,{result:d}),d}function vt(e,t){let{tracer:n}=t,r=e.usageMetadata?.promptTokenCount??0,i={in:r,out:(e.usageMetadata?.totalTokenCount??r)-r};if(!e)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};if(e.promptFeedback&&e.promptFeedback.blockReason)return{type:`error`,error:{type:`Blocked`,message:`Response blocked by Google AI: ${e.promptFeedback.blockReason}, ${e.promptFeedback.blockReasonMessage}`},usage:i,raw:e};if(!e.candidates||e.candidates.length===0)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};e.candidates.length>1&&n?.warn(`We received ${e.candidates.length} response candidates`);let a=e.candidates[0],o=(a.content?.parts||[]).map(e=>e.text).filter(e=>e!==void 0).join(``),[s,c]=gt(a.finishReason);if(s){let t=[];if(o&&t.push({type:`text`,text:o}),e.functionCalls)for(let n of e.functionCalls)if(n.args==null)t.push({type:`tool-call`,id:n.id??``,name:n.name??``,parameters:{}});else if(typeof n.args!=`object`||Array.isArray(n.args))throw Error(`Invalid tool call arguments for ${n.name}: expected object, got ${typeof n.args}`);else t.push({type:`tool-call`,id:n.id??``,name:n.name??``,parameters:n.args});return{type:`success`,id:e.responseId??``,model:e.modelVersion??``,role:`assistant`,finishReason:e.functionCalls?`function_call`:c,content:t,text:O(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function yt(){let e=0,t=-1,n=!1,r=``,i=``,a=0,o=0,s=null;function c(e){t<0||(s===`text`?e.push({type:`text-complete`,data:{index:t}}):s===`thinking`&&e.push({type:`thinking-complete`,data:{index:t}}),s=null,t=-1)}function l(l){let u=[];r||(r=l.responseId||`gemini-${Date.now()}`,i=l.modelVersion||`gemini`,u.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}})),l.usageMetadata&&(a=l.usageMetadata.promptTokenCount||0,o=(l.usageMetadata.totalTokenCount||0)-a);let d=l.candidates?.[0];if(!d)return u;let f=d.content?.parts||[];for(let r of f){let i=`thought`in r&&r.thought===!0,a=Object.keys(r);if(!(`thoughtSignature`in r&&!r.text&&!r.functionCall||a.length===2&&`text`in r&&`thoughtSignature`in r&&!r.text)&&(i&&r.text?(s!==`thinking`&&(c(u),t=e++,s=`thinking`,u.push({type:`thinking-start`,data:{index:t}})),u.push({type:`thinking-delta`,data:{index:t,text:r.text}})):r.text&&!i?(s!==`text`&&(c(u),t=e++,s=`text`,u.push({type:`text-start`,data:{index:t}})),u.push({type:`text-delta`,data:{text:r.text,index:t}})):r.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(r))}`),r.functionCall)){c(u),n=!0;let t=e++,i=r.functionCall.id||`tool-${t}`,a=r.functionCall.name??``;u.push({type:`tool-call-start`,data:{index:t,id:i,name:a}});let o=r.functionCall.args??{},s=JSON.stringify(o);u.push({type:`tool-call-args-delta`,data:{index:t,id:i,name:a,delta:s,accumulated:s}});let l={index:t,id:i,name:a,arguments:o},d=r;d.thoughtSignature&&(l.providerMetadata={thoughtSignature:d.thoughtSignature}),u.push({type:`tool-call-complete`,data:l})}}if(d.finishReason&&d.finishReason!==g.FINISH_REASON_UNSPECIFIED){c(u);let[e,t]=gt(d.finishReason),r=n?`function_call`:t;!e&&!n?u.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${d.finishReason}`,usage:{in:a,out:o},raw:l}}):u.push({type:`complete`,data:{finishReason:r,usage:{in:a,out:o}}})}return u}return{handleChunk:l}}async function*bt(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,signal:s,options:c,reasoning:l}=e,u=o?.tracer,{providerTools:d,...f}=c??{},p={...ot(l),...f};p.max_tokens&&(p.maxOutputTokens=p.max_tokens,delete p.max_tokens),p.stop&&(p.stopSequences=Array.isArray(p.stop)?p.stop:[p.stop],delete p.stop),p.top_p!==void 0&&(p.topP=p.top_p,delete p.top_p);let m=at(a,i,p);if(d){let e={web_search:`googleSearch`,code_execution:`codeExecution`};m.tools||=[];for(let t of d){let n=e[t.name]??t.name;m.tools.push({[n]:t.config??{}})}}let h=yt();try{let e={contents:await st(r,{model:n,fileResolver:o?.fileResolver,signal:s}),config:m};u?.debug(`Gemini streaming request`,{request:G(e)});let i=await t.models.generateContentStream({model:n,...e});for await(let e of i){let t=h.handleChunk(e);for(let e of t)yield e}}catch(e){if(s?.aborted)return;u?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function xt(e){let t=new _({apiKey:e});return{name:`Gemini`,async createGenerationRequest(e,n){return await _t({client:t,model:e,...n})},createStreamingRequest(e,n){return bt({client:t,model:e,...n})}}}async function St(e){let{provider:t,model:n,messages:r,system:i,tools:a,tracer:o,fileResolver:s,options:c,reasoning:l}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,context:{tracer:o,fileResolver:s},options:c,reasoning:l})}async function Ct(e){let{provider:t,model:n,messages:r,system:i,onToolCall:a,maxIterations:o,tracer:s,fileResolver:c,options:l,reasoning:u,signal:d=new AbortController().signal}=e,f=N(e),p=[...r],m=[],h={in:0,out:0},g=0,_,v=e=>{p.push(e),m.push(e)},y=e=>(s?.setResult({kind:`llm`,model:n,request:{messages:r},response:{content:e.result===`success`?e.final?.content:null},usage:e.usage?{inputTokens:e.usage.in,outputTokens:e.usage.out}:void 0,finishReason:e.result===`success`?e.final?.finishReason:void 0}),s?.end(e.result===`error`?`error`:`ok`),e),b=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??n,request:{messages:p},response:{content:t.content},usage:t.usage?{inputTokens:t.usage.in,outputTokens:t.usage.out}:void 0,finishReason:t.finishReason}),e.end()};for(;;){if(o!==void 0&&g>=o)return y({result:`error`,messages:m,error:{type:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${o})`}}},usage:h});g+=1;let e=s?.startSpan(`turn-${g}`,{type:`llm`}),r=f.executable(),x=await St({provider:t,model:n,messages:p,system:i,tools:r.length>0?r.map(e=>({name:e.name,description:e.description,schema:e.schema})):void 0,tracer:e,fileResolver:c,options:l,reasoning:u});if(j(h,x),b(e,x),x.type===`error`)return y({result:`error`,messages:m,error:{type:`model`,error:x},usage:h});let S={role:`assistant`,id:x.id,model:x.model,content:x.content,finishReason:x.finishReason};if(v(S),_=S,x.finishReason!==`function_call`)return y({result:`success`,messages:m,final:_,usage:h});let C=k(x.content);if(C.length===0)return y({result:`success`,messages:m,final:_,usage:h});let{results:w}=await te(C,a,d,f,s);w.length>0&&v({role:`tool`,id:crypto.randomUUID(),content:w})}}function Z(e){if(e&&e.length>0)return e.map(e=>({type:`function`,strict:!0,name:e.name,description:e.description,parameters:f.toJSONSchema(e.schema)}))}function wt(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`minimal`}}:{}}async function Tt(e,t={model:``}){return(await Promise.all(e.map(e=>Et(e,t)))).flat(1)}async function Et(e,t){switch(e.role){case`tool`:return Dt(e,t);case`assistant`:return Ot(e);default:return kt(e,t)}}async function Dt(e,t){return Promise.all(e.content.map(async e=>({type:`function_call_output`,call_id:e.id,output:typeof e.content==`string`?e.content:await Promise.all(e.content.map(e=>e.type===`text`?Promise.resolve({type:`input_text`,text:e.text}):jt(e.file,t,`tool-result`)))})))}function Ot(e){let t=[],n=O(e.content);n&&t.push({role:e.role,content:n});let r=e.content.filter(e=>e.type===`tool-call`);for(let e of r)t.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.parameters)});let i=e.content.filter(e=>e.type===`provider-tool`);for(let e of i)e.output!=null&&t.push(e.output);return t}async function kt(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>At(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function At(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?jt(e.file,t,`user-message`):(e.type,null)}async function jt(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:Mt(await J(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e),detail:`auto`};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`OpenAI file inputs currently support PDF documents. Received ${e.mimeType}`);return Nt(await J(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}let r=await J(e,{provider:`openai`,model:t.model,accepted:[`text`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return r.type===`text`?{type:`input_text`,text:r.content}:Nt(r,e)}function Mt(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported OpenAI image source: ${e.type}`)}function Nt(e,t){if(e.type===`url`)return{type:`input_file`,filename:e.name??t.name,file_url:e.url};if(e.type===`base64`)return{type:`input_file`,filename:e.name??t.name,file_data:`data:${e.mimeType??t.mimeType};base64,${e.data}`};throw Error(`Unsupported OpenAI file source: ${e.type}`)}async function Pt(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,options:s,reasoning:c}=e,l=o?.tracer,u;try{let e=Z(a),d={model:n,input:await Tt(r,{model:n,fileResolver:o?.fileResolver}),...i&&{instructions:i},...e?{tools:e}:{},...wt(c),...s};l?.debug(`OpenAI ResponsesAPI request`,{request:G(d)}),u=Ft(await t.responses.create(d))}catch(e){l?.error(e instanceof Error?e.message:String(e)),u=K(e)}return l?.debug(`OpenAI ResponsesAPI response`,{result:u}),u}function Ft(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:{in:e.usage?.input_tokens??0,out:e.usage?.output_tokens??0},raw:e};let t=e.output?.filter(e=>e.type===`reasoning`)?.map(e=>e),n=[];if(t&&t.length>0)for(let e of t){let t=e.summary?.[0]?.text||e.content?.[0]?.text||``;(t||e.encrypted_content)&&n.push({type:`thinking`,text:t,...e.encrypted_content&&{encrypted:e.encrypted_content}})}e.output_text&&n.push({type:`text`,text:e.output_text});let r=e.output?.filter(e=>e.type===`function_call`);if(r&&r.length>0)for(let e of r){let t=e;try{n.push({type:`tool-call`,id:t.id||``,name:t.name||``,parameters:t.arguments?JSON.parse(t.arguments):{}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${t.arguments}`)}}return{type:`success`,id:e.id,model:e.model||``,role:`assistant`,finishReason:e.incomplete_details?`error`:`stop`,content:n,text:O(n),usage:{in:e.usage?.input_tokens??0,out:e.usage?.output_tokens??0},raw:e}}function It(){let e=``,t=``,n=0,r=-1,i=!1,a=new Map,o=new Map,s=new Set([`web_search_call`,`file_search_call`,`code_interpreter_call`]),c=new Map;function l(l){let u=[];switch(l.type){case`response.created`:e=l.response.id||`openai-${Date.now()}`,t=l.response.model,u.push({type:`start`,id:e,data:{model:t,timestamp:Date.now()}});break;case`response.output_text.delta`:r===-1&&(r=n++,u.push({type:`text-start`,data:{index:r}})),u.push({type:`text-delta`,data:{text:l.delta,index:r}});break;case`response.output_text.done`:r>=0&&(u.push({type:`text-complete`,data:{index:r}}),r=-1);break;case`response.function_call_arguments.delta`:{let e=l.item_id;if(!c.has(e)){let t=a.get(e),r=t?.name||``,i=t?.callId||e,o=n++;c.set(e,{id:e,callId:i,name:r,argumentsBuffer:``,partIdx:o}),u.push({type:`tool-call-start`,data:{index:o,id:i,name:r}})}let t=c.get(e);t.argumentsBuffer+=l.delta,u.push({type:`tool-call-args-delta`,data:{index:t.partIdx,id:t.callId,name:t.name,delta:l.delta,accumulated:t.argumentsBuffer}});break}case`response.function_call_arguments.done`:{i=!0;let e=l.item_id,t=c.get(e),n=l.name||t?.name||``;if(t){try{let e=l.arguments?JSON.parse(l.arguments):{};u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.callId,name:n,arguments:e}})}catch(e){throw Error(`Failed to parse function call arguments for ${n}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${l.arguments}`)}c.delete(e)}break}case`response.completed`:{let e=l.response.usage;u.push({type:`complete`,data:{finishReason:l.response.incomplete_details?`error`:i?`function_call`:`stop`,usage:{in:e?.input_tokens||0,out:e?.output_tokens||0}}});break}case`response.failed`:u.push({type:`error`,data:{type:`RESPONSES_API_ERROR`,message:`Response failed: ${l.response.status}`,raw:l}});break;case`response.output_item.added`:if(l.item?.type===`reasoning`)r=n++,u.push({type:`thinking-start`,data:{index:r}});else if(l.item?.type===`function_call`){let e=l.item,t=e.id||e.call_id;t&&a.set(t,{name:e.name||``,callId:e.call_id||t})}else if(l.item&&s.has(l.item.type)){let e=l.item,t=n++;o.set(e.id,t),u.push({type:`provider-tool-start`,data:{index:t,id:e.id,name:e.type}})}break;case`response.output_item.done`:if(l.item?.type===`reasoning`&&r>=0)u.push({type:`thinking-complete`,data:{index:r}}),r=-1;else if(l.item&&s.has(l.item.type)){let e=l.item,t=o.get(e.id);t!==void 0&&(u.push({type:`provider-tool-complete`,data:{index:t,id:e.id,name:e.type,output:l.item}}),o.delete(e.id))}break;case`response.reasoning_text.delta`:l.delta&&u.push({type:`thinking-delta`,data:{index:r,text:l.delta}});break;case`response.reasoning_summary_text.delta`:l.delta&&u.push({type:`thinking-summary-delta`,data:{index:r,text:l.delta}});break;case`response.in_progress`:case`response.content_part.added`:case`response.content_part.done`:case`response.reasoning_summary_part.added`:case`response.reasoning_summary_part.done`:case`response.reasoning_summary_text.done`:case`response.reasoning_text.done`:case`response.web_search_call.in_progress`:case`response.web_search_call.searching`:case`response.web_search_call.completed`:break;default:console.log(`[OpenAI] unhandled stream event: ${l.type}`)}return u}return{handleEvent:l}}async function*Lt(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,signal:s,options:c,reasoning:l}=e,u=o?.tracer,{providerTools:d,...f}=c??{},p=Z(a)??[];if(d){let e={web_search:`web_search_preview`,code_execution:`code_interpreter`};for(let t of d){let n=e[t.name]??t.name;p.push({type:n,...t.config})}}let m=It();try{let e={model:n,input:await Tt(r,{model:n,fileResolver:o?.fileResolver,signal:s}),...i&&{instructions:i},stream:!0,...p.length>0?{tools:p}:{},...wt(l),...f};u?.debug(`OpenAI ResponsesAPI streaming request`,{request:G(e)});let a=t.responses.stream(e,...s?[{signal:s}]:[]);for await(let e of a){let t=m.handleEvent(e);for(let e of t)yield e}}catch(e){if(s?.aborted)return;u?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function Rt(e){let t=new v({apiKey:e});return{name:`OpenAI`,async createGenerationRequest(e,n){return await Pt({client:t,model:e,...n})},createStreamingRequest(e,n){return Lt({client:t,model:e,...n})}}}const zt=d.object({searchTerm:d.string().describe(`The search term to query`)}),Bt=new class{name=`brave`;description=`Perform a search using the Brave search engine`;schema=zt;apiKey;throttle;lastExecTime=0;constructor(e){e&&this.configure(e)}configure(e){let{rateLimit:t}=e;this.apiKey=e[`api-key`],this.throttle=t?1100/t:void 0}async execute(e,t){let{searchTerm:n}=e;if(this.throttle){for(;Date.now()-this.lastExecTime<this.throttle;)await ie(this.throttle-(Date.now()-this.lastExecTime));this.lastExecTime=Date.now()}try{let e=this.apiKey,t=new URL(`https://api.search.brave.com/res/v1/web/search`);t.searchParams.append(`q`,n),t.searchParams.append(`format`,`json`);let r=await fetch(t.toString(),{method:`GET`,headers:{Accept:`application/json`,"X-Subscription-Token":e??``}});if(!r.ok)throw Error(`[Brave] HTTP error ${r.status}: ${r.statusText}`);let i=await r.json();return JSON.stringify(i)}catch(e){throw e instanceof Error?Error(`[Brave] Error fetching search results: ${e.message}`):e}}},Vt={name:`calculator`,description:`Performs basic arithmetic operations`,schema:p.object({operation:p.enum([`add`,`subtract`,`multiply`,`divide`]).describe(`The operation to perform (add, subtract, multiply, divide)`),a:p.number().describe(`First operand`),b:p.number().describe(`Second operand`)}),execute:async({operation:e,a:t,b:n})=>{switch(e){case`add`:return`${t} + ${n} = ${t+n}`;case`subtract`:return`${t} - ${n} = ${t-n}`;case`multiply`:return`${t} * ${n} = ${t*n}`;case`divide`:if(n===0)throw Error(`Cannot divide by zero`);return`${t} / ${n} = ${t/n}`;default:throw Error(`Unknown operation: ${e}`)}}};async function Ht(e,t={}){let n=t.timeout??3e4,r=t.maxBuffer??1048576;return new Promise((i,a)=>{let o=y(e,[],{shell:!0,cwd:t.cwd}),s=``,c=``,l=!1,u=!1,d=!1,f=setTimeout(()=>{l=!0,o.kill(`SIGTERM`)},n),p=()=>{u=!0,o.kill(`SIGTERM`)};t.signal?.addEventListener(`abort`,p);let m=()=>{clearTimeout(f),t.signal?.removeEventListener(`abort`,p)};o.stdout?.setEncoding(`utf-8`),o.stderr?.setEncoding(`utf-8`),o.stdout?.on(`data`,e=>{if(s+=e,s.length+c.length>r){d=!0,o.kill(`SIGTERM`);return}t.onChunk?.(e)}),o.stderr?.on(`data`,e=>{if(c+=e,s.length+c.length>r){d=!0,o.kill(`SIGTERM`);return}t.onChunk?.(e)}),o.on(`error`,e=>{m(),a(e)}),o.on(`close`,e=>{if(m(),l){let e=Error(`Command timed out after ${n}ms`);e.stdout=s,e.stderr=c,a(e);return}if(u){let e=Error(`Command aborted`);e.stdout=s,e.stderr=c,a(e);return}if(d){let e=Error(`Command output exceeded maxBuffer (${r} bytes)`);e.stdout=s,e.stderr=c,a(e);return}if(e!==0){let t=Error(`Command failed with exit code ${e}`);t.stdout=s,t.stderr=c,t.code=e??-1,a(t);return}i({stdout:s,stderr:c})})})}function Ut(e){if(e instanceof Error){let t=e,n=`Error executing command: ${e.message}`;return t.stdout&&(n+=`\n[stdout]: ${t.stdout}`),t.stderr&&(n+=`\n[stderr]: ${t.stderr}`),n}return`Error executing command: ${String(e)}`}function Wt(e,t){return t&&t.trim()?`${e}\n[stderr]: ${t}`:e}const Gt=d.object({command:d.string().describe(`The shell command to execute`)}),Kt=new class{name=`exec`;description=`Execute a shell command and return the output.`;schema=Gt;timeout=3e4;maxBuffer=1024*1024;cwd;constructor(e){e&&this.configure(e)}configure(e){this.timeout=e.timeout??3e4,this.maxBuffer=e.maxBuffer??1024*1024,this.cwd=e.cwd}summarize(e){return e.command}async execute(e,t){let{command:n}=e;try{let e=await Ht(n,{timeout:this.timeout,maxBuffer:this.maxBuffer,cwd:this.cwd,signal:t.signal,onChunk:e=>t.emit(e)});return Wt(e.stdout,e.stderr)}catch(e){return Ut(e)}}},qt={name:`patch-file`,description:`Patch a file by replacing an exact string match within a specified line range`,schema:p.object({path:p.string().describe(`The file path to patch`),old_string:p.string().describe(`The exact text to find and replace`),new_string:p.string().describe(`The replacement text`),start_line:p.number().int().positive().describe(`1-indexed start line of the region to match within`),end_line:p.number().int().positive().describe(`1-indexed end line (inclusive) of the region to match within`)}),summarize:({path:e,start_line:t,end_line:n})=>`${e}:${t}:${n}`,execute:async({path:e,old_string:t,new_string:n,start_line:r,end_line:a})=>{if(a<r)throw Error(`end_line (${a}) must be >= start_line (${r})`);let s;try{s=await i(e,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to read file "${e}": ${t.message}`):t}let c=s.split(`
12
+ `);if(r>c.length)throw Error(`start_line (${r}) exceeds file length (${c.length} lines)`);if(a>c.length)throw Error(`end_line (${a}) exceeds file length (${c.length} lines)`);let l=c.slice(r-1,a).join(`
13
+ `),u=l.indexOf(t);if(u===-1)throw Error(`old_string not found within lines ${r}-${a} of "${e}"`);if(l.indexOf(t,u+1)!==-1)throw Error(`old_string matches multiple times within lines ${r}-${a} of "${e}"`);let d=l.replace(t,n),f=[...c.slice(0,r-1),...d.split(`
14
+ `),...c.slice(a)].join(`
15
+ `);try{await o(e,f,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to write file "${e}": ${t.message}`):t}return`Successfully patched "${e}" (lines ${r}-${a})`}},Jt={name:`read-file`,description:`Read the contents of a file from disk`,schema:p.object({path:p.string().describe(`The file path to read from`)}),summarize:({path:e})=>e,execute:async({path:e})=>{try{return await i(e,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to read file "${e}": ${t.message}`):t}}},Yt={name:`write-file`,description:`Write content to a file on disk, creating directories if needed`,schema:p.object({path:p.string().describe(`The file path to write to`),content:p.string().describe(`The content to write to the file`)}),summarize:({path:e})=>e,execute:async({path:e,content:t})=>{try{return await r(c(e),{recursive:!0}),await o(e,t,`utf-8`),`Successfully wrote ${t.length} characters to "${e}"`}catch(t){throw t instanceof Error?Error(`Failed to write file "${e}": ${t.message}`):t}}};function Xt(e){try{let t=f.fromJSONSchema(e);return t instanceof f.ZodObject?t.strict():f.object({}).passthrough()}catch{return f.object({}).passthrough()}}function Zt(e,t,n){return e.map(e=>$t(e,t,n))}function Qt(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=Xt(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function $t(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=Xt(e.inputSchema);return{name:r,description:e.description??``,schema:i,async execute(n){let r=await t.callTool({name:e.name,arguments:n});if(`isError`in r&&r.isError)throw Error(tn(r.content));return en(r.content)}}}function en(e){return e.some(e=>e.type===`image`)?e.filter(e=>e.type===`text`||e.type===`image`).map(e=>{if(e.type===`text`)return{type:`text`,text:e.text};let t=e;return{type:`file`,file:{kind:`image`,mimeType:t.mimeType,name:`mcp-image`,source:{type:`base64`,data:t.data}}}}):e.filter(e=>e.type===`text`).map(e=>e.text).join(`
16
+ `)}function tn(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
17
+ `)||`MCP tool execution error`}var nn=class{config;client;transport;cachedMcpTools;_connected=!1;constructor(e){this.config=e}get name(){return this.config.name??this.client?.getServerVersion()?.name}get connected(){return this._connected}async connect(e){if(this._connected)return;let t=e?.tracer?.startSpan(`mcp:connect`,{type:`internal`});this.client=new b({name:`axle`,version:`1.0.0`}),this.config.transport===`stdio`?this.transport=new x({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new S(new URL(this.config.url),{requestInit:this.config.headers?{headers:this.config.headers}:void 0});try{await this.client.connect(this.transport),this._connected=!0,t?.end(`ok`)}catch(e){throw t?.end(`error`),e}}async listTools(e){let t=this.assertConnected();return Zt(await this.fetchTools(t,e?.tracer),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return Qt(await this.fetchTools(t,e?.tracer),e?.prefix)}async refreshTools(){return this.assertConnected(),this.cachedMcpTools=void 0,this.listTools()}async close(e){this._connected&&(e?.tracer?.debug(`mcp:close`),await this.client?.close(),this._connected=!1,this.client=void 0,this.transport=void 0,this.cachedMcpTools=void 0)}async fetchTools(e,t){if(this.cachedMcpTools)return this.cachedMcpTools;t?.debug(`mcp:listTools`);let n=await e.listTools();return this.cachedMcpTools=n.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})),this.cachedMcpTools}assertConnected(){if(!this._connected||!this.client)throw Error(`MCP not connected. Call connect() first.`);return this.client}};const rn={debug:0,info:1,warn:2,error:3};var an=class{writers=[];_minLevel=`info`;get minLevel(){return this._minLevel}set minLevel(e){this._minLevel=e}addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.writers.forEach(e=>e.onSpanStart(n)),new on(n,this)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}_notifySpanEnd(e){this.writers.forEach(t=>t.onSpanEnd(e))}_notifySpanUpdate(e){this.writers.forEach(t=>t.onSpanUpdate?.(e))}_notifyEvent(e,t){this.writers.forEach(n=>n.onEvent?.(e,t))}_notifySpanStart(e){this.writers.forEach(t=>t.onSpanStart(e))}_shouldLog(e){return rn[e]>=rn[this._minLevel]}},on=class e{data;tracer;ended=!1;constructor(e,t){this.data=e,this.tracer=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.tracer._notifySpanStart(r),new e(r,this.tracer)}end(e=`ok`){this.ended||(this.ended=!0,this.data.endTime=performance.now(),this.data.status=e,this.tracer._notifySpanEnd(this.data))}addEvent(e,t,n){if(this.ended||!this.tracer._shouldLog(t))return;let r={name:e,timestamp:performance.now(),level:t,attributes:n};this.data.events.push(r),this.tracer._notifyEvent(this.data,r)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,this.tracer._notifySpanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.tracer._notifySpanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.tracer._notifySpanUpdate(this.data))}};const sn={debug:0,info:1,warn:2,error:3};var cn=class{minLevel;showInternal;showTimestamp;showDuration;markdown;output;spans=new Map;visibleDepths=new Map;constructor(e={}){this.minLevel=e.minLevel??`info`,this.showInternal=e.showInternal??!1,this.showTimestamp=e.showTimestamp??!0,this.showDuration=e.showDuration??!0,this.markdown=e.markdown??!1,this.output=e.output??console.log}shouldShowEvent(e){return sn[e]>=sn[this.minLevel]}isSpanVisible(e){return!(e.type===`internal`&&!this.showInternal)}findVisibleAncestor(e){let t=e.parentSpanId;for(;t;){let e=this.spans.get(t);if(!e)break;if(this.isSpanVisible(e))return e;t=e.parentSpanId}return null}calculateVisibleDepth(e){if(!this.isSpanVisible(e))return-1;let t=this.findVisibleAncestor(e);return t?(this.visibleDepths.get(t.spanId)??0)+1:0}formatTimestamp(){if(!this.showTimestamp)return``;let e=new Date;return`[${e.toTimeString().slice(0,8)}.${e.getMilliseconds().toString().padStart(3,`0`)}] `}formatDuration(e){if(!this.showDuration||!e.endTime)return``;let t=e.endTime-e.startTime;return t<1e3?` (${Math.round(t)}ms)`:` (${(t/1e3).toFixed(2)}s)`}formatIndent(e){return` `.repeat(e)}formatSpanName(e){return e.type?`[${e.type}] ${e.name}`:e.name}renderMarkdown(e){return ln(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,t);let n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatSpanName(e);this.output(`${r}${n}START ${i}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.visibleDepths.get(e.spanId)??0,n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatDuration(e),a=this.formatSpanName(e),o=e.status===`error`?` [ERROR]`:``;if(this.output(`${r}${n}END ${a}${i}${o}`),e.result?.kind===`llm`){let t=e.result,i=[`model=${t.model}`];if(t.finishReason&&i.push(`finishReason=${t.finishReason}`),t.usage&&(t.usage.inputTokens!==void 0&&i.push(`inputTokens=${t.usage.inputTokens}`),t.usage.outputTokens!==void 0&&i.push(`outputTokens=${t.usage.outputTokens}`)),this.output(`${r}${n} INFO LLM complete ${i.join(` `)}`),this.shouldShowEvent(`debug`)&&t.response.content){let e=(typeof t.response.content==`string`?t.response.content:JSON.stringify(t.response.content,null,2)).split(`
18
+ `);for(let t of e)this.output(`${r}${n} DEBUG ${t}`)}}}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,t){if(!this.shouldShowEvent(t.level))return;this.spans.set(e.spanId,e);let n;if(this.isSpanVisible(e))n=this.visibleDepths.get(e.spanId)??0;else{let t=this.findVisibleAncestor(e);n=t?this.visibleDepths.get(t.spanId)??0:0}let r=this.formatIndent(n+1),i=this.formatTimestamp(),a=t.level.toUpperCase().padEnd(5),o=this.markdown&&t.attributes?.markdown===!0,s=t.attributes?Object.entries(t.attributes).filter(([e])=>e!==`markdown`):[],c=t.name;o&&(c=this.renderMarkdown(c));let l=`${i}${r}${a} ${c}`;if(s.length>0){let e=s.map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(` `);l+=` ${e}`}this.output(l)}};function ln(e){return Q(w.lexer(e))}function Q(e=[]){return e.map(e=>un(e)).filter(e=>e.length>0).join(`
19
+ `)}function un(e){switch(e.type){case`space`:return``;case`heading`:return C.bold($(e.tokens));case`paragraph`:return $(e.tokens);case`blockquote`:return gn(Q(e.tokens),`> `);case`code`:return(e.lang?C.dim(`${e.lang}\n`):``)+C.yellow(e.text);case`list`:return fn(e)?mn(e):e.raw;case`hr`:return C.dim(`-`.repeat(40));case`table`:return pn(e)?hn(e):e.raw;case`html`:return e.text;case`text`:return e.tokens?$(e.tokens):vn(e.text);default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function $(e=[]){return e.map(e=>dn(e)).join(``)}function dn(e){switch(e.type){case`text`:case`escape`:return vn(e.text);case`strong`:return C.bold($(e.tokens));case`em`:return C.italic($(e.tokens));case`codespan`:return C.yellow(e.text);case`del`:return C.strikethrough($(e.tokens));case`link`:{let t=$(e.tokens);return e.href&&e.href!==e.text?`${C.blue.underline(t)} ${C.dim(`(${e.href})`)}`:C.blue.underline(t)}case`image`:return e.text?`${e.text} (${e.href})`:e.href;case`br`:return`
20
+ `;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function fn(e){return e.type===`list`&&`items`in e&&Array.isArray(e.items)}function pn(e){return e.type===`table`&&`header`in e&&`rows`in e}function mn(e){return e.items.map((t,n)=>{let r=e.ordered?`${Number(e.start||1)+n}. `:`- `,i=t.task?`[${t.checked?`x`:` `}] `:``,a=Q(t.tokens).trimEnd();return r+i+_n(a,r.length+i.length)}).join(`
21
+ `)}function hn(e){let t=e.header.map(e=>$(e.tokens)).join(` | `),n=e.rows.map(e=>e.map(e=>$(e.tokens)).join(` | `));return[C.bold(t),...n].join(`
22
+ `)}function gn(e,t){return e.split(`
23
+ `).map(e=>t+e).join(`
24
+ `)}function _n(e,t){let[n=``,...r]=e.split(`
25
+ `);if(r.length===0)return n;let i=` `.repeat(t);return[n,...r.map(e=>i+e)].join(`
26
+ `)}function vn(e){return e.replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/g,`&`)}var yn=class{provider;model;enableTools;lastStore;lastName;lastScope;constructor(e){this.provider=e.provider,this.model=e.model,this.enableTools=e.enableTools??!1}async recall(e){let t=e.tracer?.startSpan(`memory.recall`,{type:`internal`});this.lastStore=e.store,this.lastName=e.name,this.lastScope=e.scope;let n=await this.loadStore(e.store,e.name,e.scope);if(n.instructions.length===0)return t?.info(`no stored instructions`),t?.end(),{};t?.info(`loaded instructions`,{count:n.instructions.length});let r=n.instructions.map((e,t)=>`${t+1}. ${e}`).join(`
27
+ `);return t?.end(),{systemSuffix:`## Learned Instructions\n\n${r}`}}async record(e){if(!e.newMessages||e.newMessages.length===0)return;let t=e.tracer?.startSpan(`memory.record`,{type:`internal`}),n=this.formatMessages(e.newMessages);if(!n.trim()){t?.info(`no text content to extract from`),t?.end();return}let r=t?.startSpan(`memory.extract`,{type:`llm`}),i=await Ct({provider:this.provider,model:this.model,messages:[{role:`user`,content:n}],system:`You are a memory extraction system. Your job is to extract learnings from a conversation that should be remembered for future runs.
28
+
29
+ Only extract:
30
+ - Explicit user corrections (e.g., "No, always use bullet points")
31
+ - Stated preferences (e.g., "I prefer concise summaries")
32
+ - Patterns that clearly emerged from user feedback
33
+
34
+ Do NOT extract:
35
+ - General knowledge or facts from the conversation content
36
+ - Inferences or speculation about what the user might want
37
+ - Task-specific details that won't apply to future runs
38
+
39
+ Respond with a JSON array of instruction strings. Each instruction should be a clear, actionable directive.
40
+ If there are no learnings to extract, respond with an empty array: []
41
+
42
+ Example response:
43
+ ["Always use bullet points for lists", "Keep summaries under 3 sentences"]`,tracer:r});if(i.result!==`success`||!i.final){t?.warn(`extraction failed`,{result:i.result}),t?.end();return}let a=O(i.final.content);if(!a){t?.end();return}let o=this.parseInstructions(a);if(o.length===0){t?.info(`no instructions extracted`),t?.end();return}let s=await this.loadStore(e.store,e.name,e.scope);s.instructions.push(...o),await this.saveStore(e.store,e.name,e.scope,s),t?.info(`saved instructions`,{count:o.length}),t?.end()}tools(){if(!this.enableTools)return[];let e=this;return[{name:`add_instruction`,description:`Save a learned instruction for future runs. Use this when the user explicitly asks you to remember something.`,schema:p.object({instruction:p.string().describe(`The instruction to remember`)}),async execute(t){if(!e.lastStore)return`Error: memory not initialized (no recall has been called yet)`;let n=await e.loadStore(e.lastStore,e.lastName,e.lastScope);return n.instructions.push(t.instruction),await e.saveStore(e.lastStore,e.lastName,e.lastScope,n),`Instruction saved: "${t.instruction}"`}}]}formatMessages(e){let t=[];for(let n of e)if(n.role===`user`){let e=typeof n.content==`string`?n.content:O(n.content);e&&t.push(`User: ${e}`)}else if(n.role===`assistant`){let e=O(n.content);e&&t.push(`Assistant: ${e}`)}return t.join(`
44
+
45
+ `)}parseInstructions(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);n&&(t=n[1].trim());try{let e=JSON.parse(t);if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}catch{}return[]}getStorePath(e,t){let n=e??`default`,r=n;if(t&&Object.keys(t).length>0){let e=Object.entries(t).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}=${t}`).join(`&`);r=`${n}-${ee.createHash(`sha256`).update(e).digest(`hex`).slice(0,8)}`}return`memory/procedural/${r}.json`}async loadStore(e,t,n){let r=this.getStorePath(t,n),i=await e.read(r);if(i)try{let e=JSON.parse(i);if(e&&Array.isArray(e.instructions))return{instructions:e.instructions}}catch{}return{instructions:[]}}async saveStore(e,t,n,r){if(!r)return;let i=this.getStorePath(t,n);await e.write(i,JSON.stringify(r,null,2))}};export{ce as C,I as D,R as E,P as O,de as S,V as T,Se as _,Yt as a,pe as b,Kt as c,Rt as d,Ct as f,Be as g,it as h,nn as i,A as k,Vt as l,xt as m,cn as n,Jt as o,St as p,an as r,qt as s,yn as t,Bt as u,ve as v,oe as w,fe as x,he as y};
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{_ as e,a as t,b as n,c as r,d as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,r as f,s as p,t as m,u as h,v as g,y as _}from"./ProceduralMemory-D3JlLSfC.js";import{i as v,s as y,t as b}from"./models-We2CaWSH.js";import{appendFile as x,mkdir as S,readFile as C}from"node:fs/promises";import{basename as w,dirname as T,extname as ee}from"node:path";import{z as E}from"zod";import{glob as te}from"glob";import{createHash as ne}from"node:crypto";import{Command as re}from"@commander-js/extra-typings";import D from"yaml";import{createInterface as ie}from"node:readline";var ae=`0.12.0`;E.object({value:E.string()});const oe=E.object({"api-key":E.string(),rateLimit:E.number().optional()});E.object({timeout:E.number().optional(),maxBuffer:E.number().optional(),cwd:E.string().optional()});const se=E.object({type:E.literal(`chatcompletions`)}).loose(),ce=E.object({type:E.literal(`anthropic`)}).loose(),le=E.object({type:E.literal(`openai`)}).loose(),O=E.object({type:E.literal(`gemini`)}).loose(),k=E.discriminatedUnion(`type`,[se,ce,le,O]),ue=E.object({chatcompletions:E.custom().optional(),anthropic:E.custom().optional(),openai:E.custom().optional(),gemini:E.custom().optional(),brave:oe.optional()}).loose(),de=E.object({transport:E.literal(`stdio`),name:E.string().optional(),command:E.string(),args:E.array(E.string()).optional(),env:E.record(E.string(),E.string()).optional()}),fe=E.object({transport:E.literal(`http`),name:E.string().optional(),url:E.string(),headers:E.record(E.string(),E.string()).optional()}),pe=E.discriminatedUnion(`transport`,[de,fe]),me=E.object({files:E.string(),resume:E.boolean().default(!1),concurrency:E.number().int().positive().default(3)}),A=E.object({name:E.string().optional(),provider:k,task:E.string(),tools:E.array(E.string()).optional(),server_tools:E.array(E.string()).optional(),files:E.array(E.string()).optional(),mcps:E.array(pe).optional(),batch:me.optional()}),j=[`yaml`,`yml`,`json`];async function M(e,t){let{tracer:n}=t,{content:r,format:i,path:a}=await g(e,{defaults:{name:`axle.job`,formats:j},tag:`Job File`}),o=null;if(i===`json`)o=JSON.parse(r);else if(i===`yaml`||i===`yml`)o=D.parse(r);else throw Error(`Invalid job file format`);n?.debug(`Job config: `+JSON.stringify(o,null,2));let s=A.safeParse(o);if(!s.success)throw Error(`The job file is not valid:\n${F(s.error)}`);return s.data.name||(s.data.name=w(a,ee(a))),s.data}const N=[`yaml`,`yml`,`json`];async function P(e,t){let{tracer:n}=t,{content:r,format:i}=await g(e,{defaults:{name:`axle.config`,formats:N},tag:`Config File`}),a=null;if(i===`json`)a=JSON.parse(r);else if(i===`yaml`||i===`yml`)a=D.parse(r);else throw Error(`Invalid config file format`);n?.debug(`Service config: `+JSON.stringify(a,null,2));let o=ue.safeParse(a);if(!o.success)throw Error(`The config file is not valid:\n${F(o.error)}`);return o.data}function F(e){return e.issues.map(e=>` - ${e.path.join(`.`)||`root`}: ${e.message}`).join(`
3
- `)}async function I(e,t){let n=[];for(let r of e){let e=new s(r);await e.connect({tracer:t}),n.push(e)}return n}async function L(e,t){for(let n of e)try{await n.close({tracer:t})}catch{}}const R=`.axle/batch.jsonl`;function z(e,t){let n=ne(`sha256`);return n.update(e),n.update(`\0`),n.update(t),n.digest(`hex`)}async function he(e=R){let t=new Map,n;try{n=await C(e,`utf-8`)}catch{return t}for(let e of n.split(`
4
- `)){let n=e.trim();if(n)try{let e=JSON.parse(n);e.file&&e.hash&&t.set(e.file,e)}catch{}}return t}async function B(e,t=R){await S(T(t),{recursive:!0}),await x(t,JSON.stringify(e)+`
5
- `,`utf-8`)}async function ge(t,r,i,a,o,s,c,l,u,d){let f=new _(t.task);if(t.files)for(let n of t.files)f.addFile(await e(n));let p=u.startSpan(`job`,{type:`workflow`}),m=new n({provider:r,model:i,tools:a,mcps:o,tracer:p,name:t.name,memory:d,options:{strictVariables:!c.allowMissingVars}});try{let e=await m.send(f,{variables:s}).final;if(l.in+=e.usage.in,l.out+=e.usage.out,e.response){let t=typeof e.response==`string`?e.response:JSON.stringify(e.response,null,2);u.info(t,{markdown:!0})}c.interactive&&await _e(m,l,u),p.end()}catch(e){let t=e instanceof Error?e.message:String(e);throw p.error(t),p.end(`error`),e}}async function _e(e,t,n){let r=ie({input:process.stdin,output:process.stdout});r.on(`SIGINT`,()=>{r.close()});let i=e=>new Promise(t=>{r.question(e,t),r.once(`close`,()=>t(null))});try{for(;;){let r=await i(`
6
- > `);if(r===null||r.trim()===``)break;try{let i=await e.send(r.trim()).final;if(t.in+=i.usage.in,t.out+=i.usage.out,i.response){let e=typeof i.response==`string`?i.response:JSON.stringify(i.response,null,2);n.info(e,{markdown:!0})}}catch(e){let t=e instanceof Error?e.message:String(e);n.error(t)}}}finally{r.close()}}async function ve(t,r,i,a,o,s,c,l,u,d){let f=t.batch,p=await te(f.files);if(p.length===0){u.warn(`No files matched pattern: ${f.files}`);return}u.info(`Batch: ${p.length} file(s) matched "${f.files}"`);let m=f.resume?await he():new Map,h=t.files?await Promise.all(t.files.map(t=>e(t))):[],g=0,v=0,y=0;await ye(f.concurrency??3,p,async p=>{let b=u.startSpan(`batch:${p}`,{type:`workflow`});try{let u=await C(p),y=z(t.task,u),x=m.get(p);if(f.resume&&x&&x.hash===y){b.info(`Skipped (already completed)`),b.end(),v++;return}let S=new _(t.task);for(let e of h)S.addFile(e);S.addFile(await e(p));let w={...s,file:p},T=await new n({provider:r,model:i,tools:a,mcps:o,tracer:b,name:t.name,memory:d,options:{strictVariables:!c.allowMissingVars}}).send(S,{variables:w}).final;l.in+=T.usage.in,l.out+=T.usage.out,await B({file:p,hash:y,timestamp:Date.now()}),b.end(),g++}catch(e){let t=e instanceof Error?e.message:String(e);b.error(`Failed: ${t}`),b.end(`error`),y++}}),u.info(`Batch complete: ${g} completed, ${v} skipped, ${y} failed`)}async function ye(e,t,n){let r=0;async function i(){for(;r<t.length;)await n(t[r++])}let a=Array.from({length:Math.min(e,t.length)},()=>i());await Promise.all(a)}function be(e,n){switch(e){case`brave`:{let e=n?.brave;return e&&h.configure(e),h}case`calculator`:return c;case`exec`:{let e=n?.exec;return e&&r.configure(e),r}case`patch-file`:return p;case`read-file`:return d;case`write-file`:return t;default:throw Error(`Unknown tool: ${e}`)}}function xe(e,t){return e.map(e=>be(e,t))}const V=new re().name(`axle`).description(`Axle is a CLI tool for running AI workflows`).version(ae).option(`-c, --config <path>`,`Path to the config file`).option(`-j, --job <path>`,`Path to the job file`).option(`--no-log`,`Do not write the output to a log file`).option(`-d, --debug`,`Print additional debug information`).option(`-i, --interactive`,`Continue the conversation interactively after the initial task`).option(`--args <args...>`,`Additional arguments in the form key=value`).option(`--ignore-warn-unused`,`Don't error on unresolved {{variables}} in task templates`);V.parse(process.argv);const H=V.opts(),U={date:new Date().toISOString().split(`T`)[0],datetime:new Date().toISOString(),cwd:process.cwd()};H.args&&H.args.forEach(e=>{let[t,n]=e.split(`=`);t&&n&&(U[t.trim()]=n.trim())});const W=new f;H.debug&&(W.minLevel=`debug`);const Se=new u({minLevel:H.debug?`debug`:`info`,showInternal:H.debug,showTimestamp:!0,markdown:!0});if(W.addWriter(Se),H.log){let e=new u({minLevel:`debug`,showInternal:!0,showTimestamp:!0,output:e=>{}});W.addWriter(e)}const G=W.startSpan(`cli`,{type:`root`});process.on(`uncaughtException`,async e=>{console.error(`Uncaught exception:`),console.error(e),G.error(`Uncaught exception:`),G.error(e.message),G.error(e.stack||``),G.end(`error`),await W.flush(),process.exit(1)}),H.debug&&(G.debug(`Options: `+JSON.stringify(H,null,2)),G.debug(`Additional Arguments: `+JSON.stringify(U,null,2)));let K,q;try{K=await P(H.config??null,{tracer:G}),q=await M(H.job??null,{tracer:G})}catch(e){let t=e instanceof Error?e:Error(String(e));G.error(t.message),G.debug(t.stack??``),G.end(`error`),await W.flush(),V.outputHelp(),process.exit(1)}let J,Y;try{let{type:e,...t}=q.provider;switch(e){case`openai`:{let e={...K.openai,...t},n=e[`api-key`];if(!n)throw Error(`The provider openai is not configured. Please check your configuration.`);let r={"api-key":n,model:e.model};J=i(r[`api-key`]),Y=r.model||b;break}case`anthropic`:{let e={...K.anthropic,...t},n=e[`api-key`];if(!n)throw Error(`The provider anthropic is not configured. Please check your configuration.`);let r={"api-key":n,model:e.model};J=a(r[`api-key`]),Y=r.model||y;break}case`gemini`:{let e={...K.gemini,...t},n=e[`api-key`];if(!n)throw Error(`The provider gemini is not configured. Please check your configuration.`);let r={"api-key":n,model:e.model};J=l(r[`api-key`]),Y=r.model||v;break}case`chatcompletions`:{let e={...K.chatcompletions,...t},n=e[`base-url`],r=e.model;if(!n||!r)throw Error(`The provider chatcompletions is not configured. Please check your configuration.`);let i={"base-url":n,model:r,"api-key":e[`api-key`]};J=o(i[`base-url`],i[`api-key`]),Y=i.model;break}}}catch(e){let t=e instanceof Error?e:Error(String(e));G.error(t.message),G.error(t.stack??``),G.end(`error`),await W.flush(),V.outputHelp(),process.exit(1)}G.info(`All systems operational. Running job...`);const X=new m({provider:J,model:Y}),Ce=(q.server_tools??[]).map(e=>({type:`server`,name:e})),Z=[...q.tools?.length?xe(q.tools):[],...Ce];let Q=[];if(q.mcps?.length)try{Q=await I(q.mcps,G)}catch(e){let t=e instanceof Error?e:Error(String(e));G.error(`Failed to connect MCP servers: `+t.message),G.end(`error`),await W.flush(),process.exit(1)}const $={in:0,out:0},we=performance.now();try{q.batch?await ve(q,J,Y,Z,Q,U,H,$,G,X):await ge(q,J,Y,Z,Q,U,H,$,G,X)}catch(e){let t=e instanceof Error?e:Error(String(e));G.error(t.message),G.debug(t.stack??``)}finally{Q.length>0&&await L(Q,G)}const Te=performance.now()-we;G.info(`Total run time: ${Math.round(Te)}ms`),G.info(`Input tokens: ${$.in}`),G.info(`Output tokens: ${$.out}`),G.info(`Complete. Goodbye`),G.end(),await W.flush();export{};
2
+ import{_ as e,a as t,b as n,c as r,d as i,g as a,h as o,i as s,l as c,m as l,n as u,o as d,r as f,s as p,t as m,u as h,v as g,y as _}from"./ProceduralMemory-ChCjb9PW.js";import{i as v,s as y,t as b}from"./models-DlE4tfcj.js";import{appendFile as x,mkdir as S,readFile as C}from"node:fs/promises";import{basename as w,dirname as T,extname as E}from"node:path";import{z as D}from"zod";import{glob as ee}from"glob";import{createHash as O}from"node:crypto";import{Command as k}from"@commander-js/extra-typings";import A from"yaml";import{createInterface as te}from"node:readline";var ne=`0.13.0`;D.object({value:D.string()});const re=D.object({"api-key":D.string(),rateLimit:D.number().optional()});D.object({timeout:D.number().optional(),maxBuffer:D.number().optional(),cwd:D.string().optional()});const ie=D.object({type:D.literal(`chatcompletions`)}).loose(),ae=D.object({type:D.literal(`anthropic`)}).loose(),oe=D.object({type:D.literal(`openai`)}).loose(),se=D.object({type:D.literal(`gemini`)}).loose(),ce=D.discriminatedUnion(`type`,[ie,ae,oe,se]),le=D.object({chatcompletions:D.custom().optional(),anthropic:D.custom().optional(),openai:D.custom().optional(),gemini:D.custom().optional(),brave:re.optional()}).loose(),ue=D.object({transport:D.literal(`stdio`),name:D.string().optional(),command:D.string(),args:D.array(D.string()).optional(),env:D.record(D.string(),D.string()).optional()}),de=D.object({transport:D.literal(`http`),name:D.string().optional(),url:D.string(),headers:D.record(D.string(),D.string()).optional()}),fe=D.discriminatedUnion(`transport`,[ue,de]),pe=D.object({files:D.string(),resume:D.boolean().default(!1),concurrency:D.number().int().positive().default(3)}),me=D.object({name:D.string().optional(),provider:ce,task:D.string(),tools:D.array(D.string()).optional(),provider_tools:D.array(D.string()).optional(),files:D.array(D.string()).optional(),mcps:D.array(fe).optional(),batch:pe.optional()}),he=[`yaml`,`yml`,`json`];async function j(e,t){let{tracer:n}=t,{content:r,format:i,path:a}=await g(e,{defaults:{name:`axle.job`,formats:he},tag:`Job File`}),o=null;if(i===`json`)o=JSON.parse(r);else if(i===`yaml`||i===`yml`)o=A.parse(r);else throw Error(`Invalid job file format`);n?.debug(`Job config: `+JSON.stringify(o,null,2));let s=me.safeParse(o);if(!s.success)throw Error(`The job file is not valid:\n${P(s.error)}`);return s.data.name||(s.data.name=w(a,E(a))),s.data}const M=[`yaml`,`yml`,`json`];async function N(e,t){let{tracer:n}=t,{content:r,format:i}=await g(e,{defaults:{name:`axle.config`,formats:M},tag:`Config File`}),a=null;if(i===`json`)a=JSON.parse(r);else if(i===`yaml`||i===`yml`)a=A.parse(r);else throw Error(`Invalid config file format`);n?.debug(`Service config: `+JSON.stringify(a,null,2));let o=le.safeParse(a);if(!o.success)throw Error(`The config file is not valid:\n${P(o.error)}`);return o.data}function P(e){return e.issues.map(e=>` - ${e.path.join(`.`)||`root`}: ${e.message}`).join(`
3
+ `)}async function F(e,t){let n=[];for(let r of e){let e=new s(r);await e.connect({tracer:t}),n.push(e)}return n}async function I(e,t){for(let n of e)try{await n.close({tracer:t})}catch{}}const L=`.axle/batch.jsonl`;function R(e,t){let n=O(`sha256`);return n.update(e),n.update(`\0`),n.update(t),n.digest(`hex`)}async function ge(e=L){let t=new Map,n;try{n=await C(e,`utf-8`)}catch{return t}for(let e of n.split(`
4
+ `)){let n=e.trim();if(n)try{let e=JSON.parse(n);e.file&&e.hash&&t.set(e.file,e)}catch{}}return t}async function _e(e,t=L){await S(T(t),{recursive:!0}),await x(t,JSON.stringify(e)+`
5
+ `,`utf-8`)}async function ve(t,r,i,a,o,s,c,l,u,d,f){let p=new _(t.task);if(t.files)for(let n of t.files)p.addFile(await e(n));let m=d.startSpan(`job`,{type:`workflow`}),h=new n({provider:r,model:i,tools:a,providerTools:o,mcps:s,tracer:m,name:t.name,memory:f,options:{strictVariables:!l.allowMissingVars}});try{let e=await h.send(p,{variables:c}).final;if(u.in+=e.usage.in,u.out+=e.usage.out,e.response){let t=typeof e.response==`string`?e.response:JSON.stringify(e.response,null,2);d.info(t,{markdown:!0})}l.interactive&&await ye(h,u,d),m.end()}catch(e){let t=e instanceof Error?e.message:String(e);throw m.error(t),m.end(`error`),e}}async function ye(e,t,n){let r=te({input:process.stdin,output:process.stdout});r.on(`SIGINT`,()=>{r.close()});let i=e=>new Promise(t=>{r.question(e,t),r.once(`close`,()=>t(null))});try{for(;;){let r=await i(`
6
+ > `);if(r===null||r.trim()===``)break;try{let i=await e.send(r.trim()).final;if(t.in+=i.usage.in,t.out+=i.usage.out,i.response){let e=typeof i.response==`string`?i.response:JSON.stringify(i.response,null,2);n.info(e,{markdown:!0})}}catch(e){let t=e instanceof Error?e.message:String(e);n.error(t)}}}finally{r.close()}}async function be(t,r,i,a,o,s,c,l,u,d,f){let p=t.batch,m=await ee(p.files);if(m.length===0){d.warn(`No files matched pattern: ${p.files}`);return}d.info(`Batch: ${m.length} file(s) matched "${p.files}"`);let h=p.resume?await ge():new Map,g=t.files?await Promise.all(t.files.map(t=>e(t))):[],v=0,y=0,b=0;await xe(p.concurrency??3,m,async m=>{let x=d.startSpan(`batch:${m}`,{type:`workflow`});try{let d=await C(m),b=R(t.task,d),S=h.get(m);if(p.resume&&S&&S.hash===b){x.info(`Skipped (already completed)`),x.end(),y++;return}let w=new _(t.task);for(let e of g)w.addFile(e);w.addFile(await e(m));let T={...c,file:m},E=await new n({provider:r,model:i,tools:a,providerTools:o,mcps:s,tracer:x,name:t.name,memory:f,options:{strictVariables:!l.allowMissingVars}}).send(w,{variables:T}).final;u.in+=E.usage.in,u.out+=E.usage.out,await _e({file:m,hash:b,timestamp:Date.now()}),x.end(),v++}catch(e){let t=e instanceof Error?e.message:String(e);x.error(`Failed: ${t}`),x.end(`error`),b++}}),d.info(`Batch complete: ${v} completed, ${y} skipped, ${b} failed`)}async function xe(e,t,n){let r=0;async function i(){for(;r<t.length;)await n(t[r++])}let a=Array.from({length:Math.min(e,t.length)},()=>i());await Promise.all(a)}function Se(e,n){switch(e){case`brave`:{let e=n?.brave;return e&&h.configure(e),h}case`calculator`:return c;case`exec`:{let e=n?.exec;return e&&r.configure(e),r}case`patch-file`:return p;case`read-file`:return d;case`write-file`:return t;default:throw Error(`Unknown tool: ${e}`)}}function Ce(e,t){return e.map(e=>Se(e,t))}const z=new k().name(`axle`).description(`Axle is a CLI tool for running AI workflows`).version(ne).option(`-c, --config <path>`,`Path to the config file`).option(`-j, --job <path>`,`Path to the job file`).option(`--no-log`,`Do not write the output to a log file`).option(`-d, --debug`,`Print additional debug information`).option(`-i, --interactive`,`Continue the conversation interactively after the initial task`).option(`--args <args...>`,`Additional arguments in the form key=value`).option(`--ignore-warn-unused`,`Don't error on unresolved {{variables}} in task templates`);z.parse(process.argv);const B=z.opts(),V={date:new Date().toISOString().split(`T`)[0],datetime:new Date().toISOString(),cwd:process.cwd()};B.args&&B.args.forEach(e=>{let[t,n]=e.split(`=`);t&&n&&(V[t.trim()]=n.trim())});const H=new f;B.debug&&(H.minLevel=`debug`);const U=new u({minLevel:B.debug?`debug`:`info`,showInternal:B.debug,showTimestamp:!0,markdown:!0});if(H.addWriter(U),B.log){let e=new u({minLevel:`debug`,showInternal:!0,showTimestamp:!0,output:e=>{}});H.addWriter(e)}const W=H.startSpan(`cli`,{type:`root`});process.on(`uncaughtException`,async e=>{console.error(`Uncaught exception:`),console.error(e),W.error(`Uncaught exception:`),W.error(e.message),W.error(e.stack||``),W.end(`error`),await H.flush(),process.exit(1)}),B.debug&&(W.debug(`Options: `+JSON.stringify(B,null,2)),W.debug(`Additional Arguments: `+JSON.stringify(V,null,2)));let G,K;try{G=await N(B.config??null,{tracer:W}),K=await j(B.job??null,{tracer:W})}catch(e){let t=e instanceof Error?e:Error(String(e));W.error(t.message),W.debug(t.stack??``),W.end(`error`),await H.flush(),z.outputHelp(),process.exit(1)}let q,J;try{let{type:e,...t}=K.provider;switch(e){case`openai`:{let e={...G.openai,...t},n=e[`api-key`];if(!n)throw Error(`The provider openai is not configured. Please check your configuration.`);let r={"api-key":n,model:e.model};q=i(r[`api-key`]),J=r.model||b;break}case`anthropic`:{let e={...G.anthropic,...t},n=e[`api-key`];if(!n)throw Error(`The provider anthropic is not configured. Please check your configuration.`);let r={"api-key":n,model:e.model};q=a(r[`api-key`]),J=r.model||y;break}case`gemini`:{let e={...G.gemini,...t},n=e[`api-key`];if(!n)throw Error(`The provider gemini is not configured. Please check your configuration.`);let r={"api-key":n,model:e.model};q=l(r[`api-key`]),J=r.model||v;break}case`chatcompletions`:{let e={...G.chatcompletions,...t},n=e[`base-url`],r=e.model;if(!n||!r)throw Error(`The provider chatcompletions is not configured. Please check your configuration.`);let i={"base-url":n,model:r,"api-key":e[`api-key`]};q=o(i[`base-url`],i[`api-key`]),J=i.model;break}}}catch(e){let t=e instanceof Error?e:Error(String(e));W.error(t.message),W.error(t.stack??``),W.end(`error`),await H.flush(),z.outputHelp(),process.exit(1)}W.info(`All systems operational. Running job...`);const Y=new m({provider:q,model:J}),X=(K.provider_tools??[]).map(e=>({type:`provider`,name:e})),Z=K.tools?.length?Ce(K.tools):[];let Q=[];if(K.mcps?.length)try{Q=await F(K.mcps,W)}catch(e){let t=e instanceof Error?e:Error(String(e));W.error(`Failed to connect MCP servers: `+t.message),W.end(`error`),await H.flush(),process.exit(1)}const $={in:0,out:0},we=performance.now();try{K.batch?await be(K,q,J,Z,X,Q,V,B,$,W,Y):await ve(K,q,J,Z,X,Q,V,B,$,W,Y)}catch(e){let t=e instanceof Error?e:Error(String(e));W.error(t.message),W.debug(t.stack??``)}finally{Q.length>0&&await I(Q,W)}const Te=performance.now()-we;W.info(`Total run time: ${Math.round(Te)}ms`),W.info(`Input tokens: ${$.in}`),W.info(`Output tokens: ${$.out}`),W.info(`Complete. Goodbye`),W.end(),await H.flush();export{};
package/dist/index.d.ts CHANGED
@@ -9,7 +9,7 @@ interface Stats {
9
9
  //#endregion
10
10
  //#region src/messages/stream.d.ts
11
11
  interface StreamChunk {
12
- type: "start" | "text-start" | "text-delta" | "text-complete" | "tool-call-start" | "tool-call-complete" | "thinking-start" | "thinking-delta" | "thinking-summary-delta" | "thinking-complete" | "internal-tool-start" | "internal-tool-complete" | "complete" | "error";
12
+ type: "start" | "text-start" | "text-delta" | "text-complete" | "tool-call-start" | "tool-call-args-delta" | "tool-call-complete" | "thinking-start" | "thinking-delta" | "thinking-summary-delta" | "thinking-complete" | "provider-tool-start" | "provider-tool-complete" | "complete" | "error";
13
13
  id?: string;
14
14
  data?: any;
15
15
  }
@@ -93,6 +93,16 @@ interface StreamToolCallStartChunk extends StreamChunk {
93
93
  name: string;
94
94
  };
95
95
  }
96
+ interface StreamToolCallArgsDeltaChunk extends StreamChunk {
97
+ type: "tool-call-args-delta";
98
+ data: {
99
+ index: number;
100
+ id: string;
101
+ name: string;
102
+ delta: string;
103
+ accumulated: string;
104
+ };
105
+ }
96
106
  interface StreamToolCallCompleteChunk extends StreamChunk {
97
107
  type: "tool-call-complete";
98
108
  data: {
@@ -103,16 +113,16 @@ interface StreamToolCallCompleteChunk extends StreamChunk {
103
113
  providerMetadata?: Record<string, unknown>;
104
114
  };
105
115
  }
106
- interface StreamInternalToolStartChunk extends StreamChunk {
107
- type: "internal-tool-start";
116
+ interface StreamProviderToolStartChunk extends StreamChunk {
117
+ type: "provider-tool-start";
108
118
  data: {
109
119
  index: number;
110
120
  id: string;
111
121
  name: string;
112
122
  };
113
123
  }
114
- interface StreamInternalToolCompleteChunk extends StreamChunk {
115
- type: "internal-tool-complete";
124
+ interface StreamProviderToolCompleteChunk extends StreamChunk {
125
+ type: "provider-tool-complete";
116
126
  data: {
117
127
  index: number;
118
128
  id: string;
@@ -120,7 +130,7 @@ interface StreamInternalToolCompleteChunk extends StreamChunk {
120
130
  output?: unknown;
121
131
  };
122
132
  }
123
- type AnyStreamChunk = StreamStartChunk | StreamCompleteChunk | StreamErrorChunk | StreamTextStartChunk | StreamTextDeltaChunk | StreamTextCompleteChunk | StreamThinkingStartChunk | StreamThinkingDeltaChunk | StreamThinkingSummaryDeltaChunk | StreamThinkingCompleteChunk | StreamToolCallStartChunk | StreamToolCallCompleteChunk | StreamInternalToolStartChunk | StreamInternalToolCompleteChunk;
133
+ type AnyStreamChunk = StreamStartChunk | StreamCompleteChunk | StreamErrorChunk | StreamTextStartChunk | StreamTextDeltaChunk | StreamTextCompleteChunk | StreamThinkingStartChunk | StreamThinkingDeltaChunk | StreamThinkingSummaryDeltaChunk | StreamThinkingCompleteChunk | StreamToolCallStartChunk | StreamToolCallArgsDeltaChunk | StreamToolCallCompleteChunk | StreamProviderToolStartChunk | StreamProviderToolCompleteChunk;
124
134
  //#endregion
125
135
  //#region src/tracer/types.d.ts
126
136
  type SpanStatus = "ok" | "error";
@@ -385,7 +395,7 @@ interface AxleAssistantMessage {
385
395
  role: "assistant";
386
396
  id: string;
387
397
  model?: string;
388
- content: Array<ContentPartText | ContentPartThinking | ContentPartToolCall | ContentPartInternalTool>;
398
+ content: Array<ContentPartText | ContentPartThinking | ContentPartToolCall | ContentPartProviderTool>;
389
399
  finishReason?: AxleStopReason;
390
400
  }
391
401
  interface AxleToolCallMessage {
@@ -399,7 +409,7 @@ interface AxleToolCallResult {
399
409
  content: string | ToolResultPart[];
400
410
  isError?: boolean;
401
411
  }
402
- type ContentPart = ContentPartText | ContentPartFile | ContentPartToolCall | ContentPartThinking | ContentPartInternalTool;
412
+ type ContentPart = ContentPartText | ContentPartFile | ContentPartToolCall | ContentPartThinking | ContentPartProviderTool;
403
413
  interface ContentPartText {
404
414
  type: "text";
405
415
  text: string;
@@ -424,30 +434,56 @@ interface ContentPartToolCall {
424
434
  parameters: Record<string, unknown>;
425
435
  providerMetadata?: Record<string, unknown>;
426
436
  }
427
- interface ContentPartInternalTool {
428
- type: "internal-tool";
437
+ interface ContentPartProviderTool {
438
+ type: "provider-tool";
429
439
  id: string;
430
440
  name: string;
431
441
  input?: unknown;
432
442
  output?: unknown;
433
443
  }
434
444
  //#endregion
445
+ //#region src/tools/registry.d.ts
446
+ declare class ToolRegistry {
447
+ private executableTools;
448
+ private providerTools;
449
+ constructor(init?: {
450
+ tools?: ExecutableTool[];
451
+ providerTools?: ProviderTool[];
452
+ });
453
+ add(tool: ExecutableTool): void;
454
+ add(tools: ExecutableTool[]): void;
455
+ addProvider(tool: ProviderTool): void;
456
+ addProvider(tools: ProviderTool[]): void;
457
+ remove(name: string): boolean;
458
+ has(name: string): boolean;
459
+ get(name: string): ExecutableTool | undefined;
460
+ getProvider(name: string): ProviderTool | undefined;
461
+ executable(): ExecutableTool[];
462
+ provider(): ProviderTool[];
463
+ get size(): number;
464
+ }
465
+ //#endregion
435
466
  //#region src/tools/types.d.ts
467
+ interface ToolContext {
468
+ registry: ToolRegistry;
469
+ signal: AbortSignal;
470
+ emit: (chunk: string) => void;
471
+ tracer?: TracingContext;
472
+ }
436
473
  interface ExecutableTool<TSchema extends ZodObject<any> = ZodObject<any>> {
437
474
  type?: "function";
438
475
  name: string;
439
476
  description: string;
440
477
  schema: TSchema;
441
- execute(input: z.infer<TSchema>): Promise<string | ToolResultPart[]>;
478
+ execute(input: z.infer<TSchema>, ctx: ToolContext): Promise<string | ToolResultPart[]>;
442
479
  configure?(config: Record<string, any>): void;
443
480
  summarize?(input: z.infer<TSchema>): string;
444
481
  }
445
- interface ServerTool {
446
- type: "server";
482
+ interface ProviderTool {
483
+ type: "provider";
447
484
  name: string;
448
485
  config?: Record<string, unknown>;
449
486
  }
450
- type AxleTool = ExecutableTool | ServerTool;
451
487
  type ToolDefinition = Pick<ExecutableTool, "name" | "description" | "schema">;
452
488
  //#endregion
453
489
  //#region src/mcp/MCP.d.ts
@@ -565,6 +601,7 @@ interface ToolAction extends ActionPartBase {
565
601
  detail: {
566
602
  name: string;
567
603
  parameters: Record<string, unknown>;
604
+ pendingArgs?: string;
568
605
  result?: ActionResult;
569
606
  };
570
607
  }
@@ -577,16 +614,19 @@ interface SubagentAction extends ActionPartBase {
577
614
  result?: ActionResult;
578
615
  };
579
616
  }
580
- interface InternalToolAction extends ActionPartBase {
581
- kind: "internal-tool";
617
+ interface ProviderToolAction extends ActionPartBase {
618
+ kind: "provider-tool";
582
619
  detail: {
583
620
  name: string;
584
621
  input?: unknown;
585
622
  result?: ActionResult;
586
623
  };
587
624
  }
588
- type ActionPart = ToolAction | SubagentAction | InternalToolAction;
625
+ type ActionPart = ToolAction | SubagentAction | ProviderToolAction;
589
626
  type ActionResult = {
627
+ type: "in-progress";
628
+ content: string;
629
+ } | {
590
630
  type: "success";
591
631
  content: unknown;
592
632
  } | {
@@ -633,11 +673,22 @@ type AgentEvent = {
633
673
  turnId: string;
634
674
  partId: string;
635
675
  timing?: TimingInfo;
676
+ } | {
677
+ type: "action:args-delta";
678
+ turnId: string;
679
+ partId: string;
680
+ delta: string;
681
+ accumulated: string;
636
682
  } | {
637
683
  type: "action:running";
638
684
  turnId: string;
639
685
  partId: string;
640
686
  parameters?: Record<string, unknown>;
687
+ } | {
688
+ type: "action:progress";
689
+ turnId: string;
690
+ partId: string;
691
+ chunk: string;
641
692
  } | {
642
693
  type: "action:complete";
643
694
  turnId: string;
@@ -730,7 +781,8 @@ interface AgentConfig {
730
781
  system?: string;
731
782
  name?: string;
732
783
  scope?: Record<string, string>;
733
- tools?: AxleTool[];
784
+ tools?: ExecutableTool[];
785
+ providerTools?: ProviderTool[];
734
786
  mcps?: MCP[];
735
787
  memory?: AgentMemory;
736
788
  tracer?: TracingContext;
@@ -763,18 +815,15 @@ declare class Agent {
763
815
  readonly store: FileStore;
764
816
  readonly fileResolver?: FileResolver;
765
817
  readonly reasoning?: boolean;
818
+ readonly registry: ToolRegistry;
766
819
  system: string | undefined;
767
- tools: Record<string, ExecutableTool>;
768
- serverTools: ServerTool[];
769
820
  private mcps;
770
- private mcpToolsResolved;
821
+ private resolvedMcps;
771
822
  private memory?;
772
823
  private options;
773
824
  private eventCallbacks;
774
825
  private sendQueue;
775
826
  constructor(config: AgentConfig);
776
- addTool(tool: AxleTool): void;
777
- addTools(tools: AxleTool[]): void;
778
827
  addMcp(mcp: MCP): void;
779
828
  addMcps(mcps: MCP[]): void;
780
829
  hasTools(): boolean;
@@ -828,10 +877,14 @@ declare function gemini(apiKey: string): AIProvider;
828
877
  declare const Gemini: {
829
878
  readonly Models: {
830
879
  readonly GEMINI_3_1_PRO_PREVIEW: "gemini-3.1-pro-preview";
880
+ readonly GEMINI_3_1_PRO: "gemini-3.1-pro-preview";
831
881
  readonly GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS: "gemini-3.1-pro-preview-customtools";
832
882
  readonly GEMINI_3_1_FLASH_LITE_PREVIEW: "gemini-3.1-flash-lite-preview";
883
+ readonly GEMINI_3_1_FLASH_LITE: "gemini-3.1-flash-lite-preview";
833
884
  readonly GEMINI_3_PRO_PREVIEW: "gemini-3-pro-preview";
885
+ readonly GEMINI_3_PRO: "gemini-3-pro-preview";
834
886
  readonly GEMINI_3_FLASH_PREVIEW: "gemini-3-flash-preview";
887
+ readonly GEMINI_3_FLASH: "gemini-3-flash-preview";
835
888
  readonly GEMINI_2_5_PRO: "gemini-2.5-pro";
836
889
  readonly GEMINI_2_5_FLASH: "gemini-2.5-flash";
837
890
  readonly GEMINI_2_5_FLASH_LITE: "gemini-2.5-flash-lite";
@@ -842,14 +895,6 @@ declare const Gemini: {
842
895
  readonly GEMINI_FLASH_LATEST: "gemini-flash-latest";
843
896
  readonly GEMINI_FLASH_LITE_LATEST: "gemini-flash-lite-latest";
844
897
  readonly GEMINI_PRO_LATEST: "gemini-pro-latest";
845
- readonly GEMMA_4_31B_IT: "gemma-4-31b-it";
846
- readonly GEMMA_4_E4B_IT: "gemma-4-26b-a4b-it";
847
- readonly GEMMA_3_27B_IT: "gemma-3-27b-it";
848
- readonly GEMMA_3_12B_IT: "gemma-3-12b-it";
849
- readonly GEMMA_3_4B_IT: "gemma-3-4b-it";
850
- readonly GEMMA_3_1B_IT: "gemma-3-1b-it";
851
- readonly GEMMA_3N_E4B_IT: "gemma-3n-e4b-it";
852
- readonly GEMMA_3N_E2B_IT: "gemma-3n-e2b-it";
853
898
  };
854
899
  readonly DefaultModel: "gemini-3.1-flash-lite-preview";
855
900
  };
@@ -867,7 +912,7 @@ type ToolCallResult = {
867
912
  retryable?: boolean;
868
913
  };
869
914
  };
870
- type ToolCallCallback = (name: string, parameters: Record<string, unknown>) => Promise<ToolCallResult | null | undefined>;
915
+ type ToolCallCallback = (name: string, parameters: Record<string, unknown>, ctx: ToolContext) => Promise<ToolCallResult | null | undefined>;
871
916
  type GenerateError = {
872
917
  type: "model";
873
918
  error: ModelError;
@@ -916,13 +961,16 @@ interface GenerateOptions {
916
961
  model: string;
917
962
  messages: Array<AxleMessage>;
918
963
  system?: string;
919
- tools?: Array<ToolDefinition>;
964
+ tools?: ExecutableTool[];
965
+ providerTools?: ProviderTool[];
966
+ registry?: ToolRegistry;
920
967
  onToolCall?: ToolCallCallback;
921
968
  maxIterations?: number;
922
969
  tracer?: TracingContext;
923
970
  fileResolver?: FileResolver;
924
971
  options?: GenerateTurnOptions;
925
972
  reasoning?: boolean;
973
+ signal?: AbortSignal;
926
974
  }
927
975
  declare function generate(options: GenerateOptions): Promise<GenerateResult>;
928
976
  //#endregion
@@ -970,12 +1018,25 @@ type StreamEvent = {
970
1018
  index: number;
971
1019
  id: string;
972
1020
  name: string;
1021
+ } | {
1022
+ type: "tool:args-delta";
1023
+ index: number;
1024
+ id: string;
1025
+ name: string;
1026
+ delta: string;
1027
+ accumulated: string;
973
1028
  } | {
974
1029
  type: "tool:exec-start";
975
1030
  index: number;
976
1031
  id: string;
977
1032
  name: string;
978
1033
  parameters: Record<string, unknown>;
1034
+ } | {
1035
+ type: "tool:exec-delta";
1036
+ index: number;
1037
+ id: string;
1038
+ name: string;
1039
+ chunk: string;
979
1040
  } | {
980
1041
  type: "tool:exec-complete";
981
1042
  index: number;
@@ -983,12 +1044,12 @@ type StreamEvent = {
983
1044
  name: string;
984
1045
  result: ToolCallResult;
985
1046
  } | {
986
- type: "internal-tool:start";
1047
+ type: "provider-tool:start";
987
1048
  index: number;
988
1049
  id: string;
989
1050
  name: string;
990
1051
  } | {
991
- type: "internal-tool:complete";
1052
+ type: "provider-tool:complete";
992
1053
  index: number;
993
1054
  id: string;
994
1055
  name: string;
@@ -1003,8 +1064,9 @@ interface StreamOptions {
1003
1064
  model: string;
1004
1065
  messages: Array<AxleMessage>;
1005
1066
  system?: string;
1006
- tools?: Array<ToolDefinition>;
1007
- serverTools?: Array<ServerTool>;
1067
+ tools?: ExecutableTool[];
1068
+ providerTools?: ProviderTool[];
1069
+ registry?: ToolRegistry;
1008
1070
  onToolCall?: ToolCallCallback;
1009
1071
  maxIterations?: number;
1010
1072
  tracer?: TracingContext;
@@ -1063,8 +1125,6 @@ declare const OpenAI: {
1063
1125
  readonly GPT_4_1_NANO_2025_04_14: "gpt-4.1-nano-2025-04-14";
1064
1126
  readonly GPT_4_1_NANO: "gpt-4.1-nano";
1065
1127
  readonly GPT_4O_2024_11_20: "gpt-4o-2024-11-20";
1066
- readonly GPT_4O_2024_08_06: "gpt-4o-2024-08-06";
1067
- readonly GPT_4O_2024_05_13: "gpt-4o-2024-05-13";
1068
1128
  readonly GPT_4O: "gpt-4o";
1069
1129
  readonly GPT_4O_MINI_2024_07_18: "gpt-4o-mini-2024-07-18";
1070
1130
  readonly GPT_4O_MINI: "gpt-4o-mini";
@@ -1076,10 +1136,6 @@ declare const OpenAI: {
1076
1136
  readonly O3_PRO: "o3-pro";
1077
1137
  readonly O3_MINI_2025_01_31: "o3-mini-2025-01-31";
1078
1138
  readonly O3_MINI: "o3-mini";
1079
- readonly O1_2024_12_17: "o1-2024-12-17";
1080
- readonly O1: "o1";
1081
- readonly O1_PRO_2025_03_19: "o1-pro-2025-03-19";
1082
- readonly O1_PRO: "o1-pro";
1083
1139
  };
1084
1140
  readonly DefaultModel: "gpt-5.4-mini";
1085
1141
  };
@@ -1090,6 +1146,12 @@ declare const BraveProviderConfigSchema: z.ZodObject<{
1090
1146
  rateLimit: z.ZodOptional<z.ZodNumber>;
1091
1147
  }, z.core.$strip>;
1092
1148
  type BraveProviderConfig = z.infer<typeof BraveProviderConfigSchema>;
1149
+ declare const ExecProviderConfigSchema: z.ZodObject<{
1150
+ timeout: z.ZodOptional<z.ZodNumber>;
1151
+ maxBuffer: z.ZodOptional<z.ZodNumber>;
1152
+ cwd: z.ZodOptional<z.ZodString>;
1153
+ }, z.core.$strip>;
1154
+ type ExecProviderConfig = z.infer<typeof ExecProviderConfigSchema>;
1093
1155
  //#endregion
1094
1156
  //#region src/tools/brave.d.ts
1095
1157
  declare const braveSearchSchema: z$2.ZodObject<{
@@ -1106,7 +1168,7 @@ declare class BraveSearchTool implements ExecutableTool<typeof braveSearchSchema
1106
1168
  lastExecTime: number;
1107
1169
  constructor(config?: BraveProviderConfig);
1108
1170
  configure(config: BraveProviderConfig): void;
1109
- execute(params: z$2.infer<typeof braveSearchSchema>): Promise<string>;
1171
+ execute(params: z$2.infer<typeof braveSearchSchema>, _ctx: ToolContext): Promise<string>;
1110
1172
  }
1111
1173
  declare const braveSearchTool: BraveSearchTool;
1112
1174
  //#endregion
@@ -1123,6 +1185,49 @@ declare const calculatorSchema: z.ZodObject<{
1123
1185
  }, z.core.$strip>;
1124
1186
  declare const calculatorTool: ExecutableTool<typeof calculatorSchema>;
1125
1187
  //#endregion
1188
+ //#region src/tools/exec/index.d.ts
1189
+ declare const execSchema: z$2.ZodObject<{
1190
+ command: z$2.ZodString;
1191
+ }, z$2.core.$strip>;
1192
+ declare class ExecTool implements ExecutableTool<typeof execSchema> {
1193
+ name: string;
1194
+ description: string;
1195
+ schema: z$2.ZodObject<{
1196
+ command: z$2.ZodString;
1197
+ }, z$2.core.$strip>;
1198
+ private timeout;
1199
+ private maxBuffer;
1200
+ private cwd?;
1201
+ constructor(config?: ExecProviderConfig);
1202
+ configure(config: ExecProviderConfig): void;
1203
+ summarize(params: z$2.infer<typeof execSchema>): string;
1204
+ execute(params: z$2.infer<typeof execSchema>, ctx: ToolContext): Promise<string>;
1205
+ }
1206
+ declare const execTool: ExecTool;
1207
+ //#endregion
1208
+ //#region src/tools/patch-file.d.ts
1209
+ declare const patchFileSchema: z.ZodObject<{
1210
+ path: z.ZodString;
1211
+ old_string: z.ZodString;
1212
+ new_string: z.ZodString;
1213
+ start_line: z.ZodNumber;
1214
+ end_line: z.ZodNumber;
1215
+ }, z.core.$strip>;
1216
+ declare const patchFileTool: ExecutableTool<typeof patchFileSchema>;
1217
+ //#endregion
1218
+ //#region src/tools/read-file.d.ts
1219
+ declare const readFileSchema: z.ZodObject<{
1220
+ path: z.ZodString;
1221
+ }, z.core.$strip>;
1222
+ declare const readFileTool: ExecutableTool<typeof readFileSchema>;
1223
+ //#endregion
1224
+ //#region src/tools/write-file.d.ts
1225
+ declare const writeFileSchema: z.ZodObject<{
1226
+ path: z.ZodString;
1227
+ content: z.ZodString;
1228
+ }, z.core.$strip>;
1229
+ declare const writeFileTool: ExecutableTool<typeof writeFileSchema>;
1230
+ //#endregion
1126
1231
  //#region src/turns/builder.d.ts
1127
1232
  declare class TurnBuilder {
1128
1233
  private currentTurn;
@@ -1251,4 +1356,4 @@ declare class LocalFileStore implements FileStore {
1251
1356
  write(path: string, content: string): Promise<void>;
1252
1357
  }
1253
1358
  //#endregion
1254
- export { type AIProvider, type ActionPart, type ActionResult, Agent, type AgentConfig, type AgentEvent, type AgentEventCallback, type AgentHandle, type AgentMemory, type AgentResult, Anthropic, type AxleAssistantMessage, type AxleMessage, AxleStopReason, type AxleTool, type AxleToolCallMessage, type AxleToolCallResult, type AxleUserMessage, type ContentPart, type ContentPartFile, type ContentPartInternalTool, type ContentPartText, type ContentPartThinking, type ContentPartToolCall, type DeferredFileInfo, type EventLevel, type ExecutableTool, type FileInfo, type FileKind, type FilePart, type FileProviderId, type FileResolveFormat, type FileResolveRequest, type FileResolver, type FileStore, Gemini, type Handle, History, Instruct, type InternalToolAction, LocalFileStore, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MemoryContext, OpenAI, ProceduralMemory, type ProceduralMemoryConfig, type RecallResult, type ResolvedFileSource, type SendInstructOptions, type SendMessageOptions, type ServerTool, SimpleWriter, type SimpleWriterOptions, type SpanData, type SpanOptions, type SpanType, type StreamEvent, type StreamEventCallback, type StreamHandle, type StreamResult, type SubagentAction, type TextPart, type ThinkingPart, type ToolAction, type ToolDefinition, type ToolResultPart, type TraceWriter, Tracer, type TracingContext, type Turn, TurnBuilder, type TurnPart, type TurnStatus, anthropic, braveSearchTool, calculatorTool, chatCompletions, compileInstruct, createHandle, gemini, generate, generateTurn, loadFileContent, openai, parseResponse, stream };
1359
+ export { type AIProvider, type ActionPart, type ActionResult, Agent, type AgentConfig, type AgentEvent, type AgentEventCallback, type AgentHandle, type AgentMemory, type AgentResult, Anthropic, type AxleAssistantMessage, type AxleMessage, AxleStopReason, type AxleToolCallMessage, type AxleToolCallResult, type AxleUserMessage, type ContentPart, type ContentPartFile, type ContentPartProviderTool, type ContentPartText, type ContentPartThinking, type ContentPartToolCall, type DeferredFileInfo, type EventLevel, type ExecutableTool, type FileInfo, type FileKind, type FilePart, type FileProviderId, type FileResolveFormat, type FileResolveRequest, type FileResolver, type FileStore, Gemini, type Handle, History, Instruct, LocalFileStore, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MemoryContext, OpenAI, ProceduralMemory, type ProceduralMemoryConfig, type ProviderTool, type ProviderToolAction, type RecallResult, type ResolvedFileSource, type SendInstructOptions, type SendMessageOptions, SimpleWriter, type SimpleWriterOptions, type SpanData, type SpanOptions, type SpanType, type StreamEvent, type StreamEventCallback, type StreamHandle, type StreamResult, type SubagentAction, type TextPart, type ThinkingPart, type ToolAction, type ToolContext, type ToolDefinition, ToolRegistry, type ToolResultPart, type TraceWriter, Tracer, type TracingContext, type Turn, TurnBuilder, type TurnPart, type TurnStatus, anthropic, braveSearchTool, calculatorTool, chatCompletions, compileInstruct, createHandle, execTool, gemini, generate, generateTurn, loadFileContent, openai, parseResponse, patchFileTool, readFileTool, stream, writeFileTool };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{C as e,D as t,E as n,O as r,S as i,T as a,_ as o,b as s,d as c,f as l,g as u,h as d,i as f,l as p,m,n as h,p as g,r as _,t as v,u as y,w as b,x,y as S}from"./ProceduralMemory-D3JlLSfC.js";import{i as C,o as w,r as T,s as E,t as D,u as O}from"./models-We2CaWSH.js";const k={Models:O,DefaultModel:E},A={Models:w,DefaultModel:C},j={Models:T,DefaultModel:D};export{s as Agent,k as Anthropic,r as AxleStopReason,A as Gemini,x as History,S as Instruct,n as LocalFileStore,f as MCP,j as OpenAI,v as ProceduralMemory,h as SimpleWriter,_ as Tracer,a as TurnBuilder,u as anthropic,y as braveSearchTool,p as calculatorTool,d as chatCompletions,i as compileInstruct,b as createHandle,m as gemini,l as generate,g as generateTurn,o as loadFileContent,c as openai,e as parseResponse,t as stream};
1
+ import{C as e,D as t,E as n,O as r,S as i,T as a,_ as o,a as s,b as c,c as l,d as u,f as d,g as f,h as p,i as m,k as h,l as g,m as _,n as v,o as y,p as b,r as x,s as S,t as C,u as w,w as T,x as E,y as D}from"./ProceduralMemory-ChCjb9PW.js";import{i as O,o as k,r as A,s as j,t as M,u as N}from"./models-DlE4tfcj.js";const P={Models:N,DefaultModel:j},F={Models:k,DefaultModel:O},I={Models:A,DefaultModel:M};export{c as Agent,P as Anthropic,r as AxleStopReason,F as Gemini,E as History,D as Instruct,n as LocalFileStore,m as MCP,I as OpenAI,C as ProceduralMemory,v as SimpleWriter,h as ToolRegistry,x as Tracer,a as TurnBuilder,f as anthropic,w as braveSearchTool,g as calculatorTool,p as chatCompletions,i as compileInstruct,T as createHandle,l as execTool,_ as gemini,d as generate,b as generateTurn,o as loadFileContent,u as openai,e as parseResponse,S as patchFileTool,y as readFileTool,t as stream,s as writeFileTool};
@@ -22,10 +22,14 @@ declare const DEFAULT_MODEL$2: "claude-haiku-4-5-20251001";
22
22
  //#region src/providers/gemini/models.d.ts
23
23
  declare const Models$1: {
24
24
  readonly GEMINI_3_1_PRO_PREVIEW: "gemini-3.1-pro-preview";
25
+ readonly GEMINI_3_1_PRO: "gemini-3.1-pro-preview";
25
26
  readonly GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS: "gemini-3.1-pro-preview-customtools";
26
27
  readonly GEMINI_3_1_FLASH_LITE_PREVIEW: "gemini-3.1-flash-lite-preview";
28
+ readonly GEMINI_3_1_FLASH_LITE: "gemini-3.1-flash-lite-preview";
27
29
  readonly GEMINI_3_PRO_PREVIEW: "gemini-3-pro-preview";
30
+ readonly GEMINI_3_PRO: "gemini-3-pro-preview";
28
31
  readonly GEMINI_3_FLASH_PREVIEW: "gemini-3-flash-preview";
32
+ readonly GEMINI_3_FLASH: "gemini-3-flash-preview";
29
33
  readonly GEMINI_2_5_PRO: "gemini-2.5-pro";
30
34
  readonly GEMINI_2_5_FLASH: "gemini-2.5-flash";
31
35
  readonly GEMINI_2_5_FLASH_LITE: "gemini-2.5-flash-lite";
@@ -36,16 +40,8 @@ declare const Models$1: {
36
40
  readonly GEMINI_FLASH_LATEST: "gemini-flash-latest";
37
41
  readonly GEMINI_FLASH_LITE_LATEST: "gemini-flash-lite-latest";
38
42
  readonly GEMINI_PRO_LATEST: "gemini-pro-latest";
39
- readonly GEMMA_4_31B_IT: "gemma-4-31b-it";
40
- readonly GEMMA_4_E4B_IT: "gemma-4-26b-a4b-it";
41
- readonly GEMMA_3_27B_IT: "gemma-3-27b-it";
42
- readonly GEMMA_3_12B_IT: "gemma-3-12b-it";
43
- readonly GEMMA_3_4B_IT: "gemma-3-4b-it";
44
- readonly GEMMA_3_1B_IT: "gemma-3-1b-it";
45
- readonly GEMMA_3N_E4B_IT: "gemma-3n-e4b-it";
46
- readonly GEMMA_3N_E2B_IT: "gemma-3n-e2b-it";
47
43
  };
48
- declare const MULTIMODAL_MODELS$1: readonly ["gemini-3.1-pro-preview", "gemini-3.1-pro-preview-customtools", "gemini-3.1-flash-lite-preview", "gemini-3-pro-preview", "gemini-3-flash-preview", "gemini-2.5-pro", "gemini-2.5-flash", "gemini-2.5-flash-lite", "gemini-2.0-flash", "gemini-2.0-flash-001", "gemini-2.0-flash-lite", "gemini-2.0-flash-lite-001", "gemini-flash-latest", "gemini-flash-lite-latest", "gemini-pro-latest", "gemma-4-31b-it", "gemma-4-26b-a4b-it", "gemma-3-27b-it", "gemma-3-12b-it", "gemma-3-4b-it", "gemma-3-1b-it", "gemma-3n-e4b-it", "gemma-3n-e2b-it"];
44
+ declare const MULTIMODAL_MODELS$1: readonly ["gemini-3.1-pro-preview", "gemini-3.1-pro-preview-customtools", "gemini-3.1-flash-lite-preview", "gemini-3-pro-preview", "gemini-3-flash-preview", "gemini-2.5-pro", "gemini-2.5-flash", "gemini-2.5-flash-lite", "gemini-2.0-flash", "gemini-2.0-flash-lite", "gemini-flash-latest", "gemini-flash-lite-latest", "gemini-pro-latest"];
49
45
  declare const DEFAULT_MODEL$1: "gemini-3.1-flash-lite-preview";
50
46
  //#endregion
51
47
  //#region src/providers/openai/models.d.ts
@@ -87,8 +83,6 @@ declare const Models: {
87
83
  readonly GPT_4_1_NANO_2025_04_14: "gpt-4.1-nano-2025-04-14";
88
84
  readonly GPT_4_1_NANO: "gpt-4.1-nano";
89
85
  readonly GPT_4O_2024_11_20: "gpt-4o-2024-11-20";
90
- readonly GPT_4O_2024_08_06: "gpt-4o-2024-08-06";
91
- readonly GPT_4O_2024_05_13: "gpt-4o-2024-05-13";
92
86
  readonly GPT_4O: "gpt-4o";
93
87
  readonly GPT_4O_MINI_2024_07_18: "gpt-4o-mini-2024-07-18";
94
88
  readonly GPT_4O_MINI: "gpt-4o-mini";
@@ -100,12 +94,8 @@ declare const Models: {
100
94
  readonly O3_PRO: "o3-pro";
101
95
  readonly O3_MINI_2025_01_31: "o3-mini-2025-01-31";
102
96
  readonly O3_MINI: "o3-mini";
103
- readonly O1_2024_12_17: "o1-2024-12-17";
104
- readonly O1: "o1";
105
- readonly O1_PRO_2025_03_19: "o1-pro-2025-03-19";
106
- readonly O1_PRO: "o1-pro";
107
97
  };
108
- declare const MULTIMODAL_MODELS: readonly ["gpt-5.5", "gpt-5.5-pro", "gpt-5.4", "gpt-5.4-pro", "gpt-5.4-mini", "gpt-5.4-nano", "gpt-5.3-chat-latest", "gpt-5.2", "gpt-5.2-pro", "gpt-5.1", "gpt-5", "gpt-5-pro", "gpt-5-mini", "gpt-5-nano", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", "gpt-4o", "gpt-4o-mini", "o4-mini", "o3", "o3-pro", "o3-mini", "o1", "o1-pro"];
98
+ declare const MULTIMODAL_MODELS: readonly ["gpt-5.5", "gpt-5.5-pro", "gpt-5.4", "gpt-5.4-pro", "gpt-5.4-mini", "gpt-5.4-nano", "gpt-5.3-chat-latest", "gpt-5.2", "gpt-5.2-chat-latest", "gpt-5.2-pro", "gpt-5.1", "gpt-5.1-chat-latest", "gpt-5", "gpt-5-chat-latest", "gpt-5-pro", "gpt-5-mini", "gpt-5-nano", "gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", "gpt-4o", "gpt-4o-mini", "o4-mini", "o3", "o3-pro", "o3-mini"];
109
99
  declare const DEFAULT_MODEL: "gpt-5.4-mini";
110
100
  //#endregion
111
101
  export { MULTIMODAL_MODELS$1 as a, MULTIMODAL_MODELS$2 as c, DEFAULT_MODEL$1 as i, Models$2 as l, MULTIMODAL_MODELS as n, Models$1 as o, Models as r, DEFAULT_MODEL$2 as s, DEFAULT_MODEL as t };
@@ -0,0 +1 @@
1
+ const e={CLAUDE_OPUS_4_7:`claude-opus-4-7`,CLAUDE_SONNET_4_6:`claude-sonnet-4-6`,CLAUDE_OPUS_4_6:`claude-opus-4-6`,CLAUDE_OPUS_4_5_20251101:`claude-opus-4-5-20251101`,CLAUDE_OPUS_4_5:`claude-opus-4-5-20251101`,CLAUDE_SONNET_4_5_20250929:`claude-sonnet-4-5-20250929`,CLAUDE_SONNET_4_5:`claude-sonnet-4-5-20250929`,CLAUDE_HAIKU_4_5_20251001:`claude-haiku-4-5-20251001`,CLAUDE_HAIKU_4_5:`claude-haiku-4-5-20251001`,CLAUDE_OPUS_4_1_20250805:`claude-opus-4-1-20250805`,CLAUDE_OPUS_4_1:`claude-opus-4-1-20250805`,CLAUDE_OPUS_4_20250514:`claude-opus-4-20250514`,CLAUDE_OPUS_4:`claude-opus-4-20250514`,CLAUDE_SONNET_4_20250514:`claude-sonnet-4-20250514`,CLAUDE_SONNET_4:`claude-sonnet-4-20250514`},t=[e.CLAUDE_OPUS_4_7,e.CLAUDE_SONNET_4_6,e.CLAUDE_OPUS_4_6,e.CLAUDE_OPUS_4_5,e.CLAUDE_SONNET_4_5,e.CLAUDE_HAIKU_4_5,e.CLAUDE_OPUS_4_1,e.CLAUDE_OPUS_4,e.CLAUDE_SONNET_4],n={[e.CLAUDE_OPUS_4_7]:128e3,[e.CLAUDE_OPUS_4_6]:128e3,[e.CLAUDE_SONNET_4_6]:64e3,[e.CLAUDE_OPUS_4_5]:64e3,[e.CLAUDE_SONNET_4_5]:64e3,[e.CLAUDE_HAIKU_4_5]:64e3,[e.CLAUDE_SONNET_4]:64e3,[e.CLAUDE_OPUS_4_1]:32e3,[e.CLAUDE_OPUS_4]:32e3},r=e.CLAUDE_HAIKU_4_5,i={GEMINI_3_1_PRO_PREVIEW:`gemini-3.1-pro-preview`,GEMINI_3_1_PRO:`gemini-3.1-pro-preview`,GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS:`gemini-3.1-pro-preview-customtools`,GEMINI_3_1_FLASH_LITE_PREVIEW:`gemini-3.1-flash-lite-preview`,GEMINI_3_1_FLASH_LITE:`gemini-3.1-flash-lite-preview`,GEMINI_3_PRO_PREVIEW:`gemini-3-pro-preview`,GEMINI_3_PRO:`gemini-3-pro-preview`,GEMINI_3_FLASH_PREVIEW:`gemini-3-flash-preview`,GEMINI_3_FLASH:`gemini-3-flash-preview`,GEMINI_2_5_PRO:`gemini-2.5-pro`,GEMINI_2_5_FLASH:`gemini-2.5-flash`,GEMINI_2_5_FLASH_LITE:`gemini-2.5-flash-lite`,GEMINI_2_0_FLASH:`gemini-2.0-flash`,GEMINI_2_0_FLASH_001:`gemini-2.0-flash-001`,GEMINI_2_0_FLASH_LITE:`gemini-2.0-flash-lite`,GEMINI_2_0_FLASH_LITE_001:`gemini-2.0-flash-lite-001`,GEMINI_FLASH_LATEST:`gemini-flash-latest`,GEMINI_FLASH_LITE_LATEST:`gemini-flash-lite-latest`,GEMINI_PRO_LATEST:`gemini-pro-latest`},a=[i.GEMINI_3_1_PRO,i.GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS,i.GEMINI_3_1_FLASH_LITE,i.GEMINI_3_PRO,i.GEMINI_3_FLASH,i.GEMINI_2_5_PRO,i.GEMINI_2_5_FLASH,i.GEMINI_2_5_FLASH_LITE,i.GEMINI_2_0_FLASH,i.GEMINI_2_0_FLASH_LITE,i.GEMINI_FLASH_LATEST,i.GEMINI_FLASH_LITE_LATEST,i.GEMINI_PRO_LATEST],o=i.GEMINI_3_1_FLASH_LITE,s={GPT_5_5_2026_04_23:`gpt-5.5-2026-04-23`,GPT_5_5:`gpt-5.5`,GPT_5_5_PRO_2026_04_23:`gpt-5.5-pro-2026-04-23`,GPT_5_5_PRO:`gpt-5.5-pro`,GPT_5_4_2026_03_05:`gpt-5.4-2026-03-05`,GPT_5_4:`gpt-5.4`,GPT_5_4_PRO_2026_03_05:`gpt-5.4-pro-2026-03-05`,GPT_5_4_PRO:`gpt-5.4-pro`,GPT_5_4_MINI_2026_03_17:`gpt-5.4-mini-2026-03-17`,GPT_5_4_MINI:`gpt-5.4-mini`,GPT_5_4_NANO_2026_03_17:`gpt-5.4-nano-2026-03-17`,GPT_5_4_NANO:`gpt-5.4-nano`,GPT_5_3_CHAT_LATEST:`gpt-5.3-chat-latest`,GPT_5_2_2025_12_11:`gpt-5.2-2025-12-11`,GPT_5_2:`gpt-5.2`,GPT_5_2_CHAT_LATEST:`gpt-5.2-chat-latest`,GPT_5_2_PRO_2025_12_11:`gpt-5.2-pro-2025-12-11`,GPT_5_2_PRO:`gpt-5.2-pro`,GPT_5_1_2025_11_13:`gpt-5.1-2025-11-13`,GPT_5_1:`gpt-5.1`,GPT_5_1_CHAT_LATEST:`gpt-5.1-chat-latest`,GPT_5_2025_08_07:`gpt-5-2025-08-07`,GPT_5:`gpt-5`,GPT_5_CHAT_LATEST:`gpt-5-chat-latest`,GPT_5_PRO_2025_10_06:`gpt-5-pro-2025-10-06`,GPT_5_PRO:`gpt-5-pro`,GPT_5_MINI_2025_08_07:`gpt-5-mini-2025-08-07`,GPT_5_MINI:`gpt-5-mini`,GPT_5_NANO_2025_08_07:`gpt-5-nano-2025-08-07`,GPT_5_NANO:`gpt-5-nano`,GPT_4_1_2025_04_14:`gpt-4.1-2025-04-14`,GPT_4_1:`gpt-4.1`,GPT_4_1_MINI_2025_04_14:`gpt-4.1-mini-2025-04-14`,GPT_4_1_MINI:`gpt-4.1-mini`,GPT_4_1_NANO_2025_04_14:`gpt-4.1-nano-2025-04-14`,GPT_4_1_NANO:`gpt-4.1-nano`,GPT_4O_2024_11_20:`gpt-4o-2024-11-20`,GPT_4O:`gpt-4o`,GPT_4O_MINI_2024_07_18:`gpt-4o-mini-2024-07-18`,GPT_4O_MINI:`gpt-4o-mini`,O4_MINI_2025_04_16:`o4-mini-2025-04-16`,O4_MINI:`o4-mini`,O3_2025_04_16:`o3-2025-04-16`,O3:`o3`,O3_PRO_2025_06_10:`o3-pro-2025-06-10`,O3_PRO:`o3-pro`,O3_MINI_2025_01_31:`o3-mini-2025-01-31`,O3_MINI:`o3-mini`},c=[s.GPT_5_5,s.GPT_5_5_PRO,s.GPT_5_4,s.GPT_5_4_PRO,s.GPT_5_4_MINI,s.GPT_5_4_NANO,s.GPT_5_3_CHAT_LATEST,s.GPT_5_2,s.GPT_5_2_CHAT_LATEST,s.GPT_5_2_PRO,s.GPT_5_1,s.GPT_5_1_CHAT_LATEST,s.GPT_5,s.GPT_5_CHAT_LATEST,s.GPT_5_PRO,s.GPT_5_MINI,s.GPT_5_NANO,s.GPT_4_1,s.GPT_4_1_MINI,s.GPT_4_1_NANO,s.GPT_4O,s.GPT_4O_MINI,s.O4_MINI,s.O3,s.O3_PRO,s.O3_MINI],l=s.GPT_5_4_MINI;export{a,n as c,o as i,t as l,c as n,i as o,s as r,r as s,l as t,e as u};
@@ -1,2 +1,2 @@
1
- import { a as MULTIMODAL_MODELS$1, c as MULTIMODAL_MODELS, i as DEFAULT_MODEL$1, l as Models, n as MULTIMODAL_MODELS$2, o as Models$1, r as Models$2, s as DEFAULT_MODEL, t as DEFAULT_MODEL$2 } from "../models-4ZkNLnS_.js";
1
+ import { a as MULTIMODAL_MODELS$1, c as MULTIMODAL_MODELS, i as DEFAULT_MODEL$1, l as Models, n as MULTIMODAL_MODELS$2, o as Models$1, r as Models$2, s as DEFAULT_MODEL, t as DEFAULT_MODEL$2 } from "../models-C7teS0rN.js";
2
2
  export { DEFAULT_MODEL as ANTHROPIC_DEFAULT_MODEL, MULTIMODAL_MODELS as ANTHROPIC_MULTIMODAL_MODELS, Models as AnthropicModels, DEFAULT_MODEL$1 as GEMINI_DEFAULT_MODEL, MULTIMODAL_MODELS$1 as GEMINI_MULTIMODAL_MODELS, Models$1 as GeminiModels, DEFAULT_MODEL$2 as OPENAI_DEFAULT_MODEL, MULTIMODAL_MODELS$2 as OPENAI_MULTIMODAL_MODELS, Models$2 as OpenAIModels };
@@ -1 +1 @@
1
- import{a as e,i as t,l as n,n as r,o as i,r as a,s as o,t as s,u as c}from"../models-We2CaWSH.js";export{o as ANTHROPIC_DEFAULT_MODEL,n as ANTHROPIC_MULTIMODAL_MODELS,c as AnthropicModels,t as GEMINI_DEFAULT_MODEL,e as GEMINI_MULTIMODAL_MODELS,i as GeminiModels,s as OPENAI_DEFAULT_MODEL,r as OPENAI_MULTIMODAL_MODELS,a as OpenAIModels};
1
+ import{a as e,i as t,l as n,n as r,o as i,r as a,s as o,t as s,u as c}from"../models-DlE4tfcj.js";export{o as ANTHROPIC_DEFAULT_MODEL,n as ANTHROPIC_MULTIMODAL_MODELS,c as AnthropicModels,t as GEMINI_DEFAULT_MODEL,e as GEMINI_MULTIMODAL_MODELS,i as GeminiModels,s as OPENAI_DEFAULT_MODEL,r as OPENAI_MULTIMODAL_MODELS,a as OpenAIModels};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fifthrevision/axle",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/johncch/axle.git"
@@ -1,45 +0,0 @@
1
- import{c as e}from"./models-We2CaWSH.js";import t,{access as n,mkdir as r,readFile as i,stat as a,writeFile as o}from"node:fs/promises";import s,{dirname as c,extname as l,resolve as u}from"node:path";import*as d from"zod";import f,{z as p}from"zod";import m from"@anthropic-ai/sdk";import"glob";import h from"mime";import{FinishReason as g,GoogleGenAI as _}from"@google/genai";import v from"openai";import{exec as y}from"node:child_process";import{promisify as b}from"node:util";import{Client as x}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as S}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as C}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import w from"chalk";import{marked as T}from"marked";import E from"node:crypto";var D=class e extends Error{code;id;details;constructor(t,n){super(t,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||`AXLE_ERROR`,this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id?{id:this.id}:{},...this.details?{details:this.details}:{},...this.cause?{cause:O(this.cause)}:{}}}};function O(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:O(e.cause)}:{}}:e}function k(e){let{text:t,files:n}=e,r=[];if(t&&r.push({type:`text`,text:t}),n)for(let e of n)r.push({type:`file`,file:e});return r}function A(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
-
3
- `)}function j(e){return e.filter(e=>e.type===`tool-call`)}function M(e,t){let n=t.usage??{in:0,out:0};e.in+=n.in??0,e.out+=n.out??0}function N(e){return JSON.stringify({error:e})}async function ee(e,t=async()=>null,n){let r=[];for(let i of e){let e=n?.startSpan(i.name,{type:`tool`}),a;try{a=await t(i.name,i.parameters)}catch(e){a={type:`error`,error:{type:`exception`,message:e instanceof Error?e.message:String(e)}}}if(a==null){let t=`Tool not found: ${i.name}`;e?.setResult({kind:`tool`,name:i.name,input:i.parameters,output:{type:`not-found`,message:t}}),e?.end(`error`),r.push({id:i.id,name:i.name,content:N({type:`not-found`,message:t}),isError:!0});continue}a.type===`success`?(e?.setResult({kind:`tool`,name:i.name,input:i.parameters,output:a.content}),e?.end(`ok`),r.push({id:i.id,name:i.name,content:a.content})):(e?.setResult({kind:`tool`,name:i.name,input:i.parameters,output:a.error}),e?.end(`error`),r.push({id:i.id,name:i.name,content:N(a.error),isError:!0}))}return{results:r}}let P=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function F(e,t){for(let n of e)n(t)}function te(e){return{type:`error`,error:{type:`not-found`,message:`Tool not found: ${e}`}}}function I(e){let t=[],n=new AbortController,r=e.signal?AbortSignal.any([n.signal,e.signal]):n.signal,{promise:i,resolve:a,reject:o}=Promise.withResolvers();return Promise.resolve().then(()=>L(e,r,t).then(a,o)),{on(e){t.push(e)},cancel(){n.abort()},get final(){return i}}}async function L(e,t,n){let{provider:r,model:i,messages:a,system:o,tools:s,serverTools:c,onToolCall:l,maxIterations:u,tracer:d,fileResolver:f,options:p,reasoning:m}=e,h=[...a],g=[],_={in:0,out:0},v=0,y=0,b=e=>{h.push(e),g.push(e)},x=e=>{e.result===`error`&&F(n,{type:`error`,error:e.error});let t=e.result===`success`?e.final?.content:e.result===`cancelled`?e.partial?.content:null,r=e.result===`success`?e.final?.finishReason:e.result===`cancelled`?`cancelled`:void 0;return d?.setResult({kind:`llm`,model:i,request:{messages:a},response:{content:t??null},usage:e.usage?{inputTokens:e.usage.in,outputTokens:e.usage.out}:void 0,finishReason:r}),d?.end(e.result===`error`?`error`:`ok`),e},S=(e,t,n,r)=>{r();let i=e.length>0?{role:`assistant`,id:t,model:n,content:e,finishReason:`cancelled`}:void 0;return i&&b(i),d?.end(`ok`),{result:`cancelled`,messages:g,partial:i,usage:_}};for(;;){if(t.aborted)return S([],``,``,()=>{});if(u!==void 0&&y>=u)return x({result:`error`,messages:g,error:{type:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${u})`}}},usage:_});y+=1;let e=d?.startSpan(`turn-${y}`,{type:`llm`}),a=c?{...p,serverTools:c}:p,C=r.createStreamingRequest(i,{messages:h,system:o,tools:s,context:{tracer:e,fileResolver:f},signal:t,options:a,reasoning:m}),w=[],T=``,E=``,D=null,O={in:0,out:0},k=-1,A=null,j=``,M=new Map,N=-1,P=()=>{A!==null&&k>=0&&(F(n,{type:A===`text`?`text:end`:`thinking:end`,index:k,final:j}),A=null,j=``,k=-1)};for await(let r of C){switch(r.type){case`start`:T=r.id,E=r.data.model,F(n,{type:`turn:start`,id:T,model:E});break;case`text-start`:P(),w.push({type:`text`,text:``}),N=w.length-1,k=v++,A=`text`,j=``,F(n,{type:`text:start`,index:k});break;case`text-delta`:{let e=w[N];e.text+=r.data.text,j=e.text,F(n,{type:`text:delta`,index:k,delta:r.data.text,accumulated:j});break}case`text-complete`:P();break;case`thinking-start`:P(),w.push({type:`thinking`,text:``}),N=w.length-1,k=v++,A=`thinking`,j=``,F(n,{type:`thinking:start`,index:k});break;case`thinking-delta`:{let e=w[N];e.text+=r.data.text,j=e.text,F(n,{type:`thinking:delta`,index:k,delta:r.data.text,accumulated:j});break}case`thinking-summary-delta`:{let e=w[N];e.text+=r.data.text,j=e.text,F(n,{type:`thinking:delta`,index:k,delta:r.data.text,accumulated:j});break}case`thinking-complete`:P();break;case`tool-call-start`:{P();let e=v++;w.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),N=w.length-1,M.set(r.data.id,e),F(n,{type:`tool:request`,index:e,id:r.data.id,name:r.data.name});break}case`tool-call-complete`:{let e=w[N];r.data.id&&(e.id=r.data.id),r.data.name&&(e.name=r.data.name),e.parameters=r.data.arguments,r.data.providerMetadata&&(e.providerMetadata=r.data.providerMetadata);break}case`internal-tool-start`:{P();let e=v++;w.push({type:`internal-tool`,id:r.data.id,name:r.data.name}),N=w.length-1,F(n,{type:`internal-tool:start`,index:e,id:r.data.id,name:r.data.name});break}case`internal-tool-complete`:{let e=w[N];r.data.output!=null&&(e.output=r.data.output),F(n,{type:`internal-tool:complete`,index:r.data.index,id:r.data.id,name:r.data.name,output:r.data.output});break}case`complete`:P(),D=r.data.finishReason,O=r.data.usage;break;case`error`:{P();let t=r.data.usage??{in:0,out:0};return _.in+=t.in??0,_.out+=t.out??0,e?.end(`error`),x({result:`error`,messages:g,error:{type:`model`,error:{type:`error`,error:{type:r.data.type,message:r.data.message}}},usage:_})}default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.aborted)break}if(t.aborted)return e?.end(`ok`),S(w,T,E,P);if(D===null)return P(),e?.end(`error`),x({result:`error`,messages:g,error:{type:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:_});_.in+=O.in??0,_.out+=O.out??0;let I={kind:`llm`,model:E,request:{messages:h},response:{content:w},usage:{inputTokens:O.in,outputTokens:O.out},finishReason:D};e?.setResult(I),e?.end();let L={role:`assistant`,id:T,model:E,content:w,finishReason:D};if(b(L),F(n,{type:`turn:complete`,message:L,usage:O}),D!==`function_call`)return x({result:`success`,messages:g,final:L,usage:_});let R=w.filter(e=>e.type===`tool-call`);if(R.length===0)return x({result:`success`,messages:g,final:L,usage:_});if(t.aborted)return d?.end(`ok`),{result:`cancelled`,messages:g,usage:_};let z=crypto.randomUUID();F(n,{type:`tool-results:start`,id:z});let B=0,{results:V}=await ee(R,async(e,t)=>{let r=R[B++],i=M.get(r.id)??-1;F(n,{type:`tool:exec-start`,index:i,id:r.id,name:e,parameters:t});let a=(l?await l(e,t):null)??te(e);return F(n,{type:`tool:exec-complete`,index:i,id:r.id,name:e,result:a}),a},d);if(V.length>0){let e={role:`tool`,id:z,content:V};b(e),F(n,{type:`tool-results:complete`,message:e})}}}var R=class{rootPath;constructor(e){this.rootPath=e}async read(e){let n=s.join(this.rootPath,e);try{return await t.readFile(n,`utf-8`)}catch{return null}}async write(e,n){let r=s.join(this.rootPath,e);await t.mkdir(s.dirname(r),{recursive:!0}),await t.writeFile(r,n,`utf-8`)}};function z(e=new Date){return{start:e.toISOString()}}function B(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var V=class{currentTurn=null;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage={in:0,out:0};createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=B(z(r),r),a=()=>({...i});if(typeof e.content==`string`)n.push({id:crypto.randomUUID(),type:`text`,text:e.content,timing:a()});else for(let t of e.content)t.type===`text`?n.push({id:crypto.randomUUID(),type:`text`,text:t.text,timing:a()}):t.type===`file`&&n.push({id:crypto.randomUUID(),type:`file`,file:t.file,timing:a()});let o={id:t,owner:`user`,parts:n,status:`complete`,timing:i};return{turn:o,events:[{type:`turn:user`,turn:o}]}}startAgentTurn(){let e=crypto.randomUUID(),t={id:e,owner:`agent`,parts:[],status:`streaming`,timing:z()};return this.currentTurn=t,this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage={in:0,out:0},{turn:t,events:[{type:`turn:start`,turnId:e}]}}handleStreamEvent(e){let t=this.currentTurn;if(!t)return[];let n=[];switch(e.type){case`turn:start`:break;case`text:start`:{this.closeOpenParts(t,n);let e={id:crypto.randomUUID(),type:`text`,text:``,timing:z()};t.parts.push(e),this.currentTextPart=e,n.push({type:`part:start`,turnId:t.id,part:{...e}});break}case`text:delta`:this.currentTextPart&&(this.currentTextPart.text=e.accumulated,n.push({type:`text:delta`,turnId:t.id,partId:this.currentTextPart.id,delta:e.delta}));break;case`text:end`:this.currentTextPart&&=(this.currentTextPart.text=e.final,this.currentTextPart.timing=B(this.currentTextPart.timing),n.push({type:`part:end`,turnId:t.id,partId:this.currentTextPart.id,timing:this.currentTextPart.timing}),null);break;case`thinking:start`:{this.closeOpenParts(t,n);let e={id:crypto.randomUUID(),type:`thinking`,text:``,timing:z()};t.parts.push(e),this.currentThinkingPart=e,n.push({type:`part:start`,turnId:t.id,part:{...e}});break}case`thinking:delta`:this.currentThinkingPart&&(this.currentThinkingPart.text=e.accumulated,n.push({type:`thinking:delta`,turnId:t.id,partId:this.currentThinkingPart.id,delta:e.delta}));break;case`thinking:end`:this.currentThinkingPart&&=(this.currentThinkingPart.text=e.final,this.currentThinkingPart.timing=B(this.currentThinkingPart.timing),n.push({type:`part:end`,turnId:t.id,partId:this.currentThinkingPart.id,timing:this.currentThinkingPart.timing}),null);break;case`tool:request`:{this.closeOpenParts(t,n);let r=crypto.randomUUID(),i={id:r,type:`action`,kind:`tool`,status:`pending`,timing:z(),detail:{name:e.name,parameters:{}}};t.parts.push(i),this.toolIdMap.set(e.id,{partId:r,turnId:t.id}),n.push({type:`part:start`,turnId:t.id,part:{...i,detail:{...i.detail}}});break}case`tool:exec-start`:{let r=this.toolIdMap.get(e.id);if(r){let i=this.findActionPart(t,r.partId);i&&(i.status=`running`,i.detail.parameters=e.parameters,n.push({type:`action:running`,turnId:t.id,partId:r.partId,parameters:e.parameters}))}break}case`tool:exec-complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=this.findActionPart(t,r.partId);i&&(e.result.type===`success`?(i.status=`complete`,i.timing=B(i.timing),i.detail.result={type:`success`,content:e.result.content},n.push({type:`action:complete`,turnId:t.id,partId:r.partId,result:i.detail.result})):(i.status=`error`,i.timing=B(i.timing),i.detail.result={type:`error`,error:e.result.error},n.push({type:`action:error`,turnId:t.id,partId:r.partId,error:e.result.error})))}break}case`internal-tool:start`:{this.closeOpenParts(t,n);let r=crypto.randomUUID(),i={id:r,type:`action`,kind:`internal-tool`,status:`running`,timing:z(),detail:{name:e.name}};t.parts.push(i),this.toolIdMap.set(e.id,{partId:r,turnId:t.id}),n.push({type:`part:start`,turnId:t.id,part:{...i,detail:{...i.detail}}}),n.push({type:`action:running`,turnId:t.id,partId:r});break}case`internal-tool:complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=this.findActionPart(t,r.partId);i&&(i.status=`complete`,i.timing=B(i.timing),i.detail.result={type:`success`,content:e.output},n.push({type:`action:complete`,turnId:t.id,partId:r.partId,result:i.detail.result}))}break}case`turn:complete`:{this.closeOpenParts(t,n);let r=e.usage??{in:0,out:0};this.accumulatedUsage.in+=r.in,this.accumulatedUsage.out+=r.out;break}case`tool-results:start`:case`tool-results:complete`:break;case`error`:{let t=e.error,r=t.type===`model`?t.error.error.message:`Tool error (${t.error.name}): ${t.error.message}`;n.push({type:`error`,error:{type:t.type,message:r}});break}}return n}finalizeTurn(e=`complete`){let t=this.currentTurn;if(!t)return[];let n=[];return this.closeOpenParts(t,n),t.status=e,t.usage={...this.accumulatedUsage},t.timing=B(t.timing),n.push({type:`turn:end`,turnId:t.id,status:e,usage:t.usage,timing:t.timing}),this.currentTurn=null,n}closeOpenParts(e,t){this.currentTextPart&&=(this.currentTextPart.timing=B(this.currentTextPart.timing),t.push({type:`part:end`,turnId:e.id,partId:this.currentTextPart.id,timing:this.currentTextPart.timing}),null),this.currentThinkingPart&&=(this.currentThinkingPart.timing=B(this.currentThinkingPart.timing),t.push({type:`part:end`,turnId:e.id,partId:this.currentThinkingPart.id,timing:this.currentThinkingPart.timing}),null)}findActionPart(e,t){return e.parts.find(e=>e.id===t&&e.type===`action`)}};function ne(e){return Array.isArray(e)?e:[e]}function re(e){return new Promise(t=>setTimeout(t,e))}function ie(e){return e.then(()=>{},()=>{})}function ae(e,t,n){let r=new AbortController,i=n?AbortSignal.any([n,r.signal]):r.signal,a=e.then(()=>t(i));return{handle:{cancel:()=>r.abort(),get final(){return a}},settled:ie(a)}}function oe(e,t,n={}){let{placeholderStyle:r=`{{}}`,strict:i=!1}=n,a=r===`{{}}`?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g,o=[];if(e=e.replace(a,(e,n)=>{if(n=n.trim(),Object.prototype.hasOwnProperty.call(t,n)){let e=t[n];return e==null?``:String(e)}return i&&o.push(n),e}),o.length>0){let e=[...new Set(o)];throw Error(`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}. Pass them as --args key=value or use --allow-missing-vars to suppress this error.`)}return e}function H(e){if(e instanceof d.ZodString)return[`string`,`Your answer`];if(e instanceof d.ZodNumber)return[`number`,42];if(e instanceof d.ZodBoolean)return[`boolean`,!0];if(e instanceof d.ZodArray){let t=e.element;if(t instanceof d.ZodString)return[`string array`,[`answer 1`,`answer 2`,`third answer`]];if(t instanceof d.ZodNumber)return[`number array`,[42,59,3.14]];if(t instanceof d.ZodBoolean)return[`boolean array`,[!0,!1,!1]];if(t instanceof d.ZodObject){let[,e]=H(t);return[`object array`,[e,e]]}return[`array`,[]]}if(e instanceof d.ZodObject){let t=e.shape,n={};for(let[e,r]of Object.entries(t)){let[,t]=H(r);n[e]=t}return[`JSON object`,n]}if(e instanceof d.ZodOptional){let[t,n]=H(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function se(e,t){if(!t)return e;if(Object.keys(t).length===0){if(e.trim()===`{}`||e.trim()===``)return{};throw Error(`Schema is empty, but rawValue is not an empty object representation or empty string.`)}let n=le(e),r={};for(let[e,i]of Object.entries(t)){let t=n.tags[e];if(t!==void 0)r[e]=ce(i,t);else if(i.def.type!==`optional`)throw Error(`Expected results with tag ${e} but it does not exist`)}try{let e={};for(let[n,i]of Object.entries(t))n in r&&(e[n]=i.parse(r[n]));return e}catch(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Validation failed: ${t}`)}throw e}}function ce(e,t){switch(t=t.trim(),e.def.type){case`string`:try{return JSON.parse(t)}catch{if(typeof t==`string`)return t;throw Error(`Cannot parse '${t}' as string. Ensure it is a valid JSON string or a plain string.`)}case`number`:{let e=parseFloat(t);if(isNaN(e))throw Error(`Cannot parse '${t}' as number`);return e}case`boolean`:{let e=t.toLowerCase();if(e===`true`)return!0;if(e===`false`)return!1;throw Error(`Cannot parse '${t}' as boolean. Expected 'true' or 'false'`)}case`array`:if(t===``)return[];try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}if(t.includes(`,`))return t.split(`,`).map(e=>{let t=e.trim();try{return JSON.parse(t)}catch{return t}}).filter(e=>e!==``);case`object`:t.includes("```json")&&(t=t.replace(/```json/g,``).replace(/```/g,``));try{return JSON.parse(t)}catch(e){throw Error(`Cannot parse object as JSON: ${e.message}`)}case`optional`:{let n=e.def.innerType;return ce(n,t)}default:return t}}function le(e){e.trim().startsWith("```json")&&e.trim().endsWith("```")&&(e=e.trim().slice(7,-3).trim());let t=/<(\w+)>(.*?)<\/\1>/gs,n={},r=e;return r=r.replace(t,(e,t,r)=>(n[t]=r,``)),r=r.replace(/<(\w+)>(.*?)(?:<\/?\w+>|$)/gs,(e,t,r)=>(n[t]=r,``)),{tags:n,remaining:r.trim()}}function U(e,t={},n={}){let r={...t,...e.inputs},i=oe(e.prompt,r,{strict:n.strictVariables});if(e.textReferences.length>0)for(let[t,n]of e.textReferences.entries()){let e=n.name?`: ${n.name}`:``;i+=`\n\n## Reference ${t+1}${e}\n\n\`\`\`${n.content}'''`}if((e.schema?Object.keys(e.schema):[]).length===0)return i;let a=`# Output Format Instructions
4
-
5
- Here is how you should format your output. Follow the instructions strictly.
6
- `;for(let[t,n]of Object.entries(e.schema)){let[e,r]=H(n);a+=`\n- Use <${t}></${t}> tags to indicate the answer for ${t}. The answer must be a ${e}.\n Example: <${t}>${JSON.stringify(r)}</${t}>\n`}return a+i}var ue=class{_turns=[];_log=[];constructor(e){e?.turns&&(this._turns=e.turns),e?.log&&(this._log=e.log)}get turns(){return[...this._turns]}get log(){return[...this._log]}addTurn(e){this._turns.push(e)}appendToLog(e){Array.isArray(e)?this._log.push(...e):this._log.push(e)}latestTurn(){return this._turns[this._turns.length-1]}toString(){return JSON.stringify({turns:this._turns})}};function de(e){return e.type===`server`}var fe=class{provider;model;history;tracer;name;scope;store;fileResolver;reasoning;system;tools={};serverTools=[];mcps=[];mcpToolsResolved=!1;memory;options;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e){if(this.provider=e.provider,this.model=e.model,this.history=new ue,this.tracer=e.tracer,this.system=e.system,this.name=e.name,this.scope=e.scope,this.store=new R(`.axle`),this.fileResolver=e.fileResolver,this.reasoning=e.reasoning,this.options=e.options??{},e.tools&&this.addTools(e.tools),e.mcps&&(this.mcps=[...e.mcps]),e.memory){if(!e.name)throw new D(`Agent requires a 'name' when memory is provided. The name is used to partition memory storage.`);this.memory=e.memory;let t=e.memory.tools?.();t&&this.addTools(t)}}addTool(e){de(e)?this.serverTools.push(e):this.tools[e.name]=e}addTools(e){for(let t of e)this.addTool(t)}addMcp(e){this.mcps.push(e),this.mcpToolsResolved=!1}addMcps(e){this.mcps.push(...e),this.mcpToolsResolved=!1}hasTools(){return Object.keys(this.tools).length>0||this.serverTools.length>0||this.mcps.length>0}on(e){this.eventCallbacks.push(e)}send(e,t){let n,r;if(typeof e==`string`)r={role:`user`,id:crypto.randomUUID(),content:[{type:`text`,text:e}]};else{let i=U(e,t?.variables,{strictVariables:this.options.strictVariables}),a=e.files;r={role:`user`,id:crypto.randomUUID(),content:k({text:i,files:a})},n=e.schema}let i=t?.reasoning??this.reasoning,{handle:a,settled:o}=ae(this.sendQueue,e=>this.run(r,n,e,t?.fileResolver,i),t?.signal);return this.sendQueue=o,a}async resolveMcpTools(){if(!this.mcpToolsResolved){this.tracer?.debug(`resolving MCP tools`,{count:this.mcps.length});for(let e of this.mcps){let t=await e.listTools({prefix:e.name,tracer:this.tracer});this.addTools(t)}this.mcpToolsResolved=!0}}emitEvent(e){for(let t of this.eventCallbacks)t(e)}async run(e,t,n,r,i){let a=new V;await this.resolveMcpTools();let o=this.system,s=[...this.history.log,e];if(this.memory){let e=await this.memory.recall({name:this.name,scope:this.scope,system:this.system,messages:s,store:this.store,tracer:this.tracer});e.systemSuffix&&(o=(o??``)+`
7
-
8
- `+e.systemSuffix)}if(n.aborted)return{response:null,turn:void 0,usage:{in:0,out:0}};let{turn:c,events:l}=a.createUserTurn(e);this.history.addTurn(c),this.history.appendToLog(e);for(let e of l)this.emitEvent(e);let u=this.tools,d=Object.values(u).map(e=>({name:e.name,description:e.description,schema:e.schema})),{turn:f,events:p}=a.startAgentTurn();this.history.addTurn(f);for(let e of p)this.emitEvent(e);let m=I({provider:this.provider,model:this.model,messages:s,system:o,tools:d.length>0?d:void 0,serverTools:this.serverTools.length>0?this.serverTools:void 0,tracer:this.tracer,fileResolver:r??this.fileResolver,reasoning:i,onToolCall:async(e,t)=>{let n=u[e];if(!n)return null;try{return{type:`success`,content:await n.execute(t)}}catch(e){return{type:`error`,error:{type:`execution`,message:e instanceof Error?e.message:String(e)}}}},signal:n});m.on(e=>{let t=a.handleStreamEvent(e);for(let e of t)this.emitEvent(e)});let h=await m.final,g=h.result===`cancelled`?`cancelled`:h.result===`error`?`error`:`complete`;h.messages.length>0&&this.history.appendToLog(h.messages);let _=a.finalizeTurn(g);for(let e of _)this.emitEvent(e);if(h.result===`error`)throw new D(pe(h.error),{code:h.error.type===`model`?`MODEL_ERROR`:`TOOL_ERROR`,details:{error:h.error}});let v=null;if(h.result===`success`&&(h.final&&(v=se(A(h.final.content),t)),this.memory))try{await this.memory.record({name:this.name,scope:this.scope,system:this.system,messages:this.history.log,newMessages:h.messages,store:this.store,tracer:this.tracer})}catch(e){this.tracer?.warn(`memory record failed`,{error:e instanceof Error?e.message:String(e)})}let y=h.usage??{in:0,out:0};return{response:v,turn:f,usage:y}}};function pe(e){return e.type===`model`?`Model error: ${e.error.error.message}`:`Tool error (${e.error.name}): ${e.error.message}`}var me=class{prompt;inputs={};files=[];textReferences=[];schema;constructor(e,t){this.prompt=e,this.schema=t}setInputs(e){this.inputs=e}addInput(e,t){this.inputs[e]=t}addFile(e,t){if(typeof e==`string`){this.textReferences.push({content:e,name:t?.name});return}if(e.kind===`text`&&e.source.type===`text`){this.textReferences.push({content:e.source.content,name:t?.name??e.name});return}this.files.push(t?.name?{...e,name:t.name}:e)}hasFiles(){return this.files.length>0}};function he(e,t,n=`[redacted]`){return W(e,null,t,n)}function W(e,t,n,r){if(typeof e!=`object`||!e)return typeof e==`string`&&t&&n.has(t)?r:e;if(Array.isArray(e))return e.map(e=>W(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=W(a,t,n,r);return i}const ge=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function G(e){return he(e,ge,`[redacted-file-value]`)}function K(e){if(e==null)return{type:`error`,error:{type:`Undetermined`,message:`Unknown error occurred`},usage:{in:0,out:0},raw:e};if(e instanceof Error)return{type:`error`,error:{type:e.name||`Error`,message:e.message||`Unexpected error`},usage:{in:0,out:0},raw:e};if(typeof e==`object`){let t=e,n=t?.error?.error?.type||t?.error?.type||t?.type||t?.code||t?.status||`Undetermined`,r=t?.error?.error?.message||t?.error?.message||t?.message||t?.error||`Unexpected error`;return{type:`error`,error:{type:String(n),message:String(r)},usage:{in:0,out:0},raw:e}}return{type:`error`,error:{type:`Undetermined`,message:String(e)},usage:{in:0,out:0},raw:e}}async function _e(e,t){let{defaults:n,tag:r}=t,a=null,o=``;if(e)try{o=u(e),a=await i(o,{encoding:`utf-8`})}catch{throw Error(`${r} not found, see --help for details`)}else{for(let e of n.formats)try{o=u(n.name+`.`+e),a=await i(o,{encoding:`utf-8`});break}catch{continue}if(a===null)throw Error(`${r} not found, see --help for details`)}return{content:a,format:o.split(`.`).pop()??``,path:o}}const q=20*1024*1024;async function J(e,t){if(t.signal?.aborted)throw new DOMException(`File resolution aborted`,`AbortError`);let{source:n}=e;if(n.type===`base64`)return Y({type:`base64`,data:n.data},e,t);if(n.type===`text`)return Y({type:`text`,content:n.content},e,t);if(n.type===`url`)return Y({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return Y(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function Y(e,t,n){if(n.accepted.includes(e.type))return{...e,mimeType:e.mimeType??t.mimeType,name:e.name??t.name};throw Error(`File source '${e.type}' is not supported for ${n.provider} ${t.kind} file '${t.name}'. Accepted: ${n.accepted.join(`, `)}`)}const ve=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function ye(e){return e.startsWith(`text/`)||ve.has(e)}function be(e){let t=h.getType(e);if(!t){let t=l(e).toLowerCase();throw Error(`Unsupported file type: ${t||`(no extension)`}`)}if(t.startsWith(`image/`))return{kind:`image`,mimeType:t};if(t===`application/pdf`)return{kind:`document`,mimeType:t};if(ye(t))return{kind:`text`,mimeType:t};{let n=l(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function xe(e,t){let r=u(e);try{await n(r)}catch{throw Error(`File not found: ${e}`)}let o=await a(r);if(o.size>q)throw Error(`File too large: ${o.size} bytes. Maximum allowed: ${q} bytes`);let s=r.split(`/`).pop()||``,c=be(r);if((t||(c.kind===`text`?`utf-8`:`base64`))===`utf-8`){if(c.kind!==`text`)throw Error(`Cannot read ${c.kind} file as text: ${e}`);let t=await i(r,`utf-8`);return{kind:`text`,mimeType:c.mimeType,size:o.size,name:s,source:{type:`text`,content:t}}}else{if(c.kind===`text`)throw Error(`Cannot read text file as binary: ${e}`);let t=(await i(r)).toString(`base64`);return{kind:c.kind,mimeType:c.mimeType,size:o.size,name:s,source:{type:`base64`,data:t}}}}async function Se(e,t={model:``}){return Promise.all(e.map(e=>Ce(e,t)))}async function Ce(e,t){if(e.role===`assistant`){let t=[];for(let n of e.content)n.type===`text`?t.push({type:`text`,text:n.text}):n.type===`thinking`?n.redacted?t.push({type:`redacted_thinking`,data:n.text}):n.signature&&t.push({type:`thinking`,thinking:n.text,signature:n.signature}):n.type===`tool-call`?t.push({type:`tool_use`,id:n.id,name:n.name,input:n.parameters}):n.type===`internal-tool`&&(t.push({type:`server_tool_use`,id:n.id,name:n.name,input:n.input??{}}),n.output!=null&&t.push({type:`web_search_tool_result`,tool_use_id:n.id,content:n.output}));return{role:`assistant`,content:t}}if(e.role===`tool`)return{role:`user`,content:await Promise.all(e.content.map(async e=>({type:`tool_result`,tool_use_id:e.id,content:typeof e.content==`string`?e.content:await Ne(e.content,t),...e.isError?{is_error:!0}:{}})))};if(typeof e.content==`string`)return{role:`user`,content:e.content};{let n=[];for(let r of e.content)r.type===`text`?n.push({type:`text`,text:r.text}):r.type===`file`&&n.push(await we(r.file,t,`user-message`));return{role:`user`,content:n}}}async function we(e,t,n){if(e.kind===`image`)return{type:`image`,source:Ee(await J(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`Anthropic only supports PDF document files. Received ${e.mimeType}`);let r=await J(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`document`,source:De(r),title:r.name??e.name}}let r=await J(e,{provider:`anthropic`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Anthropic text source: ${r.type}`);return n===`tool-result`?{type:`text`,text:r.content}:{type:`document`,source:{type:`text`,media_type:`text/plain`,data:r.content},title:r.name??e.name}}function Te(e){if(e===`image/jpeg`||e===`image/png`||e===`image/gif`||e===`image/webp`)return e;throw Error(`Anthropic does not support image MIME type: ${e}. Supported types: image/jpeg, image/png, image/gif, image/webp.`)}function Ee(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:Te(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function De(e){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:`application/pdf`,data:e.data};throw Error(`Unsupported Anthropic PDF source: ${e.type}`)}function Oe(e){return e===!0?{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function ke(e){return e.map(e=>{let t=f.toJSONSchema(e.schema);if(!Me(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}function Ae(e){let t=[];for(let n of e)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`thinking`)t.push({type:`thinking`,text:n.text||``,redacted:!1});else if(n.type===`redacted_thinking`)t.push({type:`thinking`,text:n.text||``,redacted:!0});else if(n.type===`tool_use`){if(typeof n.input!=`object`||n.input===null||Array.isArray(n.input))throw Error(`Invalid tool call input for ${n.name}: expected object, got ${typeof n.input}`);t.push({type:`tool-call`,id:n.id,name:n.name,parameters:n.input})}return t}function je(e){switch(e){case`max_tokens`:return`length`;case`end_turn`:return`stop`;case`stop_sequence`:return`stop`;case`tool_use`:return`function_call`;default:return`error`}}function Me(e){return e&&typeof e==`object`&&e.type===`object`}async function Ne(e,t){return Promise.all(e.map(async e=>e.type===`text`?{type:`text`,text:e.text}:we(e.file,t,`tool-result`)))}async function Pe(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,options:s,reasoning:c}=e,l=o?.tracer,{stop:u,max_tokens:d,...f}=s??{},p;try{let e=await Se(r,{model:n,fileResolver:o?.fileResolver}),s={model:n,max_tokens:d??16e3,messages:e,...i&&{system:i},...u&&{stop_sequences:ne(u)},...a&&{tools:ke(a)},...Oe(c),...f};l?.debug(`Anthropic request`,{request:G(s)}),p=Fe(await t.messages.create(s))}catch(e){p=K(e)}return l?.debug(`Anthropic response`,{result:p}),p}function Fe(e){let t=je(e.stop_reason);if(t===`error`)return{type:`error`,error:{type:`Uncaught error`,message:`Stop reason is not recognized or unhandled: ${e.stop_reason}`},usage:{in:e.usage.input_tokens,out:e.usage.output_tokens},raw:e};if(t===`function_call`){let t=Ae(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:A(t),usage:{in:e.usage.input_tokens,out:e.usage.output_tokens},raw:e}}if(e.type==`message`){let n=Ae(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:A(n),usage:{in:e.usage.input_tokens,out:e.usage.output_tokens},raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:{in:e.usage.input_tokens,out:e.usage.output_tokens},raw:e}}function Ie(){let e=new Map,t=new Map,n=new Map;function r(r){let i=[];switch(r.type){case`message_start`:i.push({type:`start`,id:r.message.id,data:{model:r.message.model,timestamp:Date.now()}});break;case`message_delta`:r.delta.stop_reason&&i.push({type:`complete`,data:{finishReason:je(r.delta.stop_reason),usage:{in:r.usage?.input_tokens||0,out:r.usage?.output_tokens||0}}});case`message_stop`:break;case`content_block_start`:if(r.content_block.type===`text`)e.set(r.index,`text`),i.push({type:`text-start`,data:{index:r.index}});else if(r.content_block.type===`tool_use`){e.set(r.index,`tool`);let t=r.content_block;n.set(r.index,{id:t.id,name:t.name,argumentsBuffer:``}),i.push({type:`tool-call-start`,data:{index:r.index,id:t.id,name:t.name}})}else if(r.content_block.type===`thinking`)e.set(r.index,`thinking`),i.push({type:`thinking-start`,data:{index:r.index,redacted:!1}});else if(r.content_block.type===`redacted_thinking`)e.set(r.index,`thinking`),i.push({type:`thinking-start`,data:{index:r.index,redacted:!0}});else if(r.content_block.type===`server_tool_use`){e.set(r.index,`internal-tool`);let n=r.content_block;t.set(n.id,{index:r.index,name:n.name}),i.push({type:`internal-tool-start`,data:{index:r.index,id:n.id,name:n.name}})}else if(r.content_block.type===`web_search_tool_result`){let e=r.content_block,n=t.get(e.tool_use_id);n&&(i.push({type:`internal-tool-complete`,data:{index:n.index,id:e.tool_use_id,name:n.name,output:e.content}}),t.delete(e.tool_use_id))}break;case`content_block_delta`:if(r.delta.type===`text_delta`)i.push({type:`text-delta`,data:{text:r.delta.text,index:r.index}});else if(r.delta.type===`input_json_delta`){let e=n.get(r.index);e&&(e.argumentsBuffer+=r.delta.partial_json)}else r.delta.type===`thinking_delta`?i.push({type:`thinking-delta`,data:{text:r.delta.thinking,index:r.index}}):r.delta.type===`signature_delta`||r.delta.type;break;case`content_block_stop`:{let t=e.get(r.index);if(t===`text`)i.push({type:`text-complete`,data:{index:r.index}});else if(t===`thinking`)i.push({type:`thinking-complete`,data:{index:r.index}});else if(t!==`internal-tool`&&t===`tool`){let e=n.get(r.index);if(e){try{let t=e.argumentsBuffer?JSON.parse(e.argumentsBuffer):{};i.push({type:`tool-call-complete`,data:{index:r.index,id:e.id,name:e.name,arguments:t}})}catch(t){throw Error(`Failed to parse tool call arguments for ${e.name}: ${t instanceof Error?t.message:String(t)}\nRaw buffer: ${e.argumentsBuffer}`)}n.delete(r.index)}}e.delete(r.index);break}}return i}return{handleEvent:r}}async function*Le(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,signal:s,options:c,reasoning:l}=e,u=o?.tracer,{stop:d,max_tokens:f,serverTools:p,...m}=c??{},h=a?ke(a):[];if(p){let e={web_search:`web_search_20250305`};for(let t of p){let n=e[t.name]??t.name;h.push({type:n,name:t.name,...t.config})}}let g=Ie();try{let e=await Se(r,{model:n,fileResolver:o?.fileResolver,signal:s}),a={model:n,max_tokens:f??Re(n),messages:e,...i&&{system:i},...d&&{stop_sequences:ne(d)},...h.length>0&&{tools:h},...Oe(l),...m};u?.debug(`Anthropic streaming request`,{request:G(a)});let c=await t.messages.create({...a,stream:!0},{signal:s});for await(let e of c){let t=g.handleEvent(e);for(let e of t)yield e}}catch(e){if(s?.aborted)return;yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function Re(t){return t in e?e[t]:t.includes(`opus`)?t.match(/opus-4-[6-9]|opus-[5-9]/)?128e3:64e3:t.includes(`sonnet`)||t.includes(`haiku`)?t.match(/claude-3-[0-5]-/)?8192:64e3:16384}function ze(e){let t=new m({apiKey:e});return{name:`anthropic`,async createGenerationRequest(e,n){return await Pe({client:t,model:e,...n})},createStreamingRequest(e,n){return Le({client:t,model:e,...n})}}}async function Be(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>He(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function X(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`minimal`}:{}}function Ve(e){if(e&&e.length>0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:f.toJSONSchema(e.schema)}}))}function Z(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`function_call`;case`content_filter`:return`error`;default:return`stop`}}async function He(e,t){switch(e.role){case`tool`:return Ue(e,t);case`assistant`:return We(e);default:return Ge(e,t)}}async function Ue(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await qe(e.content,t),tool_call_id:e.id})))}function We(e){let t=e.content.filter(e=>e.type===`tool-call`),n=e.content.filter(e=>e.type===`text`),r=t.length>0?t.map(e=>({type:`function`,id:e.id,function:{name:e.name,arguments:JSON.stringify(e.parameters)}})):void 0;return{role:`assistant`,content:n.map(e=>e.text).join(``),...r&&{tool_calls:r}}}async function Ge(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>Ke(e,t)))).filter(e=>e!==null);return n.every(e=>e.type===`text`)?{role:`user`,content:n.map(e=>e.text).join(``)}:{role:`user`,content:n}}async function Ke(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?Je(e.file,t,`user-message`):null}async function qe(e,t){let n=[];for(let r of e){if(r.type===`text`){n.push(r.text);continue}if(r.file.kind===`text`){let e=await J(r.file,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:`tool-result`,resolver:t.fileResolver,signal:t.signal});if(e.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${e.type}`);n.push(Ze(r.file,e.content,e.name,e.mimeType));continue}throw Error(`ChatCompletions tool results do not support file parts other than text`)}return n.join(`
9
- `)}async function Je(e,t,n){if(e.kind===`text`){let r=await J(e,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${r.type}`);return{type:`text`,text:Ze(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`ChatCompletions document file inputs currently support PDF only. Received ${e.mimeType}`);let r=await J(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`file`,file:{filename:r.name??e.name,file_data:Xe(r,e)}}}return{type:`image_url`,image_url:{url:Ye(await J(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}}}function Ye(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions image source: ${e.type}`)}function Xe(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions file source: ${e.type}`)}function Ze(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}async function Qe(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,context:o,apiKey:s,options:c,reasoning:l}=e,u=o?.tracer,d;try{let e=await Be(r,i,{model:n,fileResolver:o?.fileResolver}),f=Ve(a),p={model:n,messages:e,...f&&{tools:f},...X(l)};c&&(c.temperature!==void 0&&(p.temperature=c.temperature),c.top_p!==void 0&&(p.top_p=c.top_p),c.max_tokens!==void 0&&(p.max_tokens=c.max_tokens),c.frequency_penalty!==void 0&&(p.frequency_penalty=c.frequency_penalty),c.presence_penalty!==void 0&&(p.presence_penalty=c.presence_penalty),c.stop!==void 0&&(p.stop=c.stop),c.reasoning_effort!==void 0&&(p.reasoning_effort=c.reasoning_effort)),u?.debug(`ChatCompletions request`,{request:G(p)});let m={"Content-Type":`application/json`};s&&(m.Authorization=`Bearer ${s}`);let h=await fetch(`${t}/chat/completions`,{method:`POST`,headers:m,body:JSON.stringify(p)});if(!h.ok){let e=await h.text().catch(()=>``);throw Error(`HTTP error! status: ${h.status}${e?` - ${e}`:``}`)}d=$e(await h.json())}catch(e){u?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),d=K(e)}return u?.debug(`ChatCompletions response`,{result:d}),d}function $e(e){let t=e.choices?.[0];if(!t)return{type:`error`,error:{type:`ChatCompletionsError`,message:`No choices in response`},usage:{in:0,out:0},raw:e};let n=[];if(t.message.reasoning_content&&n.push({type:`thinking`,text:t.message.reasoning_content}),t.message.content&&n.push({type:`text`,text:t.message.content}),t.message.tool_calls)for(let e of t.message.tool_calls){let t;try{t=JSON.parse(e.function.arguments)}catch(t){throw Error(`Invalid tool call arguments for ${e.function.name}: ${t instanceof Error?t.message:String(t)}`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Invalid tool call arguments for ${e.function.name}: expected object, got ${typeof t}`);n.push({type:`tool-call`,id:e.id,name:e.function.name,parameters:t})}let r=n.some(e=>e.type===`tool-call`)?Z(`tool_calls`):Z(t.finish_reason);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:r,content:n,text:A(n),usage:{in:e.usage?.prompt_tokens||0,out:e.usage?.completion_tokens||0},raw:e}}function et(){let e=new Map,t=0,n=-1,r=``,i=``,a=null,o,s;function c(e){n<0||(a===`text`?e.push({type:`text-complete`,data:{index:n}}):a===`thinking`&&e.push({type:`thinking-complete`,data:{index:n}}),a=null,n=-1)}function l(l){let u=[];l.usage&&(s={in:l.usage.prompt_tokens,out:l.usage.completion_tokens});let d=l.choices?.[0];if(!d)return u;r||(r=l.id,i=l.model,u.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}}));let f=d.delta;if(f.reasoning_content&&(a!==`thinking`&&(c(u),n=t++,a=`thinking`,u.push({type:`thinking-start`,data:{index:n}})),u.push({type:`thinking-delta`,data:{index:n,text:f.reasoning_content}})),f.content&&(a!==`text`&&(c(u),n=t++,a=`text`,u.push({type:`text-start`,data:{index:n}})),u.push({type:`text-delta`,data:{text:f.content,index:n}})),f.tool_calls){c(u);for(let n of f.tool_calls){let r=n.index;if(!e.has(r)){let i=t++,a=n.id||`tool-${i}`;e.set(r,{id:a,name:n.function?.name||``,argumentsBuffer:``,partIdx:i}),u.push({type:`tool-call-start`,data:{index:i,id:a,name:n.function?.name||``}})}let i=e.get(r);n.id&&(i.id=n.id),n.function?.name&&(i.name=n.function.name),n.function?.arguments&&(i.argumentsBuffer+=n.function.arguments)}}if(d.finish_reason){c(u);for(let[,t]of e)try{let e=t.argumentsBuffer?JSON.parse(t.argumentsBuffer):{};u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.id,name:t.name,arguments:e}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw buffer: ${t.argumentsBuffer}`)}o=Z(d.finish_reason)}return u}function u(){return o===void 0?[]:[{type:`complete`,data:{finishReason:o,usage:s??{in:0,out:0}}}]}return{handleChunk:l,finalize:u}}async function*tt(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,context:o,signal:s,apiKey:c,options:l,reasoning:u}=e,d=o?.tracer;l?.serverTools&&d?.warn(`serverTools not supported by ChatCompletions provider`);let f=et();try{let e=await Be(r,i,{model:n,fileResolver:o?.fileResolver,signal:s}),p=Ve(a),m={model:n,messages:e,stream:!0,stream_options:{include_usage:!0},...p&&{tools:p},...X(u)};l&&(l.temperature!==void 0&&(m.temperature=l.temperature),l.top_p!==void 0&&(m.top_p=l.top_p),l.max_tokens!==void 0&&(m.max_tokens=l.max_tokens),l.frequency_penalty!==void 0&&(m.frequency_penalty=l.frequency_penalty),l.presence_penalty!==void 0&&(m.presence_penalty=l.presence_penalty),l.stop!==void 0&&(m.stop=l.stop),l.reasoning_effort!==void 0&&(m.reasoning_effort=l.reasoning_effort)),d?.debug(`ChatCompletions streaming request`,{request:G(m)});let h={"Content-Type":`application/json`};c&&(h.Authorization=`Bearer ${c}`);let g=await fetch(`${t}/chat/completions`,{method:`POST`,headers:h,body:JSON.stringify(m),signal:s});if(!g.ok){let e=await g.text().catch(()=>``);throw Error(`HTTP error! status: ${g.status}${e?` - ${e}`:``}`)}if(!g.body)throw Error(`Response body is null`);let _=g.body.getReader(),v=new TextDecoder,y=``;for(;;){let{done:e,value:t}=await _.read();if(e)break;y+=v.decode(t,{stream:!0});let n=y.split(`
10
- `);y=n.pop()||``;for(let e of n){let t=e.trim();if(!t||t.startsWith(`:`)||!t.startsWith(`data: `))continue;let n=t.slice(6);if(n!==`[DONE]`)try{let e=JSON.parse(n),t=f.handleChunk(e);for(let e of t)yield e}catch(e){d?.error(`Error parsing ChatCompletions stream chunk`,{error:e instanceof Error?e.message:String(e),line:t})}}}for(let e of f.finalize())yield e}catch(e){if(s?.aborted)return;d?.error(`Error in ChatCompletions streaming request`,{error:e instanceof Error?e.message:String(e)}),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function nt(e,t){return{name:`ChatCompletions`,async createGenerationRequest(n,r){return await Qe({baseUrl:e,model:n,apiKey:t,...r})},createStreamingRequest(n,r){return tt({baseUrl:e,model:n,apiKey:t,...r})}}}function rt(e,t,n){let r={};return t&&(r.systemInstruction=t),e&&e.length>0&&(r.tools=e.map(e=>({functionDeclarations:[{name:e.name,description:e.description,parametersJsonSchema:f.toJSONSchema(e.schema)}]}))),n&&Object.assign(r,n),r}function it(e){return e===!0?{thinkingConfig:{thinkingBudget:8192,includeThoughts:!0}}:e===!1?{thinkingConfig:{thinkingBudget:0}}:{}}async function at(e,t={model:``}){return(await Promise.all(e.map(e=>ot(e,t)))).filter(e=>e!==void 0)}async function ot(e,t){switch(e.role){case`tool`:return st(e,t);case`assistant`:return ct(e);case`user`:return lt(e,t)}}async function st(e,t){return{role:`user`,parts:(await Promise.all(e.content.map(async e=>{let n=typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
11
- `),r={functionResponse:{id:e.id??void 0,name:e.name,response:{output:n}}};return typeof e.content==`string`?[r]:[r,...await Promise.all(e.content.filter(e=>e.type===`file`).map(e=>dt(e.file,t,`tool-result`)))]}))).flat(1)}}function ct(e){let t=[],n=e.content.filter(e=>e.type===`text`);if(n.length>0){let e=n.map(e=>e.text).join(``);e&&t.push({text:e})}let r=e.content.filter(e=>e.type===`tool-call`);return r.length>0&&t.push(...r.map(e=>{let t={functionCall:{id:e.id??void 0,name:e.name,args:e.parameters}};return e.providerMetadata?.thoughtSignature&&(t.thoughtSignature=e.providerMetadata.thoughtSignature),t})),{role:`model`,parts:t}}async function lt(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>ut(e,t)))).filter(e=>e!==null)}}async function ut(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?dt(e.file,t,`user-message`):null}async function dt(e,t,n){if(e.kind===`text`){let r=await J(e,{provider:`gemini`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Gemini text source: ${r.type}`);return{text:pt(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`&&e.mimeType!==`application/pdf`)throw Error(`Gemini document file support is limited to PDFs. Received ${e.mimeType}`);return ft(await J(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function ft(e,t){if(e.type===`base64`)return{inlineData:{mimeType:e.mimeType??t.mimeType,data:e.data}};if(e.type===`url`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.url}};if(e.type===`gemini-file-uri`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.uri}};throw Error(`Unsupported Gemini file source: ${e.type}`)}function pt(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function mt(e){switch(e){case g.STOP:return[!0,`stop`];case g.MAX_TOKENS:return[!0,`length`];case g.FINISH_REASON_UNSPECIFIED:case g.SAFETY:case g.RECITATION:case g.LANGUAGE:case g.OTHER:case g.BLOCKLIST:case g.PROHIBITED_CONTENT:case g.SPII:case g.MALFORMED_FUNCTION_CALL:case g.IMAGE_SAFETY:return[!1,`error`]}return[!1,`error`]}async function ht(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,options:s,reasoning:c}=e,l=o?.tracer,u={...it(c),...s??{}};u.max_tokens&&(u.maxOutputTokens=u.max_tokens,delete u.max_tokens),u.stop&&(u.stopSequences=Array.isArray(u.stop)?u.stop:[u.stop],delete u.stop),u.top_p!==void 0&&(u.topP=u.top_p,delete u.top_p);let d;try{let e={contents:await at(r,{model:n,fileResolver:o?.fileResolver}),config:rt(a,i,u)};l?.debug(`Gemini request`,{request:G(e)}),d=gt(await t.models.generateContent({model:n,...e}),{tracer:l})}catch(e){l?.error(e instanceof Error?e.message:String(e)),d=K(e)}return l?.debug(`Gemini response`,{result:d}),d}function gt(e,t){let{tracer:n}=t,r=e.usageMetadata?.promptTokenCount??0,i={in:r,out:(e.usageMetadata?.totalTokenCount??r)-r};if(!e)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};if(e.promptFeedback&&e.promptFeedback.blockReason)return{type:`error`,error:{type:`Blocked`,message:`Response blocked by Google AI: ${e.promptFeedback.blockReason}, ${e.promptFeedback.blockReasonMessage}`},usage:i,raw:e};if(!e.candidates||e.candidates.length===0)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};e.candidates.length>1&&n?.warn(`We received ${e.candidates.length} response candidates`);let a=e.candidates[0],o=(a.content?.parts||[]).map(e=>e.text).filter(e=>e!==void 0).join(``),[s,c]=mt(a.finishReason);if(s){let t=[];if(o&&t.push({type:`text`,text:o}),e.functionCalls)for(let n of e.functionCalls)if(n.args==null)t.push({type:`tool-call`,id:n.id??``,name:n.name??``,parameters:{}});else if(typeof n.args!=`object`||Array.isArray(n.args))throw Error(`Invalid tool call arguments for ${n.name}: expected object, got ${typeof n.args}`);else t.push({type:`tool-call`,id:n.id??``,name:n.name??``,parameters:n.args});return{type:`success`,id:e.responseId??``,model:e.modelVersion??``,role:`assistant`,finishReason:e.functionCalls?`function_call`:c,content:t,text:A(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function _t(){let e=0,t=-1,n=!1,r=``,i=``,a=0,o=0,s=null;function c(e){t<0||(s===`text`?e.push({type:`text-complete`,data:{index:t}}):s===`thinking`&&e.push({type:`thinking-complete`,data:{index:t}}),s=null,t=-1)}function l(l){let u=[];r||(r=l.responseId||`gemini-${Date.now()}`,i=l.modelVersion||`gemini`,u.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}})),l.usageMetadata&&(a=l.usageMetadata.promptTokenCount||0,o=(l.usageMetadata.totalTokenCount||0)-a);let d=l.candidates?.[0];if(!d)return u;let f=d.content?.parts||[];for(let r of f){let i=`thought`in r&&r.thought===!0,a=Object.keys(r);if(!(`thoughtSignature`in r&&!r.text&&!r.functionCall||a.length===2&&`text`in r&&`thoughtSignature`in r&&!r.text)&&(i&&r.text?(s!==`thinking`&&(c(u),t=e++,s=`thinking`,u.push({type:`thinking-start`,data:{index:t}})),u.push({type:`thinking-delta`,data:{index:t,text:r.text}})):r.text&&!i?(s!==`text`&&(c(u),t=e++,s=`text`,u.push({type:`text-start`,data:{index:t}})),u.push({type:`text-delta`,data:{text:r.text,index:t}})):r.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(r))}`),r.functionCall)){c(u),n=!0;let t=e++,i=r.functionCall.id||`tool-${t}`,a=r.functionCall.name??``;u.push({type:`tool-call-start`,data:{index:t,id:i,name:a}});let o={index:t,id:i,name:a,arguments:r.functionCall.args??{}},s=r;s.thoughtSignature&&(o.providerMetadata={thoughtSignature:s.thoughtSignature}),u.push({type:`tool-call-complete`,data:o})}}if(d.finishReason&&d.finishReason!==g.FINISH_REASON_UNSPECIFIED){c(u);let[e,t]=mt(d.finishReason),r=n?`function_call`:t;!e&&!n?u.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${d.finishReason}`,usage:{in:a,out:o},raw:l}}):u.push({type:`complete`,data:{finishReason:r,usage:{in:a,out:o}}})}return u}return{handleChunk:l}}async function*vt(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,signal:s,options:c,reasoning:l}=e,u=o?.tracer,{serverTools:d,...f}=c??{},p={...it(l),...f};p.max_tokens&&(p.maxOutputTokens=p.max_tokens,delete p.max_tokens),p.stop&&(p.stopSequences=Array.isArray(p.stop)?p.stop:[p.stop],delete p.stop),p.top_p!==void 0&&(p.topP=p.top_p,delete p.top_p);let m=rt(a,i,p);if(d){let e={web_search:`googleSearch`,code_execution:`codeExecution`};m.tools||=[];for(let t of d){let n=e[t.name]??t.name;m.tools.push({[n]:t.config??{}})}}let h=_t();try{let e={contents:await at(r,{model:n,fileResolver:o?.fileResolver,signal:s}),config:m};u?.debug(`Gemini streaming request`,{request:G(e)});let i=await t.models.generateContentStream({model:n,...e});for await(let e of i){let t=h.handleChunk(e);for(let e of t)yield e}}catch(e){if(s?.aborted)return;u?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function yt(e){let t=new _({apiKey:e});return{name:`Gemini`,async createGenerationRequest(e,n){return await ht({client:t,model:e,...n})},createStreamingRequest(e,n){return vt({client:t,model:e,...n})}}}async function bt(e){let{provider:t,model:n,messages:r,system:i,tools:a,tracer:o,fileResolver:s,options:c,reasoning:l}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,context:{tracer:o,fileResolver:s},options:c,reasoning:l})}async function xt(e){let{provider:t,model:n,messages:r,system:i,tools:a,onToolCall:o,maxIterations:s,tracer:c,fileResolver:l,options:u,reasoning:d}=e,f=[...r],p=[],m={in:0,out:0},h=0,g,_=e=>{f.push(e),p.push(e)},v=e=>(c?.setResult({kind:`llm`,model:n,request:{messages:r},response:{content:e.result===`success`?e.final?.content:null},usage:e.usage?{inputTokens:e.usage.in,outputTokens:e.usage.out}:void 0,finishReason:e.result===`success`?e.final?.finishReason:void 0}),c?.end(e.result===`error`?`error`:`ok`),e),y=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??n,request:{messages:f},response:{content:t.content},usage:t.usage?{inputTokens:t.usage.in,outputTokens:t.usage.out}:void 0,finishReason:t.finishReason}),e.end()};for(;;){if(s!==void 0&&h>=s)return v({result:`error`,messages:p,error:{type:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${s})`}}},usage:m});h+=1;let e=c?.startSpan(`turn-${h}`,{type:`llm`}),r=await bt({provider:t,model:n,messages:f,system:i,tools:a,tracer:e,fileResolver:l,options:u,reasoning:d});if(M(m,r),y(e,r),r.type===`error`)return v({result:`error`,messages:p,error:{type:`model`,error:r},usage:m});let b={role:`assistant`,id:r.id,model:r.model,content:r.content,finishReason:r.finishReason};if(_(b),g=b,r.finishReason!==`function_call`)return v({result:`success`,messages:p,final:g,usage:m});let x=j(r.content);if(x.length===0)return v({result:`success`,messages:p,final:g,usage:m});let{results:S}=await ee(x,o,c);S.length>0&&_({role:`tool`,id:crypto.randomUUID(),content:S})}}function St(e){if(e&&e.length>0)return e.map(e=>({type:`function`,strict:!0,name:e.name,description:e.description,parameters:f.toJSONSchema(e.schema)}))}function Ct(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`minimal`}}:{}}async function wt(e,t={model:``}){return(await Promise.all(e.map(e=>Tt(e,t)))).flat(1)}async function Tt(e,t){switch(e.role){case`tool`:return Et(e,t);case`assistant`:return Dt(e);default:return Ot(e,t)}}async function Et(e,t){return Promise.all(e.content.map(async e=>({type:`function_call_output`,call_id:e.id,output:typeof e.content==`string`?e.content:await Promise.all(e.content.map(e=>e.type===`text`?Promise.resolve({type:`input_text`,text:e.text}):At(e.file,t,`tool-result`)))})))}function Dt(e){let t=[],n=A(e.content);n&&t.push({role:e.role,content:n});let r=e.content.filter(e=>e.type===`tool-call`);for(let e of r)t.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.parameters)});let i=e.content.filter(e=>e.type===`internal-tool`);for(let e of i)e.output!=null&&t.push(e.output);return t}async function Ot(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>kt(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function kt(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?At(e.file,t,`user-message`):(e.type,null)}async function At(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:jt(await J(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e),detail:`auto`};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`OpenAI file inputs currently support PDF documents. Received ${e.mimeType}`);return Mt(await J(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}let r=await J(e,{provider:`openai`,model:t.model,accepted:[`text`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return r.type===`text`?{type:`input_text`,text:r.content}:Mt(r,e)}function jt(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported OpenAI image source: ${e.type}`)}function Mt(e,t){if(e.type===`url`)return{type:`input_file`,filename:e.name??t.name,file_url:e.url};if(e.type===`base64`)return{type:`input_file`,filename:e.name??t.name,file_data:`data:${e.mimeType??t.mimeType};base64,${e.data}`};throw Error(`Unsupported OpenAI file source: ${e.type}`)}async function Nt(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,options:s,reasoning:c}=e,l=o?.tracer,u;try{let e=St(a),d={model:n,input:await wt(r,{model:n,fileResolver:o?.fileResolver}),...i&&{instructions:i},...e?{tools:e}:{},...Ct(c),...s};l?.debug(`OpenAI ResponsesAPI request`,{request:G(d)}),u=Pt(await t.responses.create(d))}catch(e){l?.error(e instanceof Error?e.message:String(e)),u=K(e)}return l?.debug(`OpenAI ResponsesAPI response`,{result:u}),u}function Pt(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:{in:e.usage?.input_tokens??0,out:e.usage?.output_tokens??0},raw:e};let t=e.output?.filter(e=>e.type===`reasoning`)?.map(e=>e),n=[];if(t&&t.length>0)for(let e of t){let t=e.summary?.[0]?.text||e.content?.[0]?.text||``;(t||e.encrypted_content)&&n.push({type:`thinking`,text:t,...e.encrypted_content&&{encrypted:e.encrypted_content}})}e.output_text&&n.push({type:`text`,text:e.output_text});let r=e.output?.filter(e=>e.type===`function_call`);if(r&&r.length>0)for(let e of r){let t=e;try{n.push({type:`tool-call`,id:t.id||``,name:t.name||``,parameters:t.arguments?JSON.parse(t.arguments):{}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${t.arguments}`)}}return{type:`success`,id:e.id,model:e.model||``,role:`assistant`,finishReason:e.incomplete_details?`error`:`stop`,content:n,text:A(n),usage:{in:e.usage?.input_tokens??0,out:e.usage?.output_tokens??0},raw:e}}function Ft(){let e=``,t=``,n=0,r=-1,i=!1,a=new Map,o=new Map,s=new Set([`web_search_call`,`file_search_call`,`code_interpreter_call`]),c=new Map;function l(l){let u=[];switch(l.type){case`response.created`:e=l.response.id||`openai-${Date.now()}`,t=l.response.model,u.push({type:`start`,id:e,data:{model:t,timestamp:Date.now()}});break;case`response.output_text.delta`:r===-1&&(r=n++,u.push({type:`text-start`,data:{index:r}})),u.push({type:`text-delta`,data:{text:l.delta,index:r}});break;case`response.output_text.done`:r>=0&&(u.push({type:`text-complete`,data:{index:r}}),r=-1);break;case`response.function_call_arguments.delta`:{let e=l.item_id;if(!c.has(e)){let t=a.get(e),r=t?.name||``,i=t?.callId||e,o=n++;c.set(e,{id:e,callId:i,name:r,argumentsBuffer:``,partIdx:o}),u.push({type:`tool-call-start`,data:{index:o,id:i,name:r}})}let t=c.get(e);t.argumentsBuffer+=l.delta;break}case`response.function_call_arguments.done`:{i=!0;let e=l.item_id,t=c.get(e),n=l.name||t?.name||``;if(t){try{let e=l.arguments?JSON.parse(l.arguments):{};u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.callId,name:n,arguments:e}})}catch(e){throw Error(`Failed to parse function call arguments for ${n}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${l.arguments}`)}c.delete(e)}break}case`response.completed`:{let e=l.response.usage;u.push({type:`complete`,data:{finishReason:l.response.incomplete_details?`error`:i?`function_call`:`stop`,usage:{in:e?.input_tokens||0,out:e?.output_tokens||0}}});break}case`response.failed`:u.push({type:`error`,data:{type:`RESPONSES_API_ERROR`,message:`Response failed: ${l.response.status}`,raw:l}});break;case`response.output_item.added`:if(l.item?.type===`reasoning`)r=n++,u.push({type:`thinking-start`,data:{index:r}});else if(l.item?.type===`function_call`){let e=l.item,t=e.id||e.call_id;t&&a.set(t,{name:e.name||``,callId:e.call_id||t})}else if(l.item&&s.has(l.item.type)){let e=l.item,t=n++;o.set(e.id,t),u.push({type:`internal-tool-start`,data:{index:t,id:e.id,name:e.type}})}break;case`response.output_item.done`:if(l.item?.type===`reasoning`&&r>=0)u.push({type:`thinking-complete`,data:{index:r}}),r=-1;else if(l.item&&s.has(l.item.type)){let e=l.item,t=o.get(e.id);t!==void 0&&(u.push({type:`internal-tool-complete`,data:{index:t,id:e.id,name:e.type,output:l.item}}),o.delete(e.id))}break;case`response.reasoning_text.delta`:l.delta&&u.push({type:`thinking-delta`,data:{index:r,text:l.delta}});break;case`response.reasoning_summary_text.delta`:l.delta&&u.push({type:`thinking-summary-delta`,data:{index:r,text:l.delta}});break;case`response.in_progress`:case`response.content_part.added`:case`response.content_part.done`:case`response.reasoning_summary_part.added`:case`response.reasoning_summary_part.done`:case`response.reasoning_summary_text.done`:case`response.reasoning_text.done`:case`response.web_search_call.in_progress`:case`response.web_search_call.searching`:case`response.web_search_call.completed`:break;default:console.log(`[OpenAI] unhandled stream event: ${l.type}`)}return u}return{handleEvent:l}}async function*It(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,signal:s,options:c,reasoning:l}=e,u=o?.tracer,{serverTools:d,...f}=c??{},p=St(a)??[];if(d){let e={web_search:`web_search_preview`,code_execution:`code_interpreter`};for(let t of d){let n=e[t.name]??t.name;p.push({type:n,...t.config})}}let m=Ft();try{let e={model:n,input:await wt(r,{model:n,fileResolver:o?.fileResolver,signal:s}),...i&&{instructions:i},stream:!0,...p.length>0?{tools:p}:{},...Ct(l),...f};u?.debug(`OpenAI ResponsesAPI streaming request`,{request:G(e)});let a=t.responses.stream(e,...s?[{signal:s}]:[]);for await(let e of a){let t=m.handleEvent(e);for(let e of t)yield e}}catch(e){if(s?.aborted)return;u?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function Lt(e){let t=new v({apiKey:e});return{name:`OpenAI`,async createGenerationRequest(e,n){return await Nt({client:t,model:e,...n})},createStreamingRequest(e,n){return It({client:t,model:e,...n})}}}const Rt=d.object({searchTerm:d.string().describe(`The search term to query`)}),zt=new class{name=`brave`;description=`Perform a search using the Brave search engine`;schema=Rt;apiKey;throttle;lastExecTime=0;constructor(e){e&&this.configure(e)}configure(e){let{rateLimit:t}=e;this.apiKey=e[`api-key`],this.throttle=t?1100/t:void 0}async execute(e){let{searchTerm:t}=e;if(this.throttle){for(;Date.now()-this.lastExecTime<this.throttle;)await re(this.throttle-(Date.now()-this.lastExecTime));this.lastExecTime=Date.now()}try{let e=this.apiKey,n=new URL(`https://api.search.brave.com/res/v1/web/search`);n.searchParams.append(`q`,t),n.searchParams.append(`format`,`json`);let r=await fetch(n.toString(),{method:`GET`,headers:{Accept:`application/json`,"X-Subscription-Token":e??``}});if(!r.ok)throw Error(`[Brave] HTTP error ${r.status}: ${r.statusText}`);let i=await r.json();return JSON.stringify(i)}catch(e){throw e instanceof Error?Error(`[Brave] Error fetching search results: ${e.message}`):e}}},Bt={name:`calculator`,description:`Performs basic arithmetic operations`,schema:p.object({operation:p.enum([`add`,`subtract`,`multiply`,`divide`]).describe(`The operation to perform (add, subtract, multiply, divide)`),a:p.number().describe(`First operand`),b:p.number().describe(`Second operand`)}),execute:async({operation:e,a:t,b:n})=>{switch(e){case`add`:return`${t} + ${n} = ${t+n}`;case`subtract`:return`${t} - ${n} = ${t-n}`;case`multiply`:return`${t} * ${n} = ${t*n}`;case`divide`:if(n===0)throw Error(`Cannot divide by zero`);return`${t} / ${n} = ${t/n}`;default:throw Error(`Unknown operation: ${e}`)}}},Vt=b(y);async function Ht(e,t={}){let{stdout:n,stderr:r}=await Vt(e,{cwd:t.cwd,timeout:t.timeout??3e4,maxBuffer:t.maxBuffer??1048576});return{stdout:n,stderr:r}}function Ut(e){if(e instanceof Error){let t=e,n=`Error executing command: ${e.message}`;return t.stdout&&(n+=`\n[stdout]: ${t.stdout}`),t.stderr&&(n+=`\n[stderr]: ${t.stderr}`),n}return`Error executing command: ${String(e)}`}function Wt(e,t){return t&&t.trim()?`${e}\n[stderr]: ${t}`:e}const Gt=d.object({command:d.string().describe(`The shell command to execute`)}),Kt=new class{name=`exec`;description=`Execute a shell command and return the output.`;schema=Gt;timeout=3e4;maxBuffer=1024*1024;cwd;constructor(e){e&&this.configure(e)}configure(e){this.timeout=e.timeout??3e4,this.maxBuffer=e.maxBuffer??1024*1024,this.cwd=e.cwd}summarize(e){return e.command}async execute(e){let{command:t}=e;try{let e=await Ht(t,{timeout:this.timeout,maxBuffer:this.maxBuffer,cwd:this.cwd});return Wt(e.stdout,e.stderr)}catch(e){return Ut(e)}}},qt={name:`patch-file`,description:`Patch a file by replacing an exact string match within a specified line range`,schema:p.object({path:p.string().describe(`The file path to patch`),old_string:p.string().describe(`The exact text to find and replace`),new_string:p.string().describe(`The replacement text`),start_line:p.number().int().positive().describe(`1-indexed start line of the region to match within`),end_line:p.number().int().positive().describe(`1-indexed end line (inclusive) of the region to match within`)}),summarize:({path:e,start_line:t,end_line:n})=>`${e}:${t}:${n}`,execute:async({path:e,old_string:t,new_string:n,start_line:r,end_line:a})=>{if(a<r)throw Error(`end_line (${a}) must be >= start_line (${r})`);let s;try{s=await i(e,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to read file "${e}": ${t.message}`):t}let c=s.split(`
12
- `);if(r>c.length)throw Error(`start_line (${r}) exceeds file length (${c.length} lines)`);if(a>c.length)throw Error(`end_line (${a}) exceeds file length (${c.length} lines)`);let l=c.slice(r-1,a).join(`
13
- `),u=l.indexOf(t);if(u===-1)throw Error(`old_string not found within lines ${r}-${a} of "${e}"`);if(l.indexOf(t,u+1)!==-1)throw Error(`old_string matches multiple times within lines ${r}-${a} of "${e}"`);let d=l.replace(t,n),f=[...c.slice(0,r-1),...d.split(`
14
- `),...c.slice(a)].join(`
15
- `);try{await o(e,f,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to write file "${e}": ${t.message}`):t}return`Successfully patched "${e}" (lines ${r}-${a})`}},Jt={name:`read-file`,description:`Read the contents of a file from disk`,schema:p.object({path:p.string().describe(`The file path to read from`)}),summarize:({path:e})=>e,execute:async({path:e})=>{try{return await i(e,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to read file "${e}": ${t.message}`):t}}},Yt={name:`write-file`,description:`Write content to a file on disk, creating directories if needed`,schema:p.object({path:p.string().describe(`The file path to write to`),content:p.string().describe(`The content to write to the file`)}),summarize:({path:e})=>e,execute:async({path:e,content:t})=>{try{return await r(c(e),{recursive:!0}),await o(e,t,`utf-8`),`Successfully wrote ${t.length} characters to "${e}"`}catch(t){throw t instanceof Error?Error(`Failed to write file "${e}": ${t.message}`):t}}};function Xt(e){try{let t=f.fromJSONSchema(e);return t instanceof f.ZodObject?t.strict():f.object({}).passthrough()}catch{return f.object({}).passthrough()}}function Zt(e,t,n){return e.map(e=>$t(e,t,n))}function Qt(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=Xt(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function $t(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=Xt(e.inputSchema);return{name:r,description:e.description??``,schema:i,async execute(n){let r=await t.callTool({name:e.name,arguments:n});if(`isError`in r&&r.isError)throw Error(tn(r.content));return en(r.content)}}}function en(e){return e.some(e=>e.type===`image`)?e.filter(e=>e.type===`text`||e.type===`image`).map(e=>{if(e.type===`text`)return{type:`text`,text:e.text};let t=e;return{type:`file`,file:{kind:`image`,mimeType:t.mimeType,name:`mcp-image`,source:{type:`base64`,data:t.data}}}}):e.filter(e=>e.type===`text`).map(e=>e.text).join(`
16
- `)}function tn(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
17
- `)||`MCP tool execution error`}var nn=class{config;client;transport;cachedMcpTools;_connected=!1;constructor(e){this.config=e}get name(){return this.config.name??this.client?.getServerVersion()?.name}get connected(){return this._connected}async connect(e){if(this._connected)return;let t=e?.tracer?.startSpan(`mcp:connect`,{type:`internal`});this.client=new x({name:`axle`,version:`1.0.0`}),this.config.transport===`stdio`?this.transport=new S({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new C(new URL(this.config.url),{requestInit:this.config.headers?{headers:this.config.headers}:void 0});try{await this.client.connect(this.transport),this._connected=!0,t?.end(`ok`)}catch(e){throw t?.end(`error`),e}}async listTools(e){let t=this.assertConnected();return Zt(await this.fetchTools(t,e?.tracer),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return Qt(await this.fetchTools(t,e?.tracer),e?.prefix)}async refreshTools(){return this.assertConnected(),this.cachedMcpTools=void 0,this.listTools()}async close(e){this._connected&&(e?.tracer?.debug(`mcp:close`),await this.client?.close(),this._connected=!1,this.client=void 0,this.transport=void 0,this.cachedMcpTools=void 0)}async fetchTools(e,t){if(this.cachedMcpTools)return this.cachedMcpTools;t?.debug(`mcp:listTools`);let n=await e.listTools();return this.cachedMcpTools=n.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})),this.cachedMcpTools}assertConnected(){if(!this._connected||!this.client)throw Error(`MCP not connected. Call connect() first.`);return this.client}};const rn={debug:0,info:1,warn:2,error:3};var an=class{writers=[];_minLevel=`info`;get minLevel(){return this._minLevel}set minLevel(e){this._minLevel=e}addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.writers.forEach(e=>e.onSpanStart(n)),new on(n,this)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}_notifySpanEnd(e){this.writers.forEach(t=>t.onSpanEnd(e))}_notifySpanUpdate(e){this.writers.forEach(t=>t.onSpanUpdate?.(e))}_notifyEvent(e,t){this.writers.forEach(n=>n.onEvent?.(e,t))}_notifySpanStart(e){this.writers.forEach(t=>t.onSpanStart(e))}_shouldLog(e){return rn[e]>=rn[this._minLevel]}},on=class e{data;tracer;ended=!1;constructor(e,t){this.data=e,this.tracer=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.tracer._notifySpanStart(r),new e(r,this.tracer)}end(e=`ok`){this.ended||(this.ended=!0,this.data.endTime=performance.now(),this.data.status=e,this.tracer._notifySpanEnd(this.data))}addEvent(e,t,n){if(this.ended||!this.tracer._shouldLog(t))return;let r={name:e,timestamp:performance.now(),level:t,attributes:n};this.data.events.push(r),this.tracer._notifyEvent(this.data,r)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,this.tracer._notifySpanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.tracer._notifySpanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.tracer._notifySpanUpdate(this.data))}};const sn={debug:0,info:1,warn:2,error:3};var cn=class{minLevel;showInternal;showTimestamp;showDuration;markdown;output;spans=new Map;visibleDepths=new Map;constructor(e={}){this.minLevel=e.minLevel??`info`,this.showInternal=e.showInternal??!1,this.showTimestamp=e.showTimestamp??!0,this.showDuration=e.showDuration??!0,this.markdown=e.markdown??!1,this.output=e.output??console.log}shouldShowEvent(e){return sn[e]>=sn[this.minLevel]}isSpanVisible(e){return!(e.type===`internal`&&!this.showInternal)}findVisibleAncestor(e){let t=e.parentSpanId;for(;t;){let e=this.spans.get(t);if(!e)break;if(this.isSpanVisible(e))return e;t=e.parentSpanId}return null}calculateVisibleDepth(e){if(!this.isSpanVisible(e))return-1;let t=this.findVisibleAncestor(e);return t?(this.visibleDepths.get(t.spanId)??0)+1:0}formatTimestamp(){if(!this.showTimestamp)return``;let e=new Date;return`[${e.toTimeString().slice(0,8)}.${e.getMilliseconds().toString().padStart(3,`0`)}] `}formatDuration(e){if(!this.showDuration||!e.endTime)return``;let t=e.endTime-e.startTime;return t<1e3?` (${Math.round(t)}ms)`:` (${(t/1e3).toFixed(2)}s)`}formatIndent(e){return` `.repeat(e)}formatSpanName(e){return e.type?`[${e.type}] ${e.name}`:e.name}renderMarkdown(e){return ln(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,t);let n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatSpanName(e);this.output(`${r}${n}START ${i}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.visibleDepths.get(e.spanId)??0,n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatDuration(e),a=this.formatSpanName(e),o=e.status===`error`?` [ERROR]`:``;if(this.output(`${r}${n}END ${a}${i}${o}`),e.result?.kind===`llm`){let t=e.result,i=[`model=${t.model}`];if(t.finishReason&&i.push(`finishReason=${t.finishReason}`),t.usage&&(t.usage.inputTokens!==void 0&&i.push(`inputTokens=${t.usage.inputTokens}`),t.usage.outputTokens!==void 0&&i.push(`outputTokens=${t.usage.outputTokens}`)),this.output(`${r}${n} INFO LLM complete ${i.join(` `)}`),this.shouldShowEvent(`debug`)&&t.response.content){let e=(typeof t.response.content==`string`?t.response.content:JSON.stringify(t.response.content,null,2)).split(`
18
- `);for(let t of e)this.output(`${r}${n} DEBUG ${t}`)}}}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,t){if(!this.shouldShowEvent(t.level))return;this.spans.set(e.spanId,e);let n;if(this.isSpanVisible(e))n=this.visibleDepths.get(e.spanId)??0;else{let t=this.findVisibleAncestor(e);n=t?this.visibleDepths.get(t.spanId)??0:0}let r=this.formatIndent(n+1),i=this.formatTimestamp(),a=t.level.toUpperCase().padEnd(5),o=this.markdown&&t.attributes?.markdown===!0,s=t.attributes?Object.entries(t.attributes).filter(([e])=>e!==`markdown`):[],c=t.name;o&&(c=this.renderMarkdown(c));let l=`${i}${r}${a} ${c}`;if(s.length>0){let e=s.map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(` `);l+=` ${e}`}this.output(l)}};function ln(e){return Q(T.lexer(e))}function Q(e=[]){return e.map(e=>un(e)).filter(e=>e.length>0).join(`
19
- `)}function un(e){switch(e.type){case`space`:return``;case`heading`:return w.bold($(e.tokens));case`paragraph`:return $(e.tokens);case`blockquote`:return gn(Q(e.tokens),`> `);case`code`:return(e.lang?w.dim(`${e.lang}\n`):``)+w.yellow(e.text);case`list`:return fn(e)?mn(e):e.raw;case`hr`:return w.dim(`-`.repeat(40));case`table`:return pn(e)?hn(e):e.raw;case`html`:return e.text;case`text`:return e.tokens?$(e.tokens):vn(e.text);default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function $(e=[]){return e.map(e=>dn(e)).join(``)}function dn(e){switch(e.type){case`text`:case`escape`:return vn(e.text);case`strong`:return w.bold($(e.tokens));case`em`:return w.italic($(e.tokens));case`codespan`:return w.yellow(e.text);case`del`:return w.strikethrough($(e.tokens));case`link`:{let t=$(e.tokens);return e.href&&e.href!==e.text?`${w.blue.underline(t)} ${w.dim(`(${e.href})`)}`:w.blue.underline(t)}case`image`:return e.text?`${e.text} (${e.href})`:e.href;case`br`:return`
20
- `;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function fn(e){return e.type===`list`&&`items`in e&&Array.isArray(e.items)}function pn(e){return e.type===`table`&&`header`in e&&`rows`in e}function mn(e){return e.items.map((t,n)=>{let r=e.ordered?`${Number(e.start||1)+n}. `:`- `,i=t.task?`[${t.checked?`x`:` `}] `:``,a=Q(t.tokens).trimEnd();return r+i+_n(a,r.length+i.length)}).join(`
21
- `)}function hn(e){let t=e.header.map(e=>$(e.tokens)).join(` | `),n=e.rows.map(e=>e.map(e=>$(e.tokens)).join(` | `));return[w.bold(t),...n].join(`
22
- `)}function gn(e,t){return e.split(`
23
- `).map(e=>t+e).join(`
24
- `)}function _n(e,t){let[n=``,...r]=e.split(`
25
- `);if(r.length===0)return n;let i=` `.repeat(t);return[n,...r.map(e=>i+e)].join(`
26
- `)}function vn(e){return e.replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/g,`&`)}var yn=class{provider;model;enableTools;lastStore;lastName;lastScope;constructor(e){this.provider=e.provider,this.model=e.model,this.enableTools=e.enableTools??!1}async recall(e){let t=e.tracer?.startSpan(`memory.recall`,{type:`internal`});this.lastStore=e.store,this.lastName=e.name,this.lastScope=e.scope;let n=await this.loadStore(e.store,e.name,e.scope);if(n.instructions.length===0)return t?.info(`no stored instructions`),t?.end(),{};t?.info(`loaded instructions`,{count:n.instructions.length});let r=n.instructions.map((e,t)=>`${t+1}. ${e}`).join(`
27
- `);return t?.end(),{systemSuffix:`## Learned Instructions\n\n${r}`}}async record(e){if(!e.newMessages||e.newMessages.length===0)return;let t=e.tracer?.startSpan(`memory.record`,{type:`internal`}),n=this.formatMessages(e.newMessages);if(!n.trim()){t?.info(`no text content to extract from`),t?.end();return}let r=t?.startSpan(`memory.extract`,{type:`llm`}),i=await xt({provider:this.provider,model:this.model,messages:[{role:`user`,content:n}],system:`You are a memory extraction system. Your job is to extract learnings from a conversation that should be remembered for future runs.
28
-
29
- Only extract:
30
- - Explicit user corrections (e.g., "No, always use bullet points")
31
- - Stated preferences (e.g., "I prefer concise summaries")
32
- - Patterns that clearly emerged from user feedback
33
-
34
- Do NOT extract:
35
- - General knowledge or facts from the conversation content
36
- - Inferences or speculation about what the user might want
37
- - Task-specific details that won't apply to future runs
38
-
39
- Respond with a JSON array of instruction strings. Each instruction should be a clear, actionable directive.
40
- If there are no learnings to extract, respond with an empty array: []
41
-
42
- Example response:
43
- ["Always use bullet points for lists", "Keep summaries under 3 sentences"]`,tracer:r});if(i.result!==`success`||!i.final){t?.warn(`extraction failed`,{result:i.result}),t?.end();return}let a=A(i.final.content);if(!a){t?.end();return}let o=this.parseInstructions(a);if(o.length===0){t?.info(`no instructions extracted`),t?.end();return}let s=await this.loadStore(e.store,e.name,e.scope);s.instructions.push(...o),await this.saveStore(e.store,e.name,e.scope,s),t?.info(`saved instructions`,{count:o.length}),t?.end()}tools(){if(!this.enableTools)return[];let e=this;return[{name:`add_instruction`,description:`Save a learned instruction for future runs. Use this when the user explicitly asks you to remember something.`,schema:p.object({instruction:p.string().describe(`The instruction to remember`)}),async execute(t){if(!e.lastStore)return`Error: memory not initialized (no recall has been called yet)`;let n=await e.loadStore(e.lastStore,e.lastName,e.lastScope);return n.instructions.push(t.instruction),await e.saveStore(e.lastStore,e.lastName,e.lastScope,n),`Instruction saved: "${t.instruction}"`}}]}formatMessages(e){let t=[];for(let n of e)if(n.role===`user`){let e=typeof n.content==`string`?n.content:A(n.content);e&&t.push(`User: ${e}`)}else if(n.role===`assistant`){let e=A(n.content);e&&t.push(`Assistant: ${e}`)}return t.join(`
44
-
45
- `)}parseInstructions(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);n&&(t=n[1].trim());try{let e=JSON.parse(t);if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}catch{}return[]}getStorePath(e,t){let n=e??`default`,r=n;if(t&&Object.keys(t).length>0){let e=Object.entries(t).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}=${t}`).join(`&`);r=`${n}-${E.createHash(`sha256`).update(e).digest(`hex`).slice(0,8)}`}return`memory/procedural/${r}.json`}async loadStore(e,t,n){let r=this.getStorePath(t,n),i=await e.read(r);if(i)try{let e=JSON.parse(i);if(e&&Array.isArray(e.instructions))return{instructions:e.instructions}}catch{}return{instructions:[]}}async saveStore(e,t,n,r){if(!r)return;let i=this.getStorePath(t,n);await e.write(i,JSON.stringify(r,null,2))}};export{se as C,I as D,R as E,P as O,U as S,V as T,xe as _,Yt as a,fe as b,Kt as c,Lt as d,xt as f,ze as g,nt as h,nn as i,Bt as l,yt as m,cn as n,Jt as o,bt as p,an as r,qt as s,yn as t,zt as u,_e as v,ae as w,ue as x,me as y};
@@ -1 +0,0 @@
1
- const e={CLAUDE_OPUS_4_7:`claude-opus-4-7`,CLAUDE_SONNET_4_6:`claude-sonnet-4-6`,CLAUDE_OPUS_4_6:`claude-opus-4-6`,CLAUDE_OPUS_4_5_20251101:`claude-opus-4-5-20251101`,CLAUDE_OPUS_4_5:`claude-opus-4-5-20251101`,CLAUDE_SONNET_4_5_20250929:`claude-sonnet-4-5-20250929`,CLAUDE_SONNET_4_5:`claude-sonnet-4-5-20250929`,CLAUDE_HAIKU_4_5_20251001:`claude-haiku-4-5-20251001`,CLAUDE_HAIKU_4_5:`claude-haiku-4-5-20251001`,CLAUDE_OPUS_4_1_20250805:`claude-opus-4-1-20250805`,CLAUDE_OPUS_4_1:`claude-opus-4-1-20250805`,CLAUDE_OPUS_4_20250514:`claude-opus-4-20250514`,CLAUDE_OPUS_4:`claude-opus-4-20250514`,CLAUDE_SONNET_4_20250514:`claude-sonnet-4-20250514`,CLAUDE_SONNET_4:`claude-sonnet-4-20250514`},t=[e.CLAUDE_OPUS_4_7,e.CLAUDE_SONNET_4_6,e.CLAUDE_OPUS_4_6,e.CLAUDE_OPUS_4_5,e.CLAUDE_SONNET_4_5,e.CLAUDE_HAIKU_4_5,e.CLAUDE_OPUS_4_1,e.CLAUDE_OPUS_4,e.CLAUDE_SONNET_4],n={[e.CLAUDE_OPUS_4_7]:128e3,[e.CLAUDE_OPUS_4_6]:128e3,[e.CLAUDE_SONNET_4_6]:64e3,[e.CLAUDE_OPUS_4_5]:64e3,[e.CLAUDE_SONNET_4_5]:64e3,[e.CLAUDE_HAIKU_4_5]:64e3,[e.CLAUDE_SONNET_4]:64e3,[e.CLAUDE_OPUS_4_1]:32e3,[e.CLAUDE_OPUS_4]:32e3},r=e.CLAUDE_HAIKU_4_5,i={GEMINI_3_1_PRO_PREVIEW:`gemini-3.1-pro-preview`,GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS:`gemini-3.1-pro-preview-customtools`,GEMINI_3_1_FLASH_LITE_PREVIEW:`gemini-3.1-flash-lite-preview`,GEMINI_3_PRO_PREVIEW:`gemini-3-pro-preview`,GEMINI_3_FLASH_PREVIEW:`gemini-3-flash-preview`,GEMINI_2_5_PRO:`gemini-2.5-pro`,GEMINI_2_5_FLASH:`gemini-2.5-flash`,GEMINI_2_5_FLASH_LITE:`gemini-2.5-flash-lite`,GEMINI_2_0_FLASH:`gemini-2.0-flash`,GEMINI_2_0_FLASH_001:`gemini-2.0-flash-001`,GEMINI_2_0_FLASH_LITE:`gemini-2.0-flash-lite`,GEMINI_2_0_FLASH_LITE_001:`gemini-2.0-flash-lite-001`,GEMINI_FLASH_LATEST:`gemini-flash-latest`,GEMINI_FLASH_LITE_LATEST:`gemini-flash-lite-latest`,GEMINI_PRO_LATEST:`gemini-pro-latest`,GEMMA_4_31B_IT:`gemma-4-31b-it`,GEMMA_4_E4B_IT:`gemma-4-26b-a4b-it`,GEMMA_3_27B_IT:`gemma-3-27b-it`,GEMMA_3_12B_IT:`gemma-3-12b-it`,GEMMA_3_4B_IT:`gemma-3-4b-it`,GEMMA_3_1B_IT:`gemma-3-1b-it`,GEMMA_3N_E4B_IT:`gemma-3n-e4b-it`,GEMMA_3N_E2B_IT:`gemma-3n-e2b-it`},a=[i.GEMINI_3_1_PRO_PREVIEW,i.GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS,i.GEMINI_3_1_FLASH_LITE_PREVIEW,i.GEMINI_3_PRO_PREVIEW,i.GEMINI_3_FLASH_PREVIEW,i.GEMINI_2_5_PRO,i.GEMINI_2_5_FLASH,i.GEMINI_2_5_FLASH_LITE,i.GEMINI_2_0_FLASH,i.GEMINI_2_0_FLASH_001,i.GEMINI_2_0_FLASH_LITE,i.GEMINI_2_0_FLASH_LITE_001,i.GEMINI_FLASH_LATEST,i.GEMINI_FLASH_LITE_LATEST,i.GEMINI_PRO_LATEST,i.GEMMA_4_31B_IT,i.GEMMA_4_E4B_IT,i.GEMMA_3_27B_IT,i.GEMMA_3_12B_IT,i.GEMMA_3_4B_IT,i.GEMMA_3_1B_IT,i.GEMMA_3N_E4B_IT,i.GEMMA_3N_E2B_IT],o=i.GEMINI_3_1_FLASH_LITE_PREVIEW,s={GPT_5_5_2026_04_23:`gpt-5.5-2026-04-23`,GPT_5_5:`gpt-5.5`,GPT_5_5_PRO_2026_04_23:`gpt-5.5-pro-2026-04-23`,GPT_5_5_PRO:`gpt-5.5-pro`,GPT_5_4_2026_03_05:`gpt-5.4-2026-03-05`,GPT_5_4:`gpt-5.4`,GPT_5_4_PRO_2026_03_05:`gpt-5.4-pro-2026-03-05`,GPT_5_4_PRO:`gpt-5.4-pro`,GPT_5_4_MINI_2026_03_17:`gpt-5.4-mini-2026-03-17`,GPT_5_4_MINI:`gpt-5.4-mini`,GPT_5_4_NANO_2026_03_17:`gpt-5.4-nano-2026-03-17`,GPT_5_4_NANO:`gpt-5.4-nano`,GPT_5_3_CHAT_LATEST:`gpt-5.3-chat-latest`,GPT_5_2_2025_12_11:`gpt-5.2-2025-12-11`,GPT_5_2:`gpt-5.2`,GPT_5_2_CHAT_LATEST:`gpt-5.2-chat-latest`,GPT_5_2_PRO_2025_12_11:`gpt-5.2-pro-2025-12-11`,GPT_5_2_PRO:`gpt-5.2-pro`,GPT_5_1_2025_11_13:`gpt-5.1-2025-11-13`,GPT_5_1:`gpt-5.1`,GPT_5_1_CHAT_LATEST:`gpt-5.1-chat-latest`,GPT_5_2025_08_07:`gpt-5-2025-08-07`,GPT_5:`gpt-5`,GPT_5_CHAT_LATEST:`gpt-5-chat-latest`,GPT_5_PRO_2025_10_06:`gpt-5-pro-2025-10-06`,GPT_5_PRO:`gpt-5-pro`,GPT_5_MINI_2025_08_07:`gpt-5-mini-2025-08-07`,GPT_5_MINI:`gpt-5-mini`,GPT_5_NANO_2025_08_07:`gpt-5-nano-2025-08-07`,GPT_5_NANO:`gpt-5-nano`,GPT_4_1_2025_04_14:`gpt-4.1-2025-04-14`,GPT_4_1:`gpt-4.1`,GPT_4_1_MINI_2025_04_14:`gpt-4.1-mini-2025-04-14`,GPT_4_1_MINI:`gpt-4.1-mini`,GPT_4_1_NANO_2025_04_14:`gpt-4.1-nano-2025-04-14`,GPT_4_1_NANO:`gpt-4.1-nano`,GPT_4O_2024_11_20:`gpt-4o-2024-11-20`,GPT_4O_2024_08_06:`gpt-4o-2024-08-06`,GPT_4O_2024_05_13:`gpt-4o-2024-05-13`,GPT_4O:`gpt-4o`,GPT_4O_MINI_2024_07_18:`gpt-4o-mini-2024-07-18`,GPT_4O_MINI:`gpt-4o-mini`,O4_MINI_2025_04_16:`o4-mini-2025-04-16`,O4_MINI:`o4-mini`,O3_2025_04_16:`o3-2025-04-16`,O3:`o3`,O3_PRO_2025_06_10:`o3-pro-2025-06-10`,O3_PRO:`o3-pro`,O3_MINI_2025_01_31:`o3-mini-2025-01-31`,O3_MINI:`o3-mini`,O1_2024_12_17:`o1-2024-12-17`,O1:`o1`,O1_PRO_2025_03_19:`o1-pro-2025-03-19`,O1_PRO:`o1-pro`},c=[s.GPT_5_5,s.GPT_5_5_PRO,s.GPT_5_4,s.GPT_5_4_PRO,s.GPT_5_4_MINI,s.GPT_5_4_NANO,s.GPT_5_3_CHAT_LATEST,s.GPT_5_2,s.GPT_5_2_PRO,s.GPT_5_1,s.GPT_5,s.GPT_5_PRO,s.GPT_5_MINI,s.GPT_5_NANO,s.GPT_4_1,s.GPT_4_1_MINI,s.GPT_4_1_NANO,s.GPT_4O,s.GPT_4O_MINI,s.O4_MINI,s.O3,s.O3_PRO,s.O3_MINI,s.O1,s.O1_PRO],l=s.GPT_5_4_MINI;export{a,n as c,o as i,t as l,c as n,i as o,s as r,r as s,l as t,e as u};