@fifthrevision/axle 0.10.2 → 0.12.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/dist/ProceduralMemory-D3JlLSfC.js +45 -0
- package/dist/cli.js +5 -5
- package/dist/index.d.ts +156 -88
- package/dist/index.js +1 -1
- package/dist/models-4ZkNLnS_.d.ts +111 -0
- package/dist/models-We2CaWSH.js +1 -0
- package/dist/providers/models.d.ts +2 -0
- package/dist/providers/models.js +1 -0
- package/package.json +16 -13
- package/dist/ProceduralMemory-nkWstVyg.js +0 -42
|
@@ -0,0 +1,45 @@
|
|
|
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(/"/g,`"`).replace(/'/g,`'`).replace(/</g,`<`).replace(/>/g,`>`).replace(/&/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};
|
package/dist/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`)}async function I(e,t){let n=[];for(let r of e){let e=new
|
|
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
|
|
5
|
-
`,`utf-8`)}async function
|
|
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
|
|
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{};
|
package/dist/index.d.ts
CHANGED
|
@@ -199,46 +199,142 @@ interface TracingContext {
|
|
|
199
199
|
setResult(result: SpanResult): void;
|
|
200
200
|
}
|
|
201
201
|
//#endregion
|
|
202
|
+
//#region src/utils/file.d.ts
|
|
203
|
+
type FileKind = "image" | "document" | "text";
|
|
204
|
+
type TextSource = {
|
|
205
|
+
type: "text";
|
|
206
|
+
content: string;
|
|
207
|
+
} | {
|
|
208
|
+
type: "url";
|
|
209
|
+
url: string;
|
|
210
|
+
} | {
|
|
211
|
+
type: "ref";
|
|
212
|
+
ref: unknown;
|
|
213
|
+
};
|
|
214
|
+
type BinarySource = {
|
|
215
|
+
type: "base64";
|
|
216
|
+
data: string;
|
|
217
|
+
} | {
|
|
218
|
+
type: "url";
|
|
219
|
+
url: string;
|
|
220
|
+
} | {
|
|
221
|
+
type: "ref";
|
|
222
|
+
ref: unknown;
|
|
223
|
+
};
|
|
224
|
+
interface BaseFile {
|
|
225
|
+
mimeType: string;
|
|
226
|
+
name: string;
|
|
227
|
+
size?: number;
|
|
228
|
+
}
|
|
229
|
+
type TextFileInfo = BaseFile & {
|
|
230
|
+
kind: "text";
|
|
231
|
+
source: TextSource;
|
|
232
|
+
};
|
|
233
|
+
type BinaryFileInfo = BaseFile & {
|
|
234
|
+
kind: "image" | "document";
|
|
235
|
+
source: BinarySource;
|
|
236
|
+
};
|
|
237
|
+
type FileInfo = TextFileInfo | BinaryFileInfo;
|
|
238
|
+
type InlineTextFile = TextFileInfo & {
|
|
239
|
+
source: {
|
|
240
|
+
type: "text";
|
|
241
|
+
content: string;
|
|
242
|
+
};
|
|
243
|
+
};
|
|
244
|
+
type InlineBinaryFile = BinaryFileInfo & {
|
|
245
|
+
source: {
|
|
246
|
+
type: "base64";
|
|
247
|
+
data: string;
|
|
248
|
+
};
|
|
249
|
+
};
|
|
250
|
+
type DeferredFileInfo = FileInfo & {
|
|
251
|
+
source: {
|
|
252
|
+
type: "ref";
|
|
253
|
+
ref: unknown;
|
|
254
|
+
};
|
|
255
|
+
};
|
|
256
|
+
type ConcreteFileInfo = FileInfo & {
|
|
257
|
+
source: {
|
|
258
|
+
type: "text";
|
|
259
|
+
} | {
|
|
260
|
+
type: "base64";
|
|
261
|
+
} | {
|
|
262
|
+
type: "url";
|
|
263
|
+
};
|
|
264
|
+
};
|
|
265
|
+
type FileProviderId = "anthropic" | "openai" | "gemini" | "chatcompletions";
|
|
266
|
+
type FileResolveFormat = "base64" | "url" | "text" | "gemini-file-uri";
|
|
267
|
+
type ResolvedFileSource = {
|
|
268
|
+
type: "base64";
|
|
269
|
+
data: string;
|
|
270
|
+
mimeType?: string;
|
|
271
|
+
name?: string;
|
|
272
|
+
} | {
|
|
273
|
+
type: "url";
|
|
274
|
+
url: string;
|
|
275
|
+
mimeType?: string;
|
|
276
|
+
name?: string;
|
|
277
|
+
} | {
|
|
278
|
+
type: "text";
|
|
279
|
+
content: string;
|
|
280
|
+
mimeType?: string;
|
|
281
|
+
name?: string;
|
|
282
|
+
} | {
|
|
283
|
+
type: "gemini-file-uri";
|
|
284
|
+
uri: string;
|
|
285
|
+
mimeType?: string;
|
|
286
|
+
name?: string;
|
|
287
|
+
};
|
|
288
|
+
interface FileResolveRequest {
|
|
289
|
+
file: DeferredFileInfo;
|
|
290
|
+
ref: unknown;
|
|
291
|
+
provider: FileProviderId;
|
|
292
|
+
model: string;
|
|
293
|
+
accepted: FileResolveFormat[];
|
|
294
|
+
signal?: AbortSignal;
|
|
295
|
+
}
|
|
296
|
+
type FileResolver = (request: FileResolveRequest) => Promise<ResolvedFileSource>;
|
|
297
|
+
/**
|
|
298
|
+
* Load a file with the specified encoding or auto-detect based on file extension
|
|
299
|
+
* @param filePath - Path to the file
|
|
300
|
+
* @param encoding - How to load the file: "utf-8" for text, "base64" for binary, or omit for auto-detection
|
|
301
|
+
* @returns FileInfo object with appropriate content based on encoding
|
|
302
|
+
*/
|
|
303
|
+
declare function loadFileContent(filePath: string): Promise<FileInfo>;
|
|
304
|
+
declare function loadFileContent(filePath: string, encoding: "utf-8"): Promise<InlineTextFile>;
|
|
305
|
+
declare function loadFileContent(filePath: string, encoding: "base64"): Promise<InlineBinaryFile>;
|
|
306
|
+
//#endregion
|
|
202
307
|
//#region src/providers/types.d.ts
|
|
308
|
+
interface ProviderRequestContext {
|
|
309
|
+
tracer?: TracingContext;
|
|
310
|
+
fileResolver?: FileResolver;
|
|
311
|
+
}
|
|
312
|
+
interface GenerateTurnOptions {
|
|
313
|
+
temperature?: number;
|
|
314
|
+
top_p?: number;
|
|
315
|
+
max_tokens?: number;
|
|
316
|
+
frequency_penalty?: number;
|
|
317
|
+
presence_penalty?: number;
|
|
318
|
+
stop?: string | string[];
|
|
319
|
+
[key: string]: any;
|
|
320
|
+
}
|
|
321
|
+
interface GenerationRequestParams {
|
|
322
|
+
messages: Array<AxleMessage>;
|
|
323
|
+
system?: string;
|
|
324
|
+
tools?: Array<ToolDefinition>;
|
|
325
|
+
context: ProviderRequestContext;
|
|
326
|
+
options?: GenerateTurnOptions;
|
|
327
|
+
reasoning?: boolean;
|
|
328
|
+
}
|
|
329
|
+
interface StreamingRequestParams extends GenerationRequestParams {
|
|
330
|
+
signal?: AbortSignal;
|
|
331
|
+
}
|
|
203
332
|
interface AIProvider {
|
|
204
333
|
get name(): string;
|
|
205
334
|
/** @internal */
|
|
206
|
-
createGenerationRequest(model: string, params:
|
|
207
|
-
messages: Array<AxleMessage>;
|
|
208
|
-
system?: string;
|
|
209
|
-
tools?: Array<ToolDefinition>;
|
|
210
|
-
context: {
|
|
211
|
-
tracer?: TracingContext;
|
|
212
|
-
};
|
|
213
|
-
options?: {
|
|
214
|
-
temperature?: number;
|
|
215
|
-
top_p?: number;
|
|
216
|
-
max_tokens?: number;
|
|
217
|
-
frequency_penalty?: number;
|
|
218
|
-
presence_penalty?: number;
|
|
219
|
-
stop?: string | string[];
|
|
220
|
-
[key: string]: any;
|
|
221
|
-
};
|
|
222
|
-
}): Promise<ModelResult>;
|
|
335
|
+
createGenerationRequest(model: string, params: GenerationRequestParams): Promise<ModelResult>;
|
|
223
336
|
/** @internal */
|
|
224
|
-
createStreamingRequest
|
|
225
|
-
messages: Array<AxleMessage>;
|
|
226
|
-
system?: string;
|
|
227
|
-
tools?: Array<ToolDefinition>;
|
|
228
|
-
context: {
|
|
229
|
-
tracer?: TracingContext;
|
|
230
|
-
};
|
|
231
|
-
signal?: AbortSignal;
|
|
232
|
-
options?: {
|
|
233
|
-
temperature?: number;
|
|
234
|
-
top_p?: number;
|
|
235
|
-
max_tokens?: number;
|
|
236
|
-
frequency_penalty?: number;
|
|
237
|
-
presence_penalty?: number;
|
|
238
|
-
stop?: string | string[];
|
|
239
|
-
[key: string]: any;
|
|
240
|
-
};
|
|
241
|
-
}): AsyncGenerator<AnyStreamChunk, void, unknown>;
|
|
337
|
+
createStreamingRequest(model: string, params: StreamingRequestParams): AsyncGenerator<AnyStreamChunk, void, unknown>;
|
|
242
338
|
}
|
|
243
339
|
interface ModelResponse {
|
|
244
340
|
type: "success";
|
|
@@ -270,38 +366,15 @@ declare enum AxleStopReason {
|
|
|
270
366
|
Cancelled = "cancelled"
|
|
271
367
|
}
|
|
272
368
|
//#endregion
|
|
273
|
-
//#region src/utils/file.d.ts
|
|
274
|
-
interface FileInfo {
|
|
275
|
-
path: string;
|
|
276
|
-
base64?: string;
|
|
277
|
-
content?: string;
|
|
278
|
-
mimeType: string;
|
|
279
|
-
size: number;
|
|
280
|
-
name: string;
|
|
281
|
-
type: "image" | "document" | "text";
|
|
282
|
-
}
|
|
283
|
-
type TextFileInfo = FileInfo & {
|
|
284
|
-
content: string;
|
|
285
|
-
base64?: never;
|
|
286
|
-
type: "text";
|
|
287
|
-
};
|
|
288
|
-
type Base64FileInfo = FileInfo & {
|
|
289
|
-
base64: string;
|
|
290
|
-
content?: never;
|
|
291
|
-
type: "image" | "document";
|
|
292
|
-
};
|
|
293
|
-
/**
|
|
294
|
-
* Load a file with the specified encoding or auto-detect based on file extension
|
|
295
|
-
* @param filePath - Path to the file
|
|
296
|
-
* @param encoding - How to load the file: "utf-8" for text, "base64" for binary, or omit for auto-detection
|
|
297
|
-
* @returns FileInfo object with appropriate content based on encoding
|
|
298
|
-
*/
|
|
299
|
-
declare function loadFileContent(filePath: string): Promise<FileInfo>;
|
|
300
|
-
declare function loadFileContent(filePath: string, encoding: "utf-8"): Promise<TextFileInfo>;
|
|
301
|
-
declare function loadFileContent(filePath: string, encoding: "base64"): Promise<Base64FileInfo>;
|
|
302
|
-
//#endregion
|
|
303
369
|
//#region src/messages/message.d.ts
|
|
304
370
|
type AxleMessage = AxleUserMessage | AxleAssistantMessage | AxleToolCallMessage;
|
|
371
|
+
type ToolResultPart = {
|
|
372
|
+
type: "text";
|
|
373
|
+
text: string;
|
|
374
|
+
} | {
|
|
375
|
+
type: "file";
|
|
376
|
+
file: ConcreteFileInfo;
|
|
377
|
+
};
|
|
305
378
|
interface AxleUserMessage {
|
|
306
379
|
role: "user";
|
|
307
380
|
id?: string;
|
|
@@ -320,14 +393,6 @@ interface AxleToolCallMessage {
|
|
|
320
393
|
id: string;
|
|
321
394
|
content: Array<AxleToolCallResult>;
|
|
322
395
|
}
|
|
323
|
-
type ToolResultPart = {
|
|
324
|
-
type: "text";
|
|
325
|
-
text: string;
|
|
326
|
-
} | {
|
|
327
|
-
type: "image";
|
|
328
|
-
data: string;
|
|
329
|
-
mimeType: string;
|
|
330
|
-
};
|
|
331
396
|
interface AxleToolCallResult {
|
|
332
397
|
id: string;
|
|
333
398
|
name: string;
|
|
@@ -640,12 +705,11 @@ declare function parseResponse<T extends OutputSchema>(rawValue: string, schema?
|
|
|
640
705
|
declare class Instruct<TSchema extends OutputSchema | undefined = undefined> {
|
|
641
706
|
prompt: string;
|
|
642
707
|
inputs: Record<string, string>;
|
|
643
|
-
files:
|
|
708
|
+
files: FileInfo[];
|
|
644
709
|
textReferences: Array<{
|
|
645
710
|
content: string;
|
|
646
711
|
name?: string;
|
|
647
712
|
}>;
|
|
648
|
-
instructions: string[];
|
|
649
713
|
schema: TSchema;
|
|
650
714
|
constructor(prompt: string, schema?: TSchema);
|
|
651
715
|
setInputs(inputs: Record<string, string>): void;
|
|
@@ -653,7 +717,6 @@ declare class Instruct<TSchema extends OutputSchema | undefined = undefined> {
|
|
|
653
717
|
addFile(file: FileInfo | string, options?: {
|
|
654
718
|
name?: string;
|
|
655
719
|
}): void;
|
|
656
|
-
addInstructions(instruction: string): void;
|
|
657
720
|
hasFiles(): boolean;
|
|
658
721
|
}
|
|
659
722
|
//#endregion
|
|
@@ -671,6 +734,8 @@ interface AgentConfig {
|
|
|
671
734
|
mcps?: MCP[];
|
|
672
735
|
memory?: AgentMemory;
|
|
673
736
|
tracer?: TracingContext;
|
|
737
|
+
fileResolver?: FileResolver;
|
|
738
|
+
reasoning?: boolean;
|
|
674
739
|
options?: AgentOptions;
|
|
675
740
|
}
|
|
676
741
|
interface AgentResult<T = string> {
|
|
@@ -682,6 +747,8 @@ type AgentHandle<T = string> = Handle<AgentResult<T>>;
|
|
|
682
747
|
type AgentEventCallback = (event: AgentEvent) => void;
|
|
683
748
|
interface SendMessageOptions {
|
|
684
749
|
signal?: AbortSignal;
|
|
750
|
+
fileResolver?: FileResolver;
|
|
751
|
+
reasoning?: boolean;
|
|
685
752
|
}
|
|
686
753
|
interface SendInstructOptions extends SendMessageOptions {
|
|
687
754
|
variables?: Record<string, string>;
|
|
@@ -694,6 +761,8 @@ declare class Agent {
|
|
|
694
761
|
readonly name?: string;
|
|
695
762
|
readonly scope?: Record<string, string>;
|
|
696
763
|
readonly store: FileStore;
|
|
764
|
+
readonly fileResolver?: FileResolver;
|
|
765
|
+
readonly reasoning?: boolean;
|
|
697
766
|
system: string | undefined;
|
|
698
767
|
tools: Record<string, ExecutableTool>;
|
|
699
768
|
serverTools: ServerTool[];
|
|
@@ -828,15 +897,6 @@ type StreamResult = GenerateResult | {
|
|
|
828
897
|
};
|
|
829
898
|
//#endregion
|
|
830
899
|
//#region src/providers/generateTurn.d.ts
|
|
831
|
-
interface GenerateTurnOptions {
|
|
832
|
-
temperature?: number;
|
|
833
|
-
top_p?: number;
|
|
834
|
-
max_tokens?: number;
|
|
835
|
-
frequency_penalty?: number;
|
|
836
|
-
presence_penalty?: number;
|
|
837
|
-
stop?: string | string[];
|
|
838
|
-
[key: string]: any;
|
|
839
|
-
}
|
|
840
900
|
interface GenerateTurnProps {
|
|
841
901
|
provider: AIProvider;
|
|
842
902
|
model: string;
|
|
@@ -844,7 +904,9 @@ interface GenerateTurnProps {
|
|
|
844
904
|
system?: string;
|
|
845
905
|
tools?: Array<ToolDefinition>;
|
|
846
906
|
tracer?: TracingContext;
|
|
907
|
+
fileResolver?: FileResolver;
|
|
847
908
|
options?: GenerateTurnOptions;
|
|
909
|
+
reasoning?: boolean;
|
|
848
910
|
}
|
|
849
911
|
declare function generateTurn(props: GenerateTurnProps): Promise<ModelResult>;
|
|
850
912
|
//#endregion
|
|
@@ -858,7 +920,9 @@ interface GenerateOptions {
|
|
|
858
920
|
onToolCall?: ToolCallCallback;
|
|
859
921
|
maxIterations?: number;
|
|
860
922
|
tracer?: TracingContext;
|
|
923
|
+
fileResolver?: FileResolver;
|
|
861
924
|
options?: GenerateTurnOptions;
|
|
925
|
+
reasoning?: boolean;
|
|
862
926
|
}
|
|
863
927
|
declare function generate(options: GenerateOptions): Promise<GenerateResult>;
|
|
864
928
|
//#endregion
|
|
@@ -944,7 +1008,9 @@ interface StreamOptions {
|
|
|
944
1008
|
onToolCall?: ToolCallCallback;
|
|
945
1009
|
maxIterations?: number;
|
|
946
1010
|
tracer?: TracingContext;
|
|
1011
|
+
fileResolver?: FileResolver;
|
|
947
1012
|
options?: GenerateTurnOptions;
|
|
1013
|
+
reasoning?: boolean;
|
|
948
1014
|
signal?: AbortSignal;
|
|
949
1015
|
}
|
|
950
1016
|
interface StreamHandle {
|
|
@@ -960,6 +1026,10 @@ declare function openai(apiKey: string): AIProvider;
|
|
|
960
1026
|
//#region src/providers/openai/index.d.ts
|
|
961
1027
|
declare const OpenAI: {
|
|
962
1028
|
readonly Models: {
|
|
1029
|
+
readonly GPT_5_5_2026_04_23: "gpt-5.5-2026-04-23";
|
|
1030
|
+
readonly GPT_5_5: "gpt-5.5";
|
|
1031
|
+
readonly GPT_5_5_PRO_2026_04_23: "gpt-5.5-pro-2026-04-23";
|
|
1032
|
+
readonly GPT_5_5_PRO: "gpt-5.5-pro";
|
|
963
1033
|
readonly GPT_5_4_2026_03_05: "gpt-5.4-2026-03-05";
|
|
964
1034
|
readonly GPT_5_4: "gpt-5.4";
|
|
965
1035
|
readonly GPT_5_4_PRO_2026_03_05: "gpt-5.4-pro-2026-03-05";
|
|
@@ -998,8 +1068,6 @@ declare const OpenAI: {
|
|
|
998
1068
|
readonly GPT_4O: "gpt-4o";
|
|
999
1069
|
readonly GPT_4O_MINI_2024_07_18: "gpt-4o-mini-2024-07-18";
|
|
1000
1070
|
readonly GPT_4O_MINI: "gpt-4o-mini";
|
|
1001
|
-
readonly GPT_4_TURBO_2024_04_09: "gpt-4-turbo-2024-04-09";
|
|
1002
|
-
readonly GPT_4_TURBO: "gpt-4-turbo";
|
|
1003
1071
|
readonly O4_MINI_2025_04_16: "o4-mini-2025-04-16";
|
|
1004
1072
|
readonly O4_MINI: "o4-mini";
|
|
1005
1073
|
readonly O3_2025_04_16: "o3-2025-04-16";
|
|
@@ -1183,4 +1251,4 @@ declare class LocalFileStore implements FileStore {
|
|
|
1183
1251
|
write(path: string, content: string): Promise<void>;
|
|
1184
1252
|
}
|
|
1185
1253
|
//#endregion
|
|
1186
|
-
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 EventLevel, type ExecutableTool, type FileInfo, type FilePart, 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 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 };
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
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};
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
//#region src/providers/anthropic/models.d.ts
|
|
2
|
+
declare const Models$2: {
|
|
3
|
+
readonly CLAUDE_OPUS_4_7: "claude-opus-4-7";
|
|
4
|
+
readonly CLAUDE_SONNET_4_6: "claude-sonnet-4-6";
|
|
5
|
+
readonly CLAUDE_OPUS_4_6: "claude-opus-4-6";
|
|
6
|
+
readonly CLAUDE_OPUS_4_5_20251101: "claude-opus-4-5-20251101";
|
|
7
|
+
readonly CLAUDE_OPUS_4_5: "claude-opus-4-5-20251101";
|
|
8
|
+
readonly CLAUDE_SONNET_4_5_20250929: "claude-sonnet-4-5-20250929";
|
|
9
|
+
readonly CLAUDE_SONNET_4_5: "claude-sonnet-4-5-20250929";
|
|
10
|
+
readonly CLAUDE_HAIKU_4_5_20251001: "claude-haiku-4-5-20251001";
|
|
11
|
+
readonly CLAUDE_HAIKU_4_5: "claude-haiku-4-5-20251001";
|
|
12
|
+
readonly CLAUDE_OPUS_4_1_20250805: "claude-opus-4-1-20250805";
|
|
13
|
+
readonly CLAUDE_OPUS_4_1: "claude-opus-4-1-20250805";
|
|
14
|
+
readonly CLAUDE_OPUS_4_20250514: "claude-opus-4-20250514";
|
|
15
|
+
readonly CLAUDE_OPUS_4: "claude-opus-4-20250514";
|
|
16
|
+
readonly CLAUDE_SONNET_4_20250514: "claude-sonnet-4-20250514";
|
|
17
|
+
readonly CLAUDE_SONNET_4: "claude-sonnet-4-20250514";
|
|
18
|
+
};
|
|
19
|
+
declare const MULTIMODAL_MODELS$2: readonly ["claude-opus-4-7", "claude-sonnet-4-6", "claude-opus-4-6", "claude-opus-4-5-20251101", "claude-sonnet-4-5-20250929", "claude-haiku-4-5-20251001", "claude-opus-4-1-20250805", "claude-opus-4-20250514", "claude-sonnet-4-20250514"];
|
|
20
|
+
declare const DEFAULT_MODEL$2: "claude-haiku-4-5-20251001";
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/providers/gemini/models.d.ts
|
|
23
|
+
declare const Models$1: {
|
|
24
|
+
readonly GEMINI_3_1_PRO_PREVIEW: "gemini-3.1-pro-preview";
|
|
25
|
+
readonly GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS: "gemini-3.1-pro-preview-customtools";
|
|
26
|
+
readonly GEMINI_3_1_FLASH_LITE_PREVIEW: "gemini-3.1-flash-lite-preview";
|
|
27
|
+
readonly GEMINI_3_PRO_PREVIEW: "gemini-3-pro-preview";
|
|
28
|
+
readonly GEMINI_3_FLASH_PREVIEW: "gemini-3-flash-preview";
|
|
29
|
+
readonly GEMINI_2_5_PRO: "gemini-2.5-pro";
|
|
30
|
+
readonly GEMINI_2_5_FLASH: "gemini-2.5-flash";
|
|
31
|
+
readonly GEMINI_2_5_FLASH_LITE: "gemini-2.5-flash-lite";
|
|
32
|
+
readonly GEMINI_2_0_FLASH: "gemini-2.0-flash";
|
|
33
|
+
readonly GEMINI_2_0_FLASH_001: "gemini-2.0-flash-001";
|
|
34
|
+
readonly GEMINI_2_0_FLASH_LITE: "gemini-2.0-flash-lite";
|
|
35
|
+
readonly GEMINI_2_0_FLASH_LITE_001: "gemini-2.0-flash-lite-001";
|
|
36
|
+
readonly GEMINI_FLASH_LATEST: "gemini-flash-latest";
|
|
37
|
+
readonly GEMINI_FLASH_LITE_LATEST: "gemini-flash-lite-latest";
|
|
38
|
+
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
|
+
};
|
|
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"];
|
|
49
|
+
declare const DEFAULT_MODEL$1: "gemini-3.1-flash-lite-preview";
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/providers/openai/models.d.ts
|
|
52
|
+
declare const Models: {
|
|
53
|
+
readonly GPT_5_5_2026_04_23: "gpt-5.5-2026-04-23";
|
|
54
|
+
readonly GPT_5_5: "gpt-5.5";
|
|
55
|
+
readonly GPT_5_5_PRO_2026_04_23: "gpt-5.5-pro-2026-04-23";
|
|
56
|
+
readonly GPT_5_5_PRO: "gpt-5.5-pro";
|
|
57
|
+
readonly GPT_5_4_2026_03_05: "gpt-5.4-2026-03-05";
|
|
58
|
+
readonly GPT_5_4: "gpt-5.4";
|
|
59
|
+
readonly GPT_5_4_PRO_2026_03_05: "gpt-5.4-pro-2026-03-05";
|
|
60
|
+
readonly GPT_5_4_PRO: "gpt-5.4-pro";
|
|
61
|
+
readonly GPT_5_4_MINI_2026_03_17: "gpt-5.4-mini-2026-03-17";
|
|
62
|
+
readonly GPT_5_4_MINI: "gpt-5.4-mini";
|
|
63
|
+
readonly GPT_5_4_NANO_2026_03_17: "gpt-5.4-nano-2026-03-17";
|
|
64
|
+
readonly GPT_5_4_NANO: "gpt-5.4-nano";
|
|
65
|
+
readonly GPT_5_3_CHAT_LATEST: "gpt-5.3-chat-latest";
|
|
66
|
+
readonly GPT_5_2_2025_12_11: "gpt-5.2-2025-12-11";
|
|
67
|
+
readonly GPT_5_2: "gpt-5.2";
|
|
68
|
+
readonly GPT_5_2_CHAT_LATEST: "gpt-5.2-chat-latest";
|
|
69
|
+
readonly GPT_5_2_PRO_2025_12_11: "gpt-5.2-pro-2025-12-11";
|
|
70
|
+
readonly GPT_5_2_PRO: "gpt-5.2-pro";
|
|
71
|
+
readonly GPT_5_1_2025_11_13: "gpt-5.1-2025-11-13";
|
|
72
|
+
readonly GPT_5_1: "gpt-5.1";
|
|
73
|
+
readonly GPT_5_1_CHAT_LATEST: "gpt-5.1-chat-latest";
|
|
74
|
+
readonly GPT_5_2025_08_07: "gpt-5-2025-08-07";
|
|
75
|
+
readonly GPT_5: "gpt-5";
|
|
76
|
+
readonly GPT_5_CHAT_LATEST: "gpt-5-chat-latest";
|
|
77
|
+
readonly GPT_5_PRO_2025_10_06: "gpt-5-pro-2025-10-06";
|
|
78
|
+
readonly GPT_5_PRO: "gpt-5-pro";
|
|
79
|
+
readonly GPT_5_MINI_2025_08_07: "gpt-5-mini-2025-08-07";
|
|
80
|
+
readonly GPT_5_MINI: "gpt-5-mini";
|
|
81
|
+
readonly GPT_5_NANO_2025_08_07: "gpt-5-nano-2025-08-07";
|
|
82
|
+
readonly GPT_5_NANO: "gpt-5-nano";
|
|
83
|
+
readonly GPT_4_1_2025_04_14: "gpt-4.1-2025-04-14";
|
|
84
|
+
readonly GPT_4_1: "gpt-4.1";
|
|
85
|
+
readonly GPT_4_1_MINI_2025_04_14: "gpt-4.1-mini-2025-04-14";
|
|
86
|
+
readonly GPT_4_1_MINI: "gpt-4.1-mini";
|
|
87
|
+
readonly GPT_4_1_NANO_2025_04_14: "gpt-4.1-nano-2025-04-14";
|
|
88
|
+
readonly GPT_4_1_NANO: "gpt-4.1-nano";
|
|
89
|
+
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
|
+
readonly GPT_4O: "gpt-4o";
|
|
93
|
+
readonly GPT_4O_MINI_2024_07_18: "gpt-4o-mini-2024-07-18";
|
|
94
|
+
readonly GPT_4O_MINI: "gpt-4o-mini";
|
|
95
|
+
readonly O4_MINI_2025_04_16: "o4-mini-2025-04-16";
|
|
96
|
+
readonly O4_MINI: "o4-mini";
|
|
97
|
+
readonly O3_2025_04_16: "o3-2025-04-16";
|
|
98
|
+
readonly O3: "o3";
|
|
99
|
+
readonly O3_PRO_2025_06_10: "o3-pro-2025-06-10";
|
|
100
|
+
readonly O3_PRO: "o3-pro";
|
|
101
|
+
readonly O3_MINI_2025_01_31: "o3-mini-2025-01-31";
|
|
102
|
+
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
|
+
};
|
|
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"];
|
|
109
|
+
declare const DEFAULT_MODEL: "gpt-5.4-mini";
|
|
110
|
+
//#endregion
|
|
111
|
+
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_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};
|
|
@@ -0,0 +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";
|
|
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 };
|
|
@@ -0,0 +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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fifthrevision/axle",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/johncch/axle.git"
|
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
".": {
|
|
12
12
|
"types": "./dist/index.d.ts",
|
|
13
13
|
"import": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./models": {
|
|
16
|
+
"types": "./dist/providers/models.d.ts",
|
|
17
|
+
"import": "./dist/providers/models.js"
|
|
14
18
|
}
|
|
15
19
|
},
|
|
16
20
|
"bin": {
|
|
@@ -28,36 +32,35 @@
|
|
|
28
32
|
"test": "vitest run",
|
|
29
33
|
"changelog": "pnpm start -j ./jobs/changelog.job.yml --args",
|
|
30
34
|
"update-models": "pnpm start -j ./jobs/bootstrap-models.job.yml",
|
|
31
|
-
"release": "pnpm test && pnpm run build && npm version"
|
|
35
|
+
"release": "pnpm test && pnpm run build && npm version",
|
|
36
|
+
"cut-release": "node scripts/cut-release.mjs"
|
|
32
37
|
},
|
|
33
38
|
"author": "Chong Han Chua",
|
|
34
39
|
"license": "ISC",
|
|
35
40
|
"dependencies": {
|
|
36
|
-
"@anthropic-ai/sdk": "^0.
|
|
41
|
+
"@anthropic-ai/sdk": "^0.91.0",
|
|
37
42
|
"@commander-js/extra-typings": "^14.0.0",
|
|
38
|
-
"@google/genai": "^1.
|
|
43
|
+
"@google/genai": "^1.50.1",
|
|
39
44
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
40
45
|
"chalk": "^5.6.2",
|
|
41
46
|
"commander": "^14.0.3",
|
|
42
47
|
"glob": "^13.0.6",
|
|
43
|
-
"marked": "^
|
|
44
|
-
"marked-terminal": "^7.3.0",
|
|
48
|
+
"marked": "^18.0.2",
|
|
45
49
|
"mime": "^4.1.0",
|
|
46
|
-
"openai": "^6.
|
|
50
|
+
"openai": "^6.34.0",
|
|
47
51
|
"serialize-error": "^13.0.1",
|
|
48
52
|
"yaml": "^2.8.3",
|
|
49
53
|
"zod": "^4.3.6"
|
|
50
54
|
},
|
|
51
55
|
"devDependencies": {
|
|
52
56
|
"@arethetypeswrong/core": "^0.18.2",
|
|
53
|
-
"
|
|
54
|
-
"
|
|
55
|
-
"prettier": "^3.8.1",
|
|
57
|
+
"dotenv": "^17.4.2",
|
|
58
|
+
"prettier": "^3.8.3",
|
|
56
59
|
"prettier-plugin-organize-imports": "^4.3.0",
|
|
57
60
|
"publint": "^0.3.18",
|
|
58
|
-
"tsdown": "^0.21.
|
|
61
|
+
"tsdown": "^0.21.10",
|
|
59
62
|
"tsx": "^4.21.0",
|
|
60
|
-
"typescript": "^6.0.
|
|
61
|
-
"vitest": "^4.1.
|
|
63
|
+
"typescript": "^6.0.3",
|
|
64
|
+
"vitest": "^4.1.5"
|
|
62
65
|
}
|
|
63
66
|
}
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import e,{access as t,mkdir as n,readFile as r,stat as i,writeFile as a}from"node:fs/promises";import o,{dirname as s,extname as c,resolve as l}from"node:path";import*as u from"zod";import d,{z as f}from"zod";import"glob";import p from"mime";import m from"@anthropic-ai/sdk";import{FinishReason as h,GoogleGenAI as g}from"@google/genai";import _ from"openai";import{exec as v}from"node:child_process";import{promisify as y}from"node:util";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{marked as C}from"marked";import{markedTerminal as w}from"marked-terminal";import T from"node:crypto";var E=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:D(this.cause)}:{}}}};function D(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:D(e.cause)}:{}}:e}function O(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 k(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
|
-
|
|
3
|
-
`)}function A(e){return e.filter(e=>e.type===`tool-call`)}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})}async function N(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:M({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:M(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 ee(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,options:f}=e,p=[...a],m=[],h={in:0,out:0},g=0,_=0,v=e=>{p.push(e),m.push(e)},y=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`?P.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},b=(e,t,n,r)=>{r();let i=e.length>0?{role:`assistant`,id:t,model:n,content:e,finishReason:P.Cancelled}:void 0;return i&&v(i),d?.end(`ok`),{result:`cancelled`,messages:m,partial:i,usage:h}};for(;;){if(t.aborted)return b([],``,``,()=>{});if(u!==void 0&&_>=u)return y({result:`error`,messages:m,error:{type:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${u})`}}},usage:h});_+=1;let e=d?.startSpan(`turn-${_}`,{type:`llm`}),a=c?{...f,serverTools:c}:f,x=r.createStreamingRequest?.(i,{messages:p,system:o,tools:s,context:{tracer:e},signal:t,options:a});if(!x)throw e?.end(`error`),Error(`Provider does not support streaming. Use generate() instead.`);let S=[],C=``,w=``,T=null,E={in:0,out:0},D=-1,O=null,k=``,A=new Map,j=-1,M=()=>{O!==null&&D>=0&&(F(n,{type:O===`text`?`text:end`:`thinking:end`,index:D,final:k}),O=null,k=``,D=-1)};for await(let r of x){switch(r.type){case`start`:C=r.id,w=r.data.model,F(n,{type:`turn:start`,id:C,model:w});break;case`text-start`:M(),S.push({type:`text`,text:``}),j=S.length-1,D=g++,O=`text`,k=``,F(n,{type:`text:start`,index:D});break;case`text-delta`:{let e=S[j];e.text+=r.data.text,k=e.text,F(n,{type:`text:delta`,index:D,delta:r.data.text,accumulated:k});break}case`text-complete`:M();break;case`thinking-start`:M(),S.push({type:`thinking`,text:``}),j=S.length-1,D=g++,O=`thinking`,k=``,F(n,{type:`thinking:start`,index:D});break;case`thinking-delta`:{let e=S[j];e.text+=r.data.text,k=e.text,F(n,{type:`thinking:delta`,index:D,delta:r.data.text,accumulated:k});break}case`thinking-summary-delta`:{let e=S[j];e.text+=r.data.text,k=e.text,F(n,{type:`thinking:delta`,index:D,delta:r.data.text,accumulated:k});break}case`thinking-complete`:M();break;case`tool-call-start`:{M();let e=g++;S.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),j=S.length-1,A.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=S[j];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`:{M();let e=g++;S.push({type:`internal-tool`,id:r.data.id,name:r.data.name}),j=S.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=S[j];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`:M(),T=r.data.finishReason,E=r.data.usage;break;case`error`:{M();let t=r.data.usage??{in:0,out:0};return h.in+=t.in??0,h.out+=t.out??0,e?.end(`error`),y({result:`error`,messages:m,error:{type:`model`,error:{type:`error`,error:{type:r.data.type,message:r.data.message}}},usage:h})}default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.aborted)break}if(t.aborted)return e?.end(`ok`),b(S,C,w,M);if(T===null)return M(),e?.end(`error`),y({result:`error`,messages:m,error:{type:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:h});h.in+=E.in??0,h.out+=E.out??0;let I={kind:`llm`,model:w,request:{messages:p},response:{content:S},usage:{inputTokens:E.in,outputTokens:E.out},finishReason:T};e?.setResult(I),e?.end();let L={role:`assistant`,id:C,model:w,content:S,finishReason:T};if(v(L),F(n,{type:`turn:complete`,message:L,usage:E}),T!==P.FunctionCall)return y({result:`success`,messages:m,final:L,usage:h});let R=S.filter(e=>e.type===`tool-call`);if(R.length===0)return y({result:`success`,messages:m,final:L,usage:h});if(t.aborted)return d?.end(`ok`),{result:`cancelled`,messages:m,usage:h};let z=crypto.randomUUID();F(n,{type:`tool-results:start`,id:z});let B=0,{results:V}=await N(R,async(e,t)=>{let r=R[B++],i=A.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)??ee(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};v(e),F(n,{type:`tool-results:complete`,message:e})}}}var R=class{rootPath;constructor(e){this.rootPath=e}async read(t){let n=o.join(this.rootPath,t);try{return await e.readFile(n,`utf-8`)}catch{return null}}async write(t,n){let r=o.join(this.rootPath,t);await e.mkdir(o.dirname(r),{recursive:!0}),await e.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 H(e){return Array.isArray(e)?e:[e]}function te(e){return new Promise(t=>setTimeout(t,e))}function ne(e){return e.then(()=>{},()=>{})}function U(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:ne(a)}}function re(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 W(e){if(e instanceof u.ZodString)return[`string`,`Your answer`];if(e instanceof u.ZodNumber)return[`number`,42];if(e instanceof u.ZodBoolean)return[`boolean`,!0];if(e instanceof u.ZodArray){let t=e.element;if(t instanceof u.ZodString)return[`string array`,[`answer 1`,`answer 2`,`third answer`]];if(t instanceof u.ZodNumber)return[`number array`,[42,59,3.14]];if(t instanceof u.ZodBoolean)return[`boolean array`,[!0,!1,!1]];if(t instanceof u.ZodObject){let[,e]=W(t);return[`object array`,[e,e]]}return[`array`,[]]}if(e instanceof u.ZodObject){let t=e.shape,n={};for(let[e,r]of Object.entries(t)){let[,t]=W(r);n[e]=t}return[`JSON object`,n]}if(e instanceof u.ZodOptional){let[t,n]=W(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function G(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=ie(e),r={};for(let[e,i]of Object.entries(t)){let t=n.tags[e];if(t!==void 0)r[e]=K(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 K(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 K(n,t)}default:return t}}function ie(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 q(e,t={},n={}){let r={...t,...e.inputs},i=re(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}'''`}let a=`# Instructions
|
|
4
|
-
|
|
5
|
-
`;if((e.schema?Object.keys(e.schema):[]).length>0){a+=`## Output Format Instructions
|
|
6
|
-
`,a+=`
|
|
7
|
-
Here is how you should format your output. Follow the instructions strictly.
|
|
8
|
-
`;for(let[t,n]of Object.entries(e.schema)){let[e,r]=W(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`}}if(e.instructions.length>0){a+=`
|
|
9
|
-
## Additional Instructions
|
|
10
|
-
|
|
11
|
-
`;for(let t of e.instructions)a+=`- ${t}\n`}return a+i}var J=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 ae(e){return e.type===`server`}var oe=class{provider;model;history;tracer;name;scope;store;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 J,this.tracer=e.tracer,this.system=e.system,this.name=e.name,this.scope=e.scope,this.store=new R(`.axle`),this.options=e.options??{},e.tools&&this.addTools(e.tools),e.mcps&&(this.mcps=[...e.mcps]),e.memory){if(!e.name)throw new E(`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){ae(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=q(e,t?.variables,{strictVariables:this.options.strictVariables}),a=e.files;r={role:`user`,id:crypto.randomUUID(),content:O({text:i,files:a})},n=e.schema}let{handle:i,settled:a}=U(this.sendQueue,e=>this.run(r,n,e),t?.signal);return this.sendQueue=a,i}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){let r=new V;await this.resolveMcpTools();let i=this.system,a=[...this.history.log,e];if(this.memory){let e=await this.memory.recall({name:this.name,scope:this.scope,system:this.system,messages:a,store:this.store,tracer:this.tracer});e.systemSuffix&&(i=(i??``)+`
|
|
12
|
-
|
|
13
|
-
`+e.systemSuffix)}if(n.aborted)return{response:null,turn:void 0,usage:{in:0,out:0}};let{turn:o,events:s}=r.createUserTurn(e);this.history.addTurn(o),this.history.appendToLog(e);for(let e of s)this.emitEvent(e);let c=this.tools,l=Object.values(c).map(e=>({name:e.name,description:e.description,schema:e.schema})),{turn:u,events:d}=r.startAgentTurn();this.history.addTurn(u);for(let e of d)this.emitEvent(e);let f=I({provider:this.provider,model:this.model,messages:a,system:i,tools:l.length>0?l:void 0,serverTools:this.serverTools.length>0?this.serverTools:void 0,tracer:this.tracer,onToolCall:async(e,t)=>{let n=c[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});f.on(e=>{let t=r.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=r.finalizeTurn(m);for(let e of h)this.emitEvent(e);if(p.result===`error`)throw new E(se(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=G(k(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 se(e){return e.type===`model`?`Model error: ${e.error.error.message}`:`Tool error (${e.error.name}): ${e.error.message}`}async function ce(e,t){let{defaults:n,tag:i}=t,a=null,o=``;if(e)try{o=l(e),a=await r(o,{encoding:`utf-8`})}catch{throw Error(`${i} not found, see --help for details`)}else{for(let e of n.formats)try{o=l(n.name+`.`+e),a=await r(o,{encoding:`utf-8`});break}catch{continue}if(a===null)throw Error(`${i} not found, see --help for details`)}return{content:a,format:o.split(`.`).pop()??``,path:o}}const le=20*1024*1024;function ue(e){return e.type===`text`}function de(e){return e.type===`image`||e.type===`document`}const fe=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function pe(e){return e.startsWith(`text/`)||fe.has(e)}function me(e){let t=p.getType(e);if(!t){let t=c(e).toLowerCase();throw Error(`Unsupported file type: ${t||`(no extension)`}`)}if(t.startsWith(`image/`))return{type:`image`,mimeType:t};if(t===`application/pdf`)return{type:`document`,mimeType:t};if(pe(t))return{type:`text`,mimeType:t};{let n=c(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function he(e,n){let a=l(e);try{await t(a)}catch{throw Error(`File not found: ${e}`)}let o=await i(a);if(o.size>le)throw Error(`File too large: ${o.size} bytes. Maximum allowed: ${le} bytes`);let s=a.split(`/`).pop()||``,c=me(a);if((n||(c.type===`text`?`utf-8`:`base64`))===`utf-8`){if(c.type!==`text`)throw Error(`Cannot read ${c.type} file as text: ${e}`);return{path:a,content:await r(a,`utf-8`),mimeType:c.mimeType,size:o.size,name:s,type:`text`}}else{if(c.type===`text`)throw Error(`Cannot read text file as binary: ${e}`);return{path:a,base64:(await r(a)).toString(`base64`),mimeType:c.mimeType,size:o.size,name:s,type:c.type}}}var ge=class{prompt;inputs={};files=[];textReferences=[];instructions=[];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}de(e)?this.files.push(e):ue(e)&&this.textReferences.push({content:e.content,name:t?.name??e.name})}addInstructions(e){if(typeof e!=`string`||e.trim()===``)throw Error(`Instruction must be a non-empty string`);this.instructions.push(e)}hasFiles(){return this.files.length>0}};const Y={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`};Y.CLAUDE_OPUS_4_7,Y.CLAUDE_SONNET_4_6,Y.CLAUDE_OPUS_4_6,Y.CLAUDE_OPUS_4_5_20251101,Y.CLAUDE_SONNET_4_5_20250929,Y.CLAUDE_HAIKU_4_5_20251001,Y.CLAUDE_OPUS_4_1_20250805,Y.CLAUDE_OPUS_4_20250514,Y.CLAUDE_SONNET_4_20250514;const _e={[Y.CLAUDE_OPUS_4_7]:128e3,[Y.CLAUDE_OPUS_4_6]:128e3,[Y.CLAUDE_SONNET_4_6]:64e3,[Y.CLAUDE_OPUS_4_5]:64e3,[Y.CLAUDE_SONNET_4_5]:64e3,[Y.CLAUDE_HAIKU_4_5]:64e3,[Y.CLAUDE_SONNET_4]:64e3,[Y.CLAUDE_OPUS_4_1]:32e3,[Y.CLAUDE_OPUS_4]:32e3},ve=Y.CLAUDE_HAIKU_4_5;function X(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}}function ye(e){return e.map(e=>{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:e.content.map(e=>({type:`tool_result`,tool_use_id:e.id,content:typeof e.content==`string`?e.content:we(e.content),...e.isError?{is_error:!0}:{}}))};if(typeof e.content==`string`)return{role:`user`,content:e.content};{let t=[];for(let n of e.content)n.type===`text`?t.push({type:`text`,text:n.text}):n.type===`file`&&(n.file.type===`image`?n.file.base64&&t.push({type:`image`,source:{type:`base64`,media_type:n.file.mimeType,data:n.file.base64}}):n.file.type===`document`&&n.file.mimeType===`application/pdf`&&n.file.base64&&t.push({type:`document`,source:{type:`base64`,media_type:`application/pdf`,data:n.file.base64}}));return{role:`user`,content:t}}})}function be(e){return e.map(e=>{let t=d.toJSONSchema(e.schema);if(!Ce(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}function xe(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 Se(e){switch(e){case`max_tokens`:return P.Length;case`end_turn`:return P.Stop;case`stop_sequence`:return P.Stop;case`tool_use`:return P.FunctionCall;default:return P.Error}}function Ce(e){return e&&typeof e==`object`&&e.type===`object`}function we(e){return e.map(e=>e.type===`text`?{type:`text`,text:e.text}:{type:`image`,source:{type:`base64`,media_type:e.mimeType,data:e.data}})}async function Te(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,options:s}=e,c=o?.tracer,{stop:l,max_tokens:u,...d}=s??{},f={model:n,max_tokens:u??16e3,messages:ye(r),...i&&{system:i},...l&&{stop_sequences:H(l)},...a&&{tools:be(a)},...d};c?.debug(`Anthropic request`,{request:f});let p;try{p=Ee(await t.messages.create(f))}catch(e){p=X(e)}return c?.debug(`Anthropic response`,{result:p}),p}function Ee(e){let t=Se(e.stop_reason);if(t===P.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===P.FunctionCall){let t=xe(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:P.FunctionCall,content:t,text:k(t),usage:{in:e.usage.input_tokens,out:e.usage.output_tokens},raw:e}}if(e.type==`message`){let n=xe(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:k(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 De(){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:Se(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*Oe(e){let{client:t,model:n,messages:r,system:i,tools:a,runtime:o,signal:s,options:c}=e,l=o?.tracer,{stop:u,max_tokens:d,serverTools:f,...p}=c??{},m=a?be(a):[];if(f){let e={web_search:`web_search_20250305`};for(let t of f){let n=e[t.name]??t.name;m.push({type:n,name:t.name,...t.config})}}let h={model:n,max_tokens:d??ke(n),messages:ye(r),...i&&{system:i},...u&&{stop_sequences:H(u)},...m.length>0&&{tools:m},...p};l?.debug(`Anthropic streaming request`,{request:h});let g=De();try{let e=await t.messages.create({...h,stream:!0},{signal:s});for await(let t of e){let e=g.handleEvent(t);for(let t of e)yield t}}catch(e){if(s?.aborted)return;yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function ke(e){return e in _e?_e[e]:e.includes(`opus`)?e.match(/opus-4-[6-9]|opus-[5-9]/)?128e3:64e3:e.includes(`sonnet`)||e.includes(`haiku`)?e.match(/claude-3-[0-5]-/)?8192:64e3:16384}function Ae(e){let t=new m({apiKey:e});return{name:`anthropic`,async createGenerationRequest(e,n){return await Te({client:t,model:e,...n})},createStreamingRequest(e,n){let{messages:r,system:i,tools:a,context:o,signal:s,options:c}=n;return Oe({client:t,model:e,messages:r,system:i,tools:a,runtime:o,signal:s,options:c})}}}function je(e,t){let n=e.map(Ne).flat(1);return t?[{role:`system`,content:t},...n]:n}function Me(e){if(e&&e.length>0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:d.toJSONSchema(e.schema)}}))}function Z(e){switch(e){case`stop`:return P.Stop;case`length`:return P.Length;case`tool_calls`:case`function_call`:return P.FunctionCall;case`content_filter`:return P.Error;default:return P.Stop}}function Ne(e){switch(e.role){case`tool`:return Pe(e);case`assistant`:return Fe(e);default:return Ie(e)}}function Pe(e){return e.content.map(e=>({role:`tool`,content:typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
14
|
-
`),tool_call_id:e.id}))}function Fe(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}}}function Ie(e){if(typeof e.content==`string`)return{role:`user`,content:e.content};let t=e.content.map(Le).filter(e=>e!==null);return t.every(e=>e.type===`text`)?{role:`user`,content:t.map(e=>e.text).join(``)}:{role:`user`,content:t}}function Le(e){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`&&e.file.type===`image`?{type:`image_url`,image_url:{url:`data:${e.file.mimeType};base64,${e.file.base64}`}}:null}async function Re(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,context:o,apiKey:s,options:c}=e,l=o?.tracer,u=je(r,i),d=Me(a),f={model:n,messages:u,...d&&{tools:d}};c&&(c.temperature!==void 0&&(f.temperature=c.temperature),c.top_p!==void 0&&(f.top_p=c.top_p),c.max_tokens!==void 0&&(f.max_tokens=c.max_tokens),c.frequency_penalty!==void 0&&(f.frequency_penalty=c.frequency_penalty),c.presence_penalty!==void 0&&(f.presence_penalty=c.presence_penalty),c.stop!==void 0&&(f.stop=c.stop)),l?.debug(`ChatCompletions request`,{request:f});let p;try{let e={"Content-Type":`application/json`};s&&(e.Authorization=`Bearer ${s}`);let n=await fetch(`${t}/chat/completions`,{method:`POST`,headers:e,body:JSON.stringify(f)});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`HTTP error! status: ${n.status}${e?` - ${e}`:``}`)}p=ze(await n.json())}catch(e){l?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),p=X(e)}return l?.debug(`ChatCompletions response`,{result:p}),p}function ze(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:k(n),usage:{in:e.usage?.prompt_tokens||0,out:e.usage?.completion_tokens||0},raw:e}}function Be(){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*Ve(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,context:o,signal:s,apiKey:c,options:l}=e,u=o?.tracer;l?.serverTools&&u?.warn(`serverTools not supported by ChatCompletions provider`);let d=je(r,i),f=Me(a),p={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},...f&&{tools:f}};l&&(l.temperature!==void 0&&(p.temperature=l.temperature),l.top_p!==void 0&&(p.top_p=l.top_p),l.max_tokens!==void 0&&(p.max_tokens=l.max_tokens),l.frequency_penalty!==void 0&&(p.frequency_penalty=l.frequency_penalty),l.presence_penalty!==void 0&&(p.presence_penalty=l.presence_penalty),l.stop!==void 0&&(p.stop=l.stop)),u?.debug(`ChatCompletions streaming request`,{request:p});let m=Be();try{let e={"Content-Type":`application/json`};c&&(e.Authorization=`Bearer ${c}`);let n=await fetch(`${t}/chat/completions`,{method:`POST`,headers:e,body:JSON.stringify(p),signal:s});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`HTTP error! status: ${n.status}${e?` - ${e}`:``}`)}if(!n.body)throw Error(`Response body is null`);let r=n.body.getReader(),i=new TextDecoder,a=``;for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
|
|
15
|
-
`);a=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=m.handleChunk(e);for(let e of t)yield e}catch(e){u?.error(`Error parsing ChatCompletions stream chunk`,{error:e instanceof Error?e.message:String(e),line:t})}}}for(let e of m.finalize())yield e}catch(e){if(s?.aborted)return;u?.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 He(e,t){return{name:`ChatCompletions`,async createGenerationRequest(n,r){return await Re({baseUrl:e,model:n,apiKey:t,...r})},createStreamingRequest(n,r){return Ve({baseUrl:e,model:n,apiKey:t,...r})}}}const Q={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`};Q.GEMINI_3_1_PRO_PREVIEW,Q.GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS,Q.GEMINI_3_1_FLASH_LITE_PREVIEW,Q.GEMINI_3_PRO_PREVIEW,Q.GEMINI_3_FLASH_PREVIEW,Q.GEMINI_2_5_PRO,Q.GEMINI_2_5_FLASH,Q.GEMINI_2_5_FLASH_LITE,Q.GEMINI_2_0_FLASH,Q.GEMINI_2_0_FLASH_001,Q.GEMINI_2_0_FLASH_LITE,Q.GEMINI_2_0_FLASH_LITE_001,Q.GEMINI_FLASH_LATEST,Q.GEMINI_FLASH_LITE_LATEST,Q.GEMINI_PRO_LATEST,Q.GEMMA_4_31B_IT,Q.GEMMA_4_E4B_IT,Q.GEMMA_3_27B_IT,Q.GEMMA_3_12B_IT,Q.GEMMA_3_4B_IT,Q.GEMMA_3_1B_IT,Q.GEMMA_3N_E4B_IT,Q.GEMMA_3N_E2B_IT;const Ue=Q.GEMINI_3_1_FLASH_LITE_PREVIEW;function We(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:d.toJSONSchema(e.schema)}]}))),n&&Object.assign(r,n),r}function Ge(e){return e.map(Ke).filter(e=>e!==void 0)}function Ke(e){switch(e.role){case`tool`:return qe(e);case`assistant`:return Je(e);case`user`:return Ye(e)}}function qe(e){return{role:`user`,parts:e.content.flatMap(e=>{let t={functionResponse:{id:e.id??void 0,name:e.name,response:{output:typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
16
|
-
`)}}};return typeof e.content==`string`?[t]:[t,...e.content.filter(e=>e.type===`image`).map(e=>({inlineData:{mimeType:e.mimeType,data:e.data}}))]})}}function Je(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}}function Ye(e){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:e.content.map(Xe).filter(e=>e!==null)}}function Xe(e){return e.type===`text`?{text:e.text}:e.type===`file`&&(e.file.type===`image`||e.file.type===`document`)?{inlineData:{mimeType:e.file.mimeType,data:e.file.base64}}:null}function Ze(e){switch(e){case h.STOP:return[!0,P.Stop];case h.MAX_TOKENS:return[!0,P.Length];case h.FINISH_REASON_UNSPECIFIED:case h.SAFETY:case h.RECITATION:case h.LANGUAGE:case h.OTHER:case h.BLOCKLIST:case h.PROHIBITED_CONTENT:case h.SPII:case h.MALFORMED_FUNCTION_CALL:case h.IMAGE_SAFETY:return[!1,P.Error]}return[!1,P.Error]}async function Qe(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,options:s}=e,c=o?.tracer,l=s?{...s}:{};l.max_tokens&&(l.maxOutputTokens=l.max_tokens,delete l.max_tokens),l.stop&&(l.stopSequences=Array.isArray(l.stop)?l.stop:[l.stop],delete l.stop),l.top_p!==void 0&&(l.topP=l.top_p,delete l.top_p);let u={contents:Ge(r),config:We(a,i,l)};c?.debug(`Gemini request`,{request:u});let d;try{d=$e(await t.models.generateContent({model:n,...u}),{tracer:c})}catch(e){c?.error(e instanceof Error?e.message:String(e)),d=X(e)}return c?.debug(`Gemini response`,{result:d}),d}function $e(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]=Ze(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?P.FunctionCall:c,content:t,text:k(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function et(){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;if(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!==h.FINISH_REASON_UNSPECIFIED){c(u);let[e,t]=Ze(d.finishReason),r=n?P.FunctionCall: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*tt(e){let{client:t,model:n,messages:r,system:i,tools:a,runtime:o,signal:s,options:c}=e,l=o?.tracer,{serverTools:u,...d}=c??{},f=d?{...d}:{};f.max_tokens&&(f.maxOutputTokens=f.max_tokens,delete f.max_tokens),f.stop&&(f.stopSequences=Array.isArray(f.stop)?f.stop:[f.stop],delete f.stop),f.top_p!==void 0&&(f.topP=f.top_p,delete f.top_p);let p=We(a,i,f);if(u){let e={web_search:`googleSearch`,code_execution:`codeExecution`};p.tools||=[];for(let t of u){let n=e[t.name]??t.name;p.tools.push({[n]:t.config??{}})}}let m={contents:Ge(r),config:p};l?.debug(`Gemini streaming request`,{request:m});let h=et();try{let e=await t.models.generateContentStream({model:n,...m});for await(let t of e){let e=h.handleChunk(t);for(let t of e)yield t}}catch(e){if(s?.aborted)return;l?.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){let t=new g({apiKey:e});return{name:`Gemini`,async createGenerationRequest(e,n){return await Qe({client:t,model:e,...n})},createStreamingRequest(e,n){let{messages:r,system:i,tools:a,context:o,signal:s,options:c}=n;return tt({client:t,model:e,messages:r,system:i,tools:a,runtime:o,signal:s,options:c})}}}async function rt(e){let{provider:t,model:n,messages:r,system:i,tools:a,tracer:o,options:s}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,context:{tracer:o},options:s})}async function it(e){let{provider:t,model:n,messages:r,system:i,tools:a,onToolCall:o,maxIterations:s,tracer:c,options:l}=e,u=[...r],d=[],f={in:0,out:0},p=0,m,h=e=>{u.push(e),d.push(e)},g=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),_=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??n,request:{messages:u},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&&p>=s)return g({result:`error`,messages:d,error:{type:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${s})`}}},usage:f});p+=1;let e=c?.startSpan(`turn-${p}`,{type:`llm`}),r=await rt({provider:t,model:n,messages:u,system:i,tools:a,tracer:e,options:l});if(j(f,r),_(e,r),r.type===`error`)return g({result:`error`,messages:d,error:{type:`model`,error:r},usage:f});let v={role:`assistant`,id:r.id,model:r.model,content:r.content,finishReason:r.finishReason};if(h(v),m=v,r.finishReason!==P.FunctionCall)return g({result:`success`,messages:d,final:m,usage:f});let y=A(r.content);if(y.length===0)return g({result:`success`,messages:d,final:m,usage:f});let{results:b}=await N(y,o,c);b.length>0&&h({role:`tool`,id:crypto.randomUUID(),content:b})}}const $={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`,GPT_4_TURBO_2024_04_09:`gpt-4-turbo-2024-04-09`,GPT_4_TURBO:`gpt-4-turbo`,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`};$.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,$.GPT_4_TURBO,$.O4_MINI,$.O3,$.O3_PRO,$.O3_MINI,$.O1,$.O1_PRO;const at=$.GPT_5_4_MINI;function ot(e){if(e&&e.length>0)return e.map(e=>({type:`function`,strict:!0,name:e.name,description:e.description,parameters:d.toJSONSchema(e.schema)}))}function st(e){return e.map(ct).flat(1)}function ct(e){switch(e.role){case`tool`:return lt(e);case`assistant`:return ut(e);default:return dt(e)}}function lt(e){return e.content.map(e=>({type:`function_call_output`,call_id:e.id,output:typeof e.content==`string`?e.content:e.content.map(e=>e.type===`text`?{type:`input_text`,text:e.text}:{type:`input_image`,image_url:`data:${e.mimeType};base64,${e.data}`})}))}function ut(e){let t=[],n=k(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}function dt(e){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let t=e.content.map(ft).filter(e=>e!==null);return{role:e.role,content:t}}}function ft(e){if(e.type===`text`)return{type:`input_text`,text:e.text};if(e.type===`file`){if(e.file.type===`image`)return{type:`input_image`,image_url:`data:${e.file.mimeType};base64,${e.file.base64}`,detail:`auto`};if(e.file.type===`document`)return{type:`input_file`,filename:e.file.path,file_data:`data:${e.file.mimeType};base64,${e.file.base64}`}}return e.type,null}async function pt(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,options:s}=e,c=o?.tracer,l=ot(a),u={model:n,input:st(r),...i&&{instructions:i},...l?{tools:l}:{},...s};c?.debug(`OpenAI ResponsesAPI request`,{request:u});let d;try{d=mt(await t.responses.create(u))}catch(e){c?.error(e instanceof Error?e.message:String(e)),d=X(e)}return c?.debug(`OpenAI ResponsesAPI response`,{result:d}),d}function mt(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?P.Error:P.Stop,content:n,text:k(n),usage:{in:e.usage?.input_tokens??0,out:e.usage?.output_tokens??0},raw:e}}function ht(){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?P.Error:i?P.FunctionCall:P.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*gt(e){let{client:t,model:n,messages:r,system:i,tools:a,runtime:o,signal:s,options:c}=e,l=o?.tracer,{serverTools:u,...d}=c??{},f=ot(a)??[];if(u){let e={web_search:`web_search_preview`,code_execution:`code_interpreter`};for(let t of u){let n=e[t.name]??t.name;f.push({type:n,...t.config})}}let p={model:n,input:st(r),...i&&{instructions:i},stream:!0,...f.length>0?{tools:f}:{},...d};l?.debug(`OpenAI ResponsesAPI streaming request`,{request:p});let m=ht();try{let e=t.responses.stream(p,...s?[{signal:s}]:[]);for await(let t of e){let e=m.handleEvent(t);for(let t of e)yield t}}catch(e){if(s?.aborted)return;l?.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 _t(e){let t=new _({apiKey:e});return{name:`OpenAI`,async createGenerationRequest(e,n){return await pt({client:t,model:e,...n})},createStreamingRequest(e,n){let{messages:r,system:i,tools:a,context:o,signal:s,options:c}=n;return gt({client:t,model:e,messages:r,system:i,tools:a,runtime:o,signal:s,options:c})}}}const vt=u.object({searchTerm:u.string().describe(`The search term to query`)}),yt=new class{name=`brave`;description=`Perform a search using the Brave search engine`;schema=vt;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 te(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:f.object({operation:f.enum([`add`,`subtract`,`multiply`,`divide`]).describe(`The operation to perform (add, subtract, multiply, divide)`),a:f.number().describe(`First operand`),b:f.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}`)}}},xt=y(v);async function St(e,t={}){let{stdout:n,stderr:r}=await xt(e,{cwd:t.cwd,timeout:t.timeout??3e4,maxBuffer:t.maxBuffer??1048576});return{stdout:n,stderr:r}}function Ct(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 Tt=u.object({command:u.string().describe(`The shell command to execute`)}),Et=new class{name=`exec`;description=`Execute a shell command and return the output.`;schema=Tt;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 St(t,{timeout:this.timeout,maxBuffer:this.maxBuffer,cwd:this.cwd});return wt(e.stdout,e.stderr)}catch(e){return Ct(e)}}},Dt={name:`patch-file`,description:`Patch a file by replacing an exact string match within a specified line range`,schema:f.object({path:f.string().describe(`The file path to patch`),old_string:f.string().describe(`The exact text to find and replace`),new_string:f.string().describe(`The replacement text`),start_line:f.number().int().positive().describe(`1-indexed start line of the region to match within`),end_line:f.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:i,end_line:o})=>{if(o<i)throw Error(`end_line (${o}) must be >= start_line (${i})`);let s;try{s=await r(e,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to read file "${e}": ${t.message}`):t}let c=s.split(`
|
|
17
|
-
`);if(i>c.length)throw Error(`start_line (${i}) exceeds file length (${c.length} lines)`);if(o>c.length)throw Error(`end_line (${o}) exceeds file length (${c.length} lines)`);let l=c.slice(i-1,o).join(`
|
|
18
|
-
`),u=l.indexOf(t);if(u===-1)throw Error(`old_string not found within lines ${i}-${o} of "${e}"`);if(l.indexOf(t,u+1)!==-1)throw Error(`old_string matches multiple times within lines ${i}-${o} of "${e}"`);let d=l.replace(t,n),f=[...c.slice(0,i-1),...d.split(`
|
|
19
|
-
`),...c.slice(o)].join(`
|
|
20
|
-
`);try{await a(e,f,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to write file "${e}": ${t.message}`):t}return`Successfully patched "${e}" (lines ${i}-${o})`}},Ot={name:`read-file`,description:`Read the contents of a file from disk`,schema:f.object({path:f.string().describe(`The file path to read from`)}),summarize:({path:e})=>e,execute:async({path:e})=>{try{return await r(e,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to read file "${e}": ${t.message}`):t}}},kt={name:`write-file`,description:`Write content to a file on disk, creating directories if needed`,schema:f.object({path:f.string().describe(`The file path to write to`),content:f.string().describe(`The content to write to the file`)}),summarize:({path:e})=>e,execute:async({path:e,content:t})=>{try{return await n(s(e),{recursive:!0}),await a(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 At(e){try{let t=d.fromJSONSchema(e);return t instanceof d.ZodObject?t.strict():d.object({}).passthrough()}catch{return d.object({}).passthrough()}}function jt(e,t,n){return e.map(e=>Nt(e,t,n))}function Mt(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=At(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function Nt(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=At(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(Ft(r.content));return Pt(r.content)}}}function Pt(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:`image`,data:t.data,mimeType:t.mimeType}}):e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
21
|
-
`)}function Ft(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
22
|
-
`)||`MCP tool execution error`}var It=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 jt(await this.fetchTools(t,e?.tracer),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return Mt(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){return this.cachedMcpTools?this.cachedMcpTools:(t?.debug(`mcp:listTools`),this.cachedMcpTools=(await e.listTools()).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 Lt={debug:0,info:1,warn:2,error:3};var Rt=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 zt(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 Lt[e]>=Lt[this._minLevel]}},zt=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 Bt={debug:0,info:1,warn:2,error:3};let Vt=!1;function Ht(){Vt||=(C.use(w()),!0)}var Ut=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 Bt[e]>=Bt[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 Ht(),C.parse(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(`
|
|
23
|
-
`);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)}},Wt=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(`
|
|
24
|
-
`);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 it({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.
|
|
25
|
-
|
|
26
|
-
Only extract:
|
|
27
|
-
- Explicit user corrections (e.g., "No, always use bullet points")
|
|
28
|
-
- Stated preferences (e.g., "I prefer concise summaries")
|
|
29
|
-
- Patterns that clearly emerged from user feedback
|
|
30
|
-
|
|
31
|
-
Do NOT extract:
|
|
32
|
-
- General knowledge or facts from the conversation content
|
|
33
|
-
- Inferences or speculation about what the user might want
|
|
34
|
-
- Task-specific details that won't apply to future runs
|
|
35
|
-
|
|
36
|
-
Respond with a JSON array of instruction strings. Each instruction should be a clear, actionable directive.
|
|
37
|
-
If there are no learnings to extract, respond with an empty array: []
|
|
38
|
-
|
|
39
|
-
Example response:
|
|
40
|
-
["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=k(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:f.object({instruction:f.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:k(n.content);e&&t.push(`User: ${e}`)}else if(n.role===`assistant`){let e=k(n.content);e&&t.push(`Assistant: ${e}`)}return t.join(`
|
|
41
|
-
|
|
42
|
-
`)}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}-${T.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{U as A,ge as C,J as D,oe as E,R as M,I as N,q as O,P,Y as S,ce as T,Ue as _,kt as a,Ae as b,Et as c,_t as d,at as f,nt as g,rt as h,It as i,V as j,G as k,bt as l,it as m,Ut as n,Ot as o,$ as p,Rt as r,Dt as s,Wt as t,yt as u,Q as v,he as w,ve as x,He as y};
|