@fifthrevision/axle 0.7.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +4 -17
- package/dist/index.js +1 -1
- package/dist/simple-PYzpQ26F.js +28 -0
- package/package.json +5 -5
- package/dist/simple-DFkTLK9N.js +0 -28
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Y=Object.defineProperty;var i=(e,t)=>Y(e,"name",{value:t,configurable:!0});import{Command as Z}from"@commander-js/extra-typings";import J from"yaml";import{l as q,a as K,n as Q,D as ee,i as te,d as oe,p as ne,r as N,o as j,I as U,h as P,w as re,t as ae,u as ie,v as se,k as ce,j as le,T as ue,S as M}from"./simple-
|
|
2
|
+
var Y=Object.defineProperty;var i=(e,t)=>Y(e,"name",{value:t,configurable:!0});import{Command as Z}from"@commander-js/extra-typings";import J from"yaml";import{l as q,a as K,n as Q,D as ee,i as te,d as oe,p as ne,r as N,o as j,I as U,h as P,w as re,t as ae,u as ie,v as se,k as ce,j as le,T as ue,S as M}from"./simple-PYzpQ26F.js";import{z as n}from"zod";import{glob as pe}from"glob";import{readFile as _,mkdir as de,appendFile as fe}from"node:fs/promises";import{createHash as me}from"node:crypto";import{dirname as he}from"node:path";import"mime";import"@anthropic-ai/sdk";import"@google/genai";import"openai";import"node:child_process";import"node:util";class A extends Error{static{i(this,"AxleError")}code;id;details;constructor(t,o){super(t,{cause:o?.cause}),this.name=this.constructor.name,this.code=o?.code||"AXLE_ERROR",this.id=o?.id,this.details=o?.details,Object.setPrototypeOf(this,A.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:R(this.cause)}}}}function R(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack&&{stack:e.stack},..."cause"in e&&e.cause&&{cause:R(e.cause)}}:e}i(R,"serializeError");function ge(e,t){if(!t||Object.keys(t).length===0)throw new A(`The provider ${e} is not configured. Please check your configuration.`);switch(e){case"openai":return{provider:ne(t["api-key"]),model:t.model||oe};case"anthropic":return{provider:te(t["api-key"]),model:t.model||ee};case"gemini":return{provider:Q(t["api-key"]),model:t.model||K};case"chatcompletions":{const o=t;return{provider:q(o["base-url"],o["api-key"]),model:o.model}}default:throw new A("The provider is unsupported")}}i(ge,"getProvider");var we="0.7.2",ye={version:we};n.object({value:n.string()});const be=n.object({"api-key":n.string(),rateLimit:n.number().optional()});n.object({timeout:n.number().optional(),maxBuffer:n.number().optional(),cwd:n.string().optional()});const ve=n.object({type:n.literal("chatcompletions")}).loose(),Se=n.object({type:n.literal("anthropic")}).loose(),ke=n.object({type:n.literal("openai")}).loose(),Ee=n.object({type:n.literal("gemini")}).loose(),Te=n.discriminatedUnion("type",[ve,Se,ke,Ee]),Ae=n.object({chatcompletions:n.custom().optional(),anthropic:n.custom().optional(),openai:n.custom().optional(),gemini:n.custom().optional(),brave:be.optional()}).loose(),Oe=n.object({files:n.string(),resume:n.boolean().default(!1),concurrency:n.number().int().positive().default(3)}),je=n.object({provider:Te,task:n.string(),tools:n.array(n.string()).optional(),files:n.array(n.string()).optional(),batch:Oe.optional()}),Le="axle.job",Fe=["yaml","yml","json"];async function xe(e,t){const{tracer:o}=t,{content:l,format:s}=await N(e,{defaults:{name:Le,formats:Fe},tag:"Job File"});let a=null;if(s==="json")a=JSON.parse(l);else if(s==="yaml"||s==="yml")a=J.parse(l);else throw new Error("Invalid job file format");o?.debug("Job config: "+JSON.stringify(a,null,2));const c=je.safeParse(a);if(!c.success)throw new Error(`The job file is not valid:
|
|
3
3
|
${B(c.error)}`);return c.data}i(xe,"getJobConfig");const De="axle.config",$e=["yaml","yml","json"];async function Ie(e,t){const{tracer:o}=t,{content:l,format:s}=await N(e,{defaults:{name:De,formats:$e},tag:"Config File"});let a=null;if(s==="json")a=JSON.parse(l);else if(s==="yaml"||s==="yml")a=J.parse(l);else throw new Error("Invalid config file format");o?.debug("Service config: "+JSON.stringify(a,null,2));const c=Ae.safeParse(a);if(!c.success)throw new Error(`The config file is not valid:
|
|
4
4
|
${B(c.error)}`);return c.data}i(Ie,"getServiceConfig");function B(e){return e.issues.map(t=>` - ${t.path.join(".")||"root"}: ${t.message}`).join(`
|
|
5
5
|
`)}i(B,"formatZodError");const W=".axle/batch.jsonl";function Ce(e,t){const o=me("sha256");return o.update(e),o.update("\0"),o.update(t),o.digest("hex")}i(Ce,"computeHash");async function Je(e=W){const t=new Map;let o;try{o=await _(e,"utf-8")}catch{return t}for(const l of o.split(`
|
package/dist/index.d.ts
CHANGED
|
@@ -571,10 +571,6 @@ declare const Anthropic: {
|
|
|
571
571
|
readonly CLAUDE_OPUS_4: "claude-opus-4-20250514";
|
|
572
572
|
readonly CLAUDE_SONNET_4_20250514: "claude-sonnet-4-20250514";
|
|
573
573
|
readonly CLAUDE_SONNET_4: "claude-sonnet-4-20250514";
|
|
574
|
-
readonly CLAUDE_3_7_SONNET_20250219: "claude-3-7-sonnet-20250219";
|
|
575
|
-
readonly CLAUDE_3_7_SONNET: "claude-3-7-sonnet-20250219";
|
|
576
|
-
readonly CLAUDE_3_5_HAIKU_20241022: "claude-3-5-haiku-20241022";
|
|
577
|
-
readonly CLAUDE_3_5_HAIKU: "claude-3-5-haiku-20241022";
|
|
578
574
|
readonly CLAUDE_3_HAIKU_20240307: "claude-3-haiku-20240307";
|
|
579
575
|
readonly CLAUDE_3_HAIKU: "claude-3-haiku-20240307";
|
|
580
576
|
};
|
|
@@ -587,6 +583,8 @@ declare function gemini(apiKey: string): AIProvider;
|
|
|
587
583
|
|
|
588
584
|
declare const Gemini: {
|
|
589
585
|
readonly Models: {
|
|
586
|
+
readonly GEMINI_3_1_PRO_PREVIEW: "gemini-3.1-pro-preview";
|
|
587
|
+
readonly GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS: "gemini-3.1-pro-preview-customtools";
|
|
590
588
|
readonly GEMINI_3_PRO_PREVIEW: "gemini-3-pro-preview";
|
|
591
589
|
readonly GEMINI_3_FLASH_PREVIEW: "gemini-3-flash-preview";
|
|
592
590
|
readonly GEMINI_3_PRO_IMAGE_PREVIEW: "gemini-3-pro-image-preview";
|
|
@@ -596,12 +594,12 @@ declare const Gemini: {
|
|
|
596
594
|
readonly GEMINI_2_5_FLASH_IMAGE: "gemini-2.5-flash-image";
|
|
597
595
|
readonly GEMINI_2_5_FLASH_LITE: "gemini-2.5-flash-lite";
|
|
598
596
|
readonly GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025: "gemini-2.5-flash-lite-preview-09-2025";
|
|
597
|
+
readonly GEMINI_2_5_FLASH_NATIVE_AUDIO_LATEST: "gemini-2.5-flash-native-audio-latest";
|
|
599
598
|
readonly GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_09_2025: "gemini-2.5-flash-native-audio-preview-09-2025";
|
|
600
599
|
readonly GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025: "gemini-2.5-flash-native-audio-preview-12-2025";
|
|
601
600
|
readonly GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025: "gemini-2.5-computer-use-preview-10-2025";
|
|
602
601
|
readonly GEMINI_2_0_FLASH: "gemini-2.0-flash";
|
|
603
602
|
readonly GEMINI_2_0_FLASH_001: "gemini-2.0-flash-001";
|
|
604
|
-
readonly GEMINI_2_0_FLASH_EXP_IMAGE_GENERATION: "gemini-2.0-flash-exp-image-generation";
|
|
605
603
|
readonly GEMINI_2_0_FLASH_LITE: "gemini-2.0-flash-lite";
|
|
606
604
|
readonly GEMINI_2_0_FLASH_LITE_001: "gemini-2.0-flash-lite-001";
|
|
607
605
|
readonly GEMINI_EXP_1206: "gemini-exp-1206";
|
|
@@ -619,7 +617,7 @@ declare const Gemini: {
|
|
|
619
617
|
readonly NANO_BANANA_PRO_PREVIEW: "nano-banana-pro-preview";
|
|
620
618
|
readonly AQA: "aqa";
|
|
621
619
|
};
|
|
622
|
-
readonly DefaultModel: "gemini-
|
|
620
|
+
readonly DefaultModel: "gemini-2.5-flash-lite";
|
|
623
621
|
};
|
|
624
622
|
|
|
625
623
|
interface GenerateOptions {
|
|
@@ -681,17 +679,6 @@ declare const OpenAI: {
|
|
|
681
679
|
readonly GPT_4O_MINI_SEARCH_PREVIEW_2025_03_11: "gpt-4o-mini-search-preview-2025-03-11";
|
|
682
680
|
readonly GPT_4_TURBO: "gpt-4-turbo";
|
|
683
681
|
readonly GPT_4_TURBO_2024_04_09: "gpt-4-turbo-2024-04-09";
|
|
684
|
-
readonly GPT_4_TURBO_PREVIEW: "gpt-4-turbo-preview";
|
|
685
|
-
readonly GPT_4_0125_PREVIEW: "gpt-4-0125-preview";
|
|
686
|
-
readonly GPT_4_1106_PREVIEW: "gpt-4-1106-preview";
|
|
687
|
-
readonly GPT_4: "gpt-4";
|
|
688
|
-
readonly GPT_4_0613: "gpt-4-0613";
|
|
689
|
-
readonly GPT_3_5_TURBO: "gpt-3.5-turbo";
|
|
690
|
-
readonly GPT_3_5_TURBO_0125: "gpt-3.5-turbo-0125";
|
|
691
|
-
readonly GPT_3_5_TURBO_1106: "gpt-3.5-turbo-1106";
|
|
692
|
-
readonly GPT_3_5_TURBO_16K: "gpt-3.5-turbo-16k";
|
|
693
|
-
readonly GPT_3_5_TURBO_INSTRUCT: "gpt-3.5-turbo-instruct";
|
|
694
|
-
readonly GPT_3_5_TURBO_INSTRUCT_0914: "gpt-3.5-turbo-instruct-0914";
|
|
695
682
|
readonly O4_MINI: "o4-mini";
|
|
696
683
|
readonly O4_MINI_2025_04_16: "o4-mini-2025-04-16";
|
|
697
684
|
readonly O4_MINI_DEEP_RESEARCH: "o4-mini-deep-research";
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var $=Object.defineProperty;var r=(n,a)=>$(n,"name",{value:a,configurable:!0});import{D as I,M as L,a as w,b as F,c as O,A,g as q,e as U,d as S,f as _}from"./simple-
|
|
1
|
+
var $=Object.defineProperty;var r=(n,a)=>$(n,"name",{value:a,configurable:!0});import{D as I,M as L,a as w,b as F,c as O,A,g as q,e as U,d as S,f as _}from"./simple-PYzpQ26F.js";import{h as oe,H as te,I as re,S as ne,T as ae,i as ie,j as le,k as ce,l as ue,m as me,n as pe,o as de,p as ge,q as fe,s as Me}from"./simple-PYzpQ26F.js";import"@anthropic-ai/sdk";import"zod";import"@google/genai";import"openai";import"glob";import"mime";import"node:fs/promises";import"node:path";import"node:child_process";import"node:util";const b={Models:L,DefaultModel:I},G={Models:F,DefaultModel:w};async function v(n){const{provider:a,model:i,messages:u,system:p,tools:d,tracer:g,options:l}=n;return a.createGenerationRequest(i,{messages:u,system:p,tools:d,context:{tracer:g},options:l})}r(v,"generateTurn");async function H(n){const{provider:a,model:i,messages:u,system:p,tools:d,onToolCall:g,maxIterations:l,tracer:m,options:C}=n,f=[...u],o=[],t={in:0,out:0};let M=0,h;const R=r(e=>{f.push(e),o.push(e)},"addMessage"),c=r(e=>(m?.setResult({kind:"llm",model:i,request:{messages:u},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}),m?.end(e.result==="error"?"error":"ok"),e),"endWithResult"),E=r((e,s)=>{if(!e||s.type==="error"){e?.end("error");return}e.setResult({kind:"llm",model:s.model??i,request:{messages:f},response:{content:s.content},usage:s.usage?{inputTokens:s.usage.in,outputTokens:s.usage.out}:void 0,finishReason:s.finishReason}),e.end()},"setTurnResult");for(;;){if(l!==void 0&&M>=l)return c({result:"error",messages:o,error:{type:"model",error:{type:"error",error:{type:"MaxIterations",message:`Exceeded max iterations (${l})`}}},usage:t});M+=1;const e=m?.startSpan(`turn-${M}`,{type:"llm"}),s=await v({provider:a,model:i,messages:f,system:p,tools:d,tracer:e,options:C});if(O(t,s),E(e,s),s.type==="error")return c({result:"error",messages:o,error:{type:"model",error:s},usage:t});const y={role:"assistant",id:s.id,model:s.model,content:s.content,finishReason:s.finishReason};if(R(y),h=y,s.finishReason!==A.FunctionCall)return c({result:"success",messages:o,final:h,usage:t});const T=q(s.content);if(T.length===0)return c({result:"success",messages:o,final:h,usage:t});for(const x of T)m?.info(`tool call: ${x.name}`,{parameters:x.parameters});const{results:D,missingTool:k}=await U(T,g);if(D.length>0&&R({role:"tool",content:D}),k)return c({result:"error",messages:o,error:{type:"tool",error:k},usage:t})}}r(H,"generate");const W={Models:_,DefaultModel:S};export{oe as Agent,b as Anthropic,A as AxleStopReason,G as Gemini,te as History,re as Instruct,W as OpenAI,ne as SimpleWriter,ae as Tracer,ie as anthropic,le as braveSearchTool,ce as calculatorTool,ue as chatCompletions,me as compileInstruct,pe as gemini,H as generate,v as generateTurn,de as loadFileContent,ge as openai,fe as parseResponse,Me as stream};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
var Pe=Object.defineProperty;var i=(t,e)=>Pe(t,"name",{value:e,configurable:!0});import*as C from"zod";import V,{z as k}from"zod";import"glob";import Le from"mime";import{readFile as H,access as Ne,stat as Ue,writeFile as re,mkdir as Ge}from"node:fs/promises";import{resolve as Y,extname as oe,dirname as ve}from"node:path";import De from"@anthropic-ai/sdk";import{FinishReason as O,GoogleGenAI as Fe}from"@google/genai";import He from"openai";import{exec as je}from"node:child_process";import{promisify as Be}from"node:util";var I=(t=>(t.Stop="stop",t.Length="length",t.FunctionCall="function_call",t.Error="error",t.Custom="custom",t.Cancelled="cancelled",t))(I||{});class ae{static{i(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:I.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 qe(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}i(qe,"toContentParts");function F(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
2
|
+
|
|
3
|
+
`)}i(F,"getTextContent");function We(t){return t.filter(e=>e.type==="tool-call")}i(We,"getToolCalls");function Ve(t,e){const n=e.usage??{in:0,out:0};t.in+=n.in??0,t.out+=n.out??0}i(Ve,"appendUsage");function ie(t){return JSON.stringify({error:t})}i(ie,"serializeToolError");async function ce(t,e){const n=[];let s;for(const r of t){let a;try{a=await e(r.name,r.parameters)}catch(o){a={type:"error",error:{type:"exception",message:o instanceof Error?o.message:String(o)}}}if(a==null){s={name:r.name,message:`Tool not found: ${r.name}`},n.push({id:r.id,name:r.name,content:ie({type:"not-found",message:s.message})});break}a.type==="success"?n.push({id:r.id,name:r.name,content:a.content}):n.push({id:r.id,name:r.name,content:ie(a.error)})}return{results:n,missingTool:s}}i(ce,"executeToolCalls");function le(t){const e=[],n=[],s=[],r=[],a=[],o=new AbortController;let l=!1,c,u;const d=new Promise((f,p)=>{c=i(m=>{l=!0,f(m)},"resolveResult"),u=i(m=>{l=!0,p(m)},"rejectResult")});return Promise.resolve().then(()=>ze(t,o.signal,e,n,s,r,a).then(c,u)),{onPartStart(f){e.push(f)},onPartUpdate(f){n.push(f)},onPartEnd(f){s.push(f)},onInternalTool(f){r.push(f)},onError(f){a.push(f)},cancel(){l||o.abort()},get final(){return d}}}i(le,"stream");function ue(t,e,n){for(const s of t)s(e,n)}i(ue,"emitPartStart");function Q(t,e,n,s,r){for(const a of t)a(e,n,s,r)}i(Q,"emitPartUpdate");function Je(t,e,n,s){for(const r of t)r(e,n,s)}i(Je,"emitPartEnd");function Ke(t,e){for(const n of t)n(e)}i(Ke,"emitError");async function ze(t,e,n,s,r,a,o){const{provider:l,model:c,messages:u,system:d,tools:f,onToolCall:p,maxIterations:m,tracer:_,options:h}=t,x=[...u],T=[],A={in:0,out:0};let U=0,G=0;const j=i(y=>{x.push(y),T.push(y)},"addMessage"),P=i(y=>{y.result==="error"&&Ke(o,y.error);const L=y.result==="success"?y.final?.content:y.result==="cancelled"?y.partial?.content:null,S=y.result==="success"?y.final?.finishReason:y.result==="cancelled"?I.Cancelled:void 0;return _?.setResult({kind:"llm",model:c,request:{messages:u},response:{content:L??null},usage:y.usage?{inputTokens:y.usage.in,outputTokens:y.usage.out}:void 0,finishReason:S}),_?.end(y.result==="error"?"error":"ok"),y},"endWithResult"),W=i((y,L,S,v)=>{v();const N=y.length>0?{role:"assistant",id:L,model:S,content:y,finishReason:I.Cancelled}:void 0;return N&&j(N),_?.end("ok"),{result:"cancelled",messages:T,partial:N,usage:A}},"buildCancelledResult");for(;;){if(e.aborted)return W([],"","",()=>{});if(m!==void 0&&G>=m)return P({result:"error",messages:T,error:{type:"model",error:{type:"error",error:{type:"MaxIterations",message:`Exceeded max iterations (${m})`}}},usage:A});G+=1;const y=_?.startSpan(`turn-${G}`,{type:"llm"});y?.startLLMStream();const L=l.createStreamingRequest?.(c,{messages:x,system:d,tools:f,context:{tracer:y},signal:e,options:h});if(!L)throw y?.end("error"),new Error("Provider does not support streaming. Use generate() instead.");const S=[];let v="",D="",N=null,B={in:0,out:0},R=-1,q=null,M="";const $=i(()=>{q!==null&&R>=0&&(Je(r,R,q,M),q=null,M="",R=-1)},"closePart");for await(const g of L){switch(g.type){case"start":v=g.id,D=g.data.model;break;case"text-start":{$(),S.push({type:"text",text:""}),R=U++,q="text",M="",ue(n,R,"text");break}case"text-delta":{const w=S[g.data.index];w.text+=g.data.text,M=w.text,y?.appendLLMStream(g.data.text),Q(s,R,"text",g.data.text,M);break}case"text-complete":{$();break}case"thinking-start":{$(),S.push({type:"thinking",text:""}),R=U++,q="thinking",M="",ue(n,R,"thinking");break}case"thinking-delta":{const w=S[g.data.index];w.text+=g.data.text,M=w.text,Q(s,R,"thinking",g.data.text,M);break}case"thinking-summary-delta":{const w=S[g.data.index];w.text+=g.data.text,M=w.text,Q(s,R,"thinking",g.data.text,M);break}case"thinking-complete":{$();break}case"tool-call-start":{$(),S.push({type:"tool-call",id:g.data.id,name:g.data.name,parameters:{}}),U++;break}case"tool-call-complete":{const w=S[g.data.index];g.data.id&&(w.id=g.data.id),g.data.name&&(w.name=g.data.name),w.parameters=g.data.arguments;break}case"internal-tool-start":{$();const w=U++;S.push({type:"internal-tool",id:g.data.id,name:g.data.name});for(const Z of a)Z({type:"start",index:w,id:g.data.id,name:g.data.name});break}case"internal-tool-complete":{const w=S[g.data.index];g.data.output!=null&&(w.output=g.data.output);for(const Z of a)Z({type:"complete",index:g.data.index,id:g.data.id,name:g.data.name,output:g.data.output});break}case"complete":{$(),N=g.data.finishReason,B=g.data.usage;break}case"error":{$();const w=g.data.usage??{in:0,out:0};return A.in+=w.in??0,A.out+=w.out??0,y?.end("error"),P({result:"error",messages:T,error:{type:"model",error:{type:"error",error:{type:g.data.type,message:g.data.message}}},usage:A})}default:console.warn("[WARN] Unhandled chunk type. Should never happen")}if(e.aborted)break}if(e.aborted)return y?.end("ok"),W(S,v,D,$);if(N===null)return $(),y?.end("error"),P({result:"error",messages:T,error:{type:"model",error:{type:"error",error:{type:"IncompleteStream",message:"Stream ended without a completion signal"}}},usage:A});A.in+=B.in??0,A.out+=B.out??0;const Me={kind:"llm",model:D,request:{messages:x},response:{content:S},usage:{inputTokens:B.in,outputTokens:B.out},finishReason:N};y?.endLLMStream(Me),y?.end();const z={role:"assistant",id:v,model:D,content:S,finishReason:N};if(j(z),N!==I.FunctionCall)return P({result:"success",messages:T,final:z,usage:A});const X=S.filter(g=>g.type==="tool-call");if(X.length===0)return P({result:"success",messages:T,final:z,usage:A});if(e.aborted)return _?.end("ok"),{result:"cancelled",messages:T,usage:A};const $e=p?async(g,w)=>p(g,w):async()=>null;for(const g of X)_?.info(`tool call: ${g.name}`,{parameters:g.parameters});const{results:ne,missingTool:se}=await ce(X,$e);if(ne.length>0&&j({role:"tool",content:ne}),se)return P({result:"error",messages:T,error:{type:"tool",error:se},usage:A})}}i(ze,"run");function Xe(t,e,n="{{}}"){const s=n==="{{}}"?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g;return t=t.replace(s,(r,a)=>{if(a=a.trim(),Object.prototype.hasOwnProperty.call(e,a)){const o=e[a];return o==null?"":String(o)}return r}),t}i(Xe,"replaceVariables");function J(t){if(t instanceof C.ZodString)return["string","Your answer"];if(t instanceof C.ZodNumber)return["number",42];if(t instanceof C.ZodBoolean)return["boolean",!0];if(t instanceof C.ZodArray){const e=t.element;if(e instanceof C.ZodString)return["string array",["answer 1","answer 2","third answer"]];if(e instanceof C.ZodNumber)return["number array",[42,59,3.14]];if(e instanceof C.ZodBoolean)return["boolean array",[!0,!1,!1]];if(e instanceof C.ZodObject){const[n,s]=J(e);return["object array",[s,s]]}return["array",[]]}if(t instanceof C.ZodObject){const e=t.shape,n={};for(const[s,r]of Object.entries(e)){const[a,o]=J(r);n[s]=o}return["JSON object",n]}if(t instanceof C.ZodOptional){const e=t.unwrap(),[n,s]=J(e);return[`${n} | undefined`,s]}}i(J,"zodToExample");function pe(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=Ze(t),r={};for(const[a,o]of Object.entries(e)){const l=s.tags[a];if(l!==void 0)r[a]=de(o,l);else if(o.def.type!=="optional")throw new Error(`Expected results with tag ${a} but it does not exist`)}try{const a={};for(const[o,l]of Object.entries(e))o in r&&(a[o]=l.parse(r[o]));return a}catch(a){if(a&&typeof a=="object"&&"issues"in a){const o=a.issues.map(l=>`${l.path.join(".")}: ${l.message}`).join(", ");throw new Error(`Validation failed: ${o}`)}throw a}}i(pe,"parseResponse");function de(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 de(n,e)}default:return e}}i(de,"preprocessValue");function Ze(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,(a,o,l)=>(n[o]=l,""));const r=/<(\w+)>(.*?)(?:<\/?\w+>|$)/gs;return s=s.replace(r,(a,o,l)=>(n[o]=l,"")),{tags:n,remaining:s.trim()}}i(Ze,"parseTaggedSections");function fe(t,e={}){const n={...e,...t.inputs};let s=Xe(t.prompt,n);if(t.textReferences.length>0)for(const[o,l]of t.textReferences.entries()){const c=l.name?`: ${l.name}`:"";s+=`
|
|
4
|
+
|
|
5
|
+
## Reference ${o+1}${c}
|
|
6
|
+
|
|
7
|
+
\`\`\`${l.content}'''`}let r=`# Instructions
|
|
8
|
+
|
|
9
|
+
`;if((t.schema?Object.keys(t.schema):[]).length>0){r+=`## Output Format Instructions
|
|
10
|
+
`,r+=`
|
|
11
|
+
Here is how you should format your output. Follow the instructions strictly.
|
|
12
|
+
`;for(const[o,l]of Object.entries(t.schema)){const[c,u]=J(l);r+=`
|
|
13
|
+
- Use <${o}></${o}> tags to indicate the answer for ${o}. The answer must be a ${c}.
|
|
14
|
+
Example: <${o}>${JSON.stringify(u)}</${o}>
|
|
15
|
+
`}}if(t.instructions.length>0){r+=`
|
|
16
|
+
## Additional Instructions
|
|
17
|
+
|
|
18
|
+
`;for(const o of t.instructions)r+=`- ${o}
|
|
19
|
+
`}return r+s}i(fe,"compileInstruct");class Ye{static{i(this,"Agent")}provider;model;history;tracer;system;tools={};partStartCallback;partUpdateCallback;partEndCallback;internalToolCallback;errorCallback;constructor(e){this.provider=e.provider,this.model=e.model,this.history=new ae,this.tracer=e.tracer,this.system=e.system,e.tools&&this.addTools(e.tools)}addTool(e){this.tools[e.name]=e}addTools(e){for(const n of e)this.tools[n.name]=n}hasTools(){return Object.keys(this.tools).length>0}onPartStart(e){this.partStartCallback=e}onPartUpdate(e){this.partUpdateCallback=e}onPartEnd(e){this.partEndCallback=e}onInternalTool(e){this.internalToolCallback=e}onError(e){this.errorCallback=e}send(e,n){let s;if(typeof e=="string")this.history.addUser(e);else{const r=fe(e,n),a=e.files;this.history.addUser(qe({text:r,files:a})),s=e.schema}return this.execute(s)}execute(e){const n=this.tools,s=Object.values(n).map(o=>({name:o.name,description:o.description,schema:o.schema})),r=le({provider:this.provider,model:this.model,messages:this.history.messages,system:this.system,tools:s.length>0?s:void 0,tracer:this.tracer,onToolCall:i(async(o,l)=>{const c=n[o];if(!c)return null;try{const u=await c.execute(l);return{type:"success",content:JSON.stringify(u)}}catch(u){return{type:"error",error:{type:"execution",message:u instanceof Error?u.message:String(u)}}}},"onToolCall")});this.partStartCallback&&r.onPartStart(this.partStartCallback),this.partUpdateCallback&&r.onPartUpdate(this.partUpdateCallback),this.partEndCallback&&r.onPartEnd(this.partEndCallback),this.internalToolCallback&&r.onInternalTool(this.internalToolCallback),this.errorCallback&&r.onError(this.errorCallback);const a=r.final.then(o=>{o.messages.length>0&&this.history.add(o.messages);let l=null,c;if(o.result==="success"){if(c=o.final,c){const d=F(c.content);l=pe(d,e)}}else o.result==="cancelled"&&(c=o.partial);const u=o.usage??{in:0,out:0};return{response:l,messages:o.messages,final:c,usage:u}});return{cancel:i(()=>r.cancel(),"cancel"),get final(){return a}}}}async function Qe(t,e){const{defaults:n,tag:s}=e;let r=null,a="";if(t)try{a=Y(t),r=await H(a,{encoding:"utf-8"})}catch{throw new Error(`${s} not found, see --help for details`)}else{for(const o of n.formats)try{a=Y(n.name+"."+o),r=await H(a,{encoding:"utf-8"});break}catch{continue}if(r===null)throw new Error(`${s} not found, see --help for details`)}return{content:r,format:a.split(".").pop()??""}}i(Qe,"searchAndLoadFile");const me=20*1024*1024;function et(t){return t.type==="text"}i(et,"isTextFileInfo");function tt(t){return t.type==="image"||t.type==="document"}i(tt,"isBase64FileInfo");const nt=new Set(["application/json","application/xml","application/yaml","application/x-yaml","application/toml"]);function st(t){return t.startsWith("text/")||nt.has(t)}i(st,"isTextLikeMimeType");function rt(t){const e=Le.getType(t);if(!e){const n=oe(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(st(e))return{type:"text",mimeType:e};{const n=oe(t).toLowerCase();throw new Error(`Unsupported file type: ${n} (${e})`)}}i(rt,"getFileCategory");async function ot(t,e){const n=Y(t);try{await Ne(n)}catch{throw new Error(`File not found: ${t}`)}const s=await Ue(n);if(s.size>me)throw new Error(`File too large: ${s.size} bytes. Maximum allowed: ${me} bytes`);const r=n.split("/").pop()||"",a=rt(n);if((e||(a.type==="text"?"utf-8":"base64"))==="utf-8"){if(a.type!=="text")throw new Error(`Cannot read ${a.type} file as text: ${t}`);const l=await H(n,"utf-8");return{path:n,content:l,mimeType:a.mimeType,size:s.size,name:r,type:"text"}}else{if(a.type==="text")throw new Error(`Cannot read text file as binary: ${t}`);const c=(await H(n)).toString("base64");return{path:n,base64:c,mimeType:a.mimeType,size:s.size,name:r,type:a.type}}}i(ot,"loadFileContent");class at{static{i(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}tt(e)?this.files.push(e):et(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 b={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"};b.CLAUDE_SONNET_4_6,b.CLAUDE_OPUS_4_6,b.CLAUDE_OPUS_4_5_20251101,b.CLAUDE_HAIKU_4_5_20251001,b.CLAUDE_SONNET_4_5_20250929,b.CLAUDE_OPUS_4_1_20250805,b.CLAUDE_OPUS_4_20250514,b.CLAUDE_SONNET_4_20250514,b.CLAUDE_3_HAIKU_20240307;const it=b.CLAUDE_HAIKU_4_5;function _e(t){return Array.isArray(t)?t:[t]}i(_e,"arrayify");function ct(t){return new Promise(e=>setTimeout(e,t))}i(ct,"delay");function K(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}}i(K,"getUndefinedError");function he(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});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:n.content}))};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}}})}i(he,"convertToProviderMessages");function ge(t){return t.map(e=>{const n=V.toJSONSchema(e.schema);if(!lt(n))throw new Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:n}})}i(ge,"convertToProviderTools");function ye(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}i(ye,"convertToAxleContentParts");function Ee(t){switch(t){case"max_tokens":return I.Length;case"end_turn":return I.Stop;case"stop_sequence":return I.Stop;case"tool_use":return I.FunctionCall;case"pause_turn":case"refusal":default:return I.Error}}i(Ee,"convertStopReason$1");function lt(t){return t&&typeof t=="object"&&t.type==="object"}i(lt,"isObjectSchema");async function ut(t){const{client:e,model:n,messages:s,system:r,tools:a,context:o,options:l}=t,c=o?.tracer,{stop:u,max_tokens:d,...f}=l??{},p={model:n,max_tokens:d??16e3,messages:he(s),...r&&{system:r},...u&&{stop_sequences:_e(u)},...a&&{tools:ge(a)},...f};c?.debug("Anthropic request",{request:p});let m;try{const _=await e.messages.create(p);m=pt(_)}catch(_){m=K(_)}return c?.debug("Anthropic response",{result:m}),m}i(ut,"createGenerationRequest$3");function pt(t){const e=Ee(t.stop_reason);if(e===I.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===I.FunctionCall){const n=ye(t.content);return{type:"success",id:t.id,model:t.model,role:t.role,finishReason:I.FunctionCall,content:n,text:F(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}if(t.type=="message"){const n=ye(t.content);return{type:"success",id:t.id,model:t.model,role:"assistant",finishReason:e,content:n,text:F(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}}i(pt,"convertToAIResponse");function dt(){const t=new Map,e=new Map,n=new Map;function s(r){const a=[];switch(r.type){case"message_start":a.push({type:"start",id:r.message.id,data:{model:r.message.model,timestamp:Date.now()}});break;case"message_delta":r.delta.stop_reason&&a.push({type:"complete",data:{finishReason:Ee(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"),a.push({type:"text-start",data:{index:r.index}});else if(r.content_block.type==="tool_use"){t.set(r.index,"tool");const o=r.content_block;n.set(r.index,{id:o.id,name:o.name,argumentsBuffer:""}),a.push({type:"tool-call-start",data:{index:r.index,id:o.id,name:o.name}})}else if(r.content_block.type==="thinking")t.set(r.index,"thinking"),a.push({type:"thinking-start",data:{index:r.index,redacted:!1}});else if(r.content_block.type==="redacted_thinking")t.set(r.index,"thinking"),a.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 o=r.content_block;e.set(o.id,{index:r.index,name:o.name}),a.push({type:"internal-tool-start",data:{index:r.index,id:o.id,name:o.name}})}else if(r.content_block.type==="web_search_tool_result"){const o=r.content_block,l=e.get(o.tool_use_id);l&&(a.push({type:"internal-tool-complete",data:{index:l.index,id:o.tool_use_id,name:l.name,output:o.content}}),e.delete(o.tool_use_id))}break;case"content_block_delta":if(r.delta.type==="text_delta")a.push({type:"text-delta",data:{text:r.delta.text,index:r.index}});else if(r.delta.type==="input_json_delta"){const o=n.get(r.index);o&&(o.argumentsBuffer+=r.delta.partial_json)}else r.delta.type==="thinking_delta"?a.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 o=t.get(r.index);if(o==="text")a.push({type:"text-complete",data:{index:r.index}});else if(o==="thinking")a.push({type:"thinking-complete",data:{index:r.index}});else if(o!=="internal-tool"){if(o==="tool"){const l=n.get(r.index);if(l){try{const c=JSON.parse(l.argumentsBuffer);a.push({type:"tool-call-complete",data:{index:r.index,id:l.id,name:l.name,arguments:c}})}catch(c){throw new Error(`Failed to parse tool call arguments for ${l.name}: ${c instanceof Error?c.message:String(c)}`)}n.delete(r.index)}}}t.delete(r.index);break}}return a}return i(s,"handleEvent"),{handleEvent:s}}i(dt,"createAnthropicStreamingAdapter");async function*ft(t){const{client:e,model:n,messages:s,system:r,tools:a,runtime:o,signal:l,options:c}=t,u=o?.tracer,{stop:d,max_tokens:f,...p}=c??{},m={model:n,max_tokens:f??mt(n),messages:he(s),...r&&{system:r},...d&&{stop_sequences:_e(d)},...a&&{tools:ge(a)},...p};u?.debug("Anthropic streaming request",{request:m});const _=dt();try{const h=await e.messages.create({...m,stream:!0},{signal:l});for await(const x of h){const T=_.handleEvent(x);for(const A of T)yield A}}catch(h){if(l?.aborted)return;yield{type:"error",data:{type:"STREAMING_ERROR",message:h instanceof Error?h.message:String(h),raw:h}}}}i(ft,"createStreamingRequest$3");const xe={[b.CLAUDE_OPUS_4_6]:128e3,[b.CLAUDE_OPUS_4_5_20251101]:64e3,[b.CLAUDE_HAIKU_4_5_20251001]:64e3,[b.CLAUDE_SONNET_4_5_20250929]:64e3,[b.CLAUDE_SONNET_4_20250514]:64e3,[b.CLAUDE_3_7_SONNET_20250219]:64e3,[b.CLAUDE_OPUS_4_1_20250805]:32e3,[b.CLAUDE_OPUS_4_20250514]:32e3,[b.CLAUDE_3_5_HAIKU_20241022]:8192,[b.CLAUDE_3_HAIKU_20240307]:4096};function mt(t){return t in xe?xe[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}i(mt,"getMaxTokens");const _t="anthropic";function ht(t){const e=new De({apiKey:t});return{name:_t,async createGenerationRequest(n,s){return await ut({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:a,tools:o,context:l,signal:c,options:u}=s;return ft({client:e,model:n,messages:r,system:a,tools:o,runtime:l,signal:c,options:u})}}}i(ht,"anthropic");function Ie(t,e){const n=t.map(gt).flat(1);return e?[{role:"system",content:e},...n]:n}i(Ie,"convertAxleMessages");function Se(t){if(t&&t.length>0)return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:V.toJSONSchema(e.schema)}}))}i(Se,"convertTools");function ee(t){switch(t){case"stop":return I.Stop;case"length":return I.Length;case"tool_calls":case"function_call":return I.FunctionCall;case"content_filter":return I.Error;default:return I.Stop}}i(ee,"convertFinishReason");function gt(t){switch(t.role){case"tool":return yt(t);case"assistant":return Et(t);default:return xt(t)}}i(gt,"convertMessage$2");function yt(t){return t.content.map(e=>({role:"tool",content:e.content,tool_call_id:e.id}))}i(yt,"convertToolMessage$2");function Et(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}}}i(Et,"convertAssistantMessage$2");function xt(t){if(typeof t.content=="string")return{role:"user",content:t.content};const e=t.content.map(It).filter(n=>n!==null);return e.every(n=>n.type==="text")?{role:"user",content:e.map(n=>n.text).join("")}:{role:"user",content:e}}i(xt,"convertUserMessage$2");function It(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}i(It,"convertContentPart$2");async function St(t){const{baseUrl:e,model:n,messages:s,system:r,tools:a,context:o,apiKey:l,options:c}=t,u=o?.tracer,d=Ie(s,r),f=Se(a),p={model:n,messages:d,...f&&{tools:f}};c&&(c.temperature!==void 0&&(p.temperature=c.temperature),c.top_p!==void 0&&(p.top_p=c.top_p),c.max_tokens!==void 0&&(p.max_tokens=c.max_tokens),c.frequency_penalty!==void 0&&(p.frequency_penalty=c.frequency_penalty),c.presence_penalty!==void 0&&(p.presence_penalty=c.presence_penalty),c.stop!==void 0&&(p.stop=c.stop)),u?.debug("ChatCompletions request",{request:p});let m;try{const _={"Content-Type":"application/json"};l&&(_.Authorization=`Bearer ${l}`);const h=await fetch(`${e}/chat/completions`,{method:"POST",headers:_,body:JSON.stringify(p)});if(!h.ok){const T=await h.text().catch(()=>"");throw new Error(`HTTP error! status: ${h.status}${T?` - ${T}`:""}`)}const x=await h.json();m=Tt(x)}catch(_){u?.error("Error fetching ChatCompletions response",{error:_ instanceof Error?_.message:String(_)}),m=K(_)}return u?.debug("ChatCompletions response",{result:m}),m}i(St,"createGenerationRequest$2");function Tt(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 a of e.message.tool_calls){let o;try{o=JSON.parse(a.function.arguments)}catch(l){throw new Error(`Invalid tool call arguments for ${a.function.name}: ${l instanceof Error?l.message:String(l)}`)}if(typeof o!="object"||o===null||Array.isArray(o))throw new Error(`Invalid tool call arguments for ${a.function.name}: expected object, got ${typeof o}`);n.push({type:"tool-call",id:a.id,name:a.function.name,parameters:o})}const s=n.some(a=>a.type==="tool-call"),r=ee(s?"tool_calls":e.finish_reason);return{type:"success",id:t.id,model:t.model,role:"assistant",finishReason:r,content:n,text:F(n)??"",usage:{in:t.usage?.prompt_tokens||0,out:t.usage?.completion_tokens||0},raw:t}}i(Tt,"fromModelResponse$2");function wt(){const t=new Map;let e=0,n=-1,s="",r="",a=null;function o(c){n<0||(a==="text"?c.push({type:"text-complete",data:{index:n}}):a==="thinking"&&c.push({type:"thinking-complete",data:{index:n}}),a=null,n=-1)}i(o,"closeActivePart");function l(c){const u=[],d=c.choices[0];if(!d)return u;s||(s=c.id,r=c.model,u.push({type:"start",id:s,data:{model:r,timestamp:Date.now()}}));const f=d.delta;if(f.reasoning_content&&(a!=="thinking"&&(o(u),n=e++,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"&&(o(u),n=e++,a="text",u.push({type:"text-start",data:{index:n}})),u.push({type:"text-delta",data:{text:f.content,index:n}})),f.tool_calls){o(u);for(const p of f.tool_calls){const m=p.index;if(!t.has(m)){const h=e++,x=p.id||`tool-${h}`;t.set(m,{id:x,name:p.function?.name||"",argumentsBuffer:"",partIdx:h}),u.push({type:"tool-call-start",data:{index:h,id:x,name:p.function?.name||""}})}const _=t.get(m);p.id&&(_.id=p.id),p.function?.name&&(_.name=p.function.name),p.function?.arguments&&(_.argumentsBuffer+=p.function.arguments)}}if(d.finish_reason){o(u);for(const[,m]of t)try{const _=JSON.parse(m.argumentsBuffer);u.push({type:"tool-call-complete",data:{index:m.partIdx,id:m.id,name:m.name,arguments:_}})}catch(_){throw new Error(`Failed to parse tool call arguments for ${m.name}: ${_ instanceof Error?_.message:String(_)}`)}const p=ee(d.finish_reason);u.push({type:"complete",data:{finishReason:p,usage:c.usage?{in:c.usage.prompt_tokens,out:c.usage.completion_tokens}:{in:0,out:0}}})}return u}return i(l,"handleChunk"),{handleChunk:l}}i(wt,"createStreamingAdapter$1");async function*bt(t){const{baseUrl:e,model:n,messages:s,system:r,tools:a,context:o,signal:l,apiKey:c,options:u}=t,d=o?.tracer,f=Ie(s,r),p=Se(a),m={model:n,messages:f,stream:!0,stream_options:{include_usage:!0},...p&&{tools:p}};u&&(u.temperature!==void 0&&(m.temperature=u.temperature),u.top_p!==void 0&&(m.top_p=u.top_p),u.max_tokens!==void 0&&(m.max_tokens=u.max_tokens),u.frequency_penalty!==void 0&&(m.frequency_penalty=u.frequency_penalty),u.presence_penalty!==void 0&&(m.presence_penalty=u.presence_penalty),u.stop!==void 0&&(m.stop=u.stop)),d?.debug("ChatCompletions streaming request",{request:m});const _=wt();try{const h={"Content-Type":"application/json"};c&&(h.Authorization=`Bearer ${c}`);const x=await fetch(`${e}/chat/completions`,{method:"POST",headers:h,body:JSON.stringify(m),signal:l});if(!x.ok){const G=await x.text().catch(()=>"");throw new Error(`HTTP error! status: ${x.status}${G?` - ${G}`:""}`)}if(!x.body)throw new Error("Response body is null");const T=x.body.getReader(),A=new TextDecoder;let U="";for(;;){const{done:G,value:j}=await T.read();if(G)break;U+=A.decode(j,{stream:!0});const P=U.split(`
|
|
20
|
+
`);U=P.pop()||"";for(const W of P){const y=W.trim();if(!y||y.startsWith(":")||!y.startsWith("data: "))continue;const L=y.slice(6);if(L!=="[DONE]")try{const S=JSON.parse(L),v=_.handleChunk(S);for(const D of v)yield D}catch(S){d?.error("Error parsing ChatCompletions stream chunk",{error:S instanceof Error?S.message:String(S),line:y})}}}}catch(h){if(l?.aborted)return;d?.error("Error in ChatCompletions streaming request",{error:h instanceof Error?h.message:String(h)}),yield{type:"error",data:{type:"STREAMING_ERROR",message:h instanceof Error?h.message:String(h),raw:h}}}}i(bt,"createStreamingRequest$2");function At(t,e){return{name:"ChatCompletions",async createGenerationRequest(n,s){return await St({baseUrl:t,model:n,apiKey:e,...s})},createStreamingRequest(n,s){return bt({baseUrl:t,model:n,apiKey:e,...s})}}}i(At,"chatCompletions");const E={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_3_PRO_IMAGE_PREVIEW:"gemini-3-pro-image-preview",GEMINI_2_5_PRO:"gemini-2.5-pro",GEMINI_2_5_FLASH:"gemini-2.5-flash",GEMINI_2_5_FLASH_PREVIEW_09_2025:"gemini-2.5-flash-preview-09-2025",GEMINI_2_5_FLASH_IMAGE:"gemini-2.5-flash-image",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_5_FLASH_NATIVE_AUDIO_LATEST:"gemini-2.5-flash-native-audio-latest",GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_09_2025:"gemini-2.5-flash-native-audio-preview-09-2025",GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025:"gemini-2.5-flash-native-audio-preview-12-2025",GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025:"gemini-2.5-computer-use-preview-10-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_EXP_1206:"gemini-exp-1206",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",DEEP_RESEARCH_PRO_PREVIEW_12_2025:"deep-research-pro-preview-12-2025",GEMINI_ROBOTICS_ER_1_5_PREVIEW:"gemini-robotics-er-1.5-preview",NANO_BANANA_PRO_PREVIEW:"nano-banana-pro-preview",AQA:"aqa"};E.GEMINI_3_1_PRO_PREVIEW,E.GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS,E.GEMINI_3_PRO_PREVIEW,E.GEMINI_3_FLASH_PREVIEW,E.GEMINI_3_PRO_IMAGE_PREVIEW,E.GEMINI_2_5_PRO,E.GEMINI_2_5_FLASH,E.GEMINI_2_5_FLASH_PREVIEW_09_2025,E.GEMINI_2_5_FLASH_IMAGE,E.GEMINI_2_5_FLASH_LITE,E.GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025,E.GEMINI_2_5_FLASH_NATIVE_AUDIO_LATEST,E.GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_09_2025,E.GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025,E.GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025,E.GEMINI_2_0_FLASH,E.GEMINI_2_0_FLASH_001,E.GEMINI_2_0_FLASH_LITE,E.GEMINI_2_0_FLASH_LITE_001,E.GEMINI_EXP_1206,E.GEMINI_FLASH_LATEST,E.GEMINI_FLASH_LITE_LATEST,E.GEMINI_PRO_LATEST,E.GEMMA_3_27B_IT,E.GEMMA_3_12B_IT,E.GEMMA_3_4B_IT,E.GEMMA_3_1B_IT,E.GEMMA_3N_E4B_IT,E.GEMMA_3N_E2B_IT,E.DEEP_RESEARCH_PRO_PREVIEW_12_2025,E.GEMINI_ROBOTICS_ER_1_5_PREVIEW,E.NANO_BANANA_PRO_PREVIEW;const kt=E.GEMINI_2_5_FLASH_LITE;function Te(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:V.toJSONSchema(r.schema)}]}))),n&&Object.assign(s,n),s}i(Te,"prepareConfig");function we(t){return t.map(Ct).filter(e=>e!==void 0)}i(we,"convertAxleMessagesToGemini");function Ct(t){switch(t.role){case"tool":return Ot(t);case"assistant":return Rt(t);case"user":return Mt(t)}}i(Ct,"convertMessage$1");function Ot(t){return{role:"user",parts:t.content.map(e=>({functionResponse:{id:e.id??void 0,name:e.name,response:{output:e.content}}}))}}i(Ot,"convertToolMessage$1");function Rt(t){const e=[],n=t.content.filter(r=>r.type==="text");if(n.length>0){const r=n.map(a=>a.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=>({functionCall:{id:r.id??void 0,name:r.name,args:r.parameters}}))),{role:"model",parts:e}}i(Rt,"convertAssistantMessage$1");function Mt(t){return typeof t.content=="string"?{role:"user",parts:[{text:t.content}]}:{role:"user",parts:t.content.map($t).filter(n=>n!==null)}}i(Mt,"convertUserMessage$1");function $t(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}i($t,"convertContentPart$1");function be(t){switch(t){case O.STOP:return[!0,I.Stop];case O.MAX_TOKENS:return[!0,I.Length];case O.FINISH_REASON_UNSPECIFIED:case O.SAFETY:case O.RECITATION:case O.LANGUAGE:case O.OTHER:case O.BLOCKLIST:case O.PROHIBITED_CONTENT:case O.SPII:case O.MALFORMED_FUNCTION_CALL:case O.IMAGE_SAFETY:return[!1,I.Error]}}i(be,"convertStopReason");async function Pt(t){const{client:e,model:n,messages:s,system:r,tools:a,context:o,options:l}=t,c=o?.tracer,u=l?{...l}:{};u.max_tokens&&(u.maxOutputTokens=u.max_tokens,delete u.max_tokens),u.stop&&(u.stopSequences=Array.isArray(u.stop)?u.stop:[u.stop],delete u.stop),u.top_p!==void 0&&(u.topP=u.top_p,delete u.top_p);const d={contents:we(s),config:Te(a,r,u)};c?.debug("Gemini request",{request:d});let f;try{const p=await e.models.generateContent({model:n,...d});f=Lt(p,{tracer:c})}catch(p){c?.error(p instanceof Error?p.message:String(p)),f=K(p)}return c?.debug("Gemini response",{result:f}),f}i(Pt,"createGenerationRequest$1");function Lt(t,e){const{tracer:n}=e,s=t.usageMetadata.promptTokenCount,r=t.usageMetadata.totalTokenCount-s,a={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:a,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 o=t.candidates[0],c=(o.content?.parts||[]).map(f=>f.text).filter(f=>f!==void 0).join(""),[u,d]=be(o.finishReason);if(u){const f=[];if(c&&f.push({type:"text",text:c}),t.functionCalls)for(const p of t.functionCalls){if(typeof p.args!="object"||p.args===null||Array.isArray(p.args))throw new Error(`Invalid tool call arguments for ${p.name}: expected object, got ${typeof p.args}`);f.push({type:"tool-call",id:p.id,name:p.name,parameters:p.args})}return{type:"success",id:t.responseId,model:t.modelVersion,role:"assistant",finishReason:t.functionCalls?I.FunctionCall:d,content:f,text:F(f)??"",usage:a,raw:t}}else return{type:"error",error:{type:"Undetermined",message:`Unexpected stop reason: ${d}`},usage:a,raw:t}}i(Lt,"fromModelResponse$1");function Nt(){let t=0,e=-1,n=!1,s="",r="",a=0,o=0,l=null;function c(d){e<0||(l==="text"?d.push({type:"text-complete",data:{index:e}}):l==="thinking"&&d.push({type:"thinking-complete",data:{index:e}}),l=null,e=-1)}i(c,"closeActivePart");function u(d){const f=[];s||(s=d.responseId||`gemini-${Date.now()}`,r=d.modelVersion||"gemini",f.push({type:"start",id:s,data:{model:r,timestamp:Date.now()}})),d.usageMetadata&&(a=d.usageMetadata.promptTokenCount||0,o=(d.usageMetadata.totalTokenCount||0)-a);const p=d.candidates?.[0];if(!p)return f;const m=p.content?.parts||[];for(const _ of m){const h="thought"in _&&_.thought===!0;if(h&&_.text?(l!=="thinking"&&(c(f),e=t++,l="thinking",f.push({type:"thinking-start",data:{index:e}})),f.push({type:"thinking-delta",data:{index:e,text:_.text}})):_.text&&!h?(l!=="text"&&(c(f),e=t++,l="text",f.push({type:"text-start",data:{index:e}})),f.push({type:"text-delta",data:{text:_.text,index:e}})):_.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(_))}`),_.functionCall){c(f),n=!0;const x=t++,T=_.functionCall.id||`tool-${x}`;f.push({type:"tool-call-start",data:{index:x,id:T,name:_.functionCall.name}}),f.push({type:"tool-call-complete",data:{index:x,id:T,name:_.functionCall.name,arguments:_.functionCall.args}})}}if(p.finishReason&&p.finishReason!==O.FINISH_REASON_UNSPECIFIED){c(f);const[_,h]=be(p.finishReason),x=n?I.FunctionCall:h;!_&&!n?f.push({type:"error",data:{type:"FinishReasonError",message:`Unexpected finish reason: ${p.finishReason}`,usage:{in:a,out:o},raw:d}}):f.push({type:"complete",data:{finishReason:x,usage:{in:a,out:o}}})}return f}return i(u,"handleChunk"),{handleChunk:u}}i(Nt,"createGeminiStreamingAdapter");async function*Ut(t){const{client:e,model:n,messages:s,system:r,tools:a,runtime:o,signal:l,options:c}=t,u=o?.tracer,d=c?{...c}:{};d.max_tokens&&(d.maxOutputTokens=d.max_tokens,delete d.max_tokens),d.stop&&(d.stopSequences=Array.isArray(d.stop)?d.stop:[d.stop],delete d.stop),d.top_p!==void 0&&(d.topP=d.top_p,delete d.top_p);const f={contents:we(s),config:Te(a,r,d)};u?.debug("Gemini streaming request",{request:f});const p=Nt();try{const m=await e.models.generateContentStream({model:n,...f});for await(const _ of m){const h=p.handleChunk(_);for(const x of h)yield x}}catch(m){if(l?.aborted)return;u?.error(m instanceof Error?m.message:String(m)),yield{type:"error",data:{type:"STREAMING_ERROR",message:m instanceof Error?m.message:String(m),raw:m}}}}i(Ut,"createStreamingRequest$1");const Gt="Gemini";function vt(t){const e=new Fe({apiKey:t});return{name:Gt,async createGenerationRequest(n,s){return await Pt({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:a,tools:o,context:l,signal:c,options:u}=s;return Ut({client:e,model:n,messages:r,system:a,tools:o,runtime:l,signal:c,options:u})}}}i(vt,"gemini");const Ae={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",O4_MINI_DEEP_RESEARCH:"o4-mini-deep-research",O4_MINI_DEEP_RESEARCH_2025_06_26:"o4-mini-deep-research-2025-06-26",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",O3_DEEP_RESEARCH:"o3-deep-research",O3_DEEP_RESEARCH_2025_06_26:"o3-deep-research-2025-06-26",O1:"o1",O1_2024_12_17:"o1-2024-12-17",O1_PRO:"o1-pro",O1_PRO_2025_03_19:"o1-pro-2025-03-19",COMPUTER_USE_PREVIEW:"computer-use-preview",COMPUTER_USE_PREVIEW_2025_03_11:"computer-use-preview-2025-03-11",CHATGPT_IMAGE_LATEST:"chatgpt-image-latest"},Dt=Ae.GPT_5_MINI;function ke(t){if(t&&t.length>0)return t.map(e=>{const n=V.toJSONSchema(e.schema);return{type:"function",strict:!0,name:e.name,description:e.description,parameters:n}})}i(ke,"prepareTools");function Ce(t){return t.map(Ft).flat(1)}i(Ce,"convertAxleMessageToResponseInput");function Ft(t){switch(t.role){case"tool":return Ht(t);case"assistant":return jt(t);default:return Bt(t)}}i(Ft,"convertMessage");function Ht(t){return t.content.map(e=>({type:"function_call_output",call_id:e.id,output:e.content}))}i(Ht,"convertToolMessage");function jt(t){const e=[],n=F(t.content);n&&e.push({role:t.role,content:n});const s=t.content.filter(r=>r.type==="tool-call");for(const r of s)e.push({type:"function_call",call_id:r.id,name:r.name,arguments:JSON.stringify(r.parameters)});return e}i(jt,"convertAssistantMessage");function Bt(t){if(typeof t.content=="string")return{role:t.role,content:t.content};{const e=t.content.map(qt).filter(n=>n!==null);return{role:t.role,content:e}}}i(Bt,"convertUserMessage");function qt(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}i(qt,"convertContentPart");async function Wt(t){const{client:e,model:n,messages:s,system:r,tools:a,context:o,options:l}=t,c=o?.tracer,u=ke(a),d={model:n,input:Ce(s),...r&&{instructions:r},...u?{tools:u}:{},...l};c?.debug("OpenAI ResponsesAPI request",{request:d});let f;try{const p=await e.responses.create(d);f=Vt(p)}catch(p){c?.error(p instanceof Error?p.message:String(p)),f=K(p)}return c?.debug("OpenAI ResponsesAPI response",{result:f}),f}i(Wt,"createGenerationRequest");function Vt(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 a=r.summary?.[0]?.text||r.content?.[0]?.text||"";(a||r.encrypted_content)&&n.push({type:"thinking",text:a,...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 a=r;try{n.push({type:"tool-call",id:a.id||"",name:a.name||"",parameters:a.arguments?JSON.parse(a.arguments):{}})}catch(o){throw new Error(`Failed to parse tool call arguments for ${a.name}: ${o instanceof Error?o.message:String(o)}`)}}return{type:"success",id:t.id,model:t.model||"",role:"assistant",finishReason:t.incomplete_details?I.Error:I.Stop,content:n,text:F(n)??"",usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t}}i(Vt,"fromModelResponse");function Jt(){let t="",e="",n=0,s=-1,r=!1;const a=new Map,o=new Map,l=new Set(["web_search_call","file_search_call","code_interpreter_call"]),c=new Map;function u(d){const f=[];switch(d.type){case"response.created":{t=d.response.id||`openai-${Date.now()}`,e=d.response.model,f.push({type:"start",id:t,data:{model:e,timestamp:Date.now()}});break}case"response.output_text.delta":{s===-1&&(s=n++,f.push({type:"text-start",data:{index:s}})),f.push({type:"text-delta",data:{text:d.delta,index:s}});break}case"response.output_text.done":{s>=0&&(f.push({type:"text-complete",data:{index:s}}),s=-1);break}case"response.function_call_arguments.delta":{const p=d.item_id;if(!c.has(p)){const _=a.get(p),h=_?.name||"",x=_?.callId||p,T=n++;c.set(p,{id:p,callId:x,name:h,argumentsBuffer:"",partIdx:T}),f.push({type:"tool-call-start",data:{index:T,id:x,name:h}})}const m=c.get(p);m.argumentsBuffer+=d.delta;break}case"response.function_call_arguments.done":{r=!0;const p=d.item_id,m=c.get(p),_=d.name||m?.name||"";if(m){try{const h=JSON.parse(d.arguments);f.push({type:"tool-call-complete",data:{index:m.partIdx,id:m.callId,name:_,arguments:h}})}catch(h){throw new Error(`Failed to parse function call arguments for ${_}: ${h instanceof Error?h.message:String(h)}`)}c.delete(p)}break}case"response.completed":{const p=d.response.usage;f.push({type:"complete",data:{finishReason:d.response.incomplete_details?I.Error:r?I.FunctionCall:I.Stop,usage:{in:p?.input_tokens||0,out:p?.output_tokens||0}}});break}case"response.failed":{f.push({type:"error",data:{type:"RESPONSES_API_ERROR",message:`Response failed: ${d.response.status}`,raw:d}});break}case"response.output_item.added":{if(d.item?.type==="reasoning")s=n++,f.push({type:"thinking-start",data:{index:s}});else if(d.item?.type==="function_call"){const p=d.item,m=p.id||p.call_id;m&&a.set(m,{name:p.name||"",callId:p.call_id||m})}else if(d.item&&l.has(d.item.type)){const p=d.item,m=n++;o.set(p.id,m),f.push({type:"internal-tool-start",data:{index:m,id:p.id,name:p.type}})}break}case"response.output_item.done":{if(d.item?.type==="reasoning"&&s>=0)f.push({type:"thinking-complete",data:{index:s}}),s=-1;else if(d.item&&l.has(d.item.type)){const p=d.item,m=o.get(p.id);m!==void 0&&(f.push({type:"internal-tool-complete",data:{index:m,id:p.id,name:p.type,output:d.item}}),o.delete(p.id))}break}case"response.reasoning_text.delta":{d.delta&&f.push({type:"thinking-delta",data:{index:s,text:d.delta}});break}case"response.reasoning_summary_text.delta":{d.delta&&f.push({type:"thinking-summary-delta",data:{index:s,text:d.delta}});break}default:console.log(`[OpenAI] unhandled stream event: ${d.type}`)}return f}return i(u,"handleEvent"),{handleEvent:u}}i(Jt,"createStreamingAdapter");async function*Kt(t){const{client:e,model:n,messages:s,system:r,tools:a,runtime:o,signal:l,options:c}=t,u=o?.tracer,d=ke(a),f={model:n,input:Ce(s),...r&&{instructions:r},stream:!0,...d?{tools:d}:{},...c};u?.debug("OpenAI ResponsesAPI streaming request",{request:f});const p=Jt();try{const m=e.responses.stream(f,...l?[{signal:l}]:[]);for await(const _ of m){const h=p.handleEvent(_);for(const x of h)yield x}}catch(m){if(l?.aborted)return;u?.error(m instanceof Error?m.message:String(m)),yield{type:"error",data:{type:"STREAMING_ERROR",message:m instanceof Error?m.message:String(m),raw:m}}}}i(Kt,"createStreamingRequest");const zt="OpenAI";function Xt(t){const e=new He({apiKey:t});return{name:zt,async createGenerationRequest(n,s){return await Wt({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:a,tools:o,context:l,signal:c,options:u}=s;return Kt({client:e,model:n,messages:r,system:a,tools:o,runtime:l,signal:c,options:u})}}}i(Xt,"openai");const Zt=C.object({searchTerm:C.string().describe("The search term to query")});class Yt{static{i(this,"BraveSearchTool")}name="brave";description="Perform a search using the Brave search engine";schema=Zt;apiKey;throttle;lastExecTime=0;constructor(e){e&&this.configure(e)}configure(e){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 ct(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",a=new URL(r);a.searchParams.append("q",n),a.searchParams.append("format","json");const o=await fetch(a.toString(),{method:"GET",headers:{Accept:"application/json","X-Subscription-Token":s}});if(!o.ok)throw new Error(`[Brave] HTTP error ${o.status}: ${o.statusText}`);const l=await o.json();return JSON.stringify(l)}catch(s){throw s instanceof Error?new Error(`[Brave] Error fetching search results: ${s.message}`):s}}}const Qt=new Yt,en=k.object({operation:k.enum(["add","subtract","multiply","divide"]).describe("The operation to perform (add, subtract, multiply, divide)"),a:k.number().describe("First operand"),b:k.number().describe("Second operand")}),tn={name:"calculator",description:"Performs basic arithmetic operations",schema:en,execute:i(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")},nn=Be(je),sn=3e4,rn=1024*1024;async function on(t,e={}){const{stdout:n,stderr:s}=await nn(t,{cwd:e.cwd,timeout:e.timeout??sn,maxBuffer:e.maxBuffer??rn});return{stdout:n,stderr:s}}i(on,"runCommand");function an(t){if(t instanceof Error){const e=t;let n=`Error executing command: ${t.message}`;return e.stdout&&(n+=`
|
|
21
|
+
[stdout]: ${e.stdout}`),e.stderr&&(n+=`
|
|
22
|
+
[stderr]: ${e.stderr}`),n}return`Error executing command: ${String(t)}`}i(an,"formatExecError");function cn(t,e){return e&&e.trim()?`${t}
|
|
23
|
+
[stderr]: ${e}`:t}i(cn,"formatOutput");const ln=C.object({command:C.string().describe("The shell command to execute")});class un{static{i(this,"ExecTool")}name="exec";description="Execute a shell command and return the output.";schema=ln;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 on(n,{timeout:this.timeout,maxBuffer:this.maxBuffer,cwd:this.cwd});return cn(s.stdout,s.stderr)}catch(s){return an(s)}}}const pn=new un,dn=k.object({path:k.string().describe("The file path to patch"),old_string:k.string().describe("The exact text to find and replace"),new_string:k.string().describe("The replacement text"),start_line:k.number().int().positive().describe("1-indexed start line of the region to match within"),end_line:k.number().int().positive().describe("1-indexed end line (inclusive) of the region to match within")}),fn={name:"patch-file",description:"Patch a file by replacing an exact string match within a specified line range",schema:dn,summarize:i(({path:t,start_line:e,end_line:n})=>`${t}:${e}:${n}`,"summarize"),execute:i(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 a;try{a=await H(t,"utf-8")}catch(_){throw _ instanceof Error?new Error(`Failed to read file "${t}": ${_.message}`):_}const o=a.split(`
|
|
24
|
+
`);if(s>o.length)throw new Error(`start_line (${s}) exceeds file length (${o.length} lines)`);if(r>o.length)throw new Error(`end_line (${r}) exceeds file length (${o.length} lines)`);const c=o.slice(s-1,r).join(`
|
|
25
|
+
`),u=c.indexOf(e);if(u===-1)throw new Error(`old_string not found within lines ${s}-${r} of "${t}"`);if(c.indexOf(e,u+1)!==-1)throw new Error(`old_string matches multiple times within lines ${s}-${r} of "${t}"`);const f=c.replace(e,n),m=[...o.slice(0,s-1),...f.split(`
|
|
26
|
+
`),...o.slice(r)].join(`
|
|
27
|
+
`);try{await re(t,m,"utf-8")}catch(_){throw _ instanceof Error?new Error(`Failed to write file "${t}": ${_.message}`):_}return`Successfully patched "${t}" (lines ${s}-${r})`},"execute")},mn=k.object({path:k.string().describe("The file path to read from")}),_n={name:"read-file",description:"Read the contents of a file from disk",schema:mn,summarize:i(({path:t})=>t,"summarize"),execute:i(async({path:t})=>{try{return await H(t,"utf-8")}catch(e){throw e instanceof Error?new Error(`Failed to read file "${t}": ${e.message}`):e}},"execute")},hn=k.object({path:k.string().describe("The file path to write to"),content:k.string().describe("The content to write to the file")}),gn={name:"write-file",description:"Write content to a file on disk, creating directories if needed",schema:hn,summarize:i(({path:t})=>t,"summarize"),execute:i(async({path:t,content:e})=>{try{return await Ge(ve(t),{recursive:!0}),await re(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")},Oe={debug:0,info:1,warn:2,error:3};class yn{static{i(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 te(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))}_notifyLLMStreamStart(e){this.writers.forEach(n=>n.onLLMStreamStart?.(e))}_notifyLLMStreamChunk(e,n){this.writers.forEach(s=>s.onLLMStreamChunk?.(e,n))}_notifyLLMStreamEnd(e,n){this.writers.forEach(s=>s.onLLMStreamEnd?.(e,n))}_shouldLog(e){return Oe[e]>=Oe[this._minLevel]}}class te{static{i(this,"Span")}data;tracer;ended=!1;llmStreamBuffer="";llmStreamActive=!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 te(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))}startLLMStream(){this.ended||(this.llmStreamActive=!0,this.llmStreamBuffer="",this.tracer._notifyLLMStreamStart(this.data))}appendLLMStream(e){this.ended||!this.llmStreamActive||(this.llmStreamBuffer+=e,this.tracer._notifyLLMStreamChunk(this.data,e))}endLLMStream(e){if(this.ended||!this.llmStreamActive)return;this.llmStreamActive=!1;const n={...e,response:{...e.response,content:e.response.content??this.llmStreamBuffer}};this.data.result=n,this.tracer._notifyLLMStreamEnd(this.data,n)}}const Re={debug:0,info:1,warn:2,error:3};class En{static{i(this,"SimpleWriter")}minLevel;showInternal;showTimestamp;showDuration;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.output=e.output??console.log}shouldShowEvent(e){return Re[e]>=Re[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}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),a=this.formatTimestamp(),o=this.formatSpanName(e);this.output(`${a}${r}START ${o}`)}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),a=this.formatTimestamp(),o=this.formatDuration(e),l=this.formatSpanName(e),c=e.status==="error"?" [ERROR]":"";this.output(`${a}${r}END ${l}${o}${c}`)}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 c=this.findVisibleAncestor(e);c?s=this.visibleDepths.get(c.spanId)??0:s=0}const r=this.formatIndent(s+1),a=this.formatTimestamp(),o=n.level.toUpperCase().padEnd(5);let l=`${a}${r}${o} ${n.name}`;if(n.attributes&&Object.keys(n.attributes).length>0){const c=Object.entries(n.attributes).map(([u,d])=>`${u}=${JSON.stringify(d)}`).join(" ");l+=` ${c}`}this.output(l)}onLLMStreamStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const n=this.visibleDepths.get(e.spanId)??0,s=this.formatIndent(n+1),r=this.formatTimestamp();this.output(`${r}${s}INFO LLM streaming started`)}onLLMStreamChunk(e,n){}onLLMStreamEnd(e,n){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const s=this.visibleDepths.get(e.spanId)??0,r=this.formatIndent(s+1),a=this.formatTimestamp(),o=[`model=${n.model}`];if(n.finishReason&&o.push(`finishReason=${n.finishReason}`),n.usage&&(n.usage.inputTokens!==void 0&&o.push(`inputTokens=${n.usage.inputTokens}`),n.usage.outputTokens!==void 0&&o.push(`outputTokens=${n.usage.outputTokens}`)),this.output(`${a}${r}INFO LLM complete ${o.join(" ")}`),this.shouldShowEvent("debug")&&n.response.content){const c=(typeof n.response.content=="string"?n.response.content:JSON.stringify(n.response.content,null,2)).split(`
|
|
28
|
+
`);for(const u of c)this.output(`${a}${r}DEBUG ${u}`)}}}export{I as A,it as D,ae as H,at as I,b as M,En as S,yn as T,kt as a,E as b,Ve as c,Dt as d,ce as e,Ae as f,We as g,Ye as h,ht as i,Qt as j,tn as k,At as l,fe as m,vt as n,ot as o,Xt as p,pe as q,Qe as r,le as s,_n as t,fn as u,pn as v,gn as w};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fifthrevision/axle",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.2",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/johncch/axle.git"
|
|
@@ -37,12 +37,12 @@
|
|
|
37
37
|
"author": "",
|
|
38
38
|
"license": "ISC",
|
|
39
39
|
"dependencies": {
|
|
40
|
-
"@anthropic-ai/sdk": "^0.
|
|
40
|
+
"@anthropic-ai/sdk": "^0.78.0",
|
|
41
41
|
"@commander-js/extra-typings": "^14.0.0",
|
|
42
|
-
"@google/genai": "^1.
|
|
42
|
+
"@google/genai": "^1.42.0",
|
|
43
43
|
"chalk": "^5.6.2",
|
|
44
44
|
"commander": "^14.0.3",
|
|
45
|
-
"glob": "^13.0.
|
|
45
|
+
"glob": "^13.0.6",
|
|
46
46
|
"mime": "^4.1.0",
|
|
47
47
|
"openai": "^6.22.0",
|
|
48
48
|
"serialize-error": "^13.0.1",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"dotenv": "^17.3.1",
|
|
54
|
-
"pkgroll": "^2.26.
|
|
54
|
+
"pkgroll": "^2.26.3",
|
|
55
55
|
"prettier": "^3.8.1",
|
|
56
56
|
"prettier-plugin-organize-imports": "^4.3.0",
|
|
57
57
|
"tsx": "^4.21.0",
|
package/dist/simple-DFkTLK9N.js
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
var Ne=Object.defineProperty;var i=(t,e)=>Ne(t,"name",{value:e,configurable:!0});import*as C from"zod";import V,{z as k}from"zod";import"glob";import Le from"mime";import{readFile as H,access as Me,stat as Ue,writeFile as se,mkdir as Ge}from"node:fs/promises";import{resolve as Y,extname as oe,dirname as De}from"node:path";import ve from"@anthropic-ai/sdk";import{FinishReason as O,GoogleGenAI as Fe}from"@google/genai";import He from"openai";import{exec as Be}from"node:child_process";import{promisify as je}from"node:util";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 ae{static{i(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 qe(t){const{text:e,files:n}=t,r=[];if(e&&r.push({type:"text",text:e}),n)for(const s of n)r.push({type:"file",file:s});return r}i(qe,"toContentParts");function F(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
2
|
-
|
|
3
|
-
`)}i(F,"getTextContent");function We(t){return t.filter(e=>e.type==="tool-call")}i(We,"getToolCalls");function Ve(t,e){const n=e.usage??{in:0,out:0};t.in+=n.in??0,t.out+=n.out??0}i(Ve,"appendUsage");function ie(t){return JSON.stringify({error:t})}i(ie,"serializeToolError");async function ce(t,e){const n=[];let r;for(const s of t){let a;try{a=await e(s.name,s.parameters)}catch(o){a={type:"error",error:{type:"exception",message:o instanceof Error?o.message:String(o)}}}if(a==null){r={name:s.name,message:`Tool not found: ${s.name}`},n.push({id:s.id,name:s.name,content:ie({type:"not-found",message:r.message})});break}a.type==="success"?n.push({id:s.id,name:s.name,content:a.content}):n.push({id:s.id,name:s.name,content:ie(a.error)})}return{results:n,missingTool:r}}i(ce,"executeToolCalls");function le(t){const e=[],n=[],r=[],s=[],a=[],o=new AbortController;let l=!1,c,u;const d=new Promise((f,p)=>{c=i(m=>{l=!0,f(m)},"resolveResult"),u=i(m=>{l=!0,p(m)},"rejectResult")});return Promise.resolve().then(()=>ze(t,o.signal,e,n,r,s,a).then(c,u)),{onPartStart(f){e.push(f)},onPartUpdate(f){n.push(f)},onPartEnd(f){r.push(f)},onInternalTool(f){s.push(f)},onError(f){a.push(f)},cancel(){l||o.abort()},get final(){return d}}}i(le,"stream");function ue(t,e,n){for(const r of t)r(e,n)}i(ue,"emitPartStart");function Q(t,e,n,r,s){for(const a of t)a(e,n,r,s)}i(Q,"emitPartUpdate");function Ke(t,e,n,r){for(const s of t)s(e,n,r)}i(Ke,"emitPartEnd");function Je(t,e){for(const n of t)n(e)}i(Je,"emitError");async function ze(t,e,n,r,s,a,o){const{provider:l,model:c,messages:u,system:d,tools:f,onToolCall:p,maxIterations:m,tracer:_,options:h}=t,I=[...u],w=[],A={in:0,out:0};let U=0,G=0;const B=i(y=>{I.push(y),w.push(y)},"addMessage"),N=i(y=>{y.result==="error"&&Je(o,y.error);const L=y.result==="success"?y.final?.content:y.result==="cancelled"?y.partial?.content:null,T=y.result==="success"?y.final?.finishReason:y.result==="cancelled"?S.Cancelled:void 0;return _?.setResult({kind:"llm",model:c,request:{messages:u},response:{content:L??null},usage:y.usage?{inputTokens:y.usage.in,outputTokens:y.usage.out}:void 0,finishReason:T}),_?.end(y.result==="error"?"error":"ok"),y},"endWithResult"),W=i((y,L,T,D)=>{D();const M=y.length>0?{role:"assistant",id:L,model:T,content:y,finishReason:S.Cancelled}:void 0;return M&&B(M),_?.end("ok"),{result:"cancelled",messages:w,partial:M,usage:A}},"buildCancelledResult");for(;;){if(e.aborted)return W([],"","",()=>{});if(m!==void 0&&G>=m)return N({result:"error",messages:w,error:{type:"model",error:{type:"error",error:{type:"MaxIterations",message:`Exceeded max iterations (${m})`}}},usage:A});G+=1;const y=_?.startSpan(`turn-${G}`,{type:"llm"});y?.startLLMStream();const L=l.createStreamingRequest?.(c,{messages:I,system:d,tools:f,context:{tracer:y},signal:e,options:h});if(!L)throw y?.end("error"),new Error("Provider does not support streaming. Use generate() instead.");const T=[];let D="",v="",M=null,j={in:0,out:0},P=-1,q=null,R="";const $=i(()=>{q!==null&&P>=0&&(Ke(s,P,q,R),q=null,R="",P=-1)},"closePart");for await(const g of L){switch(g.type){case"start":D=g.id,v=g.data.model;break;case"text-start":{$(),T.push({type:"text",text:""}),P=U++,q="text",R="",ue(n,P,"text");break}case"text-delta":{const b=T[g.data.index];b.text+=g.data.text,R=b.text,y?.appendLLMStream(g.data.text),Q(r,P,"text",g.data.text,R);break}case"text-complete":{$();break}case"thinking-start":{$(),T.push({type:"thinking",text:""}),P=U++,q="thinking",R="",ue(n,P,"thinking");break}case"thinking-delta":{const b=T[g.data.index];b.text+=g.data.text,R=b.text,Q(r,P,"thinking",g.data.text,R);break}case"thinking-summary-delta":{const b=T[g.data.index];b.text+=g.data.text,R=b.text,Q(r,P,"thinking",g.data.text,R);break}case"thinking-complete":{$();break}case"tool-call-start":{$(),T.push({type:"tool-call",id:g.data.id,name:g.data.name,parameters:{}}),U++;break}case"tool-call-complete":{const b=T[g.data.index];g.data.id&&(b.id=g.data.id),g.data.name&&(b.name=g.data.name),b.parameters=g.data.arguments;break}case"internal-tool-start":{$();const b=U++;T.push({type:"internal-tool",id:g.data.id,name:g.data.name});for(const Z of a)Z({type:"start",index:b,id:g.data.id,name:g.data.name});break}case"internal-tool-complete":{const b=T[g.data.index];g.data.output!=null&&(b.output=g.data.output);for(const Z of a)Z({type:"complete",index:g.data.index,id:g.data.id,name:g.data.name,output:g.data.output});break}case"complete":{$(),M=g.data.finishReason,j=g.data.usage;break}case"error":{$();const b=g.data.usage??{in:0,out:0};return A.in+=b.in??0,A.out+=b.out??0,y?.end("error"),N({result:"error",messages:w,error:{type:"model",error:{type:"error",error:{type:g.data.type,message:g.data.message}}},usage:A})}default:console.warn("[WARN] Unhandled chunk type. Should never happen")}if(e.aborted)break}if(e.aborted)return y?.end("ok"),W(T,D,v,$);if(M===null)return $(),y?.end("error"),N({result:"error",messages:w,error:{type:"model",error:{type:"error",error:{type:"IncompleteStream",message:"Stream ended without a completion signal"}}},usage:A});A.in+=j.in??0,A.out+=j.out??0;const Re={kind:"llm",model:v,request:{messages:I},response:{content:T},usage:{inputTokens:j.in,outputTokens:j.out},finishReason:M};y?.endLLMStream(Re),y?.end();const z={role:"assistant",id:D,model:v,content:T,finishReason:M};if(B(z),M!==S.FunctionCall)return N({result:"success",messages:w,final:z,usage:A});const X=T.filter(g=>g.type==="tool-call");if(X.length===0)return N({result:"success",messages:w,final:z,usage:A});if(e.aborted)return _?.end("ok"),{result:"cancelled",messages:w,usage:A};const $e=p?async(g,b)=>p(g,b):async()=>null;for(const g of X)_?.info(`tool call: ${g.name}`,{parameters:g.parameters});const{results:ne,missingTool:re}=await ce(X,$e);if(ne.length>0&&B({role:"tool",content:ne}),re)return N({result:"error",messages:w,error:{type:"tool",error:re},usage:A})}}i(ze,"run");function Xe(t,e,n="{{}}"){const r=n==="{{}}"?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g;return t=t.replace(r,(s,a)=>{if(a=a.trim(),Object.prototype.hasOwnProperty.call(e,a)){const o=e[a];return o==null?"":String(o)}return s}),t}i(Xe,"replaceVariables");function K(t){if(t instanceof C.ZodString)return["string","Your answer"];if(t instanceof C.ZodNumber)return["number",42];if(t instanceof C.ZodBoolean)return["boolean",!0];if(t instanceof C.ZodArray){const e=t.element;if(e instanceof C.ZodString)return["string array",["answer 1","answer 2","third answer"]];if(e instanceof C.ZodNumber)return["number array",[42,59,3.14]];if(e instanceof C.ZodBoolean)return["boolean array",[!0,!1,!1]];if(e instanceof C.ZodObject){const[n,r]=K(e);return["object array",[r,r]]}return["array",[]]}if(t instanceof C.ZodObject){const e=t.shape,n={};for(const[r,s]of Object.entries(e)){const[a,o]=K(s);n[r]=o}return["JSON object",n]}if(t instanceof C.ZodOptional){const e=t.unwrap(),[n,r]=K(e);return[`${n} | undefined`,r]}}i(K,"zodToExample");function pe(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 r=Ze(t),s={};for(const[a,o]of Object.entries(e)){const l=r.tags[a];if(l!==void 0)s[a]=de(o,l);else if(o.def.type!=="optional")throw new Error(`Expected results with tag ${a} but it does not exist`)}try{const a={};for(const[o,l]of Object.entries(e))o in s&&(a[o]=l.parse(s[o]));return a}catch(a){if(a&&typeof a=="object"&&"issues"in a){const o=a.issues.map(l=>`${l.path.join(".")}: ${l.message}`).join(", ");throw new Error(`Validation failed: ${o}`)}throw a}}i(pe,"parseResponse");function de(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 r=n.trim();try{return JSON.parse(r)}catch{return r}}).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 de(n,e)}default:return e}}i(de,"preprocessValue");function Ze(t){t.trim().startsWith("```json")&&t.trim().endsWith("```")&&(t=t.trim().slice(7,-3).trim());const e=/<(\w+)>(.*?)<\/\1>/gs,n={};let r=t;r=r.replace(e,(a,o,l)=>(n[o]=l,""));const s=/<(\w+)>(.*?)(?:<\/?\w+>|$)/gs;return r=r.replace(s,(a,o,l)=>(n[o]=l,"")),{tags:n,remaining:r.trim()}}i(Ze,"parseTaggedSections");function fe(t,e={}){const n={...e,...t.inputs};let r=Xe(t.prompt,n);if(t.textReferences.length>0)for(const[o,l]of t.textReferences.entries()){const c=l.name?`: ${l.name}`:"";r+=`
|
|
4
|
-
|
|
5
|
-
## Reference ${o+1}${c}
|
|
6
|
-
|
|
7
|
-
\`\`\`${l.content}'''`}let s=`# Instructions
|
|
8
|
-
|
|
9
|
-
`;if((t.schema?Object.keys(t.schema):[]).length>0){s+=`## Output Format Instructions
|
|
10
|
-
`,s+=`
|
|
11
|
-
Here is how you should format your output. Follow the instructions strictly.
|
|
12
|
-
`;for(const[o,l]of Object.entries(t.schema)){const[c,u]=K(l);s+=`
|
|
13
|
-
- Use <${o}></${o}> tags to indicate the answer for ${o}. The answer must be a ${c}.
|
|
14
|
-
Example: <${o}>${JSON.stringify(u)}</${o}>
|
|
15
|
-
`}}if(t.instructions.length>0){s+=`
|
|
16
|
-
## Additional Instructions
|
|
17
|
-
|
|
18
|
-
`;for(const o of t.instructions)s+=`- ${o}
|
|
19
|
-
`}return s+r}i(fe,"compileInstruct");class Ye{static{i(this,"Agent")}provider;model;history;tracer;system;tools={};partStartCallback;partUpdateCallback;partEndCallback;internalToolCallback;errorCallback;constructor(e){this.provider=e.provider,this.model=e.model,this.history=new ae,this.tracer=e.tracer,this.system=e.system,e.tools&&this.addTools(e.tools)}addTool(e){this.tools[e.name]=e}addTools(e){for(const n of e)this.tools[n.name]=n}hasTools(){return Object.keys(this.tools).length>0}onPartStart(e){this.partStartCallback=e}onPartUpdate(e){this.partUpdateCallback=e}onPartEnd(e){this.partEndCallback=e}onInternalTool(e){this.internalToolCallback=e}onError(e){this.errorCallback=e}send(e,n){let r;if(typeof e=="string")this.history.addUser(e);else{const s=fe(e,n),a=e.files;this.history.addUser(qe({text:s,files:a})),r=e.schema}return this.execute(r)}execute(e){const n=this.tools,r=Object.values(n).map(o=>({name:o.name,description:o.description,schema:o.schema})),s=le({provider:this.provider,model:this.model,messages:this.history.messages,system:this.system,tools:r.length>0?r:void 0,tracer:this.tracer,onToolCall:i(async(o,l)=>{const c=n[o];if(!c)return null;try{const u=await c.execute(l);return{type:"success",content:JSON.stringify(u)}}catch(u){return{type:"error",error:{type:"execution",message:u instanceof Error?u.message:String(u)}}}},"onToolCall")});this.partStartCallback&&s.onPartStart(this.partStartCallback),this.partUpdateCallback&&s.onPartUpdate(this.partUpdateCallback),this.partEndCallback&&s.onPartEnd(this.partEndCallback),this.internalToolCallback&&s.onInternalTool(this.internalToolCallback),this.errorCallback&&s.onError(this.errorCallback);const a=s.final.then(o=>{o.messages.length>0&&this.history.add(o.messages);let l=null,c;if(o.result==="success"){if(c=o.final,c){const d=F(c.content);l=pe(d,e)}}else o.result==="cancelled"&&(c=o.partial);const u=o.usage??{in:0,out:0};return{response:l,messages:o.messages,final:c,usage:u}});return{cancel:i(()=>s.cancel(),"cancel"),get final(){return a}}}}async function Qe(t,e){const{defaults:n,tag:r}=e;let s=null,a="";if(t)try{a=Y(t),s=await H(a,{encoding:"utf-8"})}catch{throw new Error(`${r} not found, see --help for details`)}else{for(const o of n.formats)try{a=Y(n.name+"."+o),s=await H(a,{encoding:"utf-8"});break}catch{continue}if(s===null)throw new Error(`${r} not found, see --help for details`)}return{content:s,format:a.split(".").pop()??""}}i(Qe,"searchAndLoadFile");const me=20*1024*1024;function et(t){return t.type==="text"}i(et,"isTextFileInfo");function tt(t){return t.type==="image"||t.type==="document"}i(tt,"isBase64FileInfo");const nt=new Set(["application/json","application/xml","application/yaml","application/x-yaml","application/toml"]);function rt(t){return t.startsWith("text/")||nt.has(t)}i(rt,"isTextLikeMimeType");function st(t){const e=Le.getType(t);if(!e){const n=oe(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(rt(e))return{type:"text",mimeType:e};{const n=oe(t).toLowerCase();throw new Error(`Unsupported file type: ${n} (${e})`)}}i(st,"getFileCategory");async function ot(t,e){const n=Y(t);try{await Me(n)}catch{throw new Error(`File not found: ${t}`)}const r=await Ue(n);if(r.size>me)throw new Error(`File too large: ${r.size} bytes. Maximum allowed: ${me} bytes`);const s=n.split("/").pop()||"",a=st(n);if((e||(a.type==="text"?"utf-8":"base64"))==="utf-8"){if(a.type!=="text")throw new Error(`Cannot read ${a.type} file as text: ${t}`);const l=await H(n,"utf-8");return{path:n,content:l,mimeType:a.mimeType,size:r.size,name:s,type:"text"}}else{if(a.type==="text")throw new Error(`Cannot read text file as binary: ${t}`);const c=(await H(n)).toString("base64");return{path:n,base64:c,mimeType:a.mimeType,size:r.size,name:s,type:a.type}}}i(ot,"loadFileContent");class at{static{i(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}tt(e)?this.files.push(e):et(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 E={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_7_SONNET_20250219:"claude-3-7-sonnet-20250219",CLAUDE_3_7_SONNET:"claude-3-7-sonnet-20250219",CLAUDE_3_5_HAIKU_20241022:"claude-3-5-haiku-20241022",CLAUDE_3_5_HAIKU:"claude-3-5-haiku-20241022",CLAUDE_3_HAIKU_20240307:"claude-3-haiku-20240307",CLAUDE_3_HAIKU:"claude-3-haiku-20240307"};E.CLAUDE_SONNET_4_6,E.CLAUDE_OPUS_4_6,E.CLAUDE_OPUS_4_5_20251101,E.CLAUDE_OPUS_4_5,E.CLAUDE_HAIKU_4_5_20251001,E.CLAUDE_HAIKU_4_5,E.CLAUDE_SONNET_4_5_20250929,E.CLAUDE_SONNET_4_5,E.CLAUDE_OPUS_4_1_20250805,E.CLAUDE_OPUS_4_1,E.CLAUDE_OPUS_4_20250514,E.CLAUDE_OPUS_4,E.CLAUDE_SONNET_4_20250514,E.CLAUDE_SONNET_4,E.CLAUDE_3_7_SONNET_20250219,E.CLAUDE_3_7_SONNET,E.CLAUDE_3_5_HAIKU_20241022,E.CLAUDE_3_5_HAIKU,E.CLAUDE_3_HAIKU_20240307,E.CLAUDE_3_HAIKU;const it=E.CLAUDE_HAIKU_4_5;function _e(t){return Array.isArray(t)?t:[t]}i(_e,"arrayify");function ct(t){return new Promise(e=>setTimeout(e,t))}i(ct,"delay");function J(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",r=e?.error?.error?.message||e?.error?.message||e?.message||e?.error||"Unexpected error";return{type:"error",error:{type:String(n),message:String(r)},usage:{in:0,out:0},raw:t}}return{type:"error",error:{type:"Undetermined",message:String(t)},usage:{in:0,out:0},raw:t}}i(J,"getUndefinedError");function he(t){return t.map(e=>{if(e.role==="assistant"){const n=[];for(const r of e.content)r.type==="text"?n.push({type:"text",text:r.text}):r.type==="thinking"?r.redacted?n.push({type:"redacted_thinking",data:r.text}):n.push({type:"thinking",thinking:r.text,signature:r.signature}):r.type==="tool-call"&&n.push({type:"tool_use",id:r.id,name:r.name,input:r.parameters});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:n.content}))};if(typeof e.content=="string")return{role:"user",content:e.content};{const n=[];for(const r of e.content)r.type==="text"?n.push({type:"text",text:r.text}):r.type==="file"&&(r.file.type==="image"?n.push({type:"image",source:{type:"base64",media_type:r.file.mimeType,data:r.file.base64}}):r.file.type==="document"&&r.file.mimeType==="application/pdf"&&n.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:r.file.base64}}));return{role:"user",content:n}}})}i(he,"convertToProviderMessages");function ge(t){return t.map(e=>{const n=V.toJSONSchema(e.schema);if(!lt(n))throw new Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:n}})}i(ge,"convertToProviderTools");function ye(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}i(ye,"convertToAxleContentParts");function Ee(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}}i(Ee,"convertStopReason$1");function lt(t){return t&&typeof t=="object"&&t.type==="object"}i(lt,"isObjectSchema");async function ut(t){const{client:e,model:n,messages:r,system:s,tools:a,context:o,options:l}=t,c=o?.tracer,{stop:u,max_tokens:d,...f}=l??{},p={model:n,max_tokens:d??16e3,messages:he(r),...s&&{system:s},...u&&{stop_sequences:_e(u)},...a&&{tools:ge(a)},...f};c?.debug("Anthropic request",{request:p});let m;try{const _=await e.messages.create(p);m=pt(_)}catch(_){m=J(_)}return c?.debug("Anthropic response",{result:m}),m}i(ut,"createGenerationRequest$3");function pt(t){const e=Ee(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=ye(t.content);return{type:"success",id:t.id,model:t.model,role:t.role,finishReason:S.FunctionCall,content:n,text:F(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}if(t.type=="message"){const n=ye(t.content);return{type:"success",id:t.id,model:t.model,role:"assistant",finishReason:e,content:n,text:F(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}}i(pt,"convertToAIResponse");function dt(){const t=new Map,e=new Map,n=new Map;function r(s){const a=[];switch(s.type){case"message_start":a.push({type:"start",id:s.message.id,data:{model:s.message.model,timestamp:Date.now()}});break;case"message_delta":s.delta.stop_reason&&a.push({type:"complete",data:{finishReason:Ee(s.delta.stop_reason),usage:s.usage?{in:s.usage.input_tokens||0,out:s.usage.output_tokens||0}:void 0}});case"message_stop":break;case"content_block_start":if(s.content_block.type==="text")t.set(s.index,"text"),a.push({type:"text-start",data:{index:s.index}});else if(s.content_block.type==="tool_use"){t.set(s.index,"tool");const o=s.content_block;n.set(s.index,{id:o.id,name:o.name,argumentsBuffer:""}),a.push({type:"tool-call-start",data:{index:s.index,id:o.id,name:o.name}})}else if(s.content_block.type==="thinking")t.set(s.index,"thinking"),a.push({type:"thinking-start",data:{index:s.index,redacted:!1}});else if(s.content_block.type==="redacted_thinking")t.set(s.index,"thinking"),a.push({type:"thinking-start",data:{index:s.index,redacted:!0}});else if(s.content_block.type==="server_tool_use"){t.set(s.index,"internal-tool");const o=s.content_block;e.set(o.id,{index:s.index,name:o.name}),a.push({type:"internal-tool-start",data:{index:s.index,id:o.id,name:o.name}})}else if(s.content_block.type==="web_search_tool_result"){const o=s.content_block,l=e.get(o.tool_use_id);l&&(a.push({type:"internal-tool-complete",data:{index:l.index,id:o.tool_use_id,name:l.name,output:o.content}}),e.delete(o.tool_use_id))}break;case"content_block_delta":if(s.delta.type==="text_delta")a.push({type:"text-delta",data:{text:s.delta.text,index:s.index}});else if(s.delta.type==="input_json_delta"){const o=n.get(s.index);o&&(o.argumentsBuffer+=s.delta.partial_json)}else s.delta.type==="thinking_delta"?a.push({type:"thinking-delta",data:{text:s.delta.thinking,index:s.index}}):s.delta.type==="signature_delta"||s.delta.type;break;case"content_block_stop":{const o=t.get(s.index);if(o==="text")a.push({type:"text-complete",data:{index:s.index}});else if(o==="thinking")a.push({type:"thinking-complete",data:{index:s.index}});else if(o!=="internal-tool"){if(o==="tool"){const l=n.get(s.index);if(l){try{const c=JSON.parse(l.argumentsBuffer);a.push({type:"tool-call-complete",data:{index:s.index,id:l.id,name:l.name,arguments:c}})}catch(c){throw new Error(`Failed to parse tool call arguments for ${l.name}: ${c instanceof Error?c.message:String(c)}`)}n.delete(s.index)}}}t.delete(s.index);break}}return a}return i(r,"handleEvent"),{handleEvent:r}}i(dt,"createAnthropicStreamingAdapter");async function*ft(t){const{client:e,model:n,messages:r,system:s,tools:a,runtime:o,signal:l,options:c}=t,u=o?.tracer,{stop:d,max_tokens:f,...p}=c??{},m={model:n,max_tokens:f??mt(n),messages:he(r),...s&&{system:s},...d&&{stop_sequences:_e(d)},...a&&{tools:ge(a)},...p};u?.debug("Anthropic streaming request",{request:m});const _=dt();try{const h=await e.messages.create({...m,stream:!0},{signal:l});for await(const I of h){const w=_.handleEvent(I);for(const A of w)yield A}}catch(h){if(l?.aborted)return;yield{type:"error",data:{type:"STREAMING_ERROR",message:h instanceof Error?h.message:String(h),raw:h}}}}i(ft,"createStreamingRequest$3");const xe={[E.CLAUDE_OPUS_4_6]:128e3,[E.CLAUDE_OPUS_4_5_20251101]:64e3,[E.CLAUDE_HAIKU_4_5_20251001]:64e3,[E.CLAUDE_SONNET_4_5_20250929]:64e3,[E.CLAUDE_SONNET_4_20250514]:64e3,[E.CLAUDE_3_7_SONNET_20250219]:64e3,[E.CLAUDE_OPUS_4_1_20250805]:32e3,[E.CLAUDE_OPUS_4_20250514]:32e3,[E.CLAUDE_3_5_HAIKU_20241022]:8192,[E.CLAUDE_3_HAIKU_20240307]:4096};function mt(t){return t in xe?xe[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}i(mt,"getMaxTokens");const _t="anthropic";function ht(t){const e=new ve({apiKey:t});return{name:_t,async createGenerationRequest(n,r){return await ut({client:e,model:n,...r})},createStreamingRequest(n,r){const{messages:s,system:a,tools:o,context:l,signal:c,options:u}=r;return ft({client:e,model:n,messages:s,system:a,tools:o,runtime:l,signal:c,options:u})}}}i(ht,"anthropic");function Ie(t,e){const n=t.map(gt).flat(1);return e?[{role:"system",content:e},...n]:n}i(Ie,"convertAxleMessages");function Se(t){if(t&&t.length>0)return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:V.toJSONSchema(e.schema)}}))}i(Se,"convertTools");function ee(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}}i(ee,"convertFinishReason");function gt(t){switch(t.role){case"tool":return yt(t);case"assistant":return Et(t);default:return xt(t)}}i(gt,"convertMessage$2");function yt(t){return t.content.map(e=>({role:"tool",content:e.content,tool_call_id:e.id}))}i(yt,"convertToolMessage$2");function Et(t){const e=t.content.filter(s=>s.type==="tool-call"),n=t.content.filter(s=>s.type==="text"),r=e.length>0?e.map(s=>({type:"function",id:s.id,function:{name:s.name,arguments:JSON.stringify(s.parameters)}})):void 0;return{role:"assistant",content:n.map(s=>s.text).join(""),...r&&{tool_calls:r}}}i(Et,"convertAssistantMessage$2");function xt(t){if(typeof t.content=="string")return{role:"user",content:t.content};const e=t.content.map(It).filter(n=>n!==null);return e.every(n=>n.type==="text")?{role:"user",content:e.map(n=>n.text).join("")}:{role:"user",content:e}}i(xt,"convertUserMessage$2");function It(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}i(It,"convertContentPart$2");async function St(t){const{baseUrl:e,model:n,messages:r,system:s,tools:a,context:o,apiKey:l,options:c}=t,u=o?.tracer,d=Ie(r,s),f=Se(a),p={model:n,messages:d,...f&&{tools:f}};c&&(c.temperature!==void 0&&(p.temperature=c.temperature),c.top_p!==void 0&&(p.top_p=c.top_p),c.max_tokens!==void 0&&(p.max_tokens=c.max_tokens),c.frequency_penalty!==void 0&&(p.frequency_penalty=c.frequency_penalty),c.presence_penalty!==void 0&&(p.presence_penalty=c.presence_penalty),c.stop!==void 0&&(p.stop=c.stop)),u?.debug("ChatCompletions request",{request:p});let m;try{const _={"Content-Type":"application/json"};l&&(_.Authorization=`Bearer ${l}`);const h=await fetch(`${e}/chat/completions`,{method:"POST",headers:_,body:JSON.stringify(p)});if(!h.ok){const w=await h.text().catch(()=>"");throw new Error(`HTTP error! status: ${h.status}${w?` - ${w}`:""}`)}const I=await h.json();m=Tt(I)}catch(_){u?.error("Error fetching ChatCompletions response",{error:_ instanceof Error?_.message:String(_)}),m=J(_)}return u?.debug("ChatCompletions response",{result:m}),m}i(St,"createGenerationRequest$2");function Tt(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 a of e.message.tool_calls){let o;try{o=JSON.parse(a.function.arguments)}catch(l){throw new Error(`Invalid tool call arguments for ${a.function.name}: ${l instanceof Error?l.message:String(l)}`)}if(typeof o!="object"||o===null||Array.isArray(o))throw new Error(`Invalid tool call arguments for ${a.function.name}: expected object, got ${typeof o}`);n.push({type:"tool-call",id:a.id,name:a.function.name,parameters:o})}const r=n.some(a=>a.type==="tool-call"),s=ee(r?"tool_calls":e.finish_reason);return{type:"success",id:t.id,model:t.model,role:"assistant",finishReason:s,content:n,text:F(n)??"",usage:{in:t.usage?.prompt_tokens||0,out:t.usage?.completion_tokens||0},raw:t}}i(Tt,"fromModelResponse$2");function wt(){const t=new Map;let e=0,n=-1,r="",s="",a=null;function o(c){n<0||(a==="text"?c.push({type:"text-complete",data:{index:n}}):a==="thinking"&&c.push({type:"thinking-complete",data:{index:n}}),a=null,n=-1)}i(o,"closeActivePart");function l(c){const u=[],d=c.choices[0];if(!d)return u;r||(r=c.id,s=c.model,u.push({type:"start",id:r,data:{model:s,timestamp:Date.now()}}));const f=d.delta;if(f.reasoning_content&&(a!=="thinking"&&(o(u),n=e++,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"&&(o(u),n=e++,a="text",u.push({type:"text-start",data:{index:n}})),u.push({type:"text-delta",data:{text:f.content,index:n}})),f.tool_calls){o(u);for(const p of f.tool_calls){const m=p.index;if(!t.has(m)){const h=e++,I=p.id||`tool-${h}`;t.set(m,{id:I,name:p.function?.name||"",argumentsBuffer:"",partIdx:h}),u.push({type:"tool-call-start",data:{index:h,id:I,name:p.function?.name||""}})}const _=t.get(m);p.id&&(_.id=p.id),p.function?.name&&(_.name=p.function.name),p.function?.arguments&&(_.argumentsBuffer+=p.function.arguments)}}if(d.finish_reason){o(u);for(const[,m]of t)try{const _=JSON.parse(m.argumentsBuffer);u.push({type:"tool-call-complete",data:{index:m.partIdx,id:m.id,name:m.name,arguments:_}})}catch(_){throw new Error(`Failed to parse tool call arguments for ${m.name}: ${_ instanceof Error?_.message:String(_)}`)}const p=ee(d.finish_reason);u.push({type:"complete",data:{finishReason:p,usage:c.usage?{in:c.usage.prompt_tokens,out:c.usage.completion_tokens}:{in:0,out:0}}})}return u}return i(l,"handleChunk"),{handleChunk:l}}i(wt,"createStreamingAdapter$1");async function*bt(t){const{baseUrl:e,model:n,messages:r,system:s,tools:a,context:o,signal:l,apiKey:c,options:u}=t,d=o?.tracer,f=Ie(r,s),p=Se(a),m={model:n,messages:f,stream:!0,stream_options:{include_usage:!0},...p&&{tools:p}};u&&(u.temperature!==void 0&&(m.temperature=u.temperature),u.top_p!==void 0&&(m.top_p=u.top_p),u.max_tokens!==void 0&&(m.max_tokens=u.max_tokens),u.frequency_penalty!==void 0&&(m.frequency_penalty=u.frequency_penalty),u.presence_penalty!==void 0&&(m.presence_penalty=u.presence_penalty),u.stop!==void 0&&(m.stop=u.stop)),d?.debug("ChatCompletions streaming request",{request:m});const _=wt();try{const h={"Content-Type":"application/json"};c&&(h.Authorization=`Bearer ${c}`);const I=await fetch(`${e}/chat/completions`,{method:"POST",headers:h,body:JSON.stringify(m),signal:l});if(!I.ok){const G=await I.text().catch(()=>"");throw new Error(`HTTP error! status: ${I.status}${G?` - ${G}`:""}`)}if(!I.body)throw new Error("Response body is null");const w=I.body.getReader(),A=new TextDecoder;let U="";for(;;){const{done:G,value:B}=await w.read();if(G)break;U+=A.decode(B,{stream:!0});const N=U.split(`
|
|
20
|
-
`);U=N.pop()||"";for(const W of N){const y=W.trim();if(!y||y.startsWith(":")||!y.startsWith("data: "))continue;const L=y.slice(6);if(L!=="[DONE]")try{const T=JSON.parse(L),D=_.handleChunk(T);for(const v of D)yield v}catch(T){d?.error("Error parsing ChatCompletions stream chunk",{error:T instanceof Error?T.message:String(T),line:y})}}}}catch(h){if(l?.aborted)return;d?.error("Error in ChatCompletions streaming request",{error:h instanceof Error?h.message:String(h)}),yield{type:"error",data:{type:"STREAMING_ERROR",message:h instanceof Error?h.message:String(h),raw:h}}}}i(bt,"createStreamingRequest$2");function At(t,e){return{name:"ChatCompletions",async createGenerationRequest(n,r){return await St({baseUrl:t,model:n,apiKey:e,...r})},createStreamingRequest(n,r){return bt({baseUrl:t,model:n,apiKey:e,...r})}}}i(At,"chatCompletions");const x={GEMINI_3_PRO_PREVIEW:"gemini-3-pro-preview",GEMINI_3_FLASH_PREVIEW:"gemini-3-flash-preview",GEMINI_3_PRO_IMAGE_PREVIEW:"gemini-3-pro-image-preview",GEMINI_2_5_PRO:"gemini-2.5-pro",GEMINI_2_5_FLASH:"gemini-2.5-flash",GEMINI_2_5_FLASH_PREVIEW_09_2025:"gemini-2.5-flash-preview-09-2025",GEMINI_2_5_FLASH_IMAGE:"gemini-2.5-flash-image",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_5_FLASH_NATIVE_AUDIO_PREVIEW_09_2025:"gemini-2.5-flash-native-audio-preview-09-2025",GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025:"gemini-2.5-flash-native-audio-preview-12-2025",GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025:"gemini-2.5-computer-use-preview-10-2025",GEMINI_2_0_FLASH:"gemini-2.0-flash",GEMINI_2_0_FLASH_001:"gemini-2.0-flash-001",GEMINI_2_0_FLASH_EXP_IMAGE_GENERATION:"gemini-2.0-flash-exp-image-generation",GEMINI_2_0_FLASH_LITE:"gemini-2.0-flash-lite",GEMINI_2_0_FLASH_LITE_001:"gemini-2.0-flash-lite-001",GEMINI_EXP_1206:"gemini-exp-1206",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",DEEP_RESEARCH_PRO_PREVIEW_12_2025:"deep-research-pro-preview-12-2025",GEMINI_ROBOTICS_ER_1_5_PREVIEW:"gemini-robotics-er-1.5-preview",NANO_BANANA_PRO_PREVIEW:"nano-banana-pro-preview",AQA:"aqa"};x.GEMINI_3_PRO_PREVIEW,x.GEMINI_3_FLASH_PREVIEW,x.GEMINI_3_PRO_IMAGE_PREVIEW,x.GEMINI_2_5_PRO,x.GEMINI_2_5_FLASH,x.GEMINI_2_5_FLASH_PREVIEW_09_2025,x.GEMINI_2_5_FLASH_IMAGE,x.GEMINI_2_5_FLASH_LITE,x.GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025,x.GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_09_2025,x.GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025,x.GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025,x.GEMINI_2_0_FLASH,x.GEMINI_2_0_FLASH_001,x.GEMINI_2_0_FLASH_EXP_IMAGE_GENERATION,x.GEMINI_2_0_FLASH_LITE,x.GEMINI_2_0_FLASH_LITE_001,x.GEMINI_EXP_1206,x.GEMINI_FLASH_LATEST,x.GEMINI_FLASH_LITE_LATEST,x.GEMINI_PRO_LATEST,x.GEMMA_3_27B_IT,x.GEMMA_3_12B_IT,x.GEMMA_3_4B_IT,x.GEMMA_3_1B_IT,x.GEMMA_3N_E4B_IT,x.GEMMA_3N_E2B_IT,x.DEEP_RESEARCH_PRO_PREVIEW_12_2025,x.GEMINI_ROBOTICS_ER_1_5_PREVIEW,x.NANO_BANANA_PRO_PREVIEW;const kt=x.GEMINI_3_FLASH_PREVIEW;function Te(t,e,n){const r={};return e&&(r.systemInstruction=e),t&&t.length>0&&(r.tools=t.map(s=>({functionDeclarations:[{name:s.name,description:s.description,parametersJsonSchema:V.toJSONSchema(s.schema)}]}))),n&&Object.assign(r,n),r}i(Te,"prepareConfig");function we(t){return t.map(Ct).filter(e=>e!==void 0)}i(we,"convertAxleMessagesToGemini");function Ct(t){switch(t.role){case"tool":return Ot(t);case"assistant":return Pt(t);case"user":return Rt(t)}}i(Ct,"convertMessage$1");function Ot(t){return{role:"user",parts:t.content.map(e=>({functionResponse:{id:e.id??void 0,name:e.name,response:{output:e.content}}}))}}i(Ot,"convertToolMessage$1");function Pt(t){const e=[],n=t.content.filter(s=>s.type==="text");if(n.length>0){const s=n.map(a=>a.text).join("");s&&e.push({text:s})}const r=t.content.filter(s=>s.type==="tool-call");return r.length>0&&e.push(...r.map(s=>({functionCall:{id:s.id??void 0,name:s.name,args:s.parameters}}))),{role:"model",parts:e}}i(Pt,"convertAssistantMessage$1");function Rt(t){return typeof t.content=="string"?{role:"user",parts:[{text:t.content}]}:{role:"user",parts:t.content.map($t).filter(n=>n!==null)}}i(Rt,"convertUserMessage$1");function $t(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}i($t,"convertContentPart$1");function be(t){switch(t){case O.STOP:return[!0,S.Stop];case O.MAX_TOKENS:return[!0,S.Length];case O.FINISH_REASON_UNSPECIFIED:case O.SAFETY:case O.RECITATION:case O.LANGUAGE:case O.OTHER:case O.BLOCKLIST:case O.PROHIBITED_CONTENT:case O.SPII:case O.MALFORMED_FUNCTION_CALL:case O.IMAGE_SAFETY:return[!1,S.Error]}}i(be,"convertStopReason");async function Nt(t){const{client:e,model:n,messages:r,system:s,tools:a,context:o,options:l}=t,c=o?.tracer,u=l?{...l}:{};u.max_tokens&&(u.maxOutputTokens=u.max_tokens,delete u.max_tokens),u.stop&&(u.stopSequences=Array.isArray(u.stop)?u.stop:[u.stop],delete u.stop),u.top_p!==void 0&&(u.topP=u.top_p,delete u.top_p);const d={contents:we(r),config:Te(a,s,u)};c?.debug("Gemini request",{request:d});let f;try{const p=await e.models.generateContent({model:n,...d});f=Lt(p,{tracer:c})}catch(p){c?.error(p instanceof Error?p.message:String(p)),f=J(p)}return c?.debug("Gemini response",{result:f}),f}i(Nt,"createGenerationRequest$1");function Lt(t,e){const{tracer:n}=e,r=t.usageMetadata.promptTokenCount,s=t.usageMetadata.totalTokenCount-r,a={in:r,out:s};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:a,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 o=t.candidates[0],c=(o.content?.parts||[]).map(f=>f.text).filter(f=>f!==void 0).join(""),[u,d]=be(o.finishReason);if(u){const f=[];if(c&&f.push({type:"text",text:c}),t.functionCalls)for(const p of t.functionCalls){if(typeof p.args!="object"||p.args===null||Array.isArray(p.args))throw new Error(`Invalid tool call arguments for ${p.name}: expected object, got ${typeof p.args}`);f.push({type:"tool-call",id:p.id,name:p.name,parameters:p.args})}return{type:"success",id:t.responseId,model:t.modelVersion,role:"assistant",finishReason:t.functionCalls?S.FunctionCall:d,content:f,text:F(f)??"",usage:a,raw:t}}else return{type:"error",error:{type:"Undetermined",message:`Unexpected stop reason: ${d}`},usage:a,raw:t}}i(Lt,"fromModelResponse$1");function Mt(){let t=0,e=-1,n=!1,r="",s="",a=0,o=0,l=null;function c(d){e<0||(l==="text"?d.push({type:"text-complete",data:{index:e}}):l==="thinking"&&d.push({type:"thinking-complete",data:{index:e}}),l=null,e=-1)}i(c,"closeActivePart");function u(d){const f=[];r||(r=d.responseId||`gemini-${Date.now()}`,s=d.modelVersion||"gemini",f.push({type:"start",id:r,data:{model:s,timestamp:Date.now()}})),d.usageMetadata&&(a=d.usageMetadata.promptTokenCount||0,o=(d.usageMetadata.totalTokenCount||0)-a);const p=d.candidates?.[0];if(!p)return f;const m=p.content?.parts||[];for(const _ of m){const h="thought"in _&&_.thought===!0;if(h&&_.text?(l!=="thinking"&&(c(f),e=t++,l="thinking",f.push({type:"thinking-start",data:{index:e}})),f.push({type:"thinking-delta",data:{index:e,text:_.text}})):_.text&&!h?(l!=="text"&&(c(f),e=t++,l="text",f.push({type:"text-start",data:{index:e}})),f.push({type:"text-delta",data:{text:_.text,index:e}})):_.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(_))}`),_.functionCall){c(f),n=!0;const I=t++,w=_.functionCall.id||`tool-${I}`;f.push({type:"tool-call-start",data:{index:I,id:w,name:_.functionCall.name}}),f.push({type:"tool-call-complete",data:{index:I,id:w,name:_.functionCall.name,arguments:_.functionCall.args}})}}if(p.finishReason&&p.finishReason!==O.FINISH_REASON_UNSPECIFIED){c(f);const[_,h]=be(p.finishReason),I=n?S.FunctionCall:h;!_&&!n?f.push({type:"error",data:{type:"FinishReasonError",message:`Unexpected finish reason: ${p.finishReason}`,usage:{in:a,out:o},raw:d}}):f.push({type:"complete",data:{finishReason:I,usage:{in:a,out:o}}})}return f}return i(u,"handleChunk"),{handleChunk:u}}i(Mt,"createGeminiStreamingAdapter");async function*Ut(t){const{client:e,model:n,messages:r,system:s,tools:a,runtime:o,signal:l,options:c}=t,u=o?.tracer,d=c?{...c}:{};d.max_tokens&&(d.maxOutputTokens=d.max_tokens,delete d.max_tokens),d.stop&&(d.stopSequences=Array.isArray(d.stop)?d.stop:[d.stop],delete d.stop),d.top_p!==void 0&&(d.topP=d.top_p,delete d.top_p);const f={contents:we(r),config:Te(a,s,d)};u?.debug("Gemini streaming request",{request:f});const p=Mt();try{const m=await e.models.generateContentStream({model:n,...f});for await(const _ of m){const h=p.handleChunk(_);for(const I of h)yield I}}catch(m){if(l?.aborted)return;u?.error(m instanceof Error?m.message:String(m)),yield{type:"error",data:{type:"STREAMING_ERROR",message:m instanceof Error?m.message:String(m),raw:m}}}}i(Ut,"createStreamingRequest$1");const Gt="Gemini";function Dt(t){const e=new Fe({apiKey:t});return{name:Gt,async createGenerationRequest(n,r){return await Nt({client:e,model:n,...r})},createStreamingRequest(n,r){const{messages:s,system:a,tools:o,context:l,signal:c,options:u}=r;return Ut({client:e,model:n,messages:s,system:a,tools:o,runtime:l,signal:c,options:u})}}}i(Dt,"gemini");const Ae={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",GPT_4_TURBO_PREVIEW:"gpt-4-turbo-preview",GPT_4_0125_PREVIEW:"gpt-4-0125-preview",GPT_4_1106_PREVIEW:"gpt-4-1106-preview",GPT_4:"gpt-4",GPT_4_0613:"gpt-4-0613",GPT_3_5_TURBO:"gpt-3.5-turbo",GPT_3_5_TURBO_0125:"gpt-3.5-turbo-0125",GPT_3_5_TURBO_1106:"gpt-3.5-turbo-1106",GPT_3_5_TURBO_16K:"gpt-3.5-turbo-16k",GPT_3_5_TURBO_INSTRUCT:"gpt-3.5-turbo-instruct",GPT_3_5_TURBO_INSTRUCT_0914:"gpt-3.5-turbo-instruct-0914",O4_MINI:"o4-mini",O4_MINI_2025_04_16:"o4-mini-2025-04-16",O4_MINI_DEEP_RESEARCH:"o4-mini-deep-research",O4_MINI_DEEP_RESEARCH_2025_06_26:"o4-mini-deep-research-2025-06-26",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",O3_DEEP_RESEARCH:"o3-deep-research",O3_DEEP_RESEARCH_2025_06_26:"o3-deep-research-2025-06-26",O1:"o1",O1_2024_12_17:"o1-2024-12-17",O1_PRO:"o1-pro",O1_PRO_2025_03_19:"o1-pro-2025-03-19",COMPUTER_USE_PREVIEW:"computer-use-preview",COMPUTER_USE_PREVIEW_2025_03_11:"computer-use-preview-2025-03-11",CHATGPT_IMAGE_LATEST:"chatgpt-image-latest"},vt=Ae.GPT_5_MINI;function ke(t){if(t&&t.length>0)return t.map(e=>{const n=V.toJSONSchema(e.schema);return{type:"function",strict:!0,name:e.name,description:e.description,parameters:n}})}i(ke,"prepareTools");function Ce(t){return t.map(Ft).flat(1)}i(Ce,"convertAxleMessageToResponseInput");function Ft(t){switch(t.role){case"tool":return Ht(t);case"assistant":return Bt(t);default:return jt(t)}}i(Ft,"convertMessage");function Ht(t){return t.content.map(e=>({type:"function_call_output",call_id:e.id,output:e.content}))}i(Ht,"convertToolMessage");function Bt(t){const e=[],n=F(t.content);n&&e.push({role:t.role,content:n});const r=t.content.filter(s=>s.type==="tool-call");for(const s of r)e.push({type:"function_call",call_id:s.id,name:s.name,arguments:JSON.stringify(s.parameters)});return e}i(Bt,"convertAssistantMessage");function jt(t){if(typeof t.content=="string")return{role:t.role,content:t.content};{const e=t.content.map(qt).filter(n=>n!==null);return{role:t.role,content:e}}}i(jt,"convertUserMessage");function qt(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}i(qt,"convertContentPart");async function Wt(t){const{client:e,model:n,messages:r,system:s,tools:a,context:o,options:l}=t,c=o?.tracer,u=ke(a),d={model:n,input:Ce(r),...s&&{instructions:s},...u?{tools:u}:{},...l};c?.debug("OpenAI ResponsesAPI request",{request:d});let f;try{const p=await e.responses.create(d);f=Vt(p)}catch(p){c?.error(p instanceof Error?p.message:String(p)),f=J(p)}return c?.debug("OpenAI ResponsesAPI response",{result:f}),f}i(Wt,"createGenerationRequest");function Vt(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(s=>s.type==="reasoning")?.map(s=>s),n=[];if(e&&e.length>0)for(const s of e){const a=s.summary?.[0]?.text||s.content?.[0]?.text||"";(a||s.encrypted_content)&&n.push({type:"thinking",text:a,...s.encrypted_content&&{encrypted:s.encrypted_content}})}t.output_text&&n.push({type:"text",text:t.output_text});const r=t.output?.filter(s=>s.type==="function_call");if(r&&r.length>0)for(const s of r){const a=s;try{n.push({type:"tool-call",id:a.id||"",name:a.name||"",parameters:a.arguments?JSON.parse(a.arguments):{}})}catch(o){throw new Error(`Failed to parse tool call arguments for ${a.name}: ${o instanceof Error?o.message:String(o)}`)}}return{type:"success",id:t.id,model:t.model||"",role:"assistant",finishReason:t.incomplete_details?S.Error:S.Stop,content:n,text:F(n)??"",usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t}}i(Vt,"fromModelResponse");function Kt(){let t="",e="",n=0,r=-1,s=!1;const a=new Map,o=new Map,l=new Set(["web_search_call","file_search_call","code_interpreter_call"]),c=new Map;function u(d){const f=[];switch(d.type){case"response.created":{t=d.response.id||`openai-${Date.now()}`,e=d.response.model,f.push({type:"start",id:t,data:{model:e,timestamp:Date.now()}});break}case"response.output_text.delta":{r===-1&&(r=n++,f.push({type:"text-start",data:{index:r}})),f.push({type:"text-delta",data:{text:d.delta,index:r}});break}case"response.output_text.done":{r>=0&&(f.push({type:"text-complete",data:{index:r}}),r=-1);break}case"response.function_call_arguments.delta":{const p=d.item_id;if(!c.has(p)){const _=a.get(p),h=_?.name||"",I=_?.callId||p,w=n++;c.set(p,{id:p,callId:I,name:h,argumentsBuffer:"",partIdx:w}),f.push({type:"tool-call-start",data:{index:w,id:I,name:h}})}const m=c.get(p);m.argumentsBuffer+=d.delta;break}case"response.function_call_arguments.done":{s=!0;const p=d.item_id,m=c.get(p),_=d.name||m?.name||"";if(m){try{const h=JSON.parse(d.arguments);f.push({type:"tool-call-complete",data:{index:m.partIdx,id:m.callId,name:_,arguments:h}})}catch(h){throw new Error(`Failed to parse function call arguments for ${_}: ${h instanceof Error?h.message:String(h)}`)}c.delete(p)}break}case"response.completed":{const p=d.response.usage;f.push({type:"complete",data:{finishReason:d.response.incomplete_details?S.Error:s?S.FunctionCall:S.Stop,usage:{in:p?.input_tokens||0,out:p?.output_tokens||0}}});break}case"response.failed":{f.push({type:"error",data:{type:"RESPONSES_API_ERROR",message:`Response failed: ${d.response.status}`,raw:d}});break}case"response.output_item.added":{if(d.item?.type==="reasoning")r=n++,f.push({type:"thinking-start",data:{index:r}});else if(d.item?.type==="function_call"){const p=d.item,m=p.id||p.call_id;m&&a.set(m,{name:p.name||"",callId:p.call_id||m})}else if(d.item&&l.has(d.item.type)){const p=d.item,m=n++;o.set(p.id,m),f.push({type:"internal-tool-start",data:{index:m,id:p.id,name:p.type}})}break}case"response.output_item.done":{if(d.item?.type==="reasoning"&&r>=0)f.push({type:"thinking-complete",data:{index:r}}),r=-1;else if(d.item&&l.has(d.item.type)){const p=d.item,m=o.get(p.id);m!==void 0&&(f.push({type:"internal-tool-complete",data:{index:m,id:p.id,name:p.type,output:d.item}}),o.delete(p.id))}break}case"response.reasoning_text.delta":{d.delta&&f.push({type:"thinking-delta",data:{index:r,text:d.delta}});break}case"response.reasoning_summary_text.delta":{d.delta&&f.push({type:"thinking-summary-delta",data:{index:r,text:d.delta}});break}default:console.log(`[OpenAI] unhandled stream event: ${d.type}`)}return f}return i(u,"handleEvent"),{handleEvent:u}}i(Kt,"createStreamingAdapter");async function*Jt(t){const{client:e,model:n,messages:r,system:s,tools:a,runtime:o,signal:l,options:c}=t,u=o?.tracer,d=ke(a),f={model:n,input:Ce(r),...s&&{instructions:s},stream:!0,...d?{tools:d}:{},...c};u?.debug("OpenAI ResponsesAPI streaming request",{request:f});const p=Kt();try{const m=e.responses.stream(f,...l?[{signal:l}]:[]);for await(const _ of m){const h=p.handleEvent(_);for(const I of h)yield I}}catch(m){if(l?.aborted)return;u?.error(m instanceof Error?m.message:String(m)),yield{type:"error",data:{type:"STREAMING_ERROR",message:m instanceof Error?m.message:String(m),raw:m}}}}i(Jt,"createStreamingRequest");const zt="OpenAI";function Xt(t){const e=new He({apiKey:t});return{name:zt,async createGenerationRequest(n,r){return await Wt({client:e,model:n,...r})},createStreamingRequest(n,r){const{messages:s,system:a,tools:o,context:l,signal:c,options:u}=r;return Jt({client:e,model:n,messages:s,system:a,tools:o,runtime:l,signal:c,options:u})}}}i(Xt,"openai");const Zt=C.object({searchTerm:C.string().describe("The search term to query")});class Yt{static{i(this,"BraveSearchTool")}name="brave";description="Perform a search using the Brave search engine";schema=Zt;apiKey;throttle;lastExecTime=0;constructor(e){e&&this.configure(e)}configure(e){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 ct(this.throttle-(Date.now()-this.lastExecTime));this.lastExecTime=Date.now()}try{const r=this.apiKey,s="https://api.search.brave.com/res/v1/web/search",a=new URL(s);a.searchParams.append("q",n),a.searchParams.append("format","json");const o=await fetch(a.toString(),{method:"GET",headers:{Accept:"application/json","X-Subscription-Token":r}});if(!o.ok)throw new Error(`[Brave] HTTP error ${o.status}: ${o.statusText}`);const l=await o.json();return JSON.stringify(l)}catch(r){throw r instanceof Error?new Error(`[Brave] Error fetching search results: ${r.message}`):r}}}const Qt=new Yt,en=k.object({operation:k.enum(["add","subtract","multiply","divide"]).describe("The operation to perform (add, subtract, multiply, divide)"),a:k.number().describe("First operand"),b:k.number().describe("Second operand")}),tn={name:"calculator",description:"Performs basic arithmetic operations",schema:en,execute:i(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")},nn=je(Be),rn=3e4,sn=1024*1024;async function on(t,e={}){const{stdout:n,stderr:r}=await nn(t,{cwd:e.cwd,timeout:e.timeout??rn,maxBuffer:e.maxBuffer??sn});return{stdout:n,stderr:r}}i(on,"runCommand");function an(t){if(t instanceof Error){const e=t;let n=`Error executing command: ${t.message}`;return e.stdout&&(n+=`
|
|
21
|
-
[stdout]: ${e.stdout}`),e.stderr&&(n+=`
|
|
22
|
-
[stderr]: ${e.stderr}`),n}return`Error executing command: ${String(t)}`}i(an,"formatExecError");function cn(t,e){return e&&e.trim()?`${t}
|
|
23
|
-
[stderr]: ${e}`:t}i(cn,"formatOutput");const ln=C.object({command:C.string().describe("The shell command to execute")});class un{static{i(this,"ExecTool")}name="exec";description="Execute a shell command and return the output.";schema=ln;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 r=await on(n,{timeout:this.timeout,maxBuffer:this.maxBuffer,cwd:this.cwd});return cn(r.stdout,r.stderr)}catch(r){return an(r)}}}const pn=new un,dn=k.object({path:k.string().describe("The file path to patch"),old_string:k.string().describe("The exact text to find and replace"),new_string:k.string().describe("The replacement text"),start_line:k.number().int().positive().describe("1-indexed start line of the region to match within"),end_line:k.number().int().positive().describe("1-indexed end line (inclusive) of the region to match within")}),fn={name:"patch-file",description:"Patch a file by replacing an exact string match within a specified line range",schema:dn,summarize:i(({path:t,start_line:e,end_line:n})=>`${t}:${e}:${n}`,"summarize"),execute:i(async({path:t,old_string:e,new_string:n,start_line:r,end_line:s})=>{if(s<r)throw new Error(`end_line (${s}) must be >= start_line (${r})`);let a;try{a=await H(t,"utf-8")}catch(_){throw _ instanceof Error?new Error(`Failed to read file "${t}": ${_.message}`):_}const o=a.split(`
|
|
24
|
-
`);if(r>o.length)throw new Error(`start_line (${r}) exceeds file length (${o.length} lines)`);if(s>o.length)throw new Error(`end_line (${s}) exceeds file length (${o.length} lines)`);const c=o.slice(r-1,s).join(`
|
|
25
|
-
`),u=c.indexOf(e);if(u===-1)throw new Error(`old_string not found within lines ${r}-${s} of "${t}"`);if(c.indexOf(e,u+1)!==-1)throw new Error(`old_string matches multiple times within lines ${r}-${s} of "${t}"`);const f=c.replace(e,n),m=[...o.slice(0,r-1),...f.split(`
|
|
26
|
-
`),...o.slice(s)].join(`
|
|
27
|
-
`);try{await se(t,m,"utf-8")}catch(_){throw _ instanceof Error?new Error(`Failed to write file "${t}": ${_.message}`):_}return`Successfully patched "${t}" (lines ${r}-${s})`},"execute")},mn=k.object({path:k.string().describe("The file path to read from")}),_n={name:"read-file",description:"Read the contents of a file from disk",schema:mn,summarize:i(({path:t})=>t,"summarize"),execute:i(async({path:t})=>{try{return await H(t,"utf-8")}catch(e){throw e instanceof Error?new Error(`Failed to read file "${t}": ${e.message}`):e}},"execute")},hn=k.object({path:k.string().describe("The file path to write to"),content:k.string().describe("The content to write to the file")}),gn={name:"write-file",description:"Write content to a file on disk, creating directories if needed",schema:hn,summarize:i(({path:t})=>t,"summarize"),execute:i(async({path:t,content:e})=>{try{return await Ge(De(t),{recursive:!0}),await se(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")},Oe={debug:0,info:1,warn:2,error:3};class yn{static{i(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 r={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:n?.type,startTime:performance.now(),status:"ok",attributes:{},events:[]};return this.writers.forEach(s=>s.onSpanStart(r)),new te(r,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(r=>r.onEvent?.(e,n))}_notifySpanStart(e){this.writers.forEach(n=>n.onSpanStart(e))}_notifyLLMStreamStart(e){this.writers.forEach(n=>n.onLLMStreamStart?.(e))}_notifyLLMStreamChunk(e,n){this.writers.forEach(r=>r.onLLMStreamChunk?.(e,n))}_notifyLLMStreamEnd(e,n){this.writers.forEach(r=>r.onLLMStreamEnd?.(e,n))}_shouldLog(e){return Oe[e]>=Oe[this._minLevel]}}class te{static{i(this,"Span")}data;tracer;ended=!1;llmStreamBuffer="";llmStreamActive=!1;constructor(e,n){this.data=e,this.tracer=n}startSpan(e,n){const r={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(r),new te(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,n,r){if(this.ended||!this.tracer._shouldLog(n))return;const s={name:e,timestamp:performance.now(),level:n,attributes:r};this.data.events.push(s),this.tracer._notifyEvent(this.data,s)}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))}startLLMStream(){this.ended||(this.llmStreamActive=!0,this.llmStreamBuffer="",this.tracer._notifyLLMStreamStart(this.data))}appendLLMStream(e){this.ended||!this.llmStreamActive||(this.llmStreamBuffer+=e,this.tracer._notifyLLMStreamChunk(this.data,e))}endLLMStream(e){if(this.ended||!this.llmStreamActive)return;this.llmStreamActive=!1;const n={...e,response:{...e.response,content:e.response.content??this.llmStreamBuffer}};this.data.result=n,this.tracer._notifyLLMStreamEnd(this.data,n)}}const Pe={debug:0,info:1,warn:2,error:3};class En{static{i(this,"SimpleWriter")}minLevel;showInternal;showTimestamp;showDuration;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.output=e.output??console.log}shouldShowEvent(e){return Pe[e]>=Pe[this.minLevel]}isSpanVisible(e){return!(e.type==="internal"&&!this.showInternal)}findVisibleAncestor(e){let n=e.parentSpanId;for(;n;){const r=this.spans.get(n);if(!r)break;if(this.isSpanVisible(r))return r;n=r.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),r=e.getMilliseconds().toString().padStart(3,"0");return`[${n}.${r}] `}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}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const r=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,r);const s=this.formatIndent(r),a=this.formatTimestamp(),o=this.formatSpanName(e);this.output(`${a}${s}START ${o}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const r=this.visibleDepths.get(e.spanId)??0,s=this.formatIndent(r),a=this.formatTimestamp(),o=this.formatDuration(e),l=this.formatSpanName(e),c=e.status==="error"?" [ERROR]":"";this.output(`${a}${s}END ${l}${o}${c}`)}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,n){if(!this.shouldShowEvent(n.level))return;this.spans.set(e.spanId,e);let r;if(this.isSpanVisible(e))r=this.visibleDepths.get(e.spanId)??0;else{const c=this.findVisibleAncestor(e);c?r=this.visibleDepths.get(c.spanId)??0:r=0}const s=this.formatIndent(r+1),a=this.formatTimestamp(),o=n.level.toUpperCase().padEnd(5);let l=`${a}${s}${o} ${n.name}`;if(n.attributes&&Object.keys(n.attributes).length>0){const c=Object.entries(n.attributes).map(([u,d])=>`${u}=${JSON.stringify(d)}`).join(" ");l+=` ${c}`}this.output(l)}onLLMStreamStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const n=this.visibleDepths.get(e.spanId)??0,r=this.formatIndent(n+1),s=this.formatTimestamp();this.output(`${s}${r}INFO LLM streaming started`)}onLLMStreamChunk(e,n){}onLLMStreamEnd(e,n){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const r=this.visibleDepths.get(e.spanId)??0,s=this.formatIndent(r+1),a=this.formatTimestamp(),o=[`model=${n.model}`];if(n.finishReason&&o.push(`finishReason=${n.finishReason}`),n.usage&&(n.usage.inputTokens!==void 0&&o.push(`inputTokens=${n.usage.inputTokens}`),n.usage.outputTokens!==void 0&&o.push(`outputTokens=${n.usage.outputTokens}`)),this.output(`${a}${s}INFO LLM complete ${o.join(" ")}`),this.shouldShowEvent("debug")&&n.response.content){const c=(typeof n.response.content=="string"?n.response.content:JSON.stringify(n.response.content,null,2)).split(`
|
|
28
|
-
`);for(const u of c)this.output(`${a}${s}DEBUG ${u}`)}}}export{S as A,it as D,ae as H,at as I,E as M,En as S,yn as T,kt as a,x as b,Ve as c,vt as d,ce as e,Ae as f,We as g,Ye as h,ht as i,Qt as j,tn as k,At as l,fe as m,Dt as n,ot as o,Xt as p,pe as q,Qe as r,le as s,_n as t,fn as u,pn as v,gn as w};
|