@fifthrevision/axle 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -8
- package/dist/index.d.mts +1173 -0
- package/dist/index.mjs +38 -0
- package/package.json +15 -13
- package/dist/ProceduralMemory-BtEMO_Cx.js +0 -59
- package/dist/cli.js +0 -8
- package/dist/index.d.ts +0 -953
- package/dist/index.js +0 -1
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import e,{access as t,readFile as n,stat as r}from"node:fs/promises";import i,{extname as a,resolve as o}from"node:path";import*as s from"zod";import c,{z as l}from"zod";import"glob";import u from"mime";import d from"@anthropic-ai/sdk";import{FinishReason as f,GoogleGenAI as p}from"@google/genai";import m from"openai";import{exec as h}from"node:child_process";import{promisify as g}from"node:util";import{Client as _}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as v}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as y}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{marked as b}from"marked";import{markedTerminal as x}from"marked-terminal";import S from"node:crypto";var C=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:w(this.cause)}:{}}}};function w(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:w(e.cause)}:{}}:e}function T(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 E(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
|
+
|
|
3
|
+
`)}function D(e){return e.filter(e=>e.type===`tool-call`)}function O(e,t){let n=t.usage??{in:0,out:0};e.in+=n.in??0,e.out+=n.out??0}function k(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:k({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:k(a.error),isError:!0}))}return{results:r}}let A=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function j(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 M(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(()=>N(e,r,t).then(a,o)),{on(e){t.push(e)},cancel(){n.abort()},get final(){return i}}}async function N(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`&&j(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`?A.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:A.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=``,M=new Map,N=-1,P=()=>{O!==null&&D>=0&&(j(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,j(n,{type:`turn:start`,id:C,model:w});break;case`text-start`:P(),S.push({type:`text`,text:``}),N=S.length-1,D=g++,O=`text`,k=``,j(n,{type:`text:start`,index:D});break;case`text-delta`:{let e=S[N];e.text+=r.data.text,k=e.text,j(n,{type:`text:delta`,index:D,delta:r.data.text,accumulated:k});break}case`text-complete`:P();break;case`thinking-start`:P(),S.push({type:`thinking`,text:``}),N=S.length-1,D=g++,O=`thinking`,k=``,j(n,{type:`thinking:start`,index:D});break;case`thinking-delta`:{let e=S[N];e.text+=r.data.text,k=e.text,j(n,{type:`thinking:delta`,index:D,delta:r.data.text,accumulated:k});break}case`thinking-summary-delta`:{let e=S[N];e.text+=r.data.text,k=e.text,j(n,{type:`thinking:delta`,index:D,delta:r.data.text,accumulated:k});break}case`thinking-complete`:P();break;case`tool-call-start`:{P();let e=g++;S.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),N=S.length-1,M.set(r.data.id,e),j(n,{type:`tool:request`,index:e,id:r.data.id,name:r.data.name});break}case`tool-call-complete`:{let e=S[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=g++;S.push({type:`internal-tool`,id:r.data.id,name:r.data.name}),N=S.length-1,j(n,{type:`internal-tool:start`,index:e,id:r.data.id,name:r.data.name});break}case`internal-tool-complete`:{let e=S[N];r.data.output!=null&&(e.output=r.data.output),j(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(),T=r.data.finishReason,E=r.data.usage;break;case`error`:{P();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,P);if(T===null)return P(),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 F={kind:`llm`,model:w,request:{messages:p},response:{content:S},usage:{inputTokens:E.in,outputTokens:E.out},finishReason:T};e?.setResult(F),e?.end();let I={role:`assistant`,id:C,model:w,content:S,finishReason:T};if(v(I),j(n,{type:`turn:complete`,message:I,usage:E}),T!==A.FunctionCall)return y({result:`success`,messages:m,final:I,usage:h});let L=S.filter(e=>e.type===`tool-call`);if(L.length===0)return y({result:`success`,messages:m,final:I,usage:h});if(t.aborted)return d?.end(`ok`),{result:`cancelled`,messages:m,usage:h};let R=crypto.randomUUID();j(n,{type:`tool-results:start`,id:R});let z=0,{results:B}=await ee(L,async(e,t)=>{let r=L[z++],i=M.get(r.id)??-1;j(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 j(n,{type:`tool:exec-complete`,index:i,id:r.id,name:e,result:a}),a},d);if(B.length>0){let e={role:`tool`,id:R,content:B};v(e),j(n,{type:`tool-results:complete`,message:e})}}}var P=class{rootPath;constructor(e){this.rootPath=e}async read(t){let n=i.join(this.rootPath,t);try{return await e.readFile(n,`utf-8`)}catch{return null}}async write(t,n){let r=i.join(this.rootPath,t);await e.mkdir(i.dirname(r),{recursive:!0}),await e.writeFile(r,n,`utf-8`)}},F=class{currentTurn=null;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage={in:0,out:0};createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[];if(typeof e.content==`string`)n.push({id:crypto.randomUUID(),type:`text`,text:e.content});else for(let t of e.content)t.type===`text`?n.push({id:crypto.randomUUID(),type:`text`,text:t.text}):t.type===`file`&&n.push({id:crypto.randomUUID(),type:`file`,file:t.file});let r={id:t,owner:`user`,parts:n,status:`complete`};return{turn:r,events:[{type:`turn:user`,turn:r}]}}startAgentTurn(){let e=crypto.randomUUID(),t={id:e,owner:`agent`,parts:[],status:`streaming`};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:``};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,n.push({type:`part:end`,turnId:t.id,partId:this.currentTextPart.id}),null);break;case`thinking:start`:{this.closeOpenParts(t,n);let e={id:crypto.randomUUID(),type:`thinking`,text:``};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,n.push({type:`part:end`,turnId:t.id,partId:this.currentThinkingPart.id}),null);break;case`tool:request`:{this.closeOpenParts(t,n);let r=crypto.randomUUID(),i={id:r,type:`action`,kind:`tool`,status:`pending`,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.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.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`,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.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},n.push({type:`turn:end`,turnId:t.id,status:e,usage:t.usage}),this.currentTurn=null,n}closeOpenParts(e,t){this.currentTextPart&&=(t.push({type:`part:end`,turnId:e.id,partId:this.currentTextPart.id}),null),this.currentThinkingPart&&=(t.push({type:`part:end`,turnId:e.id,partId:this.currentThinkingPart.id}),null)}findActionPart(e,t){return e.parts.find(e=>e.id===t&&e.type===`action`)}};function I(e){return Array.isArray(e)?e:[e]}function L(e){return new Promise(t=>setTimeout(t,e))}function R(e){return e.then(()=>{},()=>{})}function z(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:R(a)}}function B(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 V(e){if(e instanceof s.ZodString)return[`string`,`Your answer`];if(e instanceof s.ZodNumber)return[`number`,42];if(e instanceof s.ZodBoolean)return[`boolean`,!0];if(e instanceof s.ZodArray){let t=e.element;if(t instanceof s.ZodString)return[`string array`,[`answer 1`,`answer 2`,`third answer`]];if(t instanceof s.ZodNumber)return[`number array`,[42,59,3.14]];if(t instanceof s.ZodBoolean)return[`boolean array`,[!0,!1,!1]];if(t instanceof s.ZodObject){let[,e]=V(t);return[`object array`,[e,e]]}return[`array`,[]]}if(e instanceof s.ZodObject){let t=e.shape,n={};for(let[e,r]of Object.entries(t)){let[,t]=V(r);n[e]=t}return[`JSON object`,n]}if(e instanceof s.ZodOptional){let[t,n]=V(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function H(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=ne(e),r={};for(let[e,i]of Object.entries(t)){let t=n.tags[e];if(t!==void 0)r[e]=U(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 U(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 U(n,t)}default:return t}}function ne(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 W(e,t={},n={}){let r={...t,...e.inputs},i=B(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]=V(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 G=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 re(e){return e.type===`server`}var ie=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 G,this.tracer=e.tracer,this.system=e.system,this.name=e.name,this.scope=e.scope,this.store=new P(`.axle`),this.options=e.options??{},e.tools&&this.addTools(e.tools),e.mcps&&(this.mcps=[...e.mcps]),e.memory){if(!e.name)throw new C(`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){re(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=W(e,t?.variables,{strictVariables:this.options.strictVariables}),a=e.files;r={role:`user`,id:crypto.randomUUID(),content:T({text:i,files:a})},n=e.schema}let{handle:i,settled:a}=z(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 F;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=M({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 C(ae(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=H(E(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 ae(e){return e.type===`model`?`Model error: ${e.error.error.message}`:`Tool error (${e.error.name}): ${e.error.message}`}const K=20*1024*1024;function oe(e){return e.type===`text`}function se(e){return e.type===`image`||e.type===`document`}const ce=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function le(e){return e.startsWith(`text/`)||ce.has(e)}function ue(e){let t=u.getType(e);if(!t){let t=a(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(le(t))return{type:`text`,mimeType:t};{let n=a(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function de(e,i){let a=o(e);try{await t(a)}catch{throw Error(`File not found: ${e}`)}let s=await r(a);if(s.size>K)throw Error(`File too large: ${s.size} bytes. Maximum allowed: ${K} bytes`);let c=a.split(`/`).pop()||``,l=ue(a);if((i||(l.type===`text`?`utf-8`:`base64`))===`utf-8`){if(l.type!==`text`)throw Error(`Cannot read ${l.type} file as text: ${e}`);return{path:a,content:await n(a,`utf-8`),mimeType:l.mimeType,size:s.size,name:c,type:`text`}}else{if(l.type===`text`)throw Error(`Cannot read text file as binary: ${e}`);return{path:a,base64:(await n(a)).toString(`base64`),mimeType:l.mimeType,size:s.size,name:c,type:l.type}}}var fe=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}se(e)?this.files.push(e):oe(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 q={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`,CLAUDE_3_HAIKU_20240307:`claude-3-haiku-20240307`,CLAUDE_3_HAIKU:`claude-3-haiku-20240307`};q.CLAUDE_SONNET_4_6,q.CLAUDE_OPUS_4_6,q.CLAUDE_OPUS_4_5_20251101,q.CLAUDE_SONNET_4_5_20250929,q.CLAUDE_HAIKU_4_5_20251001,q.CLAUDE_OPUS_4_1_20250805,q.CLAUDE_OPUS_4_20250514,q.CLAUDE_SONNET_4_20250514,q.CLAUDE_3_HAIKU_20240307;const pe=q.CLAUDE_HAIKU_4_5;function J(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 Y(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:_e(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 X(e){return e.map(e=>{let t=c.toJSONSchema(e.schema);if(!ge(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}function me(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 he(e){switch(e){case`max_tokens`:return A.Length;case`end_turn`:return A.Stop;case`stop_sequence`:return A.Stop;case`tool_use`:return A.FunctionCall;default:return A.Error}}function ge(e){return e&&typeof e==`object`&&e.type===`object`}function _e(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 ve(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:Y(r),...i&&{system:i},...l&&{stop_sequences:I(l)},...a&&{tools:X(a)},...d};c?.debug(`Anthropic request`,{request:f});let p;try{p=ye(await t.messages.create(f))}catch(e){p=J(e)}return c?.debug(`Anthropic response`,{result:p}),p}function ye(e){let t=he(e.stop_reason);if(t===A.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===A.FunctionCall){let t=me(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:A.FunctionCall,content:t,text:E(t),usage:{in:e.usage.input_tokens,out:e.usage.output_tokens},raw:e}}if(e.type==`message`){let n=me(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:E(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 be(){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:he(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*xe(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?X(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??Ce(n),messages:Y(r),...i&&{system:i},...u&&{stop_sequences:I(u)},...m.length>0&&{tools:m},...p};l?.debug(`Anthropic streaming request`,{request:h});let g=be();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}}}}const Se={[q.CLAUDE_OPUS_4_6]:128e3,[q.CLAUDE_OPUS_4_5_20251101]:64e3,[q.CLAUDE_HAIKU_4_5_20251001]:64e3,[q.CLAUDE_SONNET_4_5_20250929]:64e3,[q.CLAUDE_SONNET_4_20250514]:64e3,[q.CLAUDE_OPUS_4_1_20250805]:32e3,[q.CLAUDE_OPUS_4_20250514]:32e3,[q.CLAUDE_3_HAIKU_20240307]:4096};function Ce(e){return e in Se?Se[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 we(e){let t=new d({apiKey:e});return{name:`anthropic`,async createGenerationRequest(e,n){return await ve({client:t,model:e,...n})},createStreamingRequest(e,n){let{messages:r,system:i,tools:a,context:o,signal:s,options:c}=n;return xe({client:t,model:e,messages:r,system:i,tools:a,runtime:o,signal:s,options:c})}}}const Te={Models:q,DefaultModel:pe};function Ee(e,t){let n=e.map(Oe).flat(1);return t?[{role:`system`,content:t},...n]:n}function De(e){if(e&&e.length>0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:c.toJSONSchema(e.schema)}}))}function Z(e){switch(e){case`stop`:return A.Stop;case`length`:return A.Length;case`tool_calls`:case`function_call`:return A.FunctionCall;case`content_filter`:return A.Error;default:return A.Stop}}function Oe(e){switch(e.role){case`tool`:return ke(e);case`assistant`:return Ae(e);default:return je(e)}}function ke(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 Ae(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 je(e){if(typeof e.content==`string`)return{role:`user`,content:e.content};let t=e.content.map(Me).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 Me(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 Ne(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,context:o,apiKey:s,options:c}=e,l=o?.tracer,u=Ee(r,i),d=De(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=Pe(await n.json())}catch(e){l?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),p=J(e)}return l?.debug(`ChatCompletions response`,{result:p}),p}function Pe(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:E(n),usage:{in:e.usage?.prompt_tokens||0,out:e.usage?.completion_tokens||0},raw:e}}function Fe(){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*Ie(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=Ee(r,i),f=De(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=Fe();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 Le(e,t){return{name:`ChatCompletions`,async createGenerationRequest(n,r){return await Ne({baseUrl:e,model:n,apiKey:t,...r})},createStreamingRequest(n,r){return Ie({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 Re=Q.GEMINI_3_1_FLASH_LITE_PREVIEW;function ze(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:c.toJSONSchema(e.schema)}]}))),n&&Object.assign(r,n),r}function Be(e){return e.map(Ve).filter(e=>e!==void 0)}function Ve(e){switch(e.role){case`tool`:return He(e);case`assistant`:return Ue(e);case`user`:return We(e)}}function He(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 Ue(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 We(e){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:e.content.map(Ge).filter(e=>e!==null)}}function Ge(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 Ke(e){switch(e){case f.STOP:return[!0,A.Stop];case f.MAX_TOKENS:return[!0,A.Length];case f.FINISH_REASON_UNSPECIFIED:case f.SAFETY:case f.RECITATION:case f.LANGUAGE:case f.OTHER:case f.BLOCKLIST:case f.PROHIBITED_CONTENT:case f.SPII:case f.MALFORMED_FUNCTION_CALL:case f.IMAGE_SAFETY:return[!1,A.Error]}return[!1,A.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:Be(r),config:ze(a,i,l)};c?.debug(`Gemini request`,{request:u});let d;try{d=Je(await t.models.generateContent({model:n,...u}),{tracer:c})}catch(e){c?.error(e instanceof Error?e.message:String(e)),d=J(e)}return c?.debug(`Gemini response`,{result:d}),d}function Je(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]=Ke(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?A.FunctionCall:c,content:t,text:E(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function Ye(){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 p=d.content?.parts||[];for(let r of p){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!==f.FINISH_REASON_UNSPECIFIED){c(u);let[e,t]=Ke(d.finishReason),r=n?A.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*Xe(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=ze(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:Be(r),config:p};l?.debug(`Gemini streaming request`,{request:m});let h=Ye();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 Ze(e){let t=new p({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 Xe({client:t,model:e,messages:r,system:i,tools:a,runtime:o,signal:s,options:c})}}}const Qe={Models:Q,DefaultModel:Re};async function $e(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 et(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 $e({provider:t,model:n,messages:u,system:i,tools:a,tracer:e,options:l});if(O(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!==A.FunctionCall)return g({result:`success`,messages:d,final:m,usage:f});let y=D(r.content);if(y.length===0)return g({result:`success`,messages:d,final:m,usage:f});let{results:b}=await ee(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_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`};$.GPT_5_4,$.GPT_5_4_PRO,$.GPT_5_4_MINI,$.GPT_5_4_NANO,$.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,$.O1,$.O1_PRO;const tt=$.GPT_5_4_MINI;function nt(e){if(e&&e.length>0)return e.map(e=>({type:`function`,strict:!0,name:e.name,description:e.description,parameters:c.toJSONSchema(e.schema)}))}function rt(e){return e.map(it).flat(1)}function it(e){switch(e.role){case`tool`:return at(e);case`assistant`:return ot(e);default:return st(e)}}function at(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 ot(e){let t=[],n=E(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 st(e){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let t=e.content.map(ct).filter(e=>e!==null);return{role:e.role,content:t}}}function ct(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 lt(e){let{client:t,model:n,messages:r,system:i,tools:a,context:o,options:s}=e,c=o?.tracer,l=nt(a),u={model:n,input:rt(r),...i&&{instructions:i},...l?{tools:l}:{},...s};c?.debug(`OpenAI ResponsesAPI request`,{request:u});let d;try{d=ut(await t.responses.create(u))}catch(e){c?.error(e instanceof Error?e.message:String(e)),d=J(e)}return c?.debug(`OpenAI ResponsesAPI response`,{result:d}),d}function ut(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?A.Error:A.Stop,content:n,text:E(n),usage:{in:e.usage?.input_tokens??0,out:e.usage?.output_tokens??0},raw:e}}function dt(){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?A.Error:i?A.FunctionCall:A.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*ft(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=nt(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:rt(r),...i&&{instructions:i},stream:!0,...f.length>0?{tools:f}:{},...d};l?.debug(`OpenAI ResponsesAPI streaming request`,{request:p});let m=dt();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 pt(e){let t=new m({apiKey:e});return{name:`OpenAI`,async createGenerationRequest(e,n){return await lt({client:t,model:e,...n})},createStreamingRequest(e,n){let{messages:r,system:i,tools:a,context:o,signal:s,options:c}=n;return ft({client:t,model:e,messages:r,system:i,tools:a,runtime:o,signal:s,options:c})}}}const mt={Models:$,DefaultModel:tt},ht=s.object({searchTerm:s.string().describe(`The search term to query`)}),gt=new class{name=`brave`;description=`Perform a search using the Brave search engine`;schema=ht;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 L(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}}},_t={name:`calculator`,description:`Performs basic arithmetic operations`,schema:l.object({operation:l.enum([`add`,`subtract`,`multiply`,`divide`]).describe(`The operation to perform (add, subtract, multiply, divide)`),a:l.number().describe(`First operand`),b:l.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=g(h);async function yt(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 bt(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 xt(e,t){return t&&t.trim()?`${e}\n[stderr]: ${t}`:e}const St=s.object({command:s.string().describe(`The shell command to execute`)});new class{name=`exec`;description=`Execute a shell command and return the output.`;schema=St;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 yt(t,{timeout:this.timeout,maxBuffer:this.maxBuffer,cwd:this.cwd});return xt(e.stdout,e.stderr)}catch(e){return bt(e)}}},l.object({path:l.string().describe(`The file path to patch`),old_string:l.string().describe(`The exact text to find and replace`),new_string:l.string().describe(`The replacement text`),start_line:l.number().int().positive().describe(`1-indexed start line of the region to match within`),end_line:l.number().int().positive().describe(`1-indexed end line (inclusive) of the region to match within`)}),l.object({path:l.string().describe(`The file path to read from`)}),l.object({path:l.string().describe(`The file path to write to`),content:l.string().describe(`The content to write to the file`)});function Ct(e){try{let t=c.fromJSONSchema(e);return t instanceof c.ZodObject?t.strict():c.object({}).passthrough()}catch{return c.object({}).passthrough()}}function wt(e,t,n){return e.map(e=>Et(e,t,n))}function Tt(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=Ct(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function Et(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=Ct(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(Ot(r.content));return Dt(r.content)}}}function Dt(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(`
|
|
17
|
+
`)}function Ot(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
18
|
+
`)||`MCP tool execution error`}var kt=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 _({name:`axle`,version:`1.0.0`}),this.config.transport===`stdio`?this.transport=new v({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new y(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 wt(await this.fetchTools(t,e?.tracer),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return Tt(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 At={debug:0,info:1,warn:2,error:3};var jt=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 Mt(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 At[e]>=At[this._minLevel]}},Mt=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 Nt={debug:0,info:1,warn:2,error:3};let Pt=!1;function Ft(){Pt||=(b.use(x()),!0)}var It=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 Nt[e]>=Nt[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 Ft(),b.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(`
|
|
19
|
+
`);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)}},Lt=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(`
|
|
20
|
+
`);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 et({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.
|
|
21
|
+
|
|
22
|
+
Only extract:
|
|
23
|
+
- Explicit user corrections (e.g., "No, always use bullet points")
|
|
24
|
+
- Stated preferences (e.g., "I prefer concise summaries")
|
|
25
|
+
- Patterns that clearly emerged from user feedback
|
|
26
|
+
|
|
27
|
+
Do NOT extract:
|
|
28
|
+
- General knowledge or facts from the conversation content
|
|
29
|
+
- Inferences or speculation about what the user might want
|
|
30
|
+
- Task-specific details that won't apply to future runs
|
|
31
|
+
|
|
32
|
+
Respond with a JSON array of instruction strings. Each instruction should be a clear, actionable directive.
|
|
33
|
+
If there are no learnings to extract, respond with an empty array: []
|
|
34
|
+
|
|
35
|
+
Example response:
|
|
36
|
+
["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=E(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:l.object({instruction:l.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:E(n.content);e&&t.push(`User: ${e}`)}else if(n.role===`assistant`){let e=E(n.content);e&&t.push(`Assistant: ${e}`)}return t.join(`
|
|
37
|
+
|
|
38
|
+
`)}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}-${S.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{ie as Agent,Te as Anthropic,A as AxleStopReason,Qe as Gemini,G as History,fe as Instruct,P as LocalFileStore,kt as MCP,mt as OpenAI,Lt as ProceduralMemory,It as SimpleWriter,jt as Tracer,F as TurnBuilder,we as anthropic,gt as braveSearchTool,_t as calculatorTool,Le as chatCompletions,W as compileInstruct,z as createHandle,Ze as gemini,et as generate,$e as generateTurn,de as loadFileContent,pt as openai,H as parseResponse,M as stream};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fifthrevision/axle",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/johncch/axle.git"
|
|
@@ -24,38 +24,40 @@
|
|
|
24
24
|
"scripts": {
|
|
25
25
|
"prepare": "pnpm run build",
|
|
26
26
|
"start": "tsx ./src/cli.ts",
|
|
27
|
-
"build": "
|
|
28
|
-
"build:watch": "
|
|
29
|
-
"build-dev": "
|
|
27
|
+
"build": "tsdown --clean --minify",
|
|
28
|
+
"build:watch": "tsdown --watch",
|
|
29
|
+
"build-dev": "tsdown",
|
|
30
30
|
"test": "vitest run",
|
|
31
31
|
"changelog": "pnpm start -j ./jobs/changelog.job.yml --args",
|
|
32
|
+
"update-models": "pnpm start -j ./jobs/bootstrap-models.job.yml",
|
|
32
33
|
"release": "pnpm test && pnpm run build && npm version"
|
|
33
34
|
},
|
|
34
35
|
"author": "Chong Han Chua",
|
|
35
36
|
"license": "ISC",
|
|
36
37
|
"dependencies": {
|
|
37
|
-
"@anthropic-ai/sdk": "^0.
|
|
38
|
+
"@anthropic-ai/sdk": "^0.82.0",
|
|
38
39
|
"@commander-js/extra-typings": "^14.0.0",
|
|
39
|
-
"@google/genai": "^1.
|
|
40
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
40
|
+
"@google/genai": "^1.48.0",
|
|
41
|
+
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
41
42
|
"chalk": "^5.6.2",
|
|
42
43
|
"commander": "^14.0.3",
|
|
43
44
|
"glob": "^13.0.6",
|
|
44
45
|
"marked": "^15.0.12",
|
|
45
46
|
"marked-terminal": "^7.3.0",
|
|
46
47
|
"mime": "^4.1.0",
|
|
47
|
-
"openai": "^6.
|
|
48
|
+
"openai": "^6.33.0",
|
|
48
49
|
"serialize-error": "^13.0.1",
|
|
49
|
-
"yaml": "^2.8.
|
|
50
|
+
"yaml": "^2.8.3",
|
|
50
51
|
"zod": "^4.3.6"
|
|
51
52
|
},
|
|
52
53
|
"devDependencies": {
|
|
53
|
-
"
|
|
54
|
-
"
|
|
54
|
+
"@types/marked-terminal": "^6.1.1",
|
|
55
|
+
"dotenv": "^17.4.0",
|
|
55
56
|
"prettier": "^3.8.1",
|
|
56
57
|
"prettier-plugin-organize-imports": "^4.3.0",
|
|
58
|
+
"tsdown": "^0.21.7",
|
|
57
59
|
"tsx": "^4.21.0",
|
|
58
|
-
"typescript": "^
|
|
59
|
-
"vitest": "^4.
|
|
60
|
+
"typescript": "^6.0.2",
|
|
61
|
+
"vitest": "^4.1.2"
|
|
60
62
|
}
|
|
61
63
|
}
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
var Je=Object.defineProperty;var c=(t,e)=>Je(t,"name",{value:e,configurable:!0});import Q,{readFile as J,access as We,stat as ze,writeFile as ce,mkdir as Ke}from"node:fs/promises";import ee,{resolve as te,extname as le,dirname as Ve}from"node:path";import*as M from"zod";import j,{z as A}from"zod";import"glob";import Xe from"mime";import Ze from"@anthropic-ai/sdk";import{FinishReason as C,GoogleGenAI as Ye}from"@google/genai";import Qe from"openai";import{exec as et}from"node:child_process";import{promisify as tt}from"node:util";import{Client as nt}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as st}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as rt}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{marked as ue}from"marked";import{markedTerminal as ot}from"marked-terminal";import at from"node:crypto";class z extends Error{static{c(this,"AxleError")}code;id;details;constructor(e,n){super(e,{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,z.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:pe(this.cause)}}}}function pe(t){return t instanceof Error?{name:t.name,message:t.message,...t.stack&&{stack:t.stack},..."cause"in t&&t.cause&&{cause:pe(t.cause)}}:t}c(pe,"serializeError");var S=(t=>(t.Stop="stop",t.Length="length",t.FunctionCall="function_call",t.Error="error",t.Custom="custom",t.Cancelled="cancelled",t))(S||{});class de{static{c(this,"History")}system;_messages=[];constructor(e){e&&(this._messages=e)}get messages(){return[...this._messages]}addSystem(e){this.system=e}addUser(e){typeof e=="string"?this._messages.push({role:"user",content:[{type:"text",text:e}]}):this._messages.push({role:"user",content:e})}addAssistant(e){if(typeof e=="string"){const n=e;this._messages.push({role:"assistant",id:crypto.randomUUID(),content:[{type:"text",text:n}],model:"user",finishReason:S.Custom})}else this._messages.push({role:"assistant",...e})}addToolResults(e){this._messages.push({role:"tool",content:e})}add(e){Array.isArray(e)?this._messages.push(...e):this._messages.push(e)}latest(){return this._messages[this._messages.length-1]}toString(){return JSON.stringify({system:this.system,messages:this._messages})}}function it(t){const{text:e,files:n}=t,s=[];if(e&&s.push({type:"text",text:e}),n)for(const r of n)s.push({type:"file",file:r});return s}c(it,"toContentParts");function G(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
2
|
-
|
|
3
|
-
`)}c(G,"getTextContent");function ct(t){return t.filter(e=>e.type==="tool-call")}c(ct,"getToolCalls");function lt(t,e){const n=e.usage??{in:0,out:0};t.in+=n.in??0,t.out+=n.out??0}c(lt,"appendUsage");function me(t){return JSON.stringify({error:t})}c(me,"serializeToolError");async function fe(t,e=async()=>null,n){const s=[];for(const r of t){const o=n?.startSpan(r.name,{type:"tool"});let a;try{a=await e(r.name,r.parameters)}catch(l){a={type:"error",error:{type:"exception",message:l instanceof Error?l.message:String(l)}}}if(a==null){const l=`Tool not found: ${r.name}`;o?.setResult({kind:"tool",name:r.name,input:r.parameters,output:null}),o?.end("error"),s.push({id:r.id,name:r.name,content:me({type:"not-found",message:l}),isError:!0});continue}a.type==="success"?(o?.setResult({kind:"tool",name:r.name,input:r.parameters,output:a.content}),o?.end("ok"),s.push({id:r.id,name:r.name,content:a.content})):(o?.setResult({kind:"tool",name:r.name,input:r.parameters,output:a.error}),o?.end("error"),s.push({id:r.id,name:r.name,content:me(a.error),isError:!0}))}return{results:s}}c(fe,"executeToolCalls");function P(t,e){for(const n of t)n(e)}c(P,"emit");function he(t){const e=[],n=new AbortController;let s=!1,r,o;const a=new Promise((l,u)=>{r=c(p=>{s=!0,l(p)},"resolveResult"),o=c(p=>{s=!0,u(p)},"rejectResult")});return Promise.resolve().then(()=>ut(t,n.signal,e).then(r,o)),{on(l){e.push(l)},cancel(){s||n.abort()},get final(){return a}}}c(he,"stream");async function ut(t,e,n){const{provider:s,model:r,messages:o,system:a,tools:l,serverTools:u,onToolCall:p,maxIterations:m,tracer:d,options:i}=t,g=[...o],h=[],f={in:0,out:0};let _=0,w=0;const y=c(T=>{g.push(T),h.push(T)},"addMessage"),E=c(T=>{T.result==="error"&&P(n,{type:"error",error:T.error});const v=T.result==="success"?T.final?.content:T.result==="cancelled"?T.partial?.content:null,F=T.result==="success"?T.final?.finishReason:T.result==="cancelled"?S.Cancelled:void 0;return d?.setResult({kind:"llm",model:r,request:{messages:o},response:{content:v??null},usage:T.usage?{inputTokens:T.usage.in,outputTokens:T.usage.out}:void 0,finishReason:F}),d?.end(T.result==="error"?"error":"ok"),T},"endWithResult"),R=c((T,v,F,b)=>{b();const O=T.length>0?{role:"assistant",id:v,model:F,content:T,finishReason:S.Cancelled}:void 0;return O&&y(O),d?.end("ok"),{result:"cancelled",messages:h,partial:O,usage:f}},"buildCancelledResult");for(;;){if(e.aborted)return R([],"","",()=>{});if(m!==void 0&&w>=m)return E({result:"error",messages:h,error:{type:"model",error:{type:"error",error:{type:"MaxIterations",message:`Exceeded max iterations (${m})`}}},usage:f});w+=1;const T=d?.startSpan(`turn-${w}`,{type:"llm"}),v=u?{...i,serverTools:u}:i,F=s.createStreamingRequest?.(r,{messages:g,system:a,tools:l,context:{tracer:T},signal:e,options:v});if(!F)throw T?.end("error"),new Error("Provider does not support streaming. Use generate() instead.");const b=[];let q="",O="",B=null,H={in:0,out:0},N=-1,W=null,L="";const re=new Map;let D=-1;const U=c(()=>{W!==null&&N>=0&&(P(n,{type:W==="text"?"text:end":"thinking:end",index:N,final:L}),W=null,L="",N=-1)},"closePart");for await(const x of F){switch(x.type){case"start":q=x.id,O=x.data.model;break;case"text-start":{U(),b.push({type:"text",text:""}),D=b.length-1,N=_++,W="text",L="",P(n,{type:"text:start",index:N});break}case"text-delta":{const I=b[D];I.text+=x.data.text,L=I.text,P(n,{type:"text:delta",index:N,delta:x.data.text,accumulated:L});break}case"text-complete":{U();break}case"thinking-start":{U(),b.push({type:"thinking",text:""}),D=b.length-1,N=_++,W="thinking",L="",P(n,{type:"thinking:start",index:N});break}case"thinking-delta":{const I=b[D];I.text+=x.data.text,L=I.text,P(n,{type:"thinking:delta",index:N,delta:x.data.text,accumulated:L});break}case"thinking-summary-delta":{const I=b[D];I.text+=x.data.text,L=I.text,P(n,{type:"thinking:delta",index:N,delta:x.data.text,accumulated:L});break}case"thinking-complete":{U();break}case"tool-call-start":{U();const I=_++;b.push({type:"tool-call",id:x.data.id,name:x.data.name,parameters:{}}),D=b.length-1,re.set(x.data.id,I),P(n,{type:"tool:start",index:I,id:x.data.id,name:x.data.name});break}case"tool-call-complete":{const I=b[D];x.data.id&&(I.id=x.data.id),x.data.name&&(I.name=x.data.name),I.parameters=x.data.arguments,x.data.providerMetadata&&(I.providerMetadata=x.data.providerMetadata);break}case"internal-tool-start":{U();const I=_++;b.push({type:"internal-tool",id:x.data.id,name:x.data.name}),D=b.length-1,P(n,{type:"internal-tool:start",index:I,id:x.data.id,name:x.data.name});break}case"internal-tool-complete":{const I=b[D];x.data.output!=null&&(I.output=x.data.output),P(n,{type:"internal-tool:complete",index:x.data.index,id:x.data.id,name:x.data.name,output:x.data.output});break}case"complete":{U(),B=x.data.finishReason,H=x.data.usage;break}case"error":{U();const I=x.data.usage??{in:0,out:0};return f.in+=I.in??0,f.out+=I.out??0,T?.end("error"),E({result:"error",messages:h,error:{type:"model",error:{type:"error",error:{type:x.data.type,message:x.data.message}}},usage:f})}default:console.warn("[WARN] Unhandled chunk type. Should never happen")}if(e.aborted)break}if(e.aborted)return T?.end("ok"),R(b,q,O,U);if(B===null)return U(),T?.end("error"),E({result:"error",messages:h,error:{type:"model",error:{type:"error",error:{type:"IncompleteStream",message:"Stream ended without a completion signal"}}},usage:f});f.in+=H.in??0,f.out+=H.out??0;const je={kind:"llm",model:O,request:{messages:g},response:{content:b},usage:{inputTokens:H.in,outputTokens:H.out},finishReason:B};T?.setResult(je),T?.end();const X={role:"assistant",id:q,model:O,content:b,finishReason:B};if(y(X),B!==S.FunctionCall)return E({result:"success",messages:h,final:X,usage:f});const Z=b.filter(x=>x.type==="tool-call");if(Z.length===0)return E({result:"success",messages:h,final:X,usage:f});if(e.aborted)return d?.end("ok"),{result:"cancelled",messages:h,usage:f};const qe=p?async(x,I)=>p(x,I):async()=>null;let Be=0;const He=c(async(x,I)=>{const Y=Z[Be++],ae=re.get(Y.id)??-1;P(n,{type:"tool:execute",index:ae,id:Y.id,name:x,parameters:I});const ie=await qe(x,I);return P(n,{type:"tool:complete",index:ae,id:Y.id,name:x,result:ie??null}),ie},"emittingToolCall"),{results:oe}=await fe(Z,He,d);oe.length>0&&y({role:"tool",content:oe})}}c(ut,"run");class ge{static{c(this,"LocalFileStore")}rootPath;constructor(e){this.rootPath=e}async read(e){const n=ee.join(this.rootPath,e);try{return await Q.readFile(n,"utf-8")}catch{return null}}async write(e,n){const s=ee.join(this.rootPath,e);await Q.mkdir(ee.dirname(s),{recursive:!0}),await Q.writeFile(s,n,"utf-8")}}function pt(t,e,n={}){const{placeholderStyle:s="{{}}",strict:r=!1}=n,o=s==="{{}}"?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g,a=[];if(t=t.replace(o,(l,u)=>{if(u=u.trim(),Object.prototype.hasOwnProperty.call(e,u)){const p=e[u];return p==null?"":String(p)}return r&&a.push(u),l}),a.length>0){const l=[...new Set(a)];throw new Error(`Missing variable${l.length>1?"s":""}: ${l.join(", ")}. Pass them as --args key=value or use --allow-missing-vars to suppress this error.`)}return t}c(pt,"replaceVariables");function K(t){if(t instanceof M.ZodString)return["string","Your answer"];if(t instanceof M.ZodNumber)return["number",42];if(t instanceof M.ZodBoolean)return["boolean",!0];if(t instanceof M.ZodArray){const e=t.element;if(e instanceof M.ZodString)return["string array",["answer 1","answer 2","third answer"]];if(e instanceof M.ZodNumber)return["number array",[42,59,3.14]];if(e instanceof M.ZodBoolean)return["boolean array",[!0,!1,!1]];if(e instanceof M.ZodObject){const[n,s]=K(e);return["object array",[s,s]]}return["array",[]]}if(t instanceof M.ZodObject){const e=t.shape,n={};for(const[s,r]of Object.entries(e)){const[o,a]=K(r);n[s]=a}return["JSON object",n]}if(t instanceof M.ZodOptional){const e=t.unwrap(),[n,s]=K(e);return[`${n} | undefined`,s]}}c(K,"zodToExample");function _e(t,e){if(!e)return t;if(Object.keys(e).length===0){if(t.trim()==="{}"||t.trim()==="")return{};throw new Error("Schema is empty, but rawValue is not an empty object representation or empty string.")}const s=dt(t),r={};for(const[o,a]of Object.entries(e)){const l=s.tags[o];if(l!==void 0)r[o]=ye(a,l);else if(a.def.type!=="optional")throw new Error(`Expected results with tag ${o} but it does not exist`)}try{const o={};for(const[a,l]of Object.entries(e))a in r&&(o[a]=l.parse(r[a]));return o}catch(o){if(o&&typeof o=="object"&&"issues"in o){const a=o.issues.map(l=>`${l.path.join(".")}: ${l.message}`).join(", ");throw new Error(`Validation failed: ${a}`)}throw o}}c(_e,"parseResponse");function ye(t,e){switch(e=e.trim(),t.def.type){case"string":try{return JSON.parse(e)}catch{if(typeof e=="string")return e;throw new Error(`Cannot parse '${e}' as string. Ensure it is a valid JSON string or a plain string.`)}case"number":{const n=parseFloat(e);if(isNaN(n))throw new Error(`Cannot parse '${e}' as number`);return n}case"boolean":{const n=e.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;throw new Error(`Cannot parse '${e}' as boolean. Expected 'true' or 'false'`)}case"array":{if(e==="")return[];try{const n=JSON.parse(e);if(Array.isArray(n))return n}catch{}if(e.includes(","))return e.split(",").map(n=>{const s=n.trim();try{return JSON.parse(s)}catch{return s}}).filter(n=>n!=="")}case"object":{e.includes("```json")&&(e=e.replace(/```json/g,"").replace(/```/g,""));try{return JSON.parse(e)}catch(n){throw new Error(`Cannot parse object as JSON: ${n.message}`)}}case"optional":{const n=t.def.innerType;return ye(n,e)}default:return e}}c(ye,"preprocessValue");function dt(t){t.trim().startsWith("```json")&&t.trim().endsWith("```")&&(t=t.trim().slice(7,-3).trim());const e=/<(\w+)>(.*?)<\/\1>/gs,n={};let s=t;s=s.replace(e,(o,a,l)=>(n[a]=l,""));const r=/<(\w+)>(.*?)(?:<\/?\w+>|$)/gs;return s=s.replace(r,(o,a,l)=>(n[a]=l,"")),{tags:n,remaining:s.trim()}}c(dt,"parseTaggedSections");function xe(t,e={},n={}){const s={...e,...t.inputs};let r=pt(t.prompt,s,{strict:n.strictVariables});if(t.textReferences.length>0)for(const[l,u]of t.textReferences.entries()){const p=u.name?`: ${u.name}`:"";r+=`
|
|
4
|
-
|
|
5
|
-
## Reference ${l+1}${p}
|
|
6
|
-
|
|
7
|
-
\`\`\`${u.content}'''`}let o=`# Instructions
|
|
8
|
-
|
|
9
|
-
`;if((t.schema?Object.keys(t.schema):[]).length>0){o+=`## Output Format Instructions
|
|
10
|
-
`,o+=`
|
|
11
|
-
Here is how you should format your output. Follow the instructions strictly.
|
|
12
|
-
`;for(const[l,u]of Object.entries(t.schema)){const[p,m]=K(u);o+=`
|
|
13
|
-
- Use <${l}></${l}> tags to indicate the answer for ${l}. The answer must be a ${p}.
|
|
14
|
-
Example: <${l}>${JSON.stringify(m)}</${l}>
|
|
15
|
-
`}}if(t.instructions.length>0){o+=`
|
|
16
|
-
## Additional Instructions
|
|
17
|
-
|
|
18
|
-
`;for(const l of t.instructions)o+=`- ${l}
|
|
19
|
-
`}return o+r}c(xe,"compileInstruct");function mt(t){return t.type==="server"}c(mt,"isServerTool");class ft{static{c(this,"Agent")}provider;model;history;tracer;name;scope;store;system;tools={};serverTools=[];mcps=[];mcpToolsResolved=!1;memory;options;eventCallbacks=[];constructor(e){if(this.provider=e.provider,this.model=e.model,this.history=new de,this.tracer=e.tracer,this.system=e.system,this.name=e.name,this.scope=e.scope,this.store=new ge(".axle"),this.options=e.options??{},e.tools&&this.addTools(e.tools),e.mcps&&(this.mcps=[...e.mcps]),e.memory){if(!e.name)throw new z("Agent requires a 'name' when memory is provided. The name is used to partition memory storage.");this.memory=e.memory;const n=e.memory.tools?.();n&&this.addTools(n)}}addTool(e){mt(e)?this.serverTools.push(e):this.tools[e.name]=e}addTools(e){for(const n of e)this.addTool(n)}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,n){let s;if(typeof e=="string")this.history.addUser(e);else{const r=xe(e,n,{strictVariables:this.options.strictVariables}),o=e.files;this.history.addUser(it({text:r,files:o})),s=e.schema}return this.execute(s)}async resolveMcpTools(){if(!this.mcpToolsResolved){this.tracer?.debug("resolving MCP tools",{count:this.mcps.length});for(const e of this.mcps){const n=await e.listTools({prefix:e.name,tracer:this.tracer});this.addTools(n)}this.mcpToolsResolved=!0}}execute(e){let n=!1,s;const r=(async()=>{if(await this.resolveMcpTools(),n)return{response:null,messages:[],final:void 0,usage:{in:0,out:0}};let o=this.system;if(this.memory){const i=await this.memory.recall({name:this.name,scope:this.scope,system:this.system,messages:this.history.messages,store:this.store,tracer:this.tracer});i.systemSuffix&&(o=(o??"")+`
|
|
20
|
-
|
|
21
|
-
`+i.systemSuffix)}const a=this.tools,l=Object.values(a).map(i=>({name:i.name,description:i.description,schema:i.schema}));s=he({provider:this.provider,model:this.model,messages:this.history.messages,system:o,tools:l.length>0?l:void 0,serverTools:this.serverTools.length>0?this.serverTools:void 0,tracer:this.tracer,onToolCall:c(async(i,g)=>{const h=a[i];if(!h)return null;try{return{type:"success",content:await h.execute(g)}}catch(f){return{type:"error",error:{type:"execution",message:f instanceof Error?f.message:String(f)}}}},"onToolCall")});for(const i of this.eventCallbacks)s.on(i);const u=await s.final;u.messages.length>0&&this.history.add(u.messages);let p=null,m;if(u.result==="error")throw new z(ht(u.error),{code:u.error.type==="model"?"MODEL_ERROR":"TOOL_ERROR",details:{error:u.error}});if(u.result==="success"){if(m=u.final,m){const i=G(m.content);p=_e(i,e)}}else u.result==="cancelled"&&(m=u.partial);if(this.memory&&u.result==="success")try{await this.memory.record({name:this.name,scope:this.scope,system:this.system,messages:this.history.messages,newMessages:u.messages,store:this.store,tracer:this.tracer})}catch(i){this.tracer?.warn("memory record failed",{error:i instanceof Error?i.message:String(i)})}const d=u.usage??{in:0,out:0};return{response:p,messages:u.messages,final:m,usage:d}})();return{cancel:c(()=>{n=!0,s?.cancel()},"cancel"),get final(){return r}}}}function ht(t){return t.type==="model"?`Model error: ${t.error.error.message}`:`Tool error (${t.error.name}): ${t.error.message}`}c(ht,"formatGenerateError");async function gt(t,e){const{defaults:n,tag:s}=e;let r=null,o="";if(t)try{o=te(t),r=await J(o,{encoding:"utf-8"})}catch{throw new Error(`${s} not found, see --help for details`)}else{for(const a of n.formats)try{o=te(n.name+"."+a),r=await J(o,{encoding:"utf-8"});break}catch{continue}if(r===null)throw new Error(`${s} not found, see --help for details`)}return{content:r,format:o.split(".").pop()??"",path:o}}c(gt,"searchAndLoadFile");const Ee=20*1024*1024;function _t(t){return t.type==="text"}c(_t,"isTextFileInfo");function yt(t){return t.type==="image"||t.type==="document"}c(yt,"isBase64FileInfo");const xt=new Set(["application/json","application/xml","application/yaml","application/x-yaml","application/toml"]);function Et(t){return t.startsWith("text/")||xt.has(t)}c(Et,"isTextLikeMimeType");function wt(t){const e=Xe.getType(t);if(!e){const n=le(t).toLowerCase();throw new Error(`Unsupported file type: ${n||"(no extension)"}`)}if(e.startsWith("image/"))return{type:"image",mimeType:e};if(e==="application/pdf")return{type:"document",mimeType:e};if(Et(e))return{type:"text",mimeType:e};{const n=le(t).toLowerCase();throw new Error(`Unsupported file type: ${n} (${e})`)}}c(wt,"getFileCategory");async function Tt(t,e){const n=te(t);try{await We(n)}catch{throw new Error(`File not found: ${t}`)}const s=await ze(n);if(s.size>Ee)throw new Error(`File too large: ${s.size} bytes. Maximum allowed: ${Ee} bytes`);const r=n.split("/").pop()||"",o=wt(n);if((e||(o.type==="text"?"utf-8":"base64"))==="utf-8"){if(o.type!=="text")throw new Error(`Cannot read ${o.type} file as text: ${t}`);const l=await J(n,"utf-8");return{path:n,content:l,mimeType:o.mimeType,size:s.size,name:r,type:"text"}}else{if(o.type==="text")throw new Error(`Cannot read text file as binary: ${t}`);const u=(await J(n)).toString("base64");return{path:n,base64:u,mimeType:o.mimeType,size:s.size,name:r,type:o.type}}}c(Tt,"loadFileContent");class St{static{c(this,"Instruct")}prompt;inputs={};files=[];textReferences=[];instructions=[];schema;constructor(e,n){this.prompt=e,this.schema=n}setInputs(e){this.inputs=e}addInput(e,n){this.inputs[e]=n}addFile(e,n){if(typeof e=="string"){this.textReferences.push({content:e,name:n?.name});return}yt(e)?this.files.push(e):_t(e)&&this.textReferences.push({content:e.content,name:n?.name??e.name})}addInstructions(e){if(typeof e!="string"||e.trim()==="")throw new Error("Instruction must be a non-empty string");this.instructions.push(e)}hasFiles(){return this.files.length>0}}const $={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_HAIKU_4_5_20251001:"claude-haiku-4-5-20251001",CLAUDE_HAIKU_4_5:"claude-haiku-4-5-20251001",CLAUDE_SONNET_4_5_20250929:"claude-sonnet-4-5-20250929",CLAUDE_SONNET_4_5:"claude-sonnet-4-5-20250929",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",CLAUDE_3_HAIKU_20240307:"claude-3-haiku-20240307",CLAUDE_3_HAIKU:"claude-3-haiku-20240307"};$.CLAUDE_SONNET_4_6,$.CLAUDE_OPUS_4_6,$.CLAUDE_OPUS_4_5_20251101,$.CLAUDE_HAIKU_4_5_20251001,$.CLAUDE_SONNET_4_5_20250929,$.CLAUDE_OPUS_4_1_20250805,$.CLAUDE_OPUS_4_20250514,$.CLAUDE_SONNET_4_20250514,$.CLAUDE_3_HAIKU_20240307;const It=$.CLAUDE_HAIKU_4_5;function we(t){return Array.isArray(t)?t:[t]}c(we,"arrayify");function bt(t){return new Promise(e=>setTimeout(e,t))}c(bt,"delay");function V(t){if(t==null)return{type:"error",error:{type:"Undetermined",message:"Unknown error occurred"},usage:{in:0,out:0},raw:t};if(t instanceof Error)return{type:"error",error:{type:t.name||"Error",message:t.message||"Unexpected error"},usage:{in:0,out:0},raw:t};if(typeof t=="object"){const e=t,n=e?.error?.error?.type||e?.error?.type||e?.type||e?.code||e?.status||"Undetermined",s=e?.error?.error?.message||e?.error?.message||e?.message||e?.error||"Unexpected error";return{type:"error",error:{type:String(n),message:String(s)},usage:{in:0,out:0},raw:t}}return{type:"error",error:{type:"Undetermined",message:String(t)},usage:{in:0,out:0},raw:t}}c(V,"getUndefinedError");function Te(t){return t.map(e=>{if(e.role==="assistant"){const n=[];for(const s of e.content)s.type==="text"?n.push({type:"text",text:s.text}):s.type==="thinking"?s.redacted?n.push({type:"redacted_thinking",data:s.text}):n.push({type:"thinking",thinking:s.text,signature:s.signature}):s.type==="tool-call"?n.push({type:"tool_use",id:s.id,name:s.name,input:s.parameters}):s.type==="internal-tool"&&(n.push({type:"server_tool_use",id:s.id,name:s.name,input:s.input??{}}),s.output!=null&&n.push({type:"web_search_tool_result",tool_use_id:s.id,content:s.output}));return{role:"assistant",content:n}}if(e.role==="tool")return{role:"user",content:e.content.map(n=>({type:"tool_result",tool_use_id:n.id,content:typeof n.content=="string"?n.content:$t(n.content),...n.isError?{is_error:!0}:{}}))};if(typeof e.content=="string")return{role:"user",content:e.content};{const n=[];for(const s of e.content)s.type==="text"?n.push({type:"text",text:s.text}):s.type==="file"&&(s.file.type==="image"?n.push({type:"image",source:{type:"base64",media_type:s.file.mimeType,data:s.file.base64}}):s.file.type==="document"&&s.file.mimeType==="application/pdf"&&n.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:s.file.base64}}));return{role:"user",content:n}}})}c(Te,"convertToProviderMessages");function Se(t){return t.map(e=>{const n=j.toJSONSchema(e.schema);if(!kt(n))throw new Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:n}})}c(Se,"convertToProviderTools");function Ie(t){const e=[];for(const n of t)if(n.type==="text")e.push({type:"text",text:n.text});else if(n.type==="thinking")e.push({type:"thinking",text:n.text||"",redacted:!1});else if(n.type==="redacted_thinking")e.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 new Error(`Invalid tool call input for ${n.name}: expected object, got ${typeof n.input}`);e.push({type:"tool-call",id:n.id,name:n.name,parameters:n.input})}return e}c(Ie,"convertToAxleContentParts");function be(t){switch(t){case"max_tokens":return S.Length;case"end_turn":return S.Stop;case"stop_sequence":return S.Stop;case"tool_use":return S.FunctionCall;case"pause_turn":case"refusal":default:return S.Error}}c(be,"convertStopReason$1");function kt(t){return t&&typeof t=="object"&&t.type==="object"}c(kt,"isObjectSchema");function $t(t){return t.map(e=>e.type==="text"?{type:"text",text:e.text}:{type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})}c($t,"convertToolResultParts");async function At(t){const{client:e,model:n,messages:s,system:r,tools:o,context:a,options:l}=t,u=a?.tracer,{stop:p,max_tokens:m,...d}=l??{},i={model:n,max_tokens:m??16e3,messages:Te(s),...r&&{system:r},...p&&{stop_sequences:we(p)},...o&&{tools:Se(o)},...d};u?.debug("Anthropic request",{request:i});let g;try{const h=await e.messages.create(i);g=Rt(h)}catch(h){g=V(h)}return u?.debug("Anthropic response",{result:g}),g}c(At,"createGenerationRequest$3");function Rt(t){const e=be(t.stop_reason);if(e===S.Error)return{type:"error",error:{type:"Uncaught error",message:`Stop reason is not recognized or unhandled: ${t.stop_reason}`},usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t};if(e===S.FunctionCall){const n=Ie(t.content);return{type:"success",id:t.id,model:t.model,role:t.role,finishReason:S.FunctionCall,content:n,text:G(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}if(t.type=="message"){const n=Ie(t.content);return{type:"success",id:t.id,model:t.model,role:"assistant",finishReason:e,content:n,text:G(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}}c(Rt,"convertToAIResponse");function Ot(){const t=new Map,e=new Map,n=new Map;function s(r){const o=[];switch(r.type){case"message_start":o.push({type:"start",id:r.message.id,data:{model:r.message.model,timestamp:Date.now()}});break;case"message_delta":r.delta.stop_reason&&o.push({type:"complete",data:{finishReason:be(r.delta.stop_reason),usage:r.usage?{in:r.usage.input_tokens||0,out:r.usage.output_tokens||0}:void 0}});case"message_stop":break;case"content_block_start":if(r.content_block.type==="text")t.set(r.index,"text"),o.push({type:"text-start",data:{index:r.index}});else if(r.content_block.type==="tool_use"){t.set(r.index,"tool");const a=r.content_block;n.set(r.index,{id:a.id,name:a.name,argumentsBuffer:""}),o.push({type:"tool-call-start",data:{index:r.index,id:a.id,name:a.name}})}else if(r.content_block.type==="thinking")t.set(r.index,"thinking"),o.push({type:"thinking-start",data:{index:r.index,redacted:!1}});else if(r.content_block.type==="redacted_thinking")t.set(r.index,"thinking"),o.push({type:"thinking-start",data:{index:r.index,redacted:!0}});else if(r.content_block.type==="server_tool_use"){t.set(r.index,"internal-tool");const a=r.content_block;e.set(a.id,{index:r.index,name:a.name}),o.push({type:"internal-tool-start",data:{index:r.index,id:a.id,name:a.name}})}else if(r.content_block.type==="web_search_tool_result"){const a=r.content_block,l=e.get(a.tool_use_id);l&&(o.push({type:"internal-tool-complete",data:{index:l.index,id:a.tool_use_id,name:l.name,output:a.content}}),e.delete(a.tool_use_id))}break;case"content_block_delta":if(r.delta.type==="text_delta")o.push({type:"text-delta",data:{text:r.delta.text,index:r.index}});else if(r.delta.type==="input_json_delta"){const a=n.get(r.index);a&&(a.argumentsBuffer+=r.delta.partial_json)}else r.delta.type==="thinking_delta"?o.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":{const a=t.get(r.index);if(a==="text")o.push({type:"text-complete",data:{index:r.index}});else if(a==="thinking")o.push({type:"thinking-complete",data:{index:r.index}});else if(a!=="internal-tool"){if(a==="tool"){const l=n.get(r.index);if(l){try{const u=l.argumentsBuffer?JSON.parse(l.argumentsBuffer):{};o.push({type:"tool-call-complete",data:{index:r.index,id:l.id,name:l.name,arguments:u}})}catch(u){throw new Error(`Failed to parse tool call arguments for ${l.name}: ${u instanceof Error?u.message:String(u)}
|
|
22
|
-
Raw buffer: ${l.argumentsBuffer}`)}n.delete(r.index)}}}t.delete(r.index);break}}return o}return c(s,"handleEvent"),{handleEvent:s}}c(Ot,"createAnthropicStreamingAdapter");async function*Mt(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:a,signal:l,options:u}=t,p=a?.tracer,{stop:m,max_tokens:d,serverTools:i,...g}=u??{},h=o?Se(o):[];if(i){const w={web_search:"web_search_20250305"};for(const y of i){const E=w[y.name]??y.name;h.push({type:E,name:y.name,...y.config})}}const f={model:n,max_tokens:d??Ct(n),messages:Te(s),...r&&{system:r},...m&&{stop_sequences:we(m)},...h.length>0&&{tools:h},...g};p?.debug("Anthropic streaming request",{request:f});const _=Ot();try{const w=await e.messages.create({...f,stream:!0},{signal:l});for await(const y of w){const E=_.handleEvent(y);for(const R of E)yield R}}catch(w){if(l?.aborted)return;yield{type:"error",data:{type:"STREAMING_ERROR",message:w instanceof Error?w.message:String(w),raw:w}}}}c(Mt,"createStreamingRequest$3");const ke={[$.CLAUDE_OPUS_4_6]:128e3,[$.CLAUDE_OPUS_4_5_20251101]:64e3,[$.CLAUDE_HAIKU_4_5_20251001]:64e3,[$.CLAUDE_SONNET_4_5_20250929]:64e3,[$.CLAUDE_SONNET_4_20250514]:64e3,[$.CLAUDE_OPUS_4_1_20250805]:32e3,[$.CLAUDE_OPUS_4_20250514]:32e3,[$.CLAUDE_3_HAIKU_20240307]:4096};function Ct(t){return t in ke?ke[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}c(Ct,"getMaxTokens");const Pt="anthropic";function vt(t){const e=new Ze({apiKey:t});return{name:Pt,async createGenerationRequest(n,s){return await At({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:o,tools:a,context:l,signal:u,options:p}=s;return Mt({client:e,model:n,messages:r,system:o,tools:a,runtime:l,signal:u,options:p})}}}c(vt,"anthropic");function $e(t,e){const n=t.map(Nt).flat(1);return e?[{role:"system",content:e},...n]:n}c($e,"convertAxleMessages");function Ae(t){if(t&&t.length>0)return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:j.toJSONSchema(e.schema)}}))}c(Ae,"convertTools");function ne(t){switch(t){case"stop":return S.Stop;case"length":return S.Length;case"tool_calls":case"function_call":return S.FunctionCall;case"content_filter":return S.Error;default:return S.Stop}}c(ne,"convertFinishReason");function Nt(t){switch(t.role){case"tool":return Lt(t);case"assistant":return Ut(t);default:return Gt(t)}}c(Nt,"convertMessage$2");function Lt(t){return t.content.map(e=>({role:"tool",content:typeof e.content=="string"?e.content:e.content.filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
23
|
-
`),tool_call_id:e.id}))}c(Lt,"convertToolMessage$2");function Ut(t){const e=t.content.filter(r=>r.type==="tool-call"),n=t.content.filter(r=>r.type==="text"),s=e.length>0?e.map(r=>({type:"function",id:r.id,function:{name:r.name,arguments:JSON.stringify(r.parameters)}})):void 0;return{role:"assistant",content:n.map(r=>r.text).join(""),...s&&{tool_calls:s}}}c(Ut,"convertAssistantMessage$2");function Gt(t){if(typeof t.content=="string")return{role:"user",content:t.content};const e=t.content.map(Dt).filter(n=>n!==null);return e.every(n=>n.type==="text")?{role:"user",content:e.map(n=>n.text).join("")}:{role:"user",content:e}}c(Gt,"convertUserMessage$2");function Dt(t){return t.type==="text"?{type:"text",text:t.text}:t.type==="file"&&t.file.type==="image"?{type:"image_url",image_url:{url:`data:${t.file.mimeType};base64,${t.file.base64}`}}:null}c(Dt,"convertContentPart$2");async function Ft(t){const{baseUrl:e,model:n,messages:s,system:r,tools:o,context:a,apiKey:l,options:u}=t,p=a?.tracer,m=$e(s,r),d=Ae(o),i={model:n,messages:m,...d&&{tools:d}};u&&(u.temperature!==void 0&&(i.temperature=u.temperature),u.top_p!==void 0&&(i.top_p=u.top_p),u.max_tokens!==void 0&&(i.max_tokens=u.max_tokens),u.frequency_penalty!==void 0&&(i.frequency_penalty=u.frequency_penalty),u.presence_penalty!==void 0&&(i.presence_penalty=u.presence_penalty),u.stop!==void 0&&(i.stop=u.stop)),p?.debug("ChatCompletions request",{request:i});let g;try{const h={"Content-Type":"application/json"};l&&(h.Authorization=`Bearer ${l}`);const f=await fetch(`${e}/chat/completions`,{method:"POST",headers:h,body:JSON.stringify(i)});if(!f.ok){const w=await f.text().catch(()=>"");throw new Error(`HTTP error! status: ${f.status}${w?` - ${w}`:""}`)}const _=await f.json();g=jt(_)}catch(h){p?.error("Error fetching ChatCompletions response",{error:h instanceof Error?h.message:String(h)}),g=V(h)}return p?.debug("ChatCompletions response",{result:g}),g}c(Ft,"createGenerationRequest$2");function jt(t){const e=t.choices?.[0];if(!e)return{type:"error",error:{type:"ChatCompletionsError",message:"No choices in response"},usage:{in:0,out:0},raw:t};const n=[];if(e.message.reasoning_content&&n.push({type:"thinking",text:e.message.reasoning_content}),e.message.content&&n.push({type:"text",text:e.message.content}),e.message.tool_calls)for(const o of e.message.tool_calls){let a;try{a=JSON.parse(o.function.arguments)}catch(l){throw new Error(`Invalid tool call arguments for ${o.function.name}: ${l instanceof Error?l.message:String(l)}`)}if(typeof a!="object"||a===null||Array.isArray(a))throw new Error(`Invalid tool call arguments for ${o.function.name}: expected object, got ${typeof a}`);n.push({type:"tool-call",id:o.id,name:o.function.name,parameters:a})}const s=n.some(o=>o.type==="tool-call"),r=ne(s?"tool_calls":e.finish_reason);return{type:"success",id:t.id,model:t.model,role:"assistant",finishReason:r,content:n,text:G(n)??"",usage:{in:t.usage?.prompt_tokens||0,out:t.usage?.completion_tokens||0},raw:t}}c(jt,"fromModelResponse$2");function qt(){const t=new Map;let e=0,n=-1,s="",r="",o=null,a,l;function u(d){n<0||(o==="text"?d.push({type:"text-complete",data:{index:n}}):o==="thinking"&&d.push({type:"thinking-complete",data:{index:n}}),o=null,n=-1)}c(u,"closeActivePart");function p(d){const i=[];d.usage&&(l={in:d.usage.prompt_tokens,out:d.usage.completion_tokens});const g=d.choices?.[0];if(!g)return i;s||(s=d.id,r=d.model,i.push({type:"start",id:s,data:{model:r,timestamp:Date.now()}}));const h=g.delta;if(h.reasoning_content&&(o!=="thinking"&&(u(i),n=e++,o="thinking",i.push({type:"thinking-start",data:{index:n}})),i.push({type:"thinking-delta",data:{index:n,text:h.reasoning_content}})),h.content&&(o!=="text"&&(u(i),n=e++,o="text",i.push({type:"text-start",data:{index:n}})),i.push({type:"text-delta",data:{text:h.content,index:n}})),h.tool_calls){u(i);for(const f of h.tool_calls){const _=f.index;if(!t.has(_)){const y=e++,E=f.id||`tool-${y}`;t.set(_,{id:E,name:f.function?.name||"",argumentsBuffer:"",partIdx:y}),i.push({type:"tool-call-start",data:{index:y,id:E,name:f.function?.name||""}})}const w=t.get(_);f.id&&(w.id=f.id),f.function?.name&&(w.name=f.function.name),f.function?.arguments&&(w.argumentsBuffer+=f.function.arguments)}}if(g.finish_reason){u(i);for(const[,f]of t)try{const _=f.argumentsBuffer?JSON.parse(f.argumentsBuffer):{};i.push({type:"tool-call-complete",data:{index:f.partIdx,id:f.id,name:f.name,arguments:_}})}catch(_){throw new Error(`Failed to parse tool call arguments for ${f.name}: ${_ instanceof Error?_.message:String(_)}
|
|
24
|
-
Raw buffer: ${f.argumentsBuffer}`)}a=ne(g.finish_reason)}return i}c(p,"handleChunk");function m(){return a===void 0?[]:[{type:"complete",data:{finishReason:a,usage:l??{in:0,out:0}}}]}return c(m,"finalize"),{handleChunk:p,finalize:m}}c(qt,"createStreamingAdapter$1");async function*Bt(t){const{baseUrl:e,model:n,messages:s,system:r,tools:o,context:a,signal:l,apiKey:u,options:p}=t,m=a?.tracer;p?.serverTools&&m?.warn("serverTools not supported by ChatCompletions provider");const d=$e(s,r),i=Ae(o),g={model:n,messages:d,stream:!0,stream_options:{include_usage:!0},...i&&{tools:i}};p&&(p.temperature!==void 0&&(g.temperature=p.temperature),p.top_p!==void 0&&(g.top_p=p.top_p),p.max_tokens!==void 0&&(g.max_tokens=p.max_tokens),p.frequency_penalty!==void 0&&(g.frequency_penalty=p.frequency_penalty),p.presence_penalty!==void 0&&(g.presence_penalty=p.presence_penalty),p.stop!==void 0&&(g.stop=p.stop)),m?.debug("ChatCompletions streaming request",{request:g});const h=qt();try{const f={"Content-Type":"application/json"};u&&(f.Authorization=`Bearer ${u}`);const _=await fetch(`${e}/chat/completions`,{method:"POST",headers:f,body:JSON.stringify(g),signal:l});if(!_.ok){const R=await _.text().catch(()=>"");throw new Error(`HTTP error! status: ${_.status}${R?` - ${R}`:""}`)}if(!_.body)throw new Error("Response body is null");const w=_.body.getReader(),y=new TextDecoder;let E="";for(;;){const{done:R,value:T}=await w.read();if(R)break;E+=y.decode(T,{stream:!0});const v=E.split(`
|
|
25
|
-
`);E=v.pop()||"";for(const F of v){const b=F.trim();if(!b||b.startsWith(":")||!b.startsWith("data: "))continue;const q=b.slice(6);if(q!=="[DONE]")try{const O=JSON.parse(q),B=h.handleChunk(O);for(const H of B)yield H}catch(O){m?.error("Error parsing ChatCompletions stream chunk",{error:O instanceof Error?O.message:String(O),line:b})}}}for(const R of h.finalize())yield R}catch(f){if(l?.aborted)return;m?.error("Error in ChatCompletions streaming request",{error:f instanceof Error?f.message:String(f)}),yield{type:"error",data:{type:"STREAMING_ERROR",message:f instanceof Error?f.message:String(f),raw:f}}}}c(Bt,"createStreamingRequest$2");function Ht(t,e){return{name:"ChatCompletions",async createGenerationRequest(n,s){return await Ft({baseUrl:t,model:n,apiKey:e,...s})},createStreamingRequest(n,s){return Bt({baseUrl:t,model:n,apiKey:e,...s})}}}c(Ht,"chatCompletions");const k={GEMINI_3_1_PRO_PREVIEW:"gemini-3.1-pro-preview",GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS:"gemini-3.1-pro-preview-customtools",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_5_FLASH_LITE_PREVIEW_09_2025:"gemini-2.5-flash-lite-preview-09-2025",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_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"};k.GEMINI_3_1_PRO_PREVIEW,k.GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS,k.GEMINI_3_PRO_PREVIEW,k.GEMINI_3_FLASH_PREVIEW,k.GEMINI_2_5_PRO,k.GEMINI_2_5_FLASH,k.GEMINI_2_5_FLASH_LITE,k.GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025,k.GEMINI_2_0_FLASH,k.GEMINI_2_0_FLASH_001,k.GEMINI_2_0_FLASH_LITE,k.GEMINI_2_0_FLASH_LITE_001,k.GEMINI_FLASH_LATEST,k.GEMINI_FLASH_LITE_LATEST,k.GEMINI_PRO_LATEST,k.GEMMA_3_27B_IT,k.GEMMA_3_12B_IT,k.GEMMA_3_4B_IT,k.GEMMA_3_1B_IT,k.GEMMA_3N_E4B_IT,k.GEMMA_3N_E2B_IT;const Jt=k.GEMINI_3_FLASH_PREVIEW;function Re(t,e,n){const s={};return e&&(s.systemInstruction=e),t&&t.length>0&&(s.tools=t.map(r=>({functionDeclarations:[{name:r.name,description:r.description,parametersJsonSchema:j.toJSONSchema(r.schema)}]}))),n&&Object.assign(s,n),s}c(Re,"prepareConfig");function Oe(t){return t.map(Wt).filter(e=>e!==void 0)}c(Oe,"convertAxleMessagesToGemini");function Wt(t){switch(t.role){case"tool":return zt(t);case"assistant":return Kt(t);case"user":return Vt(t)}}c(Wt,"convertMessage$1");function zt(t){return{role:"user",parts:t.content.flatMap(e=>{const n={functionResponse:{id:e.id??void 0,name:e.name,response:{output:typeof e.content=="string"?e.content:e.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
26
|
-
`)}}};if(typeof e.content=="string")return[n];const s=e.content.filter(r=>r.type==="image").map(r=>({inlineData:{mimeType:r.mimeType,data:r.data}}));return[n,...s]})}}c(zt,"convertToolMessage$1");function Kt(t){const e=[],n=t.content.filter(r=>r.type==="text");if(n.length>0){const r=n.map(o=>o.text).join("");r&&e.push({text:r})}const s=t.content.filter(r=>r.type==="tool-call");return s.length>0&&e.push(...s.map(r=>{const o={functionCall:{id:r.id??void 0,name:r.name,args:r.parameters}};return r.providerMetadata?.thoughtSignature&&(o.thoughtSignature=r.providerMetadata.thoughtSignature),o})),{role:"model",parts:e}}c(Kt,"convertAssistantMessage$1");function Vt(t){return typeof t.content=="string"?{role:"user",parts:[{text:t.content}]}:{role:"user",parts:t.content.map(Xt).filter(n=>n!==null)}}c(Vt,"convertUserMessage$1");function Xt(t){return t.type==="text"?{text:t.text}:t.type==="file"&&(t.file.type==="image"||t.file.type==="document")?{inlineData:{mimeType:t.file.mimeType,data:t.file.base64}}:null}c(Xt,"convertContentPart$1");function Me(t){switch(t){case C.STOP:return[!0,S.Stop];case C.MAX_TOKENS:return[!0,S.Length];case C.FINISH_REASON_UNSPECIFIED:case C.SAFETY:case C.RECITATION:case C.LANGUAGE:case C.OTHER:case C.BLOCKLIST:case C.PROHIBITED_CONTENT:case C.SPII:case C.MALFORMED_FUNCTION_CALL:case C.IMAGE_SAFETY:return[!1,S.Error]}}c(Me,"convertStopReason");async function Zt(t){const{client:e,model:n,messages:s,system:r,tools:o,context:a,options:l}=t,u=a?.tracer,p=l?{...l}:{};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);const m={contents:Oe(s),config:Re(o,r,p)};u?.debug("Gemini request",{request:m});let d;try{const i=await e.models.generateContent({model:n,...m});d=Yt(i,{tracer:u})}catch(i){u?.error(i instanceof Error?i.message:String(i)),d=V(i)}return u?.debug("Gemini response",{result:d}),d}c(Zt,"createGenerationRequest$1");function Yt(t,e){const{tracer:n}=e,s=t.usageMetadata.promptTokenCount,r=t.usageMetadata.totalTokenCount-s,o={in:s,out:r};if(!t)return{type:"error",error:{type:"InvalidResponse",message:"Invalid or empty response from Google AI"},usage:{in:0,out:0},raw:t};if(t.promptFeedback&&t.promptFeedback.blockReason)return{type:"error",error:{type:"Blocked",message:`Response blocked by Google AI: ${t.promptFeedback.blockReason}, ${t.promptFeedback.blockReasonMessage}`},usage:o,raw:t};if(!t.candidates||t.candidates.length===0)return{type:"error",error:{type:"InvalidResponse",message:"Invalid or empty response from Google AI"},usage:{in:0,out:0},raw:t};t.candidates.length>1&&n?.warn(`We received ${t.candidates.length} response candidates`);const a=t.candidates[0],u=(a.content?.parts||[]).map(d=>d.text).filter(d=>d!==void 0).join(""),[p,m]=Me(a.finishReason);if(p){const d=[];if(u&&d.push({type:"text",text:u}),t.functionCalls)for(const i of t.functionCalls)if(i.args==null)d.push({type:"tool-call",id:i.id,name:i.name,parameters:{}});else{if(typeof i.args!="object"||Array.isArray(i.args))throw new Error(`Invalid tool call arguments for ${i.name}: expected object, got ${typeof i.args}`);d.push({type:"tool-call",id:i.id,name:i.name,parameters:i.args})}return{type:"success",id:t.responseId,model:t.modelVersion,role:"assistant",finishReason:t.functionCalls?S.FunctionCall:m,content:d,text:G(d)??"",usage:o,raw:t}}else return{type:"error",error:{type:"Undetermined",message:`Unexpected stop reason: ${m}`},usage:o,raw:t}}c(Yt,"fromModelResponse$1");function Qt(){let t=0,e=-1,n=!1,s="",r="",o=0,a=0,l=null;function u(m){e<0||(l==="text"?m.push({type:"text-complete",data:{index:e}}):l==="thinking"&&m.push({type:"thinking-complete",data:{index:e}}),l=null,e=-1)}c(u,"closeActivePart");function p(m){const d=[];s||(s=m.responseId||`gemini-${Date.now()}`,r=m.modelVersion||"gemini",d.push({type:"start",id:s,data:{model:r,timestamp:Date.now()}})),m.usageMetadata&&(o=m.usageMetadata.promptTokenCount||0,a=(m.usageMetadata.totalTokenCount||0)-o);const i=m.candidates?.[0];if(!i)return d;const g=i.content?.parts||[];for(const h of g){const f="thought"in h&&h.thought===!0;if(f&&h.text?(l!=="thinking"&&(u(d),e=t++,l="thinking",d.push({type:"thinking-start",data:{index:e}})),d.push({type:"thinking-delta",data:{index:e,text:h.text}})):h.text&&!f?(l!=="text"&&(u(d),e=t++,l="text",d.push({type:"text-start",data:{index:e}})),d.push({type:"text-delta",data:{text:h.text,index:e}})):h.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(h))}`),h.functionCall){u(d),n=!0;const _=t++,w=h.functionCall.id||`tool-${_}`;d.push({type:"tool-call-start",data:{index:_,id:w,name:h.functionCall.name}});const y={index:_,id:w,name:h.functionCall.name,arguments:h.functionCall.args??{}},E=h;E.thoughtSignature&&(y.providerMetadata={thoughtSignature:E.thoughtSignature}),d.push({type:"tool-call-complete",data:y})}}if(i.finishReason&&i.finishReason!==C.FINISH_REASON_UNSPECIFIED){u(d);const[h,f]=Me(i.finishReason),_=n?S.FunctionCall:f;!h&&!n?d.push({type:"error",data:{type:"FinishReasonError",message:`Unexpected finish reason: ${i.finishReason}`,usage:{in:o,out:a},raw:m}}):d.push({type:"complete",data:{finishReason:_,usage:{in:o,out:a}}})}return d}return c(p,"handleChunk"),{handleChunk:p}}c(Qt,"createGeminiStreamingAdapter");async function*en(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:a,signal:l,options:u}=t,p=a?.tracer,{serverTools:m,...d}=u??{},i=d?{...d}:{};i.max_tokens&&(i.maxOutputTokens=i.max_tokens,delete i.max_tokens),i.stop&&(i.stopSequences=Array.isArray(i.stop)?i.stop:[i.stop],delete i.stop),i.top_p!==void 0&&(i.topP=i.top_p,delete i.top_p);const g=Re(o,r,i);if(m){const _={web_search:"googleSearch",code_execution:"codeExecution"};g.tools||(g.tools=[]);for(const w of m){const y=_[w.name]??w.name;g.tools.push({[y]:w.config??{}})}}const h={contents:Oe(s),config:g};p?.debug("Gemini streaming request",{request:h});const f=Qt();try{const _=await e.models.generateContentStream({model:n,...h});for await(const w of _){const y=f.handleChunk(w);for(const E of y)yield E}}catch(_){if(l?.aborted)return;p?.error(_ instanceof Error?_.message:String(_)),yield{type:"error",data:{type:"STREAMING_ERROR",message:_ instanceof Error?_.message:String(_),raw:_}}}}c(en,"createStreamingRequest$1");const tn="Gemini";function nn(t){const e=new Ye({apiKey:t});return{name:tn,async createGenerationRequest(n,s){return await Zt({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:o,tools:a,context:l,signal:u,options:p}=s;return en({client:e,model:n,messages:r,system:o,tools:a,runtime:l,signal:u,options:p})}}}c(nn,"gemini");const Ce={GPT_5_2:"gpt-5.2",GPT_5_2_2025_12_11:"gpt-5.2-2025-12-11",GPT_5_2_CHAT_LATEST:"gpt-5.2-chat-latest",GPT_5_2_PRO:"gpt-5.2-pro",GPT_5_2_PRO_2025_12_11:"gpt-5.2-pro-2025-12-11",GPT_5_2_CODEX:"gpt-5.2-codex",GPT_5_1:"gpt-5.1",GPT_5_1_2025_11_13:"gpt-5.1-2025-11-13",GPT_5_1_CHAT_LATEST:"gpt-5.1-chat-latest",GPT_5_1_CODEX:"gpt-5.1-codex",GPT_5_1_CODEX_MAX:"gpt-5.1-codex-max",GPT_5_1_CODEX_MINI:"gpt-5.1-codex-mini",GPT_5:"gpt-5",GPT_5_2025_08_07:"gpt-5-2025-08-07",GPT_5_CHAT_LATEST:"gpt-5-chat-latest",GPT_5_CODEX:"gpt-5-codex",GPT_5_MINI:"gpt-5-mini",GPT_5_MINI_2025_08_07:"gpt-5-mini-2025-08-07",GPT_5_NANO:"gpt-5-nano",GPT_5_NANO_2025_08_07:"gpt-5-nano-2025-08-07",GPT_5_PRO:"gpt-5-pro",GPT_5_PRO_2025_10_06:"gpt-5-pro-2025-10-06",GPT_5_SEARCH_API:"gpt-5-search-api",GPT_5_SEARCH_API_2025_10_14:"gpt-5-search-api-2025-10-14",GPT_4_1:"gpt-4.1",GPT_4_1_2025_04_14:"gpt-4.1-2025-04-14",GPT_4_1_MINI:"gpt-4.1-mini",GPT_4_1_MINI_2025_04_14:"gpt-4.1-mini-2025-04-14",GPT_4_1_NANO:"gpt-4.1-nano",GPT_4_1_NANO_2025_04_14:"gpt-4.1-nano-2025-04-14",GPT_4O:"gpt-4o",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_MINI:"gpt-4o-mini",GPT_4O_MINI_2024_07_18:"gpt-4o-mini-2024-07-18",GPT_4O_SEARCH_PREVIEW:"gpt-4o-search-preview",GPT_4O_SEARCH_PREVIEW_2025_03_11:"gpt-4o-search-preview-2025-03-11",GPT_4O_MINI_SEARCH_PREVIEW:"gpt-4o-mini-search-preview",GPT_4O_MINI_SEARCH_PREVIEW_2025_03_11:"gpt-4o-mini-search-preview-2025-03-11",GPT_4_TURBO:"gpt-4-turbo",GPT_4_TURBO_2024_04_09:"gpt-4-turbo-2024-04-09",O4_MINI:"o4-mini",O4_MINI_2025_04_16:"o4-mini-2025-04-16",O3:"o3",O3_2025_04_16:"o3-2025-04-16",O3_PRO:"o3-pro",O3_PRO_2025_06_10:"o3-pro-2025-06-10",O3_MINI:"o3-mini",O3_MINI_2025_01_31:"o3-mini-2025-01-31",O1:"o1",O1_2024_12_17:"o1-2024-12-17",O1_PRO:"o1-pro",O1_PRO_2025_03_19:"o1-pro-2025-03-19"},sn=Ce.GPT_5_MINI;function Pe(t){if(t&&t.length>0)return t.map(e=>({type:"function",strict:!0,name:e.name,description:e.description,parameters:j.toJSONSchema(e.schema)}))}c(Pe,"prepareTools");function ve(t){return t.map(rn).flat(1)}c(ve,"convertAxleMessageToResponseInput");function rn(t){switch(t.role){case"tool":return on(t);case"assistant":return an(t);default:return cn(t)}}c(rn,"convertMessage");function on(t){return t.content.map(e=>({type:"function_call_output",call_id:e.id,output:typeof e.content=="string"?e.content:e.content.map(n=>n.type==="text"?{type:"input_text",text:n.text}:{type:"input_image",image_url:`data:${n.mimeType};base64,${n.data}`})}))}c(on,"convertToolMessage");function an(t){const e=[],n=G(t.content);n&&e.push({role:t.role,content:n});const s=t.content.filter(o=>o.type==="tool-call");for(const o of s)e.push({type:"function_call",call_id:o.id,name:o.name,arguments:JSON.stringify(o.parameters)});const r=t.content.filter(o=>o.type==="internal-tool");for(const o of r)o.output!=null&&e.push(o.output);return e}c(an,"convertAssistantMessage");function cn(t){if(typeof t.content=="string")return{role:t.role,content:t.content};{const e=t.content.map(ln).filter(n=>n!==null);return{role:t.role,content:e}}}c(cn,"convertUserMessage");function ln(t){if(t.type==="text")return{type:"input_text",text:t.text};if(t.type==="file"){if(t.file.type==="image")return{type:"input_image",image_url:`data:${t.file.mimeType};base64,${t.file.base64}`,detail:"auto"};if(t.file.type==="document")return{type:"input_file",filename:t.file.path,file_data:`data:${t.file.mimeType};base64,${t.file.base64}`}}return t.type==="thinking",null}c(ln,"convertContentPart");async function un(t){const{client:e,model:n,messages:s,system:r,tools:o,context:a,options:l}=t,u=a?.tracer,p=Pe(o),m={model:n,input:ve(s),...r&&{instructions:r},...p?{tools:p}:{},...l};u?.debug("OpenAI ResponsesAPI request",{request:m});let d;try{const i=await e.responses.create(m);d=pn(i)}catch(i){u?.error(i instanceof Error?i.message:String(i)),d=V(i)}return u?.debug("OpenAI ResponsesAPI response",{result:d}),d}c(un,"createGenerationRequest");function pn(t){if(t.error)return{type:"error",error:{type:t.error.code||"undetermined",message:t.error.message||"Response generation failed"},usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t};const e=t.output?.filter(r=>r.type==="reasoning")?.map(r=>r),n=[];if(e&&e.length>0)for(const r of e){const o=r.summary?.[0]?.text||r.content?.[0]?.text||"";(o||r.encrypted_content)&&n.push({type:"thinking",text:o,...r.encrypted_content&&{encrypted:r.encrypted_content}})}t.output_text&&n.push({type:"text",text:t.output_text});const s=t.output?.filter(r=>r.type==="function_call");if(s&&s.length>0)for(const r of s){const o=r;try{n.push({type:"tool-call",id:o.id||"",name:o.name||"",parameters:o.arguments?JSON.parse(o.arguments):{}})}catch(a){throw new Error(`Failed to parse tool call arguments for ${o.name}: ${a instanceof Error?a.message:String(a)}
|
|
27
|
-
Raw value: ${o.arguments}`)}}return{type:"success",id:t.id,model:t.model||"",role:"assistant",finishReason:t.incomplete_details?S.Error:S.Stop,content:n,text:G(n)??"",usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t}}c(pn,"fromModelResponse");function dn(){let t="",e="",n=0,s=-1,r=!1;const o=new Map,a=new Map,l=new Set(["web_search_call","file_search_call","code_interpreter_call"]),u=new Map;function p(m){const d=[];switch(m.type){case"response.created":{t=m.response.id||`openai-${Date.now()}`,e=m.response.model,d.push({type:"start",id:t,data:{model:e,timestamp:Date.now()}});break}case"response.output_text.delta":{s===-1&&(s=n++,d.push({type:"text-start",data:{index:s}})),d.push({type:"text-delta",data:{text:m.delta,index:s}});break}case"response.output_text.done":{s>=0&&(d.push({type:"text-complete",data:{index:s}}),s=-1);break}case"response.function_call_arguments.delta":{const i=m.item_id;if(!u.has(i)){const h=o.get(i),f=h?.name||"",_=h?.callId||i,w=n++;u.set(i,{id:i,callId:_,name:f,argumentsBuffer:"",partIdx:w}),d.push({type:"tool-call-start",data:{index:w,id:_,name:f}})}const g=u.get(i);g.argumentsBuffer+=m.delta;break}case"response.function_call_arguments.done":{r=!0;const i=m.item_id,g=u.get(i),h=m.name||g?.name||"";if(g){try{const f=m.arguments?JSON.parse(m.arguments):{};d.push({type:"tool-call-complete",data:{index:g.partIdx,id:g.callId,name:h,arguments:f}})}catch(f){throw new Error(`Failed to parse function call arguments for ${h}: ${f instanceof Error?f.message:String(f)}
|
|
28
|
-
Raw value: ${m.arguments}`)}u.delete(i)}break}case"response.completed":{const i=m.response.usage;d.push({type:"complete",data:{finishReason:m.response.incomplete_details?S.Error:r?S.FunctionCall:S.Stop,usage:{in:i?.input_tokens||0,out:i?.output_tokens||0}}});break}case"response.failed":{d.push({type:"error",data:{type:"RESPONSES_API_ERROR",message:`Response failed: ${m.response.status}`,raw:m}});break}case"response.output_item.added":{if(m.item?.type==="reasoning")s=n++,d.push({type:"thinking-start",data:{index:s}});else if(m.item?.type==="function_call"){const i=m.item,g=i.id||i.call_id;g&&o.set(g,{name:i.name||"",callId:i.call_id||g})}else if(m.item&&l.has(m.item.type)){const i=m.item,g=n++;a.set(i.id,g),d.push({type:"internal-tool-start",data:{index:g,id:i.id,name:i.type}})}break}case"response.output_item.done":{if(m.item?.type==="reasoning"&&s>=0)d.push({type:"thinking-complete",data:{index:s}}),s=-1;else if(m.item&&l.has(m.item.type)){const i=m.item,g=a.get(i.id);g!==void 0&&(d.push({type:"internal-tool-complete",data:{index:g,id:i.id,name:i.type,output:m.item}}),a.delete(i.id))}break}case"response.reasoning_text.delta":{m.delta&&d.push({type:"thinking-delta",data:{index:s,text:m.delta}});break}case"response.reasoning_summary_text.delta":{m.delta&&d.push({type:"thinking-summary-delta",data:{index:s,text:m.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: ${m.type}`)}return d}return c(p,"handleEvent"),{handleEvent:p}}c(dn,"createStreamingAdapter");async function*mn(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:a,signal:l,options:u}=t,p=a?.tracer,{serverTools:m,...d}=u??{},i=Pe(o)??[];if(m){const f={web_search:"web_search_preview",code_execution:"code_interpreter"};for(const _ of m){const w=f[_.name]??_.name;i.push({type:w,..._.config})}}const g={model:n,input:ve(s),...r&&{instructions:r},stream:!0,...i.length>0?{tools:i}:{},...d};p?.debug("OpenAI ResponsesAPI streaming request",{request:g});const h=dn();try{const f=e.responses.stream(g,...l?[{signal:l}]:[]);for await(const _ of f){const w=h.handleEvent(_);for(const y of w)yield y}}catch(f){if(l?.aborted)return;p?.error(f instanceof Error?f.message:String(f)),yield{type:"error",data:{type:"STREAMING_ERROR",message:f instanceof Error?f.message:String(f),raw:f}}}}c(mn,"createStreamingRequest");const fn="OpenAI";function hn(t){const e=new Qe({apiKey:t});return{name:fn,async createGenerationRequest(n,s){return await un({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:o,tools:a,context:l,signal:u,options:p}=s;return mn({client:e,model:n,messages:r,system:o,tools:a,runtime:l,signal:u,options:p})}}}c(hn,"openai");async function Ne(t){const{provider:e,model:n,messages:s,system:r,tools:o,tracer:a,options:l}=t;return e.createGenerationRequest(n,{messages:s,system:r,tools:o,context:{tracer:a},options:l})}c(Ne,"generateTurn");async function Le(t){const{provider:e,model:n,messages:s,system:r,tools:o,onToolCall:a,maxIterations:l,tracer:u,options:p}=t,m=[...s],d=[],i={in:0,out:0};let g=0,h;const f=c(y=>{m.push(y),d.push(y)},"addMessage"),_=c(y=>(u?.setResult({kind:"llm",model:n,request:{messages:s},response:{content:y.result==="success"?y.final?.content:null},usage:y.usage?{inputTokens:y.usage.in,outputTokens:y.usage.out}:void 0,finishReason:y.result==="success"?y.final?.finishReason:void 0}),u?.end(y.result==="error"?"error":"ok"),y),"endWithResult"),w=c((y,E)=>{if(!y||E.type==="error"){y?.end("error");return}y.setResult({kind:"llm",model:E.model??n,request:{messages:m},response:{content:E.content},usage:E.usage?{inputTokens:E.usage.in,outputTokens:E.usage.out}:void 0,finishReason:E.finishReason}),y.end()},"setTurnResult");for(;;){if(l!==void 0&&g>=l)return _({result:"error",messages:d,error:{type:"model",error:{type:"error",error:{type:"MaxIterations",message:`Exceeded max iterations (${l})`}}},usage:i});g+=1;const y=u?.startSpan(`turn-${g}`,{type:"llm"}),E=await Ne({provider:e,model:n,messages:m,system:r,tools:o,tracer:y,options:p});if(lt(i,E),w(y,E),E.type==="error")return _({result:"error",messages:d,error:{type:"model",error:E},usage:i});const R={role:"assistant",id:E.id,model:E.model,content:E.content,finishReason:E.finishReason};if(f(R),h=R,E.finishReason!==S.FunctionCall)return _({result:"success",messages:d,final:h,usage:i});const T=ct(E.content);if(T.length===0)return _({result:"success",messages:d,final:h,usage:i});const{results:v}=await fe(T,a,u);v.length>0&&f({role:"tool",content:v})}}c(Le,"generate");const gn=M.object({searchTerm:M.string().describe("The search term to query")});class _n{static{c(this,"BraveSearchTool")}name="brave";description="Perform a search using the Brave search engine";schema=gn;apiKey;throttle;lastExecTime=0;constructor(e){e&&this.configure(e)}configure(e){const{rateLimit:n}=e;this.apiKey=e["api-key"],this.throttle=n?1100/n:void 0}async execute(e){const{searchTerm:n}=e;if(this.throttle){for(;Date.now()-this.lastExecTime<this.throttle;)await bt(this.throttle-(Date.now()-this.lastExecTime));this.lastExecTime=Date.now()}try{const s=this.apiKey,r="https://api.search.brave.com/res/v1/web/search",o=new URL(r);o.searchParams.append("q",n),o.searchParams.append("format","json");const a=await fetch(o.toString(),{method:"GET",headers:{Accept:"application/json","X-Subscription-Token":s}});if(!a.ok)throw new Error(`[Brave] HTTP error ${a.status}: ${a.statusText}`);const l=await a.json();return JSON.stringify(l)}catch(s){throw s instanceof Error?new Error(`[Brave] Error fetching search results: ${s.message}`):s}}}const yn=new _n,xn=A.object({operation:A.enum(["add","subtract","multiply","divide"]).describe("The operation to perform (add, subtract, multiply, divide)"),a:A.number().describe("First operand"),b:A.number().describe("Second operand")}),En={name:"calculator",description:"Performs basic arithmetic operations",schema:xn,execute:c(async({operation:t,a:e,b:n})=>{switch(t){case"add":return`${e} + ${n} = ${e+n}`;case"subtract":return`${e} - ${n} = ${e-n}`;case"multiply":return`${e} * ${n} = ${e*n}`;case"divide":if(n===0)throw new Error("Cannot divide by zero");return`${e} / ${n} = ${e/n}`;default:throw new Error(`Unknown operation: ${t}`)}},"execute")},wn=tt(et),Tn=3e4,Sn=1024*1024;async function In(t,e={}){const{stdout:n,stderr:s}=await wn(t,{cwd:e.cwd,timeout:e.timeout??Tn,maxBuffer:e.maxBuffer??Sn});return{stdout:n,stderr:s}}c(In,"runCommand");function bn(t){if(t instanceof Error){const e=t;let n=`Error executing command: ${t.message}`;return e.stdout&&(n+=`
|
|
29
|
-
[stdout]: ${e.stdout}`),e.stderr&&(n+=`
|
|
30
|
-
[stderr]: ${e.stderr}`),n}return`Error executing command: ${String(t)}`}c(bn,"formatExecError");function kn(t,e){return e&&e.trim()?`${t}
|
|
31
|
-
[stderr]: ${e}`:t}c(kn,"formatOutput");const $n=M.object({command:M.string().describe("The shell command to execute")});class An{static{c(this,"ExecTool")}name="exec";description="Execute a shell command and return the output.";schema=$n;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){const{command:n}=e;try{const s=await In(n,{timeout:this.timeout,maxBuffer:this.maxBuffer,cwd:this.cwd});return kn(s.stdout,s.stderr)}catch(s){return bn(s)}}}const Rn=new An,On=A.object({path:A.string().describe("The file path to patch"),old_string:A.string().describe("The exact text to find and replace"),new_string:A.string().describe("The replacement text"),start_line:A.number().int().positive().describe("1-indexed start line of the region to match within"),end_line:A.number().int().positive().describe("1-indexed end line (inclusive) of the region to match within")}),Mn={name:"patch-file",description:"Patch a file by replacing an exact string match within a specified line range",schema:On,summarize:c(({path:t,start_line:e,end_line:n})=>`${t}:${e}:${n}`,"summarize"),execute:c(async({path:t,old_string:e,new_string:n,start_line:s,end_line:r})=>{if(r<s)throw new Error(`end_line (${r}) must be >= start_line (${s})`);let o;try{o=await J(t,"utf-8")}catch(h){throw h instanceof Error?new Error(`Failed to read file "${t}": ${h.message}`):h}const a=o.split(`
|
|
32
|
-
`);if(s>a.length)throw new Error(`start_line (${s}) exceeds file length (${a.length} lines)`);if(r>a.length)throw new Error(`end_line (${r}) exceeds file length (${a.length} lines)`);const u=a.slice(s-1,r).join(`
|
|
33
|
-
`),p=u.indexOf(e);if(p===-1)throw new Error(`old_string not found within lines ${s}-${r} of "${t}"`);if(u.indexOf(e,p+1)!==-1)throw new Error(`old_string matches multiple times within lines ${s}-${r} of "${t}"`);const d=u.replace(e,n),g=[...a.slice(0,s-1),...d.split(`
|
|
34
|
-
`),...a.slice(r)].join(`
|
|
35
|
-
`);try{await ce(t,g,"utf-8")}catch(h){throw h instanceof Error?new Error(`Failed to write file "${t}": ${h.message}`):h}return`Successfully patched "${t}" (lines ${s}-${r})`},"execute")},Cn=A.object({path:A.string().describe("The file path to read from")}),Pn={name:"read-file",description:"Read the contents of a file from disk",schema:Cn,summarize:c(({path:t})=>t,"summarize"),execute:c(async({path:t})=>{try{return await J(t,"utf-8")}catch(e){throw e instanceof Error?new Error(`Failed to read file "${t}": ${e.message}`):e}},"execute")},vn=A.object({path:A.string().describe("The file path to write to"),content:A.string().describe("The content to write to the file")}),Nn={name:"write-file",description:"Write content to a file on disk, creating directories if needed",schema:vn,summarize:c(({path:t})=>t,"summarize"),execute:c(async({path:t,content:e})=>{try{return await Ke(Ve(t),{recursive:!0}),await ce(t,e,"utf-8"),`Successfully wrote ${e.length} characters to "${t}"`}catch(n){throw n instanceof Error?new Error(`Failed to write file "${t}": ${n.message}`):n}},"execute")};function Ue(t){try{const e=j.fromJSONSchema(t);return e instanceof j.ZodObject?e.strict():j.object({}).passthrough()}catch{return j.object({}).passthrough()}}c(Ue,"jsonSchemaToZod");function Ln(t,e,n){return t.map(s=>Gn(s,e,n))}c(Ln,"createMcpTools");function Un(t,e){return t.map(n=>{const s=e?`${e}_${n.name}`:n.name,r=Ue(n.inputSchema);return{name:s,description:n.description??"",schema:r}})}c(Un,"createMcpToolDefinitions");function Gn(t,e,n){const s=n?`${n}_${t.name}`:t.name,r=Ue(t.inputSchema);return{name:s,description:t.description??"",schema:r,async execute(o){const a=await e.callTool({name:t.name,arguments:o});if("isError"in a&&a.isError)throw new Error(Fn(a.content));return Dn(a.content)}}}c(Gn,"createMcpTool");function Dn(t){return t.some(n=>n.type==="image")?t.filter(n=>n.type==="text"||n.type==="image").map(n=>{if(n.type==="text")return{type:"text",text:n.text};const s=n;return{type:"image",data:s.data,mimeType:s.mimeType}}):t.filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
36
|
-
`)}c(Dn,"formatToolResult");function Fn(t){return t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
37
|
-
`)||"MCP tool execution error"}c(Fn,"formatErrorContent");class jn{static{c(this,"MCP")}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;const n=e?.tracer?.startSpan("mcp:connect",{type:"internal"});this.client=new nt({name:"axle",version:"1.0.0"}),this.config.transport==="stdio"?this.transport=new st({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new rt(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,n?.end("ok")}catch(s){throw n?.end("error"),s}}async listTools(e){const n=this.assertConnected(),s=await this.fetchTools(n,e?.tracer);return Ln(s,n,e?.prefix)}async listToolDefinitions(e){const n=this.assertConnected(),s=await this.fetchTools(n,e?.tracer);return Un(s,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,n){if(this.cachedMcpTools)return this.cachedMcpTools;n?.debug("mcp:listTools");const s=await e.listTools();return this.cachedMcpTools=s.tools.map(r=>({name:r.name,description:r.description,inputSchema:r.inputSchema})),this.cachedMcpTools}assertConnected(){if(!this._connected||!this.client)throw new Error("MCP not connected. Call connect() first.");return this.client}}const Ge={debug:0,info:1,warn:2,error:3};class qn{static{c(this,"Tracer")}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){const n=this.writers.indexOf(e);n!==-1&&this.writers.splice(n,1)}startSpan(e,n){const s={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:n?.type,startTime:performance.now(),status:"ok",attributes:{},events:[]};return this.writers.forEach(r=>r.onSpanStart(s)),new se(s,this)}async flush(){for(const e of this.writers)e.flush&&await e.flush()}_notifySpanEnd(e){this.writers.forEach(n=>n.onSpanEnd(e))}_notifySpanUpdate(e){this.writers.forEach(n=>n.onSpanUpdate?.(e))}_notifyEvent(e,n){this.writers.forEach(s=>s.onEvent?.(e,n))}_notifySpanStart(e){this.writers.forEach(n=>n.onSpanStart(e))}_shouldLog(e){return Ge[e]>=Ge[this._minLevel]}}class se{static{c(this,"Span")}data;tracer;ended=!1;constructor(e,n){this.data=e,this.tracer=n}startSpan(e,n){const s={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:e,type:n?.type,startTime:performance.now(),status:"ok",attributes:{},events:[]};return this.tracer._notifySpanStart(s),new se(s,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,n,s){if(this.ended||!this.tracer._shouldLog(n))return;const r={name:e,timestamp:performance.now(),level:n,attributes:s};this.data.events.push(r),this.tracer._notifyEvent(this.data,r)}debug(e,n){this.addEvent(e,"debug",n)}info(e,n){this.addEvent(e,"info",n)}warn(e,n){this.addEvent(e,"warn",n)}error(e,n){this.addEvent(e,"error",n)}setAttribute(e,n){this.ended||(this.data.attributes[e]=n,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 De={debug:0,info:1,warn:2,error:3};let Fe=!1;function Bn(){Fe||(ue.use(ot()),Fe=!0)}c(Bn,"ensureMarkedInit");class Hn{static{c(this,"SimpleWriter")}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 De[e]>=De[this.minLevel]}isSpanVisible(e){return!(e.type==="internal"&&!this.showInternal)}findVisibleAncestor(e){let n=e.parentSpanId;for(;n;){const s=this.spans.get(n);if(!s)break;if(this.isSpanVisible(s))return s;n=s.parentSpanId}return null}calculateVisibleDepth(e){if(!this.isSpanVisible(e))return-1;const n=this.findVisibleAncestor(e);return n?(this.visibleDepths.get(n.spanId)??0)+1:0}formatTimestamp(){if(!this.showTimestamp)return"";const e=new Date,n=e.toTimeString().slice(0,8),s=e.getMilliseconds().toString().padStart(3,"0");return`[${n}.${s}] `}formatDuration(e){if(!this.showDuration||!e.endTime)return"";const n=e.endTime-e.startTime;return n<1e3?` (${Math.round(n)}ms)`:` (${(n/1e3).toFixed(2)}s)`}formatIndent(e){return" ".repeat(e)}formatSpanName(e){return e.type?`[${e.type}] ${e.name}`:e.name}renderMarkdown(e){return Bn(),ue.parse(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const s=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,s);const r=this.formatIndent(s),o=this.formatTimestamp(),a=this.formatSpanName(e);this.output(`${o}${r}START ${a}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const s=this.visibleDepths.get(e.spanId)??0,r=this.formatIndent(s),o=this.formatTimestamp(),a=this.formatDuration(e),l=this.formatSpanName(e),u=e.status==="error"?" [ERROR]":"";if(this.output(`${o}${r}END ${l}${a}${u}`),e.result?.kind==="llm"){const p=e.result,m=[`model=${p.model}`];if(p.finishReason&&m.push(`finishReason=${p.finishReason}`),p.usage&&(p.usage.inputTokens!==void 0&&m.push(`inputTokens=${p.usage.inputTokens}`),p.usage.outputTokens!==void 0&&m.push(`outputTokens=${p.usage.outputTokens}`)),this.output(`${o}${r} INFO LLM complete ${m.join(" ")}`),this.shouldShowEvent("debug")&&p.response.content){const i=(typeof p.response.content=="string"?p.response.content:JSON.stringify(p.response.content,null,2)).split(`
|
|
38
|
-
`);for(const g of i)this.output(`${o}${r} DEBUG ${g}`)}}}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,n){if(!this.shouldShowEvent(n.level))return;this.spans.set(e.spanId,e);let s;if(this.isSpanVisible(e))s=this.visibleDepths.get(e.spanId)??0;else{const d=this.findVisibleAncestor(e);s=d?this.visibleDepths.get(d.spanId)??0:0}const r=this.formatIndent(s+1),o=this.formatTimestamp(),a=n.level.toUpperCase().padEnd(5),l=this.markdown&&n.attributes?.markdown===!0,u=n.attributes?Object.entries(n.attributes).filter(([d])=>d!=="markdown"):[];let p=n.name;l&&(p=this.renderMarkdown(p));let m=`${o}${r}${a} ${p}`;if(u.length>0){const d=u.map(([i,g])=>`${i}=${JSON.stringify(g)}`).join(" ");m+=` ${d}`}this.output(m)}}const Jn=`You are a memory extraction system. Your job is to extract learnings from a conversation that should be remembered for future runs.
|
|
39
|
-
|
|
40
|
-
Only extract:
|
|
41
|
-
- Explicit user corrections (e.g., "No, always use bullet points")
|
|
42
|
-
- Stated preferences (e.g., "I prefer concise summaries")
|
|
43
|
-
- Patterns that clearly emerged from user feedback
|
|
44
|
-
|
|
45
|
-
Do NOT extract:
|
|
46
|
-
- General knowledge or facts from the conversation content
|
|
47
|
-
- Inferences or speculation about what the user might want
|
|
48
|
-
- Task-specific details that won't apply to future runs
|
|
49
|
-
|
|
50
|
-
Respond with a JSON array of instruction strings. Each instruction should be a clear, actionable directive.
|
|
51
|
-
If there are no learnings to extract, respond with an empty array: []
|
|
52
|
-
|
|
53
|
-
Example response:
|
|
54
|
-
["Always use bullet points for lists", "Keep summaries under 3 sentences"]`;class Wn{static{c(this,"ProceduralMemory")}provider;model;enableTools;lastStore;lastName;lastScope;constructor(e){this.provider=e.provider,this.model=e.model,this.enableTools=e.enableTools??!1}async recall(e){const n=e.tracer?.startSpan("memory.recall",{type:"internal"});this.lastStore=e.store,this.lastName=e.name,this.lastScope=e.scope;const s=await this.loadStore(e.store,e.name,e.scope);if(s.instructions.length===0)return n?.info("no stored instructions"),n?.end(),{};n?.info("loaded instructions",{count:s.instructions.length});const r=s.instructions.map((o,a)=>`${a+1}. ${o}`).join(`
|
|
55
|
-
`);return n?.end(),{systemSuffix:`## Learned Instructions
|
|
56
|
-
|
|
57
|
-
${r}`}}async record(e){if(!e.newMessages||e.newMessages.length===0)return;const n=e.tracer?.startSpan("memory.record",{type:"internal"}),s=this.formatMessages(e.newMessages);if(!s.trim()){n?.info("no text content to extract from"),n?.end();return}const r=n?.startSpan("memory.extract",{type:"llm"}),o=await Le({provider:this.provider,model:this.model,messages:[{role:"user",content:s}],system:Jn,tracer:r});if(o.result!=="success"||!o.final){n?.warn("extraction failed",{result:o.result}),n?.end();return}const a=G(o.final.content);if(!a){n?.end();return}const l=this.parseInstructions(a);if(l.length===0){n?.info("no instructions extracted"),n?.end();return}const u=await this.loadStore(e.store,e.name,e.scope);u.instructions.push(...l),await this.saveStore(e.store,e.name,e.scope,u),n?.info("saved instructions",{count:l.length}),n?.end()}tools(){if(!this.enableTools)return[];const 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:A.object({instruction:A.string().describe("The instruction to remember")}),async execute(r){if(!e.lastStore)return"Error: memory not initialized (no recall has been called yet)";const o=await e.loadStore(e.lastStore,e.lastName,e.lastScope);return o.instructions.push(r.instruction),await e.saveStore(e.lastStore,e.lastName,e.lastScope,o),`Instruction saved: "${r.instruction}"`}}]}formatMessages(e){const n=[];for(const s of e)if(s.role==="user"){const r=typeof s.content=="string"?s.content:G(s.content);r&&n.push(`User: ${r}`)}else if(s.role==="assistant"){const r=G(s.content);r&&n.push(`Assistant: ${r}`)}return n.join(`
|
|
58
|
-
|
|
59
|
-
`)}parseInstructions(e){let n=e.trim();const s=n.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);s&&(n=s[1].trim());try{const r=JSON.parse(n);if(Array.isArray(r)&&r.every(o=>typeof o=="string"))return r}catch{}return[]}getStorePath(e,n){const s=e??"default";let r=s;if(n&&Object.keys(n).length>0){const a=Object.entries(n).sort(([u],[p])=>u.localeCompare(p)).map(([u,p])=>`${u}=${p}`).join("&"),l=at.createHash("sha256").update(a).digest("hex").slice(0,8);r=`${s}-${l}`}return`memory/procedural/${r}.json`}async loadStore(e,n,s){const r=this.getStorePath(n,s),o=await e.read(r);if(o)try{const a=JSON.parse(o);if(a&&Array.isArray(a.instructions))return{instructions:a.instructions}}catch{}return{instructions:[]}}async saveStore(e,n,s,r){if(!r)return;const o=this.getStorePath(n,s);await e.write(o,JSON.stringify(r,null,2))}}export{ft as A,It as D,de as H,St as I,ge as L,$ as M,Wn as P,Hn as S,qn as T,Jt as a,k as b,sn as c,Ce as d,S as e,jn as f,vt as g,yn as h,En as i,Ht as j,xe as k,nn as l,Le as m,Ne as n,Tt as o,hn as p,_e as q,z as r,he as s,gt as t,Pn as u,Mn as v,Nn as w,Rn as x};
|
package/dist/cli.js
DELETED
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
var Q=Object.defineProperty;var l=(e,t)=>Q(e,"name",{value:t,configurable:!0});import{Command as X}from"@commander-js/extra-typings";import{basename as ee,extname as te,dirname as oe}from"node:path";import U from"yaml";import{r as J,j as re,a as ne,l as ae,D as ie,g as se,c as ce,p as le,t as N,f as pe,o as F,I as _,A as B,w as ue,u as me,v as fe,x as de,i as ge,h as he,T as we,S as G,P as ye}from"./ProceduralMemory-BtEMO_Cx.js";import{z as o}from"zod";import{glob as ve}from"glob";import{readFile as H,mkdir as be,appendFile as Se}from"node:fs/promises";import{createInterface as ke}from"node:readline";import{createHash as Ee}from"node:crypto";import"mime";import"@anthropic-ai/sdk";import"@google/genai";import"openai";import"node:child_process";import"node:util";import"@modelcontextprotocol/sdk/client/index.js";import"@modelcontextprotocol/sdk/client/stdio.js";import"@modelcontextprotocol/sdk/client/streamableHttp.js";import"marked";import"marked-terminal";function Te(e,t){if(!t||Object.keys(t).length===0)throw new J(`The provider ${e} is not configured. Please check your configuration.`);switch(e){case"openai":return{provider:le(t["api-key"]),model:t.model||ce};case"anthropic":return{provider:se(t["api-key"]),model:t.model||ie};case"gemini":return{provider:ae(t["api-key"]),model:t.model||ne};case"chatcompletions":{const r=t;return{provider:re(r["base-url"],r["api-key"]),model:r.model}}default:throw new J("The provider is unsupported")}}l(Te,"getProvider");var Ae="0.9.0",Oe={version:Ae};o.object({value:o.string()});const je=o.object({"api-key":o.string(),rateLimit:o.number().optional()});o.object({timeout:o.number().optional(),maxBuffer:o.number().optional(),cwd:o.string().optional()});const Ce=o.object({type:o.literal("chatcompletions")}).loose(),xe=o.object({type:o.literal("anthropic")}).loose(),Me=o.object({type:o.literal("openai")}).loose(),Pe=o.object({type:o.literal("gemini")}).loose(),Fe=o.discriminatedUnion("type",[Ce,xe,Me,Pe]),Le=o.object({chatcompletions:o.custom().optional(),anthropic:o.custom().optional(),openai:o.custom().optional(),gemini:o.custom().optional(),brave:je.optional()}).loose(),Ie=o.object({transport:o.literal("stdio"),name:o.string().optional(),command:o.string(),args:o.array(o.string()).optional(),env:o.record(o.string(),o.string()).optional()}),$e=o.object({transport:o.literal("http"),name:o.string().optional(),url:o.string(),headers:o.record(o.string(),o.string()).optional()}),De=o.discriminatedUnion("transport",[Ie,$e]),Ue=o.object({files:o.string(),resume:o.boolean().default(!1),concurrency:o.number().int().positive().default(3)}),Je=o.object({name:o.string().optional(),provider:Fe,task:o.string(),tools:o.array(o.string()).optional(),server_tools:o.array(o.string()).optional(),files:o.array(o.string()).optional(),mcps:o.array(De).optional(),batch:Ue.optional()}),Ne="axle.job",_e=["yaml","yml","json"];async function Be(e,t){const{tracer:r}=t,{content:s,format:c,path:i}=await N(e,{defaults:{name:Ne,formats:_e},tag:"Job File"});let n=null;if(c==="json")n=JSON.parse(s);else if(c==="yaml"||c==="yml")n=U.parse(s);else throw new Error("Invalid job file format");r?.debug("Job config: "+JSON.stringify(n,null,2));const p=Je.safeParse(n);if(!p.success)throw new Error(`The job file is not valid:
|
|
3
|
-
${W(p.error)}`);return p.data.name||(p.data.name=ee(i,te(i))),p.data}l(Be,"getJobConfig");const Ge="axle.config",He=["yaml","yml","json"];async function We(e,t){const{tracer:r}=t,{content:s,format:c}=await N(e,{defaults:{name:Ge,formats:He},tag:"Config File"});let i=null;if(c==="json")i=JSON.parse(s);else if(c==="yaml"||c==="yml")i=U.parse(s);else throw new Error("Invalid config file format");r?.debug("Service config: "+JSON.stringify(i,null,2));const n=Le.safeParse(i);if(!n.success)throw new Error(`The config file is not valid:
|
|
4
|
-
${W(n.error)}`);return n.data}l(We,"getServiceConfig");function W(e){return e.issues.map(t=>` - ${t.path.join(".")||"root"}: ${t.message}`).join(`
|
|
5
|
-
`)}l(W,"formatZodError");async function Ve(e,t){const r=[];for(const s of e){const c=new pe(s);await c.connect({tracer:t}),r.push(c)}return r}l(Ve,"connectMcps");async function Re(e,t){for(const r of e)try{await r.close({tracer:t})}catch{}}l(Re,"closeMcps");const V=".axle/batch.jsonl";function qe(e,t){const r=Ee("sha256");return r.update(e),r.update("\0"),r.update(t),r.digest("hex")}l(qe,"computeHash");async function ze(e=V){const t=new Map;let r;try{r=await H(e,"utf-8")}catch{return t}for(const s of r.split(`
|
|
6
|
-
`)){const c=s.trim();if(c)try{const i=JSON.parse(c);i.file&&i.hash&&t.set(i.file,i)}catch{}}return t}l(ze,"loadLedger");async function Ye(e,t=V){await be(oe(t),{recursive:!0}),await Se(t,JSON.stringify(e)+`
|
|
7
|
-
`,"utf-8")}l(Ye,"appendLedgerEntry");async function Ze(e,t,r,s,c,i,n,p,h,M){const d=new _(e.task);if(e.files)for(const u of e.files)d.addFile(await F(u));const w=h.startSpan("job",{type:"workflow"}),E=new B({provider:t,model:r,tools:s,mcps:c,tracer:w,name:e.name,memory:M,options:{strictVariables:!n.allowMissingVars}});try{const u=await E.send(d,i).final;if(p.in+=u.usage.in,p.out+=u.usage.out,u.response){const v=typeof u.response=="string"?u.response:JSON.stringify(u.response,null,2);h.info(v,{markdown:!0})}n.interactive&&await Ke(E,p,h),w.end()}catch(u){const v=u instanceof Error?u.message:String(u);throw w.error(v),w.end("error"),u}}l(Ze,"runSingle");async function Ke(e,t,r){const s=ke({input:process.stdin,output:process.stdout});s.on("SIGINT",()=>{s.close()});const c=l(i=>new Promise(n=>{s.question(i,n),s.once("close",()=>n(null))}),"prompt");try{for(;;){const i=await c(`
|
|
8
|
-
> `);if(i===null||i.trim()==="")break;try{const n=await e.send(i.trim()).final;if(t.in+=n.usage.in,t.out+=n.usage.out,n.response){const p=typeof n.response=="string"?n.response:JSON.stringify(n.response,null,2);r.info(p,{markdown:!0})}}catch(n){const p=n instanceof Error?n.message:String(n);r.error(p)}}}finally{s.close()}}l(Ke,"runInteractiveLoop");async function Qe(e,t,r,s,c,i,n,p,h,M){const d=e.batch,w=await ve(d.files);if(w.length===0){h.warn(`No files matched pattern: ${d.files}`);return}h.info(`Batch: ${w.length} file(s) matched "${d.files}"`);const E=d.resume?await ze():new Map,u=e.files?await Promise.all(e.files.map(y=>F(y))):[];let v=0,L=0,I=0;const Y=d.concurrency??3;await Xe(Y,w,async y=>{const b=h.startSpan(`batch:${y}`,{type:"workflow"});try{const S=await H(y),T=qe(e.task,S),$=E.get(y);if(d.resume&&$&&$.hash===T){b.info("Skipped (already completed)"),b.end(),L++;return}const P=new _(e.task);for(const K of u)P.addFile(K);P.addFile(await F(y));const Z={...i,file:y},D=await new B({provider:t,model:r,tools:s,mcps:c,tracer:b,name:e.name,memory:M,options:{strictVariables:!n.allowMissingVars}}).send(P,Z).final;p.in+=D.usage.in,p.out+=D.usage.out,await Ye({file:y,hash:T,timestamp:Date.now()}),b.end(),v++}catch(S){const T=S instanceof Error?S.message:String(S);b.error(`Failed: ${T}`),b.end("error"),I++}}),h.info(`Batch complete: ${v} completed, ${L} skipped, ${I} failed`)}l(Qe,"runBatch");async function Xe(e,t,r){let s=0;async function c(){for(;s<t.length;){const n=s++;await r(t[n])}}l(c,"worker");const i=Array.from({length:Math.min(e,t.length)},()=>c());await Promise.all(i)}l(Xe,"runWithConcurrency");function et(e,t){switch(e){case"brave":return he;case"calculator":return ge;case"exec":return de;case"patch-file":return fe;case"read-file":return me;case"write-file":return ue;default:throw new Error(`Unknown tool: ${e}`)}}l(et,"createTool");function tt(e,t){return e.map(r=>et(r))}l(tt,"createTools");const A=new X().name("axle").description("Axle is a CLI tool for running AI workflows").version(Oe.version).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");A.parse(process.argv);const m=A.opts(),O={date:new Date().toISOString().split("T")[0],datetime:new Date().toISOString(),cwd:process.cwd()};m.args&&m.args.forEach(e=>{const[t,r]=e.split("=");t&&r&&(O[t.trim()]=r.trim())});const g=new we;m.debug&&(g.minLevel="debug");const ot=new G({minLevel:m.debug?"debug":"info",showInternal:m.debug,showTimestamp:!0,markdown:!0});if(g.addWriter(ot),m.log){const e=new G({minLevel:"debug",showInternal:!0,showTimestamp:!0,output:l(t=>{},"output")});g.addWriter(e)}const a=g.startSpan("cli",{type:"root"});process.on("uncaughtException",async e=>{console.error("Uncaught exception:"),console.error(e),a.error("Uncaught exception:"),a.error(e.message),a.error(e.stack||""),a.end("error"),await g.flush(),process.exit(1)}),m.debug&&(a.debug("Options: "+JSON.stringify(m,null,2)),a.debug("Additional Arguments: "+JSON.stringify(O,null,2)));let R,f;try{R=await We(m.config??null,{tracer:a}),f=await Be(m.job??null,{tracer:a})}catch(e){const t=e instanceof Error?e:new Error(String(e));a.error(t.message),a.debug(t.stack??""),a.end("error"),await g.flush(),A.outputHelp(),process.exit(1)}let j,C;try{const{type:e,...t}=f.provider,r={...R[e],...t};({provider:j,model:C}=Te(e,r))}catch(e){const t=e instanceof Error?e:new Error(String(e));a.error(t.message),a.error(t.stack??""),a.end("error"),await g.flush(),A.outputHelp(),process.exit(1)}a.info("All systems operational. Running job...");const q=new ye({provider:j,model:C}),rt=(f.server_tools??[]).map(e=>({type:"server",name:e})),z=[...f.tools?.length?tt(f.tools):[],...rt];let k=[];if(f.mcps?.length)try{k=await Ve(f.mcps,a)}catch(e){const t=e instanceof Error?e:new Error(String(e));a.error("Failed to connect MCP servers: "+t.message),a.end("error"),await g.flush(),process.exit(1)}const x={in:0,out:0},nt=performance.now();try{f.batch?await Qe(f,j,C,z,k,O,m,x,a,q):await Ze(f,j,C,z,k,O,m,x,a,q)}catch(e){const t=e instanceof Error?e:new Error(String(e));a.error(t.message),a.debug(t.stack??"")}finally{k.length>0&&await Re(k,a)}const at=performance.now()-nt;a.info(`Total run time: ${Math.round(at)}ms`),a.info(`Input tokens: ${x.in}`),a.info(`Output tokens: ${x.out}`),a.info("Complete. Goodbye"),a.end(),await g.flush();
|