@fifthrevision/axle 0.25.0 → 0.25.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.
@@ -242,6 +242,11 @@ interface StreamToolCallCompleteChunk extends StreamChunk {
242
242
  id: string;
243
243
  name: string;
244
244
  arguments: any;
245
+ error?: {
246
+ type: string;
247
+ message: string;
248
+ raw?: string;
249
+ };
245
250
  providerMetadata?: Record<string, unknown>;
246
251
  };
247
252
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as AxleStopReason, A as TurnPart, At as TokenUsage, B as ContentPart, C as SubagentAction, Ct as Span, D as ToolAction, Dt as SpanResult, Et as SpanOptions, F as AxleToolCallResult, G as ContentPartThinking, H as ContentPartFile, I as AxleUserMessage, J as MessageMetadata, K as ContentPartToolCall, L as Citation, M as AxleAssistantMessage, Mt as TraceWriter, N as AxleMessage, O as Turn, Ot as SpanStatus, P as AxleToolCallMessage, Q as AxleModelRequestOptions, R as CitationOutputSpan, S as ProviderToolAction, St as LLMResult, T as ThinkingPart, Tt as SpanEvent, U as ContentPartProviderTool, V as ContentPartCitation, W as ContentPartText, X as ToolResultPart, Y as ThinkingContinuity, Z as AIProvider, _ as Annotation, _t as TokenStats, at as ResolvedProviderTool, b as CitationPart, bt as LLMRequest, c as ToolContext, ct as FileInfo, d as ToolRegistry, dt as FileResolveFormat, et as ContextUsage, f as AnnotationEvent, ft as FileResolveRequest, g as ActionResult, gt as Stats, h as ActionPart, ht as loadFileContent, i as TurnAccumulatorState, it as ProviderOptions, j as TurnStatus, jt as ToolResult, k as TurnMetadata, kt as SpanType, l as ToolDefinition, lt as FileKind, m as TurnEvent, mt as ResolvedFileSource, n as TurnAccumulator, nt as ModelResult, o as ExecutableTool, ot as ToolChoice, p as AnnotationTarget, pt as FileResolver, q as DocumentLocator, r as TurnAccumulatorResult, rt as ProviderClientOptions, s as ProviderTool, st as DeferredFileInfo, t as AccumulatableEvent, tt as ModelError, u as ToolProgressChunk, ut as FileProviderId, v as AnnotationPlacement, vt as UsageEntry, w as TextPart, wt as SpanData, x as FilePart, xt as LLMResponse, y as AnnotationStatus, yt as EventLevel, z as CitationSource } from "./accumulator-j9h_1Eyk.js";
1
+ import { $ as AxleStopReason, A as TurnPart, At as TokenUsage, B as ContentPart, C as SubagentAction, Ct as Span, D as ToolAction, Dt as SpanResult, Et as SpanOptions, F as AxleToolCallResult, G as ContentPartThinking, H as ContentPartFile, I as AxleUserMessage, J as MessageMetadata, K as ContentPartToolCall, L as Citation, M as AxleAssistantMessage, Mt as TraceWriter, N as AxleMessage, O as Turn, Ot as SpanStatus, P as AxleToolCallMessage, Q as AxleModelRequestOptions, R as CitationOutputSpan, S as ProviderToolAction, St as LLMResult, T as ThinkingPart, Tt as SpanEvent, U as ContentPartProviderTool, V as ContentPartCitation, W as ContentPartText, X as ToolResultPart, Y as ThinkingContinuity, Z as AIProvider, _ as Annotation, _t as TokenStats, at as ResolvedProviderTool, b as CitationPart, bt as LLMRequest, c as ToolContext, ct as FileInfo, d as ToolRegistry, dt as FileResolveFormat, et as ContextUsage, f as AnnotationEvent, ft as FileResolveRequest, g as ActionResult, gt as Stats, h as ActionPart, ht as loadFileContent, i as TurnAccumulatorState, it as ProviderOptions, j as TurnStatus, jt as ToolResult, k as TurnMetadata, kt as SpanType, l as ToolDefinition, lt as FileKind, m as TurnEvent, mt as ResolvedFileSource, n as TurnAccumulator, nt as ModelResult, o as ExecutableTool, ot as ToolChoice, p as AnnotationTarget, pt as FileResolver, q as DocumentLocator, r as TurnAccumulatorResult, rt as ProviderClientOptions, s as ProviderTool, st as DeferredFileInfo, t as AccumulatableEvent, tt as ModelError, u as ToolProgressChunk, ut as FileProviderId, v as AnnotationPlacement, vt as UsageEntry, w as TextPart, wt as SpanData, x as FilePart, xt as LLMResponse, y as AnnotationStatus, yt as EventLevel, z as CitationSource } from "./accumulator-yYlD8Bfm.js";
2
2
  import * as z$2 from "zod";
3
3
  import { ZodObject, z } from "zod";
4
4
 
@@ -700,13 +700,12 @@ declare const Anthropic: {
700
700
  };
701
701
  //#endregion
702
702
  //#region src/providers/chatcompletions/utils.d.ts
703
- type ChatCompletionsProviderDialect = "together";
703
+ type ChatCompletionsVendor = "openrouter" | "together";
704
704
  //#endregion
705
705
  //#region src/providers/chatcompletions/provider.d.ts
706
706
  interface ChatCompletionsOptions extends ProviderClientOptions {
707
707
  apiKey?: string;
708
- providerDialect?: ChatCompletionsProviderDialect;
709
- providerToolVendor?: "openrouter";
708
+ vendor?: ChatCompletionsVendor;
710
709
  }
711
710
  declare function chatCompletions(baseUrl: string, options?: ChatCompletionsOptions): AIProvider;
712
711
  declare function chatCompletions(baseUrl: string, apiKey?: string): AIProvider;
@@ -1136,4 +1135,4 @@ declare function createStats(): Stats;
1136
1135
  declare function addStats(total: Stats, usage?: Stats): void;
1137
1136
  declare function mergeStats(...usages: Array<Stats | undefined>): Stats;
1138
1137
  //#endregion
1139
- export { type AIProvider, type AccumulatableEvent, type ActionPart, type ActionResult, Agent, type AgentConfig, type AgentDefinition, type AgentDefinitionRequestOptions, type AgentDefinitionResolver, type AgentErrorResult, type AgentHandle, type AgentMemory, type AgentResult, type AgentSession, type Annotation, type AnnotationEvent, type AnnotationPlacement, type AnnotationStatus, type AnnotationTarget, Anthropic, AxleAbortError, AxleAgentAbortError, type AxleAssistantMessage, type AxleConfiguration, AxleError, type AxleMessage, type AxleModelRequestOptions, AxleStopReason, type AxleToolCallMessage, type AxleToolCallResult, AxleToolFatalError, type AxleUserMessage, type BraveWebSearchOptions, type ChatCompletionsOptions, type Citation, type CitationOutputSpan, type CitationPart, type CitationSource, type ContentPart, type ContentPartCitation, type ContentPartFile, type ContentPartProviderTool, type ContentPartText, type ContentPartThinking, type ContentPartToolCall, type ContextUsage, type CreateAgentToolOptions, type DeferredFileInfo, type DocumentLocator, type EventLevel, type ExecutableTool, type FileInfo, type FileKind, type FilePart, type FileProviderId, type FileResolveFormat, type FileResolveRequest, type FileResolver, type FileStore, Gemini, type GenerateInstructParams, type GenerateInstructResult, type GenerateParams, type Handle, History, Instruct, type InstructContextSection, type InstructInputs, type InstructOptions, type InstructResponse, InstructVariableError, type InstructVarsMode, type LLMRequest, type LLMResponse, type LLMResult, type LogEntry, type LogFn, LogWriter, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MaybePromise, type MemoryContext, type MessageMetadata, type ObservabilityOptions, OpenAI, type OutputSchema, type ParallelToolResult, type ParallelizeOptions, type ParsedSchema, type ProviderClientOptions, type ProviderDefinition, type ProviderOptions, type ProviderTool, type ProviderToolAction, type ProviderToolDefinitionRef, type RecallResult, type ResolvedAgentDefinition, type ResolvedFileSource, type SavedAgent, type SendMessageOptions, SimpleWriter, type SimpleWriterOptions, type Span, type SpanData, type SpanEvent, type SpanOptions, type SpanResult, type SpanStatus, type SpanType, type Stats, type StreamEvent, type StreamEventCallback, type StreamHandle, type StreamInstructHandle, type StreamInstructParams, type StreamInstructResult, type StreamParams, type StreamResult, type SubagentAction, TaskError, type TextPart, type ThinkingContinuity, type ThinkingPart, type TokenStats, type TokenUsage, type ToolAction, type ToolChoice, type ToolContext, type ToolDefinition, type ToolDefinitionRef, type ToolProgressChunk, ToolRegistry, type ToolResult, type ToolResultPart, type TraceWriter, Tracer, type TracerOptions, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, TurnEventBuilder, type TurnEventCallback, type TurnMetadata, type TurnPart, type TurnStatus, type UsageEntry, type WebSearchBackend, type WebSearchBackendContext, type WebSearchRequest, type WebSearchResponse, type WebSearchResult, addStats, anthropic, braveWebSearch, chatCompletions, configureAxle, createAgentConfig, createAgentTool, createHandle, createStats, estimateContextUsage, gemini, generate, generateTurn, loadFileContent, mergeStats, openai, parallelize, parseResponse, stream };
1138
+ export { type AIProvider, type AccumulatableEvent, type ActionPart, type ActionResult, Agent, type AgentConfig, type AgentDefinition, type AgentDefinitionRequestOptions, type AgentDefinitionResolver, type AgentErrorResult, type AgentHandle, type AgentMemory, type AgentResult, type AgentSession, type Annotation, type AnnotationEvent, type AnnotationPlacement, type AnnotationStatus, type AnnotationTarget, Anthropic, AxleAbortError, AxleAgentAbortError, type AxleAssistantMessage, type AxleConfiguration, AxleError, type AxleMessage, type AxleModelRequestOptions, AxleStopReason, type AxleToolCallMessage, type AxleToolCallResult, AxleToolFatalError, type AxleUserMessage, type BraveWebSearchOptions, type ChatCompletionsOptions, type ChatCompletionsVendor, type Citation, type CitationOutputSpan, type CitationPart, type CitationSource, type ContentPart, type ContentPartCitation, type ContentPartFile, type ContentPartProviderTool, type ContentPartText, type ContentPartThinking, type ContentPartToolCall, type ContextUsage, type CreateAgentToolOptions, type DeferredFileInfo, type DocumentLocator, type EventLevel, type ExecutableTool, type FileInfo, type FileKind, type FilePart, type FileProviderId, type FileResolveFormat, type FileResolveRequest, type FileResolver, type FileStore, Gemini, type GenerateInstructParams, type GenerateInstructResult, type GenerateParams, type Handle, History, Instruct, type InstructContextSection, type InstructInputs, type InstructOptions, type InstructResponse, InstructVariableError, type InstructVarsMode, type LLMRequest, type LLMResponse, type LLMResult, type LogEntry, type LogFn, LogWriter, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MaybePromise, type MemoryContext, type MessageMetadata, type ObservabilityOptions, OpenAI, type OutputSchema, type ParallelToolResult, type ParallelizeOptions, type ParsedSchema, type ProviderClientOptions, type ProviderDefinition, type ProviderOptions, type ProviderTool, type ProviderToolAction, type ProviderToolDefinitionRef, type RecallResult, type ResolvedAgentDefinition, type ResolvedFileSource, type SavedAgent, type SendMessageOptions, SimpleWriter, type SimpleWriterOptions, type Span, type SpanData, type SpanEvent, type SpanOptions, type SpanResult, type SpanStatus, type SpanType, type Stats, type StreamEvent, type StreamEventCallback, type StreamHandle, type StreamInstructHandle, type StreamInstructParams, type StreamInstructResult, type StreamParams, type StreamResult, type SubagentAction, TaskError, type TextPart, type ThinkingContinuity, type ThinkingPart, type TokenStats, type TokenUsage, type ToolAction, type ToolChoice, type ToolContext, type ToolDefinition, type ToolDefinitionRef, type ToolProgressChunk, ToolRegistry, type ToolResult, type ToolResultPart, type TraceWriter, Tracer, type TracerOptions, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, TurnEventBuilder, type TurnEventCallback, type TurnMetadata, type TurnPart, type TurnStatus, type UsageEntry, type WebSearchBackend, type WebSearchBackendContext, type WebSearchRequest, type WebSearchResponse, type WebSearchResult, addStats, anthropic, braveWebSearch, chatCompletions, configureAxle, createAgentConfig, createAgentTool, createHandle, createStats, estimateContextUsage, gemini, generate, generateTurn, loadFileContent, mergeStats, openai, parallelize, parseResponse, stream };
package/dist/index.js CHANGED
@@ -1,25 +1,25 @@
1
- import{t as e}from"./accumulator-BnFn9yqM.js";import{d as t,i as n,o as r,p as i,r as a,t as o,u as s}from"./models-Cx50YJNx.js";import*as c from"zod";import l,{z as u}from"zod";import{Client as d}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as f}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as p}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import m from"@anthropic-ai/sdk";import"glob";import h from"mime";import{access as g,readFile as _,stat as v}from"node:fs/promises";import{extname as y,resolve as b}from"node:path";import{FinishReason as x,FunctionCallingConfigMode as S,GoogleGenAI as C}from"@google/genai";import w from"openai";import T from"chalk";import{marked as E}from"marked";let D={};function O(e){D={...D,...e}}function k(){return{...D}}var A=class e extends Error{code;id;details;constructor(t,n){super(t,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||`AXLE_ERROR`,this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id?{id:this.id}:{},...this.details?{details:this.details}:{},...this.cause?{cause:j(this.cause)}:{}}}};function j(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:j(e.cause)}:{}}:e}var M=class e extends A{reason;messages;partial;usage;constructor(t=`Operation aborted`,n){super(t,{code:`ABORTED`,details:{reason:n?.reason,usage:n?.usage}}),this.name=`AbortError`,this.reason=n?.reason,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),reason:this.reason,...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}},N=class e extends M{turn;constructor(t=`Agent send aborted`,n){super(t,n),this.turn=n?.turn,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.turn?{turn:this.turn}:{}}}},P=class e extends A{toolName;messages;partial;usage;constructor(t=`Fatal tool error`,n){super(t,{code:`TOOL_FATAL_ERROR`,details:{toolName:n?.toolName,usage:n?.usage},cause:n?.cause}),this.toolName=n?.toolName,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.toolName?{toolName:this.toolName}:{},...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}};function F(e){let{text:t,files:n}=e,r=[];if(t&&r.push({type:`text`,text:t}),n)for(let e of n)r.push({type:`file`,file:e});return r}function I(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(`
1
+ import{t as e}from"./accumulator-BnFn9yqM.js";import{d as t,i as n,o as r,p as i,r as a,t as o,u as s}from"./models-Cx50YJNx.js";import*as c from"zod";import l,{z as u}from"zod";import{Client as d}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as f}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as p}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import m from"@anthropic-ai/sdk";import"glob";import h from"mime";import{access as g,readFile as _,stat as v}from"node:fs/promises";import{extname as y,resolve as b}from"node:path";import{FinishReason as x,FunctionCallingConfigMode as S,GoogleGenAI as C}from"@google/genai";import w from"openai";import T from"chalk";import{marked as E}from"marked";let D={};function O(e){D={...D,...e}}function k(){return{...D}}var A=class e extends Error{code;id;details;constructor(t,n){super(t,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||`AXLE_ERROR`,this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id?{id:this.id}:{},...this.details?{details:this.details}:{},...this.cause?{cause:j(this.cause)}:{}}}};function j(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:j(e.cause)}:{}}:e}var M=class e extends A{reason;messages;partial;usage;constructor(t=`Operation aborted`,n){super(t,{code:`ABORTED`,details:{reason:n?.reason,usage:n?.usage}}),this.name=`AbortError`,this.reason=n?.reason,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),reason:this.reason,...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}},N=class e extends M{turn;constructor(t=`Agent send aborted`,n){super(t,n),this.turn=n?.turn,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.turn?{turn:this.turn}:{}}}},P=class e extends A{toolName;messages;partial;usage;constructor(t=`Fatal tool error`,n){super(t,{code:`TOOL_FATAL_ERROR`,details:{toolName:n?.toolName,usage:n?.usage},cause:n?.cause}),this.toolName=n?.toolName,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.toolName?{toolName:this.toolName}:{},...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}};function ee(e){let{text:t,files:n}=e,r=[];if(t&&r.push({type:`text`,text:t}),n)for(let e of n)r.push({type:`file`,file:e});return r}function F(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
2
 
3
- `)}function ee(e){return e.filter(e=>e.type===`thinking`).map(e=>e.text??``).join(`
3
+ `)}function te(e){return e.filter(e=>e.type===`thinking`).map(e=>e.text??``).join(`
4
4
 
5
- `)}function L(e){return e.filter(e=>e.type===`tool-call`)}function te(e){return e.filter(e=>e.type===`provider-tool`)}function R(e){let t=[];for(let n of e)(n.type===`text`&&n.citations||n.type===`citation`)&&t.push(...n.citations);return t}function ne(e,t=500){return e.length>t?`${e.slice(0,t)}… (${e.length} chars)`:e}function z(e,t=600){if(e.length<=t)return e;let n=Math.floor(t/2);return`${e.slice(0,n)}…[${e.length} chars]…${e.slice(-n)}`}var B=class{log;constructor(e){this.log=e}onSpanStart(){}onSpanEnd(e){let t=e.status===`error`?`error`:e.type===`tool`||e.type===`workflow`?`info`:`debug`;this.log({level:t,message:e.name,fields:{...e.attributes,type:e.type,status:e.status,traceId:e.traceId,spanId:e.spanId,...e.parentSpanId?{parentSpanId:e.parentSpanId}:{},...e.endTime===void 0?{}:{durationMs:Math.round(e.endTime-e.startTime)}}})}onEvent(e,t){this.log({level:t.level,message:t.name,fields:{traceId:e.traceId,spanId:e.spanId,name:e.name,...t.attributes}})}};function re(e,t,n){if(!n)return;let r=ne(n);e?.info(t,{text:r}),r!==n&&e?.debug(t,{text:n})}function ie(e){let t=G(e.system??``),n=se(e.tools),r=se(e.mcpTools),i=ce(e.providerTools),a=e.messages.reduce((e,t)=>e+V(t),0),o=t+n+r+i+a;return{total:o,system:t,tools:n,mcpTools:r,providerTools:i,messages:a,...e.limit===void 0?{}:{limit:e.limit,free:Math.max(0,e.limit-o)}}}function V(e){switch(e.role){case`user`:return H(e.content);case`assistant`:return H(e.content);case`tool`:return e.content.reduce((e,t)=>e+oe(t),0)}}function H(e){return typeof e==`string`?G(e):e.reduce((e,t)=>e+ae(t),0)}function ae(e){switch(e.type){case`text`:return G(e.text);case`thinking`:return G(e.summary??e.text??``);case`tool-call`:return G(e.name)+W(e.parameters);case`provider-tool`:return G(e.name)+W(e.input)+W(e.output);case`citation`:return W(e.citations);case`file`:return W(e.file)}}function oe(e){return G(e.name)+U(e.content)}function U(e){return typeof e==`string`?G(e):e.reduce((e,t)=>t.type===`text`?e+G(t.text):e+W(t.file),0)}function se(e){let t=e?.map(le)??[];return t.length===0?0:W({tools:t})}function ce(e){return!e||e.length===0?0:W({providerTools:e})}function le(e){try{return{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}catch{return{name:e.name,description:e.description}}}function W(e){return e==null?0:G(JSON.stringify(e))}function G(e){return e?Math.ceil(e.length/3):0}function ue(e){if(e instanceof c.ZodString)return[`string`,`Your answer`];if(e instanceof c.ZodNumber)return[`number`,42];if(e instanceof c.ZodBoolean)return[`boolean`,!0];if(e instanceof c.ZodEnum){let t=e.options;return[t.map(fe).join(` | `),t[0]]}if(e instanceof c.ZodLiteral){let t=e.value;return[fe(t),t]}if(e instanceof c.ZodArray){let t=e.element;if(t instanceof c.ZodString)return[`string array`,[`answer 1`,`answer 2`,`third answer`]];if(t instanceof c.ZodNumber)return[`number array`,[42,59,3.14]];if(t instanceof c.ZodBoolean)return[`boolean array`,[!0,!1,!1]];if(t instanceof c.ZodObject){let[,e]=ue(t);return[`object array`,[e,e]]}else if(t instanceof c.ZodEnum||t instanceof c.ZodLiteral){let[e,n]=ue(t);return[`${e} array`,[n]]}return[`array`,[]]}if(e instanceof c.ZodObject){let t=e.shape,n={};for(let[e,r]of Object.entries(t)){let[,t]=ue(r);n[e]=t}return[`JSON object`,n]}if(e instanceof c.ZodOptional){let[t,n]=ue(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function de(e){if(e instanceof c.ZodObject)return Object.entries(e.shape).map(([e,t])=>{let[n]=ue(t);return[e,n]});let[t]=ue(e);return[[`response`,t]]}function fe(e){return typeof e==`string`?JSON.stringify(e):String(e)}function pe(e,t){if(!t)return e;let n=me(e);try{return t.parse(n)}catch(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Validation failed: ${t}`)}throw e}}function me(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i),r=n?n[1].trim():t;try{return JSON.parse(r)}catch(e){throw Error(`Cannot parse response as JSON: ${e.message}`)}}function he(e,t={}){if(typeof e==`string`)return{message:{role:`user`,id:crypto.randomUUID(),content:[{type:`text`,text:e}],...t.metadata?{metadata:t.metadata}:{}},parse:e=>ge(e,void 0)};let n=e.render(),r=e.files,i=e.schema,a=t.metadata??e.metadata;return{message:{role:`user`,id:crypto.randomUUID(),content:F({text:n,files:r}),...a?{metadata:a}:{}},parse:e=>ge(e,i)}}function ge(e,t){return e?pe(I(e.content),t):null}function K(){return{in:0,out:0}}function q(e,t){t&&(e.in+=t.in??0,e.out+=t.out??0,Se(e,`cachedIn`,t.cachedIn),Se(e,`cacheWriteIn`,t.cacheWriteIn),Se(e,`reasoningOut`,t.reasoningOut),t.breakdown?.length&&(e.breakdown=ye(e.breakdown,t.breakdown)))}function _e(...e){let t=K();for(let n of e)q(t,n);return t}function ve(e,t){return{...e,breakdown:[{provider:t.provider,model:t.model,in:e.in,out:e.out,...e.cachedIn===void 0?{}:{cachedIn:e.cachedIn},...e.cacheWriteIn===void 0?{}:{cacheWriteIn:e.cacheWriteIn},...e.reasoningOut===void 0?{}:{reasoningOut:e.reasoningOut}}]}}function ye(e,t){let n=e?[...e]:[];for(let e of t){let t=n.find(t=>t.provider===e.provider&&t.model===e.model);if(!t){n.push({...e});continue}t.in+=e.in,t.out+=e.out,Se(t,`cachedIn`,e.cachedIn),Se(t,`cacheWriteIn`,e.cacheWriteIn),Se(t,`reasoningOut`,e.reasoningOut)}return n}function be(e,t){return{...e,...Ce(`cachedIn`,t.cachedIn),...Ce(`cacheWriteIn`,t.cacheWriteIn),...Ce(`reasoningOut`,t.reasoningOut)}}function xe(e){if(e)return{inputTokens:e.in,outputTokens:e.out,...e.cachedIn===void 0?{}:{cachedInputTokens:e.cachedIn},...e.cacheWriteIn===void 0?{}:{cacheWriteInputTokens:e.cacheWriteIn},...e.reasoningOut===void 0?{}:{reasoningOutputTokens:e.reasoningOut}}}function Se(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function Ce(e,t){return typeof t==`number`?{[e]:t}:{}}var we=class{tools=new Map;mcpTools=new Map;providerTools=new Map;constructor(e){e?.tools&&this.add(e.tools),e?.providerTools&&this.addProvider(e.providerTools)}add(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.tools.set(e.name,e)}}addMcp(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.mcpTools.set(e.name,e)}}addProvider(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.providerTools.set(e.name,e)}}remove(e){let t=this.tools.delete(e),n=this.mcpTools.delete(e),r=this.providerTools.delete(e);return t||n||r}has(e){return this.tools.has(e)||this.mcpTools.has(e)||this.providerTools.has(e)}get(e){return this.tools.get(e)??this.mcpTools.get(e)}getProvider(e){return this.providerTools.get(e)}executable(){return[...this.tools.values(),...this.mcpTools.values()]}local(){return[...this.tools.values()]}mcp(){return[...this.mcpTools.values()]}provider(){return[...this.providerTools.values()]}get size(){return this.tools.size+this.mcpTools.size+this.providerTools.size}};const Te=c.object({query:c.string().trim().min(1).max(400)});function Ee(e){return{name:`web_search`,description:`Search the public web for current information. Returns source titles, URLs, and relevant extracted passages.`,schema:Te,async execute(t,n){n.span?.setAttribute(`webSearchBackend`,e.name);let r=await e.search({query:t.query},{signal:n.signal,span:n.span});return n.span?.setAttribute(`webSearchResultCount`,r.results.length),JSON.stringify({query:t.query,results:r.results})},summarize(e){return`Search the web for "${e.query}"`}}}function De(e){let t=e.apiKey.trim();if(!t)throw Error(`Brave Search apiKey is required`);let n=e.endpoint??`https://api.search.brave.com/res/v1/llm/context`,r=Oe(e.maxResults??5,`maxResults`,1,50),i=e.candidateCount===void 0?void 0:Oe(e.candidateCount,`candidateCount`,1,50),a=Oe(e.maxTokens??4096,`maxTokens`,1,32768),o=e.maxSnippets===void 0?void 0:Oe(e.maxSnippets,`maxSnippets`,1,256),s=e.maxTokensPerUrl===void 0?void 0:Oe(e.maxTokensPerUrl,`maxTokensPerUrl`,1,8192),c=e.maxSnippetsPerUrl===void 0?void 0:Oe(e.maxSnippetsPerUrl,`maxSnippetsPerUrl`,1,100),l=e.timeoutMs===void 0?void 0:Oe(e.timeoutMs,`timeoutMs`,1);return{name:`brave`,async search(u,d){let f=new URL(n);f.searchParams.set(`q`,u.query),f.searchParams.set(`maximum_number_of_urls`,String(r)),i!==void 0&&f.searchParams.set(`count`,String(i)),f.searchParams.set(`maximum_number_of_tokens`,String(a)),o!==void 0&&f.searchParams.set(`maximum_number_of_snippets`,String(o)),s!==void 0&&f.searchParams.set(`maximum_number_of_tokens_per_url`,String(s)),c!==void 0&&f.searchParams.set(`maximum_number_of_snippets_per_url`,String(c)),e.contextThresholdMode&&f.searchParams.set(`context_threshold_mode`,e.contextThresholdMode),e.country&&f.searchParams.set(`country`,e.country),e.searchLanguage&&f.searchParams.set(`search_lang`,e.searchLanguage),e.freshness&&f.searchParams.set(`freshness`,e.freshness);let p=l===void 0?void 0:AbortSignal.timeout(l),m=p?AbortSignal.any([d.signal,p]):d.signal,h=await fetch(f,{method:`GET`,headers:{Accept:`application/json`,"X-Subscription-Token":t},signal:m});if(!h.ok){let e=(await h.text().catch(()=>``)).replaceAll(t,`[REDACTED]`);throw Error(`Brave Search request failed with status ${h.status}${e?`: ${e}`:``}`)}let g=await h.json(),_=[],v=[...g.grounding?.generic??[],...g.grounding?.poi?[g.grounding.poi]:[],...g.grounding?.map??[]];for(let e of v){if(_.length>=r)break;!e.title||!e.url||!e.snippets?.length||_.push({title:e.title,url:e.url,snippets:e.snippets})}return{results:_}}}}function Oe(e,t,n,r){if(!Number.isInteger(e))throw Error(`${t} must be an integer`);if(e<n)throw Error(`${t} must be greater than or equal to ${n}`);if(r!==void 0&&e>r)throw Error(`${t} must be less than or equal to ${r}`);return e}function ke(e,t,n){t.usage&&q(e,n?ve(t.usage,n):t.usage)}function Ae(e,t){if(!e)return;re(e,`text`,I(t));let n=ee(t);n&&e.debug(`thinking`,{thinking:n});for(let n of te(t))e.info(n.name,{type:`provider-tool`,input:n.input}),n.output!==void 0&&e.trace(n.name,{type:`provider-tool`,output:n.output});je(e,R(t))}function je(e,t){if(t.length===0)return;let n=Me(t);e.info(`citations`,{count:t.length,sources:n.slice(0,8),...n.length>8?{more:n.length-8}:{}}),n.length>8&&e.debug(`citations`,{sources:n}),e.setAttribute(`citationCount`,t.length)}function Me(e){let t=new Set,n=[];for(let{source:r}of e){let e=Ne(r),i=`title`in r?r.title:void 0,a=e??i??r.type;t.has(a)||(t.add(a),n.push({type:r.type,...i?{title:i}:{},...e?{url:e}:{}}))}return n}function Ne(e){switch(e.type){case`web`:case`search-result`:return e.url;case`retrieved-context`:return e.uri;case`document`:return e.fileId;default:return}}function Pe(e){return JSON.stringify({error:e})}function Fe(e){let t=e.tools!==void 0||e.providerTools!==void 0;if(e.registry&&t)throw new A("Cannot specify both `registry` and `tools` / `providerTools`. Use one or the other.",{code:`TOOL_OPTIONS_CONFLICT`});return e.registry??new we({tools:e.tools,providerTools:e.providerTools})}function Ie(e,t){let n=e.getProvider(`web_search`),r=t.provider.resolveProviderToolName?.bind(t.provider);if(!r)return{registry:e,executable:()=>e.executable(),provider:()=>e.provider(),get:t=>e.get(t)};let i=()=>e.provider().map(e=>{let n=r(e.name,t.model);return n===void 0?e:{...e,nativeName:n}});if(!n||r(`web_search`,t.model)!==void 0)return{registry:e,executable:()=>e.executable(),provider:i,get:t=>e.get(t)};let a=t.configuration.webSearchFallback;if(!a)throw new A(`Provider ${t.provider.name} does not support native web_search and no Axle webSearchFallback is configured`,{code:`WEB_SEARCH_FALLBACK_NOT_CONFIGURED`,details:{provider:t.provider.name,model:t.model}});n.config&&t.span?.warn(`web_search provider config ignored by fallback backend`,{provider:t.provider.name,model:t.model,backend:a.name}),t.span?.info(`Using web search fallback backend`,{provider:t.provider.name,model:t.model,backend:a.name});let o=Ee(a);return{registry:e,executable:()=>[...e.executable().filter(e=>e.name!==`web_search`),o],provider:()=>i().filter(e=>e.name!==`web_search`),get:t=>t===`web_search`?o:e.get(t)}}async function Le(e,t=async()=>null,n,r,i,a){let o=[],s=K(),c=!1;for(let l of e){let e;try{e=await ze(l,t,n,r,i,a)}catch(e){throw c?Re(e,s):e}o.push(e.result),e.usage&&(q(s,e.usage),c=!0)}return{results:o,...c?{usage:s}:{}}}function Re(e,t){return e instanceof P?new P(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:_e(t,e.usage),cause:e.cause}):e instanceof M?new M(e.message,{reason:e.reason,messages:e.messages,partial:e.partial,usage:_e(t,e.usage)}):e}async function ze(e,t,n,r,i,a){if(n.aborted)throw new M(`Operation aborted`,{reason:n.reason});let o=r instanceof we?r:r.registry,s=r.get(e.name),c=i?.startSpan(e.name,{type:`tool`}),l,u={signal:n,span:c,registry:o,emit:t=>a?.onDelta?.(e,t),reportUsage:e=>{l??=K(),q(l,e)}};a?.onStart?.(e);let d,f=`exception`;try{if(d=await t(e.name,e.parameters,u),d==null&&s&&(f=`execution`,d={type:`success`,content:await s.execute(e.parameters,u)}),n.aborted)throw new M(`Operation aborted`,{reason:n.reason})}catch(t){let r=Be(t,n);if(r){c?.setResult({kind:`tool`,name:e.name,input:e.parameters,output:{type:r instanceof P?`fatal`:`aborted`,message:r.message}}),c?.end(r instanceof P?`error`:`ok`);let t=l?Re(r,l):r;throw a?.onError?.(e,t),t}d={type:`error`,error:{type:f,message:t instanceof Error?t.message:String(t)}}}d??={type:`error`,error:{type:`not-found`,message:`Tool not found: ${e.name}`}};let p={result:d,...l?{usage:l}:{}};a?.onComplete?.(e,p);let m=d.type===`success`?d.content:Pe(d.error);return c?.setResult({kind:`tool`,name:e.name,input:e.parameters,output:d.type===`success`?d.content:d.error}),c?.end(d.type===`success`?`ok`:`error`),{result:{id:e.id,name:e.name,content:m,...d.type===`error`?{isError:!0}:{}},...l?{usage:l}:{}}}function Be(e,t){if(e instanceof P||e instanceof M)return e;if(t.aborted)return new M(`Operation aborted`,{reason:t.reason})}let Ve=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function J(e,t){for(let n of e)n(t)}function He(e){return{name:e.name,description:e.description,schema:e.schema}}function Ue(e){let t=[],n,r;if(`instruct`in e){let{instruct:t,messages:i,...a}=e,o=he(t);r=o.parse,n={...a,messages:[...i??[],o.message]}}else n=e;let i=new AbortController,a=n.signal?AbortSignal.any([i.signal,n.signal]):i.signal,{promise:o,resolve:s,reject:c}=Promise.withResolvers(),l=k();return Promise.resolve().then(()=>We(n,a,t,l).then(e=>{if(r&&e.ok){try{s({...e,response:r(e.final)})}catch(t){s({ok:!1,messages:e.messages,final:e.final,usage:e.usage,error:{kind:`parse`,error:t,message:t instanceof Error?t.message:String(t)}})}return}s(e)},c)),{on(e){t.push(e)},cancel(e){i.abort(e)},get final(){return o}}}async function We(e,t,n,r){let{provider:i,model:a,messages:o,system:s,onToolCall:c,maxIterations:l,span:u,fileResolver:d,reasoning:f,maxOutputTokens:p,temperature:m,topP:h,stop:g,toolChoice:_,parallelToolCalls:v,providerOptions:y}=e,b=Ie(Fe(e),{provider:i,model:a,span:u,configuration:r}),x=[...o],S=[],C=K(),w=0,T=0,E=e=>{x.push(e),S.push(e)},D=e=>{e.ok||J(n,{type:`error`,error:e.error});let t=e.ok?e.final.content:null,r=e.ok?e.final.finishReason:void 0;return u?.setResult({kind:`llm`,model:a,request:{messages:o},response:{content:t??null},usage:xe(e.usage),finishReason:r}),u?.end(e.ok?`ok`:`error`),e},O=(e,n,r,i)=>{i();let a=e.length?{role:`assistant`,id:n,model:r,content:e,finishReason:`cancelled`}:void 0;throw a&&E(a),u?.end(`ok`),new M(`Stream aborted`,{reason:t.reason,messages:S,partial:a,usage:C})};for(;;){if(t.aborted&&O([],``,``,()=>{}),l!==void 0&&T>=l)return D({ok:!1,messages:S,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${l})`}}},usage:C});T+=1;let e=u?.startSpan(`turn-${T}`,{type:`llm`}),r=b.executable(),o=r.length>0?r.map(He):void 0,k=b.provider(),A=i.createStreamingRequest(a,{messages:x,system:s,tools:o,providerTools:k.length>0?k:void 0,runtime:{span:e,fileResolver:d},signal:t,reasoning:f,maxOutputTokens:p,temperature:m,topP:h,stop:g,toolChoice:_,parallelToolCalls:v,providerOptions:y}),j=[],N=``,F=``,I=null,ee=K(),L=-1,te=null,R=``,ne=new Map,z=new Map,B=new Map,re=new Set,ie=(e,t)=>{J(n,{type:`tool:request`,index:ne.get(e)??-1,id:e,name:t,kind:b.get(t)?.kind??`tool`})},V=-1,H=()=>{te!==null&&L>=0&&(J(n,{type:te===`text`?`text:end`:`thinking:end`,index:L,final:R}),te=null,R=``,L=-1)};for await(let r of A){switch(r.type){case`start`:N=r.id,F=r.data.model,J(n,{type:`turn:start`,id:N,model:F});break;case`text-start`:H(),j.push({type:`text`,text:``}),V=j.length-1,L=w++,z.set(r.data.index,V),B.set(r.data.index,L),te=`text`,R=``,J(n,{type:`text:start`,index:L});break;case`text-delta`:{let e=j[V];e.text+=r.data.text,R=e.text,J(n,{type:`text:delta`,index:L,delta:r.data.text,accumulated:R});break}case`text-citation`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??L,i=j[e];if(!i||i.type!==`text`)break;i.citations=[...i.citations??[],r.data.citation],J(n,{type:`text:citation`,index:t,citation:r.data.citation,citations:i.citations});break}case`citation`:{H();let e=w++;j.push({type:`citation`,citations:r.data.citations,...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),V=j.length-1,z.set(r.data.index,V),B.set(r.data.index,e),J(n,{type:`citation`,index:e,citations:r.data.citations,providerMetadata:r.data.providerMetadata});break}case`text-complete`:H();break;case`thinking-start`:H(),j.push({type:`thinking`,text:``,...r.data.id?{id:r.data.id}:{},...r.data.redacted===void 0?{}:{redacted:r.data.redacted},...r.data.continuity?{continuity:r.data.continuity}:{},...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),V=j.length-1,L=w++,z.set(r.data.index,V),B.set(r.data.index,L),te=`thinking`,R=``,J(n,{type:`thinking:start`,index:L,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break;case`thinking-delta`:{let e=j[V];e.text=(e.text??``)+r.data.text,R=e.text,J(n,{type:`thinking:delta`,index:L,delta:r.data.text,accumulated:R});break}case`thinking-summary-delta`:{let e=j[V];e.summary=(e.summary??``)+r.data.text,R=e.summary,J(n,{type:`thinking:summary-delta`,index:L,delta:r.data.text,accumulated:R});break}case`thinking-metadata`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??L,i=j[e];if(!i||i.type!==`thinking`)break;r.data.redacted!==void 0&&(i.redacted=r.data.redacted),r.data.continuity&&(i.continuity=r.data.continuity),r.data.providerMetadata&&(i.providerMetadata=r.data.providerMetadata),J(n,{type:`thinking:update`,index:t,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break}case`thinking-complete`:H();break;case`tool-call-start`:{H();let e=w++;j.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),V=j.length-1,z.set(r.data.index,V),B.set(r.data.index,e),ne.set(r.data.id,e),r.data.name?ie(r.data.id,r.data.name):re.add(r.data.id);break}case`tool-call-args-delta`:re.has(r.data.id)&&r.data.name&&(re.delete(r.data.id),ie(r.data.id,r.data.name)),J(n,{type:`tool:args-delta`,index:ne.get(r.data.id)??-1,id:r.data.id,name:r.data.name,delta:r.data.delta,accumulated:r.data.accumulated});break;case`tool-call-complete`:{let e=j[z.get(r.data.index)??V];if(!e||e.type!==`tool-call`)break;r.data.id&&(e.id=r.data.id),r.data.name&&(e.name=r.data.name),e.parameters=r.data.arguments,r.data.providerMetadata&&(e.providerMetadata=r.data.providerMetadata),re.has(e.id)&&e.name&&(re.delete(e.id),ie(e.id,e.name));break}case`provider-tool-start`:{H();let e=w++;j.push({type:`provider-tool`,id:r.data.id,name:r.data.name}),V=j.length-1,z.set(r.data.index,V),B.set(r.data.index,e),J(n,{type:`provider-tool:start`,index:e,id:r.data.id,name:r.data.name});break}case`provider-tool-complete`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??r.data.index,i=j[e];i&&i.type===`provider-tool`&&r.data.output!=null&&(i.output=r.data.output),J(n,{type:`provider-tool:complete`,index:t,id:r.data.id,name:r.data.name,output:r.data.output});break}case`complete`:H(),I=r.data.finishReason,ee=r.data.usage;break;case`error`:return H(),r.data.usage&&q(C,ve(r.data.usage,{provider:i.name,model:F||a})),e?.end(`error`),D({ok:!1,messages:S,error:{kind:`model`,error:{type:`error`,error:{type:r.data.type,message:r.data.message}}},usage:C});default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.aborted)break}if(t.aborted&&(e?.end(`ok`),O(j,N,F,H)),I===null)return H(),e?.end(`error`),D({ok:!1,messages:S,error:{kind:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:C});let ae=ve(ee,{provider:i.name,model:F||a});q(C,ae);let oe={kind:`llm`,model:F,request:{messages:x},response:{content:j},usage:xe(ee),finishReason:I};Ae(e,j),e?.setResult(oe),e?.end();let U={role:`assistant`,id:N,model:F,content:j,finishReason:I};if(E(U),J(n,{type:`turn:complete`,message:U,usage:ae}),I!==`function_call`)return D({ok:!0,response:U,messages:S,final:U,usage:C});let se=j.filter(e=>e.type===`tool-call`);if(se.length===0)return D({ok:!0,response:U,messages:S,final:U,usage:C});if(t.aborted)throw u?.end(`ok`),new M(`Stream aborted`,{reason:t.reason,messages:S,usage:C});let ce=crypto.randomUUID();J(n,{type:`tool-results:start`,id:ce});let le={onStart(e){J(n,{type:`tool:exec-start`,index:ne.get(e.id)??-1,id:e.id,name:e.name,parameters:e.parameters})},onDelta(e,t){J(n,{type:`tool:exec-delta`,index:ne.get(e.id)??-1,id:e.id,name:e.name,chunk:t})},onComplete(e,t){J(n,{type:`tool:exec-complete`,index:ne.get(e.id)??-1,id:e.id,name:e.name,result:t.result,usage:t.usage})},onError(e,t){J(n,{type:`tool:exec-error`,index:ne.get(e.id)??-1,id:e.id,name:e.name,error:{type:t instanceof P?`fatal`:`aborted`,message:t.message},usage:t.usage})}},W,G;try{({results:W,usage:G}=await Le(se,c,t,b,u,le))}catch(e){throw e instanceof P?(u?.end(`error`),new P(e.message,{toolName:e.toolName,messages:e.messages??S,partial:e.partial??U,usage:_e(C,e.usage),cause:e.cause})):e instanceof M?(u?.end(`ok`),new M(`Stream aborted`,{reason:e.reason,messages:e.messages??S,partial:e.partial,usage:_e(C,e.usage)})):e}if(q(C,G),W.length>0){let e={role:`tool`,id:ce,content:W};E(e),J(n,{type:`tool-results:complete`,message:e})}}}function Ge(e=new Date){return{start:e.toISOString()}}function Y(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var Ke=class{currentTurnId=null;currentTurnTiming;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage=K();createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=Y(Ge(r),r),a=()=>({...i});if(typeof e.content==`string`)n.push({id:crypto.randomUUID(),type:`text`,text:e.content,timing:a()});else for(let t of e.content)t.type===`text`?n.push({id:crypto.randomUUID(),type:`text`,text:t.text,...t.citations?{citations:t.citations}:{},...t.providerMetadata?{providerMetadata:t.providerMetadata}:{},timing:a()}):t.type===`file`&&n.push({id:crypto.randomUUID(),type:`file`,file:t.file,timing:a()});return[{type:`turn:user`,turn:{id:t,owner:`user`,parts:n,status:`complete`,timing:i,...e.metadata?{metadata:e.metadata}:{}}}]}startAgentTurn(){let e=crypto.randomUUID();return this.currentTurnId=e,this.currentTurnTiming=Ge(),this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage=K(),{type:`turn:start`,turnId:e,timing:this.currentTurnTiming}}handleStreamEvent(e){let t=this.currentTurnId;if(!t)return[];let n=[];switch(e.type){case`turn:start`:break;case`text:start`:{this.closeOpenParts(n);let e=crypto.randomUUID(),r={id:e,type:`text`,text:``,timing:Ge()};this.currentTextPart={id:e,timing:r.timing},n.push({type:`part:start`,turnId:t,part:r});break}case`text:delta`:this.currentTextPart&&n.push({type:`text:delta`,turnId:t,partId:this.currentTextPart.id,delta:e.delta});break;case`text:end`:if(this.currentTextPart){let e=Y(this.currentTextPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:e}),this.currentTextPart=null}break;case`citation`:{this.closeOpenParts(n);let r=Y(Ge()),i={id:crypto.randomUUID(),type:`citation`,citations:e.citations,...e.providerMetadata?{providerMetadata:e.providerMetadata}:{},timing:r};n.push({type:`part:start`,turnId:t,part:i}),n.push({type:`part:end`,turnId:t,partId:i.id,timing:r});break}case`thinking:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i={id:r,type:`thinking`,text:``,timing:Ge(),...e.redacted===void 0?{}:{redacted:e.redacted},...e.continuity?{continuity:e.continuity}:{},...e.providerMetadata?{providerMetadata:e.providerMetadata}:{}};this.currentThinkingPart={id:r,timing:i.timing},n.push({type:`part:start`,turnId:t,part:i});break}case`thinking:delta`:this.currentThinkingPart&&n.push({type:`thinking:delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`text:citation`:this.currentTextPart&&n.push({type:`text:citation`,turnId:t,partId:this.currentTextPart.id,citation:e.citation});break;case`thinking:summary-delta`:this.currentThinkingPart&&n.push({type:`thinking:summary-delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`thinking:update`:this.currentThinkingPart&&n.push({type:`thinking:update`,turnId:t,partId:this.currentThinkingPart.id,redacted:e.redacted,continuity:e.continuity,providerMetadata:e.providerMetadata});break;case`thinking:end`:if(this.currentThinkingPart){let e=Y(this.currentThinkingPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:e}),this.currentThinkingPart=null}break;case`tool:request`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=Ge(),a=e.kind===`agent`?{id:r,type:`action`,kind:`agent`,status:`pending`,timing:i,detail:{name:e.name,children:[]}}:{id:r,type:`action`,kind:`tool`,status:`pending`,timing:i,detail:{name:e.name,parameters:{}}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i,name:e.name,kind:e.kind}),n.push({type:`part:start`,turnId:t,part:a});break}case`tool:args-delta`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:args-delta`,turnId:t,partId:r.partId,delta:e.delta,accumulated:e.accumulated});break}case`tool:exec-start`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:running`,turnId:t,partId:r.partId,parameters:e.parameters});break}case`tool:exec-delta`:{let r=this.toolIdMap.get(e.id);r&&(typeof e.chunk==`string`?n.push({type:`action:progress`,turnId:t,partId:r.partId,chunk:e.chunk}):e.chunk.type===`turn-event`&&n.push({type:`action:child-event`,turnId:t,partId:r.partId,event:e.chunk.event}));break}case`tool:exec-complete`:{let r=this.toolIdMap.get(e.id);if(r){q(this.accumulatedUsage,e.usage);let i=Y(r.timing);r.timing=i,e.result.type===`success`?n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.result.content},timing:i}):n.push({type:`action:error`,turnId:t,partId:r.partId,error:e.result.error,timing:i})}break}case`tool:exec-error`:{let r=this.toolIdMap.get(e.id);if(r){q(this.accumulatedUsage,e.usage);let i=Y(r.timing);r.timing=i,n.push({type:`action:error`,turnId:t,partId:r.partId,error:e.error,timing:i})}break}case`provider-tool:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=Ge(),a={id:r,type:`action`,kind:`provider-tool`,status:`running`,timing:i,detail:{name:e.name}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i}),n.push({type:`part:start`,turnId:t,part:a}),n.push({type:`action:running`,turnId:t,partId:r});break}case`provider-tool:complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=Y(r.timing);r.timing=i,n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.output},timing:i})}break}case`turn:complete`:this.closeOpenParts(n),q(this.accumulatedUsage,e.usage);break;case`tool-results:start`:case`tool-results:complete`:break;case`error`:{let t=e.error,r=t.kind===`model`?t.error.error.message:t.kind===`tool`?`Tool error (${t.error.name}): ${t.error.message}`:`Parse error: ${t.message}`;n.push({type:`error`,error:{type:t.kind,message:r}});break}}return n}finalizeTurn(e=`complete`){let t=this.currentTurnId;if(!t)return[];let n=[];this.closeOpenParts(n);let r=Y(this.currentTurnTiming);return n.push({type:`turn:end`,turnId:t,status:e,usage:{...this.accumulatedUsage},timing:r}),this.currentTurnId=null,this.currentTurnTiming=void 0,n}closeOpenParts(e){let t=this.currentTurnId;t&&(this.currentTextPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:Y(this.currentTextPart.timing)}),null),this.currentThinkingPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:Y(this.currentThinkingPart.timing)}),null))}};function qe(e){return Array.isArray(e)?e:[e]}function Je(e){return e.then(()=>{},()=>{})}function Ye(e,t,n){let r=new AbortController,i=n?AbortSignal.any([n,r.signal]):r.signal,a=e.then(()=>t(i));return{handle:{cancel:e=>r.abort(e),get final(){return a}},settled:Je(a)}}var Xe=class{_turns=[];_log=[];_sessionAnnotations=[];constructor(e){e?.turns&&(this._turns=[...e.turns]),e?.log&&(this._log=[...e.log]),e?.sessionAnnotations&&(this._sessionAnnotations=[...e.sessionAnnotations])}get turns(){return[...this._turns]}get log(){return[...this._log]}get sessionAnnotations(){return[...this._sessionAnnotations]}addTurn(e){this._turns.push(e)}replaceTurns(e){this._turns=[...e]}replaceLog(e){this._log=[...e]}replaceSessionAnnotations(e=[]){this._sessionAnnotations=[...e]}appendToLog(e){Array.isArray(e)?this._log.push(...e):this._log.push(e)}latestTurn(){return this._turns[this._turns.length-1]}toString(){return JSON.stringify({turns:this._turns,sessionAnnotations:this._sessionAnnotations})}};const Ze={trace:0,debug:1,info:2,warn:3,error:4},Qe=()=>performance.timeOrigin+performance.now();var $e=class{writers=[];minLevel=`info`;addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}shouldLog(e){return Ze[e]>=Ze[this.minLevel]}spanStart(e){for(let t of this.writers)t.onSpanStart(e)}spanEnd(e){for(let t of this.writers)t.onSpanEnd(e)}spanUpdate(e){for(let t of this.writers)t.onSpanUpdate?.(e)}event(e,t){for(let n of this.writers)n.onEvent?.(e,t)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}},et=class{rec=new $e;constructor(e){e?.minLevel&&(this.rec.minLevel=e.minLevel);for(let t of e?.writers??[])this.rec.addWriter(t)}get minLevel(){return this.rec.minLevel}set minLevel(e){this.rec.minLevel=e}addWriter(e){this.rec.addWriter(e)}removeWriter(e){this.rec.removeWriter(e)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:Qe(),status:`ok`,attributes:{...t?.attributes??{}},events:[]};return this.rec.spanStart(n),new tt(n,this.rec)}flush(){return this.rec.flush()}},tt=class e{data;rec;ended=!1;constructor(e,t){this.data=e,this.rec=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:Qe(),status:`ok`,attributes:{...n?.attributes??{}},events:[]};return this.rec.spanStart(r),new e(r,this.rec)}end(e=`ok`){this.ended||(this.ended=!0,this.data.endTime=Qe(),this.data.status=e,this.rec.spanEnd(this.data))}addEvent(e,t,n){if(this.ended||!this.rec.shouldLog(t))return;let r={name:e,timestamp:Qe(),level:t,attributes:n};this.data.events.push(r),this.rec.event(this.data,r)}trace(e,t){this.addEvent(e,`trace`,t)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,this.rec.spanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.rec.spanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.rec.spanUpdate(this.data))}};function nt(e){if(!e)return{};let{trace:t,log:n,level:r}=e;if(t)return n&&console.warn(`[axle] observability.log is ignored when observability.trace is set; add a LogWriter to your tracer's writers instead`),{parent:t};if(n){let e=new et({minLevel:r,writers:[new B(n)]});return{parent:e,owned:e}}return{}}function rt(e){return it(e)?`cancelled`:`error`}function it(e){return e instanceof M||e instanceof N||e instanceof Error&&e.name===`AbortError`}function at(e,t){return{...e,...t,providerOptions:e?.providerOptions||t?.providerOptions?{...e?.providerOptions,...t?.providerOptions}:void 0}}var ot=class{provider;model;history;name;fileResolver;requestOptions;registry;sessionId;system;mcps=[];resolvedMcps=new WeakSet;memory;spanParent;ownedTracer;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e,t){this.provider=e.provider,this.model=e.model,this.sessionId=e.sessionId??crypto.randomUUID(),this.history=new Xe;let n=nt(e.observability);if(this.spanParent=n.parent,this.ownedTracer=n.owned,this.system=e.system,this.name=e.name,this.fileResolver=e.fileResolver,this.requestOptions={reasoning:e.reasoning,maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,stop:e.stop,toolChoice:e.toolChoice,parallelToolCalls:e.parallelToolCalls,providerOptions:e.providerOptions},this.registry=new we({tools:e.tools,providerTools:e.providerTools}),e.mcps&&(this.mcps=[...e.mcps]),e.memory){this.memory=e.memory;let t=e.memory.tools?.();t&&this.registry.add(t)}t&&this.restore(t)}addMcp(e){this.mcps.push(e)}addMcps(e){this.mcps.push(...e)}hasTools(){return this.registry.size>0||this.mcps.length>0}on(e){return this.eventCallbacks.push(e),()=>{let t=this.eventCallbacks.indexOf(e);t>=0&&this.eventCallbacks.splice(t,1)}}context(){return ie({system:this.system,messages:this.history.log,tools:this.toToolDefinitions(this.registry.local()),providerTools:this.registry.provider(),mcpTools:this.toToolDefinitions(this.registry.mcp())})}snapshot(){let e=this.history.sessionAnnotations;return{version:1,sessionId:this.sessionId,messages:this.history.log,turns:this.history.turns,sessionAnnotations:e.length>0?e:void 0}}restore(e){if(e.version!==1)throw new A(`Unsupported agent session version: ${e.version}`);this.sessionId=e.sessionId,this.history.replaceLog(e.messages),this.history.replaceTurns(e.turns??[]),this.history.replaceSessionAnnotations(e.sessionAnnotations??[])}send(e,t){let{fileResolver:n,metadata:r,...i}=t??{},a=he(e,{metadata:r}),o=at(this.requestOptions,i),{handle:s,settled:c}=Ye(this.sendQueue,async e=>{let t=this.spanParent?.startSpan(`agent.send`,{type:`workflow`,attributes:{sessionId:this.sessionId,...this.name?{agentName:this.name}:{}}});re(t,`message`,I(a.message.content));let r=`ok`;try{let i=await this.run(a,{signal:e,fileResolver:n,requestOptions:o,span:t});return i.ok||(r=`error`),t?.setAttributes({inputTokens:i.usage.in,outputTokens:i.usage.out}),i}catch(e){throw r=rt(e),t?.error(e instanceof Error?e.message:String(e)),e}finally{t?.end(r),await this.ownedTracer?.flush()}},i.signal);return this.sendQueue=c,s}async resolveMcpTools(e,t){for(let n of this.mcps){if(this.resolvedMcps.has(n))continue;let r=await n.listTools({prefix:n.name,span:t,signal:e});this.registry.addMcp(r),this.resolvedMcps.add(n)}}emitEvent(e){for(let t of this.eventCallbacks)t(e)}toToolDefinitions(e){return e.map(e=>({name:e.name,description:e.description,schema:e.schema}))}async run(t,n){let{signal:r,fileResolver:i,requestOptions:a}=n,o=n.span,s=new Ke,c=new e({turns:this.history.turns,sessionAnnotations:this.history.sessionAnnotations}),l,u=e=>{let t=c.apply(e);t.handled&&(this.history.replaceTurns(t.state.turns),this.history.replaceSessionAnnotations(t.state.sessionAnnotations??[])),this.emitEvent(e)},d=()=>l?c.state.turns.find(e=>e.id===l):void 0,f=K();if(r.aborted)throw new N(`Agent send aborted`,{reason:r.reason,usage:f});try{await this.resolveMcpTools(r,o)}catch(e){throw r.aborted||e instanceof M||e instanceof Error&&e.name===`AbortError`?new N(`Agent send aborted`,{reason:e instanceof M?e.reason:r.reason,usage:f}):e}let p=this.system,m=[...this.history.log,t.message];if(this.memory){let e=await this.memory.recall({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:m,span:o});e.systemSuffix&&(p=(p??``)+`
5
+ `)}function I(e){return e.filter(e=>e.type===`tool-call`)}function ne(e){return e.filter(e=>e.type===`provider-tool`)}function L(e){let t=[];for(let n of e)(n.type===`text`&&n.citations||n.type===`citation`)&&t.push(...n.citations);return t}function R(e,t=500){return e.length>t?`${e.slice(0,t)}… (${e.length} chars)`:e}function re(e,t=600){if(e.length<=t)return e;let n=Math.floor(t/2);return`${e.slice(0,n)}…[${e.length} chars]…${e.slice(-n)}`}var z=class{log;constructor(e){this.log=e}onSpanStart(){}onSpanEnd(e){let t=e.status===`error`?`error`:e.type===`tool`||e.type===`workflow`?`info`:`debug`;this.log({level:t,message:e.name,fields:{...e.attributes,type:e.type,status:e.status,traceId:e.traceId,spanId:e.spanId,...e.parentSpanId?{parentSpanId:e.parentSpanId}:{},...e.endTime===void 0?{}:{durationMs:Math.round(e.endTime-e.startTime)}}})}onEvent(e,t){this.log({level:t.level,message:t.name,fields:{traceId:e.traceId,spanId:e.spanId,name:e.name,...t.attributes}})}};function B(e,t,n){if(!n)return;let r=R(n);e?.info(t,{text:r}),r!==n&&e?.debug(t,{text:n})}function ie(e){let t=G(e.system??``),n=U(e.tools),r=U(e.mcpTools),i=ce(e.providerTools),a=e.messages.reduce((e,t)=>e+ae(t),0),o=t+n+r+i+a;return{total:o,system:t,tools:n,mcpTools:r,providerTools:i,messages:a,...e.limit===void 0?{}:{limit:e.limit,free:Math.max(0,e.limit-o)}}}function ae(e){switch(e.role){case`user`:return V(e.content);case`assistant`:return V(e.content);case`tool`:return e.content.reduce((e,t)=>e+oe(t),0)}}function V(e){return typeof e==`string`?G(e):e.reduce((e,t)=>e+H(t),0)}function H(e){switch(e.type){case`text`:return G(e.text);case`thinking`:return G(e.summary??e.text??``);case`tool-call`:return G(e.name)+W(e.parameters);case`provider-tool`:return G(e.name)+W(e.input)+W(e.output);case`citation`:return W(e.citations);case`file`:return W(e.file)}}function oe(e){return G(e.name)+se(e.content)}function se(e){return typeof e==`string`?G(e):e.reduce((e,t)=>t.type===`text`?e+G(t.text):e+W(t.file),0)}function U(e){let t=e?.map(le)??[];return t.length===0?0:W({tools:t})}function ce(e){return!e||e.length===0?0:W({providerTools:e})}function le(e){try{return{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}catch{return{name:e.name,description:e.description}}}function W(e){return e==null?0:G(JSON.stringify(e))}function G(e){return e?Math.ceil(e.length/3):0}function ue(e){if(e instanceof c.ZodString)return[`string`,`Your answer`];if(e instanceof c.ZodNumber)return[`number`,42];if(e instanceof c.ZodBoolean)return[`boolean`,!0];if(e instanceof c.ZodEnum){let t=e.options;return[t.map(fe).join(` | `),t[0]]}if(e instanceof c.ZodLiteral){let t=e.value;return[fe(t),t]}if(e instanceof c.ZodArray){let t=e.element;if(t instanceof c.ZodString)return[`string array`,[`answer 1`,`answer 2`,`third answer`]];if(t instanceof c.ZodNumber)return[`number array`,[42,59,3.14]];if(t instanceof c.ZodBoolean)return[`boolean array`,[!0,!1,!1]];if(t instanceof c.ZodObject){let[,e]=ue(t);return[`object array`,[e,e]]}else if(t instanceof c.ZodEnum||t instanceof c.ZodLiteral){let[e,n]=ue(t);return[`${e} array`,[n]]}return[`array`,[]]}if(e instanceof c.ZodObject){let t=e.shape,n={};for(let[e,r]of Object.entries(t)){let[,t]=ue(r);n[e]=t}return[`JSON object`,n]}if(e instanceof c.ZodOptional){let[t,n]=ue(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function de(e){if(e instanceof c.ZodObject)return Object.entries(e.shape).map(([e,t])=>{let[n]=ue(t);return[e,n]});let[t]=ue(e);return[[`response`,t]]}function fe(e){return typeof e==`string`?JSON.stringify(e):String(e)}function pe(e,t){if(!t)return e;let n=me(e);try{return t.parse(n)}catch(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Validation failed: ${t}`)}throw e}}function me(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i),r=n?n[1].trim():t;try{return JSON.parse(r)}catch(e){throw Error(`Cannot parse response as JSON: ${e.message}`)}}function he(e,t={}){if(typeof e==`string`)return{message:{role:`user`,id:crypto.randomUUID(),content:[{type:`text`,text:e}],...t.metadata?{metadata:t.metadata}:{}},parse:e=>ge(e,void 0)};let n=e.render(),r=e.files,i=e.schema,a=t.metadata??e.metadata;return{message:{role:`user`,id:crypto.randomUUID(),content:ee({text:n,files:r}),...a?{metadata:a}:{}},parse:e=>ge(e,i)}}function ge(e,t){return e?pe(F(e.content),t):null}function K(){return{in:0,out:0}}function q(e,t){t&&(e.in+=t.in??0,e.out+=t.out??0,Se(e,`cachedIn`,t.cachedIn),Se(e,`cacheWriteIn`,t.cacheWriteIn),Se(e,`reasoningOut`,t.reasoningOut),t.breakdown?.length&&(e.breakdown=ye(e.breakdown,t.breakdown)))}function _e(...e){let t=K();for(let n of e)q(t,n);return t}function ve(e,t){return{...e,breakdown:[{provider:t.provider,model:t.model,in:e.in,out:e.out,...e.cachedIn===void 0?{}:{cachedIn:e.cachedIn},...e.cacheWriteIn===void 0?{}:{cacheWriteIn:e.cacheWriteIn},...e.reasoningOut===void 0?{}:{reasoningOut:e.reasoningOut}}]}}function ye(e,t){let n=e?[...e]:[];for(let e of t){let t=n.find(t=>t.provider===e.provider&&t.model===e.model);if(!t){n.push({...e});continue}t.in+=e.in,t.out+=e.out,Se(t,`cachedIn`,e.cachedIn),Se(t,`cacheWriteIn`,e.cacheWriteIn),Se(t,`reasoningOut`,e.reasoningOut)}return n}function be(e,t){return{...e,...Ce(`cachedIn`,t.cachedIn),...Ce(`cacheWriteIn`,t.cacheWriteIn),...Ce(`reasoningOut`,t.reasoningOut)}}function xe(e){if(e)return{inputTokens:e.in,outputTokens:e.out,...e.cachedIn===void 0?{}:{cachedInputTokens:e.cachedIn},...e.cacheWriteIn===void 0?{}:{cacheWriteInputTokens:e.cacheWriteIn},...e.reasoningOut===void 0?{}:{reasoningOutputTokens:e.reasoningOut}}}function Se(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function Ce(e,t){return typeof t==`number`?{[e]:t}:{}}var we=class{tools=new Map;mcpTools=new Map;providerTools=new Map;constructor(e){e?.tools&&this.add(e.tools),e?.providerTools&&this.addProvider(e.providerTools)}add(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.tools.set(e.name,e)}}addMcp(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.mcpTools.set(e.name,e)}}addProvider(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.providerTools.set(e.name,e)}}remove(e){let t=this.tools.delete(e),n=this.mcpTools.delete(e),r=this.providerTools.delete(e);return t||n||r}has(e){return this.tools.has(e)||this.mcpTools.has(e)||this.providerTools.has(e)}get(e){return this.tools.get(e)??this.mcpTools.get(e)}getProvider(e){return this.providerTools.get(e)}executable(){return[...this.tools.values(),...this.mcpTools.values()]}local(){return[...this.tools.values()]}mcp(){return[...this.mcpTools.values()]}provider(){return[...this.providerTools.values()]}get size(){return this.tools.size+this.mcpTools.size+this.providerTools.size}};const Te=c.object({query:c.string().trim().min(1).max(400)});function Ee(e){return{name:`web_search`,description:`Search the public web for current information. Returns source titles, URLs, and relevant extracted passages.`,schema:Te,async execute(t,n){n.span?.setAttribute(`webSearchBackend`,e.name);let r=await e.search({query:t.query},{signal:n.signal,span:n.span});return n.span?.setAttribute(`webSearchResultCount`,r.results.length),JSON.stringify({query:t.query,results:r.results})},summarize(e){return`Search the web for "${e.query}"`}}}function De(e){let t=e.apiKey.trim();if(!t)throw Error(`Brave Search apiKey is required`);let n=e.endpoint??`https://api.search.brave.com/res/v1/llm/context`,r=Oe(e.maxResults??5,`maxResults`,1,50),i=e.candidateCount===void 0?void 0:Oe(e.candidateCount,`candidateCount`,1,50),a=Oe(e.maxTokens??4096,`maxTokens`,1,32768),o=e.maxSnippets===void 0?void 0:Oe(e.maxSnippets,`maxSnippets`,1,256),s=e.maxTokensPerUrl===void 0?void 0:Oe(e.maxTokensPerUrl,`maxTokensPerUrl`,1,8192),c=e.maxSnippetsPerUrl===void 0?void 0:Oe(e.maxSnippetsPerUrl,`maxSnippetsPerUrl`,1,100),l=e.timeoutMs===void 0?void 0:Oe(e.timeoutMs,`timeoutMs`,1);return{name:`brave`,async search(u,d){let f=new URL(n);f.searchParams.set(`q`,u.query),f.searchParams.set(`maximum_number_of_urls`,String(r)),i!==void 0&&f.searchParams.set(`count`,String(i)),f.searchParams.set(`maximum_number_of_tokens`,String(a)),o!==void 0&&f.searchParams.set(`maximum_number_of_snippets`,String(o)),s!==void 0&&f.searchParams.set(`maximum_number_of_tokens_per_url`,String(s)),c!==void 0&&f.searchParams.set(`maximum_number_of_snippets_per_url`,String(c)),e.contextThresholdMode&&f.searchParams.set(`context_threshold_mode`,e.contextThresholdMode),e.country&&f.searchParams.set(`country`,e.country),e.searchLanguage&&f.searchParams.set(`search_lang`,e.searchLanguage),e.freshness&&f.searchParams.set(`freshness`,e.freshness);let p=l===void 0?void 0:AbortSignal.timeout(l),m=p?AbortSignal.any([d.signal,p]):d.signal,h=await fetch(f,{method:`GET`,headers:{Accept:`application/json`,"X-Subscription-Token":t},signal:m});if(!h.ok){let e=(await h.text().catch(()=>``)).replaceAll(t,`[REDACTED]`);throw Error(`Brave Search request failed with status ${h.status}${e?`: ${e}`:``}`)}let g=await h.json(),_=[],v=[...g.grounding?.generic??[],...g.grounding?.poi?[g.grounding.poi]:[],...g.grounding?.map??[]];for(let e of v){if(_.length>=r)break;!e.title||!e.url||!e.snippets?.length||_.push({title:e.title,url:e.url,snippets:e.snippets})}return{results:_}}}}function Oe(e,t,n,r){if(!Number.isInteger(e))throw Error(`${t} must be an integer`);if(e<n)throw Error(`${t} must be greater than or equal to ${n}`);if(r!==void 0&&e>r)throw Error(`${t} must be less than or equal to ${r}`);return e}function ke(e,t,n){t.usage&&q(e,n?ve(t.usage,n):t.usage)}function Ae(e,t){if(!e)return;B(e,`text`,F(t));let n=te(t);n&&e.debug(`thinking`,{thinking:n});for(let n of ne(t))e.info(n.name,{type:`provider-tool`,input:n.input}),n.output!==void 0&&e.trace(n.name,{type:`provider-tool`,output:n.output});je(e,L(t))}function je(e,t){if(t.length===0)return;let n=Me(t);e.info(`citations`,{count:t.length,sources:n.slice(0,8),...n.length>8?{more:n.length-8}:{}}),n.length>8&&e.debug(`citations`,{sources:n}),e.setAttribute(`citationCount`,t.length)}function Me(e){let t=new Set,n=[];for(let{source:r}of e){let e=Ne(r),i=`title`in r?r.title:void 0,a=e??i??r.type;t.has(a)||(t.add(a),n.push({type:r.type,...i?{title:i}:{},...e?{url:e}:{}}))}return n}function Ne(e){switch(e.type){case`web`:case`search-result`:return e.url;case`retrieved-context`:return e.uri;case`document`:return e.fileId;default:return}}function Pe(e){return JSON.stringify({error:e})}function Fe(e){let t=e.tools!==void 0||e.providerTools!==void 0;if(e.registry&&t)throw new A("Cannot specify both `registry` and `tools` / `providerTools`. Use one or the other.",{code:`TOOL_OPTIONS_CONFLICT`});return e.registry??new we({tools:e.tools,providerTools:e.providerTools})}function Ie(e,t){let n=e.getProvider(`web_search`),r=t.provider.resolveProviderToolName?.bind(t.provider);if(!r)return{registry:e,executable:()=>e.executable(),provider:()=>e.provider(),get:t=>e.get(t)};let i=()=>e.provider().map(e=>{let n=r(e.name,t.model);return n===void 0?e:{...e,nativeName:n}});if(!n||r(`web_search`,t.model)!==void 0)return{registry:e,executable:()=>e.executable(),provider:i,get:t=>e.get(t)};let a=t.configuration.webSearchFallback;if(!a)throw new A(`Provider ${t.provider.name} does not support native web_search and no Axle webSearchFallback is configured`,{code:`WEB_SEARCH_FALLBACK_NOT_CONFIGURED`,details:{provider:t.provider.name,model:t.model}});n.config&&t.span?.warn(`web_search provider config ignored by fallback backend`,{provider:t.provider.name,model:t.model,backend:a.name}),t.span?.info(`Using web search fallback backend`,{provider:t.provider.name,model:t.model,backend:a.name});let o=Ee(a);return{registry:e,executable:()=>[...e.executable().filter(e=>e.name!==`web_search`),o],provider:()=>i().filter(e=>e.name!==`web_search`),get:t=>t===`web_search`?o:e.get(t)}}async function Le(e,t=async()=>null,n,r,i,a){let o=[],s=K(),c=!1;for(let l of e){let e;try{e=await ze(l,t,n,r,i,a)}catch(e){throw c?Re(e,s):e}o.push(e.result),e.usage&&(q(s,e.usage),c=!0)}return{results:o,...c?{usage:s}:{}}}function Re(e,t){return e instanceof P?new P(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:_e(t,e.usage),cause:e.cause}):e instanceof M?new M(e.message,{reason:e.reason,messages:e.messages,partial:e.partial,usage:_e(t,e.usage)}):e}async function ze(e,t,n,r,i,a){if(n.aborted)throw new M(`Operation aborted`,{reason:n.reason});let o=r instanceof we?r:r.registry,s=r.get(e.name),c=i?.startSpan(e.name,{type:`tool`}),l,u={signal:n,span:c,registry:o,emit:t=>a?.onDelta?.(e,t),reportUsage:e=>{l??=K(),q(l,e)}};a?.onStart?.(e);let d,f=`exception`;try{if(d=await t(e.name,e.parameters,u),d==null&&s&&(f=`execution`,d={type:`success`,content:await s.execute(e.parameters,u)}),n.aborted)throw new M(`Operation aborted`,{reason:n.reason})}catch(t){let r=Be(t,n);if(r){c?.setResult({kind:`tool`,name:e.name,input:e.parameters,output:{type:r instanceof P?`fatal`:`aborted`,message:r.message}}),c?.end(r instanceof P?`error`:`ok`);let t=l?Re(r,l):r;throw a?.onError?.(e,t),t}d={type:`error`,error:{type:f,message:t instanceof Error?t.message:String(t)}}}d??={type:`error`,error:{type:`not-found`,message:`Tool not found: ${e.name}`}};let p={result:d,...l?{usage:l}:{}};a?.onComplete?.(e,p);let m=d.type===`success`?d.content:Pe(d.error);return c?.setResult({kind:`tool`,name:e.name,input:e.parameters,output:d.type===`success`?d.content:d.error}),c?.end(d.type===`success`?`ok`:`error`),{result:{id:e.id,name:e.name,content:m,...d.type===`error`?{isError:!0}:{}},...l?{usage:l}:{}}}function Be(e,t){if(e instanceof P||e instanceof M)return e;if(t.aborted)return new M(`Operation aborted`,{reason:t.reason})}let Ve=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function J(e,t){for(let n of e)n(t)}function He(e){let t=e.raw?`${e.message}\nRaw buffer: ${e.raw}`:e.message;return{type:`error`,error:{type:e.type,message:t}}}function Ue(e){return{name:e.name,description:e.description,schema:e.schema}}function We(e){let t=[],n,r;if(`instruct`in e){let{instruct:t,messages:i,...a}=e,o=he(t);r=o.parse,n={...a,messages:[...i??[],o.message]}}else n=e;let i=new AbortController,a=n.signal?AbortSignal.any([i.signal,n.signal]):i.signal,{promise:o,resolve:s,reject:c}=Promise.withResolvers(),l=k();return Promise.resolve().then(()=>Ge(n,a,t,l).then(e=>{if(r&&e.ok){try{s({...e,response:r(e.final)})}catch(t){s({ok:!1,messages:e.messages,final:e.final,usage:e.usage,error:{kind:`parse`,error:t,message:t instanceof Error?t.message:String(t)}})}return}s(e)},c)),{on(e){t.push(e)},cancel(e){i.abort(e)},get final(){return o}}}async function Ge(e,t,n,r){let{provider:i,model:a,messages:o,system:s,onToolCall:c,maxIterations:l,span:u,fileResolver:d,reasoning:f,maxOutputTokens:p,temperature:m,topP:h,stop:g,toolChoice:_,parallelToolCalls:v,providerOptions:y}=e,b=Ie(Fe(e),{provider:i,model:a,span:u,configuration:r}),x=[...o],S=[],C=K(),w=0,T=0,E=e=>{x.push(e),S.push(e)},D=e=>{e.ok||J(n,{type:`error`,error:e.error});let t=e.ok?e.final.content:null,r=e.ok?e.final.finishReason:void 0;return u?.setResult({kind:`llm`,model:a,request:{messages:o},response:{content:t??null},usage:xe(e.usage),finishReason:r}),u?.end(e.ok?`ok`:`error`),e},O=(e,n,r,i)=>{i();let a=e.length?{role:`assistant`,id:n,model:r,content:e,finishReason:`cancelled`}:void 0;throw a&&E(a),u?.end(`ok`),new M(`Stream aborted`,{reason:t.reason,messages:S,partial:a,usage:C})};for(;;){if(t.aborted&&O([],``,``,()=>{}),l!==void 0&&T>=l)return D({ok:!1,messages:S,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${l})`}}},usage:C});T+=1;let e=u?.startSpan(`turn-${T}`,{type:`llm`}),r=b.executable(),o=r.length>0?r.map(Ue):void 0,k=b.provider(),A=i.createStreamingRequest(a,{messages:x,system:s,tools:o,providerTools:k.length>0?k:void 0,runtime:{span:e,fileResolver:d},signal:t,reasoning:f,maxOutputTokens:p,temperature:m,topP:h,stop:g,toolChoice:_,parallelToolCalls:v,providerOptions:y}),j=[],N=``,ee=``,F=null,te=K(),I=-1,ne=null,L=``,R=new Map,re=new Map,z=new Map,B=new Map,ie=new Set,ae=(e,t)=>{J(n,{type:`tool:request`,index:R.get(e)??-1,id:e,name:t,kind:b.get(t)?.kind??`tool`})},V=-1,H=()=>{ne!==null&&I>=0&&(J(n,{type:ne===`text`?`text:end`:`thinking:end`,index:I,final:L}),ne=null,L=``,I=-1)};for await(let r of A){switch(r.type){case`start`:N=r.id,ee=r.data.model,J(n,{type:`turn:start`,id:N,model:ee});break;case`text-start`:H(),j.push({type:`text`,text:``}),V=j.length-1,I=w++,z.set(r.data.index,V),B.set(r.data.index,I),ne=`text`,L=``,J(n,{type:`text:start`,index:I});break;case`text-delta`:{let e=j[V];e.text+=r.data.text,L=e.text,J(n,{type:`text:delta`,index:I,delta:r.data.text,accumulated:L});break}case`text-citation`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??I,i=j[e];if(!i||i.type!==`text`)break;i.citations=[...i.citations??[],r.data.citation],J(n,{type:`text:citation`,index:t,citation:r.data.citation,citations:i.citations});break}case`citation`:{H();let e=w++;j.push({type:`citation`,citations:r.data.citations,...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),V=j.length-1,z.set(r.data.index,V),B.set(r.data.index,e),J(n,{type:`citation`,index:e,citations:r.data.citations,providerMetadata:r.data.providerMetadata});break}case`text-complete`:H();break;case`thinking-start`:H(),j.push({type:`thinking`,text:``,...r.data.id?{id:r.data.id}:{},...r.data.redacted===void 0?{}:{redacted:r.data.redacted},...r.data.continuity?{continuity:r.data.continuity}:{},...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),V=j.length-1,I=w++,z.set(r.data.index,V),B.set(r.data.index,I),ne=`thinking`,L=``,J(n,{type:`thinking:start`,index:I,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break;case`thinking-delta`:{let e=j[V];e.text=(e.text??``)+r.data.text,L=e.text,J(n,{type:`thinking:delta`,index:I,delta:r.data.text,accumulated:L});break}case`thinking-summary-delta`:{let e=j[V];e.summary=(e.summary??``)+r.data.text,L=e.summary,J(n,{type:`thinking:summary-delta`,index:I,delta:r.data.text,accumulated:L});break}case`thinking-metadata`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??I,i=j[e];if(!i||i.type!==`thinking`)break;r.data.redacted!==void 0&&(i.redacted=r.data.redacted),r.data.continuity&&(i.continuity=r.data.continuity),r.data.providerMetadata&&(i.providerMetadata=r.data.providerMetadata),J(n,{type:`thinking:update`,index:t,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break}case`thinking-complete`:H();break;case`tool-call-start`:{H();let e=w++;j.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),V=j.length-1,z.set(r.data.index,V),B.set(r.data.index,e),R.set(r.data.id,e),r.data.name?ae(r.data.id,r.data.name):ie.add(r.data.id);break}case`tool-call-args-delta`:ie.has(r.data.id)&&r.data.name&&(ie.delete(r.data.id),ae(r.data.id,r.data.name)),J(n,{type:`tool:args-delta`,index:R.get(r.data.id)??-1,id:r.data.id,name:r.data.name,delta:r.data.delta,accumulated:r.data.accumulated});break;case`tool-call-complete`:{let e=j[z.get(r.data.index)??V];if(!e||e.type!==`tool-call`)break;r.data.id&&(e.id=r.data.id),r.data.name&&(e.name=r.data.name),e.parameters=r.data.arguments,r.data.providerMetadata&&(e.providerMetadata=r.data.providerMetadata),r.data.error&&re.set(e.id,r.data.error),ie.has(e.id)&&e.name&&(ie.delete(e.id),ae(e.id,e.name));break}case`provider-tool-start`:{H();let e=w++;j.push({type:`provider-tool`,id:r.data.id,name:r.data.name}),V=j.length-1,z.set(r.data.index,V),B.set(r.data.index,e),J(n,{type:`provider-tool:start`,index:e,id:r.data.id,name:r.data.name});break}case`provider-tool-complete`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??r.data.index,i=j[e];i&&i.type===`provider-tool`&&r.data.output!=null&&(i.output=r.data.output),J(n,{type:`provider-tool:complete`,index:t,id:r.data.id,name:r.data.name,output:r.data.output});break}case`complete`:H(),F=r.data.finishReason,te=r.data.usage;break;case`error`:return H(),r.data.usage&&q(C,ve(r.data.usage,{provider:i.name,model:ee||a})),e?.end(`error`),D({ok:!1,messages:S,error:{kind:`model`,error:{type:`error`,error:{type:r.data.type,message:r.data.message}}},usage:C});default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.aborted)break}if(t.aborted&&(e?.end(`ok`),O(j,N,ee,H)),F===null)return H(),e?.end(`error`),D({ok:!1,messages:S,error:{kind:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:C});let oe=ve(te,{provider:i.name,model:ee||a});q(C,oe);let se={kind:`llm`,model:ee,request:{messages:x},response:{content:j},usage:xe(te),finishReason:F};Ae(e,j),e?.setResult(se),e?.end();let U={role:`assistant`,id:N,model:ee,content:j,finishReason:F};if(E(U),J(n,{type:`turn:complete`,message:U,usage:oe}),F!==`function_call`)return D({ok:!0,response:U,messages:S,final:U,usage:C});let ce=j.filter(e=>e.type===`tool-call`);if(ce.length===0)return D({ok:!0,response:U,messages:S,final:U,usage:C});if(t.aborted)throw u?.end(`ok`),new M(`Stream aborted`,{reason:t.reason,messages:S,usage:C});let le=crypto.randomUUID();J(n,{type:`tool-results:start`,id:le});let W=[],G=new Map;for(let e of ce){let t=re.get(e.id);if(!t){W.push(e);continue}let r=He(t);G.set(e.id,{id:e.id,name:e.name,content:Pe(r.error),isError:!0}),J(n,{type:`tool:exec-complete`,index:R.get(e.id)??-1,id:e.id,name:e.name,result:r})}let ue={onStart(e){J(n,{type:`tool:exec-start`,index:R.get(e.id)??-1,id:e.id,name:e.name,parameters:e.parameters})},onDelta(e,t){J(n,{type:`tool:exec-delta`,index:R.get(e.id)??-1,id:e.id,name:e.name,chunk:t})},onComplete(e,t){J(n,{type:`tool:exec-complete`,index:R.get(e.id)??-1,id:e.id,name:e.name,result:t.result,usage:t.usage})},onError(e,t){J(n,{type:`tool:exec-error`,index:R.get(e.id)??-1,id:e.id,name:e.name,error:{type:t instanceof P?`fatal`:`aborted`,message:t.message},usage:t.usage})}},de=[],fe;try{W.length>0&&({results:de,usage:fe}=await Le(W,c,t,b,u,ue))}catch(e){throw e instanceof P?(u?.end(`error`),new P(e.message,{toolName:e.toolName,messages:e.messages??S,partial:e.partial??U,usage:_e(C,e.usage),cause:e.cause})):e instanceof M?(u?.end(`ok`),new M(`Stream aborted`,{reason:e.reason,messages:e.messages??S,partial:e.partial,usage:_e(C,e.usage)})):e}q(C,fe);let pe=new Map(de.map(e=>[e.id,e])),me=ce.flatMap(e=>{let t=G.get(e.id);if(t)return[t];let n=pe.get(e.id);return n?[n]:[]});if(me.length>0){let e={role:`tool`,id:le,content:me};E(e),J(n,{type:`tool-results:complete`,message:e})}}}function Ke(e=new Date){return{start:e.toISOString()}}function Y(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var qe=class{currentTurnId=null;currentTurnTiming;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage=K();createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=Y(Ke(r),r),a=()=>({...i});if(typeof e.content==`string`)n.push({id:crypto.randomUUID(),type:`text`,text:e.content,timing:a()});else for(let t of e.content)t.type===`text`?n.push({id:crypto.randomUUID(),type:`text`,text:t.text,...t.citations?{citations:t.citations}:{},...t.providerMetadata?{providerMetadata:t.providerMetadata}:{},timing:a()}):t.type===`file`&&n.push({id:crypto.randomUUID(),type:`file`,file:t.file,timing:a()});return[{type:`turn:user`,turn:{id:t,owner:`user`,parts:n,status:`complete`,timing:i,...e.metadata?{metadata:e.metadata}:{}}}]}startAgentTurn(){let e=crypto.randomUUID();return this.currentTurnId=e,this.currentTurnTiming=Ke(),this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage=K(),{type:`turn:start`,turnId:e,timing:this.currentTurnTiming}}handleStreamEvent(e){let t=this.currentTurnId;if(!t)return[];let n=[];switch(e.type){case`turn:start`:break;case`text:start`:{this.closeOpenParts(n);let e=crypto.randomUUID(),r={id:e,type:`text`,text:``,timing:Ke()};this.currentTextPart={id:e,timing:r.timing},n.push({type:`part:start`,turnId:t,part:r});break}case`text:delta`:this.currentTextPart&&n.push({type:`text:delta`,turnId:t,partId:this.currentTextPart.id,delta:e.delta});break;case`text:end`:if(this.currentTextPart){let e=Y(this.currentTextPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:e}),this.currentTextPart=null}break;case`citation`:{this.closeOpenParts(n);let r=Y(Ke()),i={id:crypto.randomUUID(),type:`citation`,citations:e.citations,...e.providerMetadata?{providerMetadata:e.providerMetadata}:{},timing:r};n.push({type:`part:start`,turnId:t,part:i}),n.push({type:`part:end`,turnId:t,partId:i.id,timing:r});break}case`thinking:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i={id:r,type:`thinking`,text:``,timing:Ke(),...e.redacted===void 0?{}:{redacted:e.redacted},...e.continuity?{continuity:e.continuity}:{},...e.providerMetadata?{providerMetadata:e.providerMetadata}:{}};this.currentThinkingPart={id:r,timing:i.timing},n.push({type:`part:start`,turnId:t,part:i});break}case`thinking:delta`:this.currentThinkingPart&&n.push({type:`thinking:delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`text:citation`:this.currentTextPart&&n.push({type:`text:citation`,turnId:t,partId:this.currentTextPart.id,citation:e.citation});break;case`thinking:summary-delta`:this.currentThinkingPart&&n.push({type:`thinking:summary-delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`thinking:update`:this.currentThinkingPart&&n.push({type:`thinking:update`,turnId:t,partId:this.currentThinkingPart.id,redacted:e.redacted,continuity:e.continuity,providerMetadata:e.providerMetadata});break;case`thinking:end`:if(this.currentThinkingPart){let e=Y(this.currentThinkingPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:e}),this.currentThinkingPart=null}break;case`tool:request`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=Ke(),a=e.kind===`agent`?{id:r,type:`action`,kind:`agent`,status:`pending`,timing:i,detail:{name:e.name,children:[]}}:{id:r,type:`action`,kind:`tool`,status:`pending`,timing:i,detail:{name:e.name,parameters:{}}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i,name:e.name,kind:e.kind}),n.push({type:`part:start`,turnId:t,part:a});break}case`tool:args-delta`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:args-delta`,turnId:t,partId:r.partId,delta:e.delta,accumulated:e.accumulated});break}case`tool:exec-start`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:running`,turnId:t,partId:r.partId,parameters:e.parameters});break}case`tool:exec-delta`:{let r=this.toolIdMap.get(e.id);r&&(typeof e.chunk==`string`?n.push({type:`action:progress`,turnId:t,partId:r.partId,chunk:e.chunk}):e.chunk.type===`turn-event`&&n.push({type:`action:child-event`,turnId:t,partId:r.partId,event:e.chunk.event}));break}case`tool:exec-complete`:{let r=this.toolIdMap.get(e.id);if(r){q(this.accumulatedUsage,e.usage);let i=Y(r.timing);r.timing=i,e.result.type===`success`?n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.result.content},timing:i}):n.push({type:`action:error`,turnId:t,partId:r.partId,error:e.result.error,timing:i})}break}case`tool:exec-error`:{let r=this.toolIdMap.get(e.id);if(r){q(this.accumulatedUsage,e.usage);let i=Y(r.timing);r.timing=i,n.push({type:`action:error`,turnId:t,partId:r.partId,error:e.error,timing:i})}break}case`provider-tool:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=Ke(),a={id:r,type:`action`,kind:`provider-tool`,status:`running`,timing:i,detail:{name:e.name}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i}),n.push({type:`part:start`,turnId:t,part:a}),n.push({type:`action:running`,turnId:t,partId:r});break}case`provider-tool:complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=Y(r.timing);r.timing=i,n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.output},timing:i})}break}case`turn:complete`:this.closeOpenParts(n),q(this.accumulatedUsage,e.usage);break;case`tool-results:start`:case`tool-results:complete`:break;case`error`:{let t=e.error,r=t.kind===`model`?t.error.error.message:t.kind===`tool`?`Tool error (${t.error.name}): ${t.error.message}`:`Parse error: ${t.message}`;n.push({type:`error`,error:{type:t.kind,message:r}});break}}return n}finalizeTurn(e=`complete`){let t=this.currentTurnId;if(!t)return[];let n=[];this.closeOpenParts(n);let r=Y(this.currentTurnTiming);return n.push({type:`turn:end`,turnId:t,status:e,usage:{...this.accumulatedUsage},timing:r}),this.currentTurnId=null,this.currentTurnTiming=void 0,n}closeOpenParts(e){let t=this.currentTurnId;t&&(this.currentTextPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:Y(this.currentTextPart.timing)}),null),this.currentThinkingPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:Y(this.currentThinkingPart.timing)}),null))}};function Je(e){return Array.isArray(e)?e:[e]}function Ye(e){return e.then(()=>{},()=>{})}function Xe(e,t,n){let r=new AbortController,i=n?AbortSignal.any([n,r.signal]):r.signal,a=e.then(()=>t(i));return{handle:{cancel:e=>r.abort(e),get final(){return a}},settled:Ye(a)}}var Ze=class{_turns=[];_log=[];_sessionAnnotations=[];constructor(e){e?.turns&&(this._turns=[...e.turns]),e?.log&&(this._log=[...e.log]),e?.sessionAnnotations&&(this._sessionAnnotations=[...e.sessionAnnotations])}get turns(){return[...this._turns]}get log(){return[...this._log]}get sessionAnnotations(){return[...this._sessionAnnotations]}addTurn(e){this._turns.push(e)}replaceTurns(e){this._turns=[...e]}replaceLog(e){this._log=[...e]}replaceSessionAnnotations(e=[]){this._sessionAnnotations=[...e]}appendToLog(e){Array.isArray(e)?this._log.push(...e):this._log.push(e)}latestTurn(){return this._turns[this._turns.length-1]}toString(){return JSON.stringify({turns:this._turns,sessionAnnotations:this._sessionAnnotations})}};const Qe={trace:0,debug:1,info:2,warn:3,error:4},$e=()=>performance.timeOrigin+performance.now();var et=class{writers=[];minLevel=`info`;addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}shouldLog(e){return Qe[e]>=Qe[this.minLevel]}spanStart(e){for(let t of this.writers)t.onSpanStart(e)}spanEnd(e){for(let t of this.writers)t.onSpanEnd(e)}spanUpdate(e){for(let t of this.writers)t.onSpanUpdate?.(e)}event(e,t){for(let n of this.writers)n.onEvent?.(e,t)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}},tt=class{rec=new et;constructor(e){e?.minLevel&&(this.rec.minLevel=e.minLevel);for(let t of e?.writers??[])this.rec.addWriter(t)}get minLevel(){return this.rec.minLevel}set minLevel(e){this.rec.minLevel=e}addWriter(e){this.rec.addWriter(e)}removeWriter(e){this.rec.removeWriter(e)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:$e(),status:`ok`,attributes:{...t?.attributes??{}},events:[]};return this.rec.spanStart(n),new nt(n,this.rec)}flush(){return this.rec.flush()}},nt=class e{data;rec;ended=!1;constructor(e,t){this.data=e,this.rec=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:$e(),status:`ok`,attributes:{...n?.attributes??{}},events:[]};return this.rec.spanStart(r),new e(r,this.rec)}end(e=`ok`){this.ended||(this.ended=!0,this.data.endTime=$e(),this.data.status=e,this.rec.spanEnd(this.data))}addEvent(e,t,n){if(this.ended||!this.rec.shouldLog(t))return;let r={name:e,timestamp:$e(),level:t,attributes:n};this.data.events.push(r),this.rec.event(this.data,r)}trace(e,t){this.addEvent(e,`trace`,t)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,this.rec.spanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.rec.spanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.rec.spanUpdate(this.data))}};function rt(e){if(!e)return{};let{trace:t,log:n,level:r}=e;if(t)return n&&console.warn(`[axle] observability.log is ignored when observability.trace is set; add a LogWriter to your tracer's writers instead`),{parent:t};if(n){let e=new tt({minLevel:r,writers:[new z(n)]});return{parent:e,owned:e}}return{}}function it(e){return at(e)?`cancelled`:`error`}function at(e){return e instanceof M||e instanceof N||e instanceof Error&&e.name===`AbortError`}function ot(e,t){return{...e,...t,providerOptions:e?.providerOptions||t?.providerOptions?{...e?.providerOptions,...t?.providerOptions}:void 0}}var st=class{provider;model;history;name;fileResolver;requestOptions;registry;sessionId;system;mcps=[];resolvedMcps=new WeakSet;memory;spanParent;ownedTracer;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e,t){this.provider=e.provider,this.model=e.model,this.sessionId=e.sessionId??crypto.randomUUID(),this.history=new Ze;let n=rt(e.observability);if(this.spanParent=n.parent,this.ownedTracer=n.owned,this.system=e.system,this.name=e.name,this.fileResolver=e.fileResolver,this.requestOptions={reasoning:e.reasoning,maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,stop:e.stop,toolChoice:e.toolChoice,parallelToolCalls:e.parallelToolCalls,providerOptions:e.providerOptions},this.registry=new we({tools:e.tools,providerTools:e.providerTools}),e.mcps&&(this.mcps=[...e.mcps]),e.memory){this.memory=e.memory;let t=e.memory.tools?.();t&&this.registry.add(t)}t&&this.restore(t)}addMcp(e){this.mcps.push(e)}addMcps(e){this.mcps.push(...e)}hasTools(){return this.registry.size>0||this.mcps.length>0}on(e){return this.eventCallbacks.push(e),()=>{let t=this.eventCallbacks.indexOf(e);t>=0&&this.eventCallbacks.splice(t,1)}}context(){return ie({system:this.system,messages:this.history.log,tools:this.toToolDefinitions(this.registry.local()),providerTools:this.registry.provider(),mcpTools:this.toToolDefinitions(this.registry.mcp())})}snapshot(){let e=this.history.sessionAnnotations;return{version:1,sessionId:this.sessionId,messages:this.history.log,turns:this.history.turns,sessionAnnotations:e.length>0?e:void 0}}restore(e){if(e.version!==1)throw new A(`Unsupported agent session version: ${e.version}`);this.sessionId=e.sessionId,this.history.replaceLog(e.messages),this.history.replaceTurns(e.turns??[]),this.history.replaceSessionAnnotations(e.sessionAnnotations??[])}send(e,t){let{fileResolver:n,metadata:r,...i}=t??{},a=he(e,{metadata:r}),o=ot(this.requestOptions,i),{handle:s,settled:c}=Xe(this.sendQueue,async e=>{let t=this.spanParent?.startSpan(`agent.send`,{type:`workflow`,attributes:{sessionId:this.sessionId,...this.name?{agentName:this.name}:{}}});B(t,`message`,F(a.message.content));let r=`ok`;try{let i=await this.run(a,{signal:e,fileResolver:n,requestOptions:o,span:t});return i.ok||(r=`error`),t?.setAttributes({inputTokens:i.usage.in,outputTokens:i.usage.out}),i}catch(e){throw r=it(e),t?.error(e instanceof Error?e.message:String(e)),e}finally{t?.end(r),await this.ownedTracer?.flush()}},i.signal);return this.sendQueue=c,s}async resolveMcpTools(e,t){for(let n of this.mcps){if(this.resolvedMcps.has(n))continue;let r=await n.listTools({prefix:n.name,span:t,signal:e});this.registry.addMcp(r),this.resolvedMcps.add(n)}}emitEvent(e){for(let t of this.eventCallbacks)t(e)}toToolDefinitions(e){return e.map(e=>({name:e.name,description:e.description,schema:e.schema}))}async run(t,n){let{signal:r,fileResolver:i,requestOptions:a}=n,o=n.span,s=new qe,c=new e({turns:this.history.turns,sessionAnnotations:this.history.sessionAnnotations}),l,u=e=>{let t=c.apply(e);t.handled&&(this.history.replaceTurns(t.state.turns),this.history.replaceSessionAnnotations(t.state.sessionAnnotations??[])),this.emitEvent(e)},d=()=>l?c.state.turns.find(e=>e.id===l):void 0,f=K();if(r.aborted)throw new N(`Agent send aborted`,{reason:r.reason,usage:f});try{await this.resolveMcpTools(r,o)}catch(e){throw r.aborted||e instanceof M||e instanceof Error&&e.name===`AbortError`?new N(`Agent send aborted`,{reason:e instanceof M?e.reason:r.reason,usage:f}):e}let p=this.system,m=[...this.history.log,t.message];if(this.memory){let e=await this.memory.recall({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:m,span:o});e.systemSuffix&&(p=(p??``)+`
6
6
 
7
- `+e.systemSuffix)}if(r.aborted)throw new N(`Agent send aborted`,{reason:r.reason,usage:f});this.history.appendToLog(t.message);for(let e of s.createUserTurn(t.message))u(e);let h=s.startAgentTurn();l=h.turnId,u(h);let g=o?.startSpan(`stream`,{type:`internal`})??void 0,{signal:_,...v}=a??{},y=Ue({provider:this.provider,model:this.model,messages:m,system:p,registry:this.registry,span:g,fileResolver:i??this.fileResolver,...v,signal:r});y.on(e=>{let t=s.handleStreamEvent(e);for(let e of t)u(e)});let b,x=`ok`;try{b=await y.final,b.ok||(x=`error`)}catch(e){if(x=rt(e),e instanceof P){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=s.finalizeTurn(`error`);for(let e of t)u(e);throw new P(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:e.usage??f,cause:e.cause})}if(e instanceof M){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=s.finalizeTurn(`cancelled`);for(let e of t)u(e);throw new N(`Agent send aborted`,{reason:e.reason,messages:e.messages,partial:e.partial,turn:d(),usage:e.usage??f})}throw e}finally{g?.end(x)}let S=b.ok?`complete`:`error`;b.ok&&b.final?.finishReason&&o?.setAttribute(`finishReason`,b.final.finishReason),b.messages.length>0&&this.history.appendToLog(b.messages);let C=s.finalizeTurn(S);for(let e of C)u(e);let w=b.usage??f,T=d();if(!b.ok)return{ok:!1,error:b.error,turn:T,usage:w};let E;try{E=t.parse(b.final)}catch(e){return{ok:!1,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)},turn:T,usage:w}}if(!T)throw new A(`Agent turn missing after send`);if(this.memory)try{await this.memory.record({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:this.history.log,newMessages:b.messages,span:o})}catch(e){o?.warn(`memory record failed`,{error:e instanceof Error?e.message:String(e)})}return{ok:!0,response:E,turn:T,usage:w}}};function st(e){try{let t=l.fromJSONSchema(e);return t instanceof l.ZodObject?t.strict():l.object({}).passthrough()}catch{return l.object({}).passthrough()}}function ct(e,t,n){return e.map(e=>ut(e,t,n))}function lt(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=st(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function ut(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=st(e.inputSchema);return{name:r,description:e.description??``,schema:i,async execute(n,i){let a;try{a=await t.callTool({name:e.name,arguments:n},void 0,{signal:i.signal})}catch(t){throw i.signal.aborted||t instanceof Error&&t.name===`AbortError`?t:new P(`MCP tool call failed: ${e.name}`,{toolName:r,cause:t})}if(`isError`in a&&a.isError)throw Error(ft(a.content));return dt(a.content)}}}function dt(e){return e.some(e=>e.type===`image`)?e.filter(e=>e.type===`text`||e.type===`image`).map(e=>{if(e.type===`text`)return{type:`text`,text:e.text};let t=e;return{type:`file`,file:{kind:`image`,mimeType:t.mimeType,name:`mcp-image`,source:{type:`base64`,data:t.data}}}}):e.filter(e=>e.type===`text`).map(e=>e.text).join(`
8
- `)}function ft(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
9
- `)||`MCP tool execution error`}var pt=class{config;client;transport;cachedMcpTools;_connected=!1;constructor(e){this.config=e}get name(){return this.config.name??this.client?.getServerVersion()?.name}get connected(){return this._connected}async connect(e){if(this._connected)return;let t=e?.span?.startSpan(`mcp:connect`,{type:`internal`});this.client=new d({name:`axle`,version:`1.0.0`}),this.config.transport===`stdio`?this.transport=new f({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new p(new URL(this.config.url),{requestInit:this.config.headers?{headers:this.config.headers}:void 0});try{await this.client.connect(this.transport,{signal:e?.signal}),this._connected=!0,t?.end(`ok`)}catch(e){throw t?.end(`error`),e}}async listTools(e){let t=this.assertConnected();return ct(await this.fetchTools(t,e?.span,e?.signal),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return lt(await this.fetchTools(t,e?.span,e?.signal),e?.prefix)}async refreshTools(){return this.assertConnected(),this.cachedMcpTools=void 0,this.listTools()}async close(e){this._connected&&(e?.span?.debug(`mcp:close`),await this.client?.close(),this._connected=!1,this.client=void 0,this.transport=void 0,this.cachedMcpTools=void 0)}async fetchTools(e,t,n){if(this.cachedMcpTools)return this.cachedMcpTools;t?.debug(`mcp:listTools`);let r=await e.listTools(void 0,{signal:n});return this.cachedMcpTools=r.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})),this.cachedMcpTools}assertConnected(){if(!this._connected||!this.client)throw Error(`MCP not connected. Call connect() first.`);return this.client}};function mt(e){return e?.map(e=>({type:`provider`,name:e.name,config:e.config}))}async function ht(e,t){if(e.version!==1)throw new A(`Unsupported agent definition version: ${e.version}`);let n=await t(e),r=e.model??n.model;if(!r)throw new A(`AgentDefinition requires a model or model resolver`);if(e.tools?.length&&!n.tools)throw new A(`AgentDefinition includes tools but resolver did not return tools`);return{provider:n.provider,model:r,system:e.system,name:e.name,tools:n.tools,providerTools:n.providerTools??mt(e.providerTools),mcps:n.mcps??e.mcps?.map(e=>new pt(e)),reasoning:e.request?.reasoning,maxOutputTokens:e.request?.maxOutputTokens,temperature:e.request?.temperature,topP:e.request?.topP,stop:e.request?.stop,toolChoice:e.request?.toolChoice,parallelToolCalls:e.request?.parallelToolCalls,providerOptions:e.request?.providerOptions}}var gt=class e extends A{missingVariables;constructor(t){super(_t(t),{code:`INSTRUCT_VARIABLE_ERROR`,details:{missingVariables:t}}),this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),missingVariables:this.missingVariables}}};function _t(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var vt=class e extends Error{missingVariables;constructor(t){super(bt(t)),this.name=`MissingVariablesError`,this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}};function yt(e,t,n={}){let{placeholderStyle:r=`{{}}`,strict:i=!0}=n,a=r===`{{}}`?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g,o=[];if(e=e.replace(a,(e,n)=>{if(n=n.trim(),Object.prototype.hasOwnProperty.call(t,n)){let e=t[n];return e==null?``:String(e)}return o.push(n),e}),o.length>0){let e=[...new Set(o)];if(i)throw new vt(e)}return e}function bt(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var xt=class e{prompt;inputs={};files=[];textReferences=[];contextSections=[];vars;metadata;schema;constructor(e){this.prompt=e.prompt,this.schema=e.schema,this.vars=e.vars??`required`,this.metadata=e.metadata}clone(){let t=new e({prompt:this.prompt,schema:this.schema,vars:this.vars,metadata:this.metadata});return t.inputs={...this.inputs},t.files=[...this.files],t.textReferences=this.textReferences.map(e=>({...e})),t.contextSections=this.contextSections.map(e=>({...e})),t}withInputs(e){let t=this.clone();return t.inputs={...t.inputs,...e},t}withInput(e,t){return this.withInputs({[e]:t})}setInputs(e){this.inputs={...e}}addInput(e,t){this.inputs[e]=t}addFile(e,t){if(typeof e==`string`){this.textReferences.push({content:e,name:t?.name});return}if(e.kind===`text`&&e.source.type===`text`){this.textReferences.push({content:e.source.content,name:t?.name??e.name});return}this.files.push(t?.name?{...e,name:t.name}:e)}addContext(e,t){return this.contextSections.push({content:e,...t?.title?{title:t.title}:{}}),this}hasFiles(){return this.files.length>0}render(e={}){let t;try{t=yt(this.prompt,this.inputs,{strict:(e.vars??this.vars)===`required`})}catch(e){throw e instanceof vt?new gt(e.missingVariables):e}if(this.textReferences.length>0)for(let[e,n]of this.textReferences.entries()){let r=n.name?`: ${n.name}`:``,i=St(n.content);t+=`\n\n## Reference ${e+1}${r}\n\n${i}\n${n.content}\n${i}`}for(let[e,n]of this.contextSections.entries()){let r=n.title?`: ${n.title}`:``,i=St(n.content);t+=`\n\n## Context ${e+1}${r}\n\n${i}\n${n.content}\n${i}`}if(!this.schema)return t;let n=`# Output Format Instructions
7
+ `+e.systemSuffix)}if(r.aborted)throw new N(`Agent send aborted`,{reason:r.reason,usage:f});this.history.appendToLog(t.message);for(let e of s.createUserTurn(t.message))u(e);let h=s.startAgentTurn();l=h.turnId,u(h);let g=o?.startSpan(`stream`,{type:`internal`})??void 0,{signal:_,...v}=a??{},y=We({provider:this.provider,model:this.model,messages:m,system:p,registry:this.registry,span:g,fileResolver:i??this.fileResolver,...v,signal:r});y.on(e=>{let t=s.handleStreamEvent(e);for(let e of t)u(e)});let b,x=`ok`;try{b=await y.final,b.ok||(x=`error`)}catch(e){if(x=it(e),e instanceof P){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=s.finalizeTurn(`error`);for(let e of t)u(e);throw new P(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:e.usage??f,cause:e.cause})}if(e instanceof M){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=s.finalizeTurn(`cancelled`);for(let e of t)u(e);throw new N(`Agent send aborted`,{reason:e.reason,messages:e.messages,partial:e.partial,turn:d(),usage:e.usage??f})}throw e}finally{g?.end(x)}let S=b.ok?`complete`:`error`;b.ok&&b.final?.finishReason&&o?.setAttribute(`finishReason`,b.final.finishReason),b.messages.length>0&&this.history.appendToLog(b.messages);let C=s.finalizeTurn(S);for(let e of C)u(e);let w=b.usage??f,T=d();if(!b.ok)return{ok:!1,error:b.error,turn:T,usage:w};let E;try{E=t.parse(b.final)}catch(e){return{ok:!1,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)},turn:T,usage:w}}if(!T)throw new A(`Agent turn missing after send`);if(this.memory)try{await this.memory.record({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:this.history.log,newMessages:b.messages,span:o})}catch(e){o?.warn(`memory record failed`,{error:e instanceof Error?e.message:String(e)})}return{ok:!0,response:E,turn:T,usage:w}}};function ct(e){try{let t=l.fromJSONSchema(e);return t instanceof l.ZodObject?t.strict():l.object({}).passthrough()}catch{return l.object({}).passthrough()}}function lt(e,t,n){return e.map(e=>dt(e,t,n))}function ut(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=ct(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function dt(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=ct(e.inputSchema);return{name:r,description:e.description??``,schema:i,async execute(n,i){let a;try{a=await t.callTool({name:e.name,arguments:n},void 0,{signal:i.signal})}catch(t){throw i.signal.aborted||t instanceof Error&&t.name===`AbortError`?t:new P(`MCP tool call failed: ${e.name}`,{toolName:r,cause:t})}if(`isError`in a&&a.isError)throw Error(pt(a.content));return ft(a.content)}}}function ft(e){return e.some(e=>e.type===`image`)?e.filter(e=>e.type===`text`||e.type===`image`).map(e=>{if(e.type===`text`)return{type:`text`,text:e.text};let t=e;return{type:`file`,file:{kind:`image`,mimeType:t.mimeType,name:`mcp-image`,source:{type:`base64`,data:t.data}}}}):e.filter(e=>e.type===`text`).map(e=>e.text).join(`
8
+ `)}function pt(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
9
+ `)||`MCP tool execution error`}var mt=class{config;client;transport;cachedMcpTools;_connected=!1;constructor(e){this.config=e}get name(){return this.config.name??this.client?.getServerVersion()?.name}get connected(){return this._connected}async connect(e){if(this._connected)return;let t=e?.span?.startSpan(`mcp:connect`,{type:`internal`});this.client=new d({name:`axle`,version:`1.0.0`}),this.config.transport===`stdio`?this.transport=new f({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new p(new URL(this.config.url),{requestInit:this.config.headers?{headers:this.config.headers}:void 0});try{await this.client.connect(this.transport,{signal:e?.signal}),this._connected=!0,t?.end(`ok`)}catch(e){throw t?.end(`error`),e}}async listTools(e){let t=this.assertConnected();return lt(await this.fetchTools(t,e?.span,e?.signal),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return ut(await this.fetchTools(t,e?.span,e?.signal),e?.prefix)}async refreshTools(){return this.assertConnected(),this.cachedMcpTools=void 0,this.listTools()}async close(e){this._connected&&(e?.span?.debug(`mcp:close`),await this.client?.close(),this._connected=!1,this.client=void 0,this.transport=void 0,this.cachedMcpTools=void 0)}async fetchTools(e,t,n){if(this.cachedMcpTools)return this.cachedMcpTools;t?.debug(`mcp:listTools`);let r=await e.listTools(void 0,{signal:n});return this.cachedMcpTools=r.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})),this.cachedMcpTools}assertConnected(){if(!this._connected||!this.client)throw Error(`MCP not connected. Call connect() first.`);return this.client}};function ht(e){return e?.map(e=>({type:`provider`,name:e.name,config:e.config}))}async function gt(e,t){if(e.version!==1)throw new A(`Unsupported agent definition version: ${e.version}`);let n=await t(e),r=e.model??n.model;if(!r)throw new A(`AgentDefinition requires a model or model resolver`);if(e.tools?.length&&!n.tools)throw new A(`AgentDefinition includes tools but resolver did not return tools`);return{provider:n.provider,model:r,system:e.system,name:e.name,tools:n.tools,providerTools:n.providerTools??ht(e.providerTools),mcps:n.mcps??e.mcps?.map(e=>new mt(e)),reasoning:e.request?.reasoning,maxOutputTokens:e.request?.maxOutputTokens,temperature:e.request?.temperature,topP:e.request?.topP,stop:e.request?.stop,toolChoice:e.request?.toolChoice,parallelToolCalls:e.request?.parallelToolCalls,providerOptions:e.request?.providerOptions}}var _t=class e extends A{missingVariables;constructor(t){super(vt(t),{code:`INSTRUCT_VARIABLE_ERROR`,details:{missingVariables:t}}),this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),missingVariables:this.missingVariables}}};function vt(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var yt=class e extends Error{missingVariables;constructor(t){super(xt(t)),this.name=`MissingVariablesError`,this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}};function bt(e,t,n={}){let{placeholderStyle:r=`{{}}`,strict:i=!0}=n,a=r===`{{}}`?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g,o=[];if(e=e.replace(a,(e,n)=>{if(n=n.trim(),Object.prototype.hasOwnProperty.call(t,n)){let e=t[n];return e==null?``:String(e)}return o.push(n),e}),o.length>0){let e=[...new Set(o)];if(i)throw new yt(e)}return e}function xt(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var St=class e{prompt;inputs={};files=[];textReferences=[];contextSections=[];vars;metadata;schema;constructor(e){this.prompt=e.prompt,this.schema=e.schema,this.vars=e.vars??`required`,this.metadata=e.metadata}clone(){let t=new e({prompt:this.prompt,schema:this.schema,vars:this.vars,metadata:this.metadata});return t.inputs={...this.inputs},t.files=[...this.files],t.textReferences=this.textReferences.map(e=>({...e})),t.contextSections=this.contextSections.map(e=>({...e})),t}withInputs(e){let t=this.clone();return t.inputs={...t.inputs,...e},t}withInput(e,t){return this.withInputs({[e]:t})}setInputs(e){this.inputs={...e}}addInput(e,t){this.inputs[e]=t}addFile(e,t){if(typeof e==`string`){this.textReferences.push({content:e,name:t?.name});return}if(e.kind===`text`&&e.source.type===`text`){this.textReferences.push({content:e.source.content,name:t?.name??e.name});return}this.files.push(t?.name?{...e,name:t.name}:e)}addContext(e,t){return this.contextSections.push({content:e,...t?.title?{title:t.title}:{}}),this}hasFiles(){return this.files.length>0}render(e={}){let t;try{t=bt(this.prompt,this.inputs,{strict:(e.vars??this.vars)===`required`})}catch(e){throw e instanceof yt?new _t(e.missingVariables):e}if(this.textReferences.length>0)for(let[e,n]of this.textReferences.entries()){let r=n.name?`: ${n.name}`:``,i=Ct(n.content);t+=`\n\n## Reference ${e+1}${r}\n\n${i}\n${n.content}\n${i}`}for(let[e,n]of this.contextSections.entries()){let r=n.title?`: ${n.title}`:``,i=Ct(n.content);t+=`\n\n## Context ${e+1}${r}\n\n${i}\n${n.content}\n${i}`}if(!this.schema)return t;let n=`# Output Format Instructions
10
10
 
11
11
  Return only valid JSON matching this schema. Do not wrap it in markdown. Do not include prose before or after the JSON.
12
- `,[,r]=ue(this.schema);for(let[e,t]of de(this.schema))n+=`\n- ${e}: ${t}`;return n+=`\n\nExample:\n${JSON.stringify(r,null,2)}\n\n`,n+t}};function St(e){let t=Math.max(0,...Array.from(e.matchAll(/`+/g),e=>e[0].length));return"`".repeat(Math.max(3,t+1))}var Ct=class e extends A{constructor(t,n){super(t,{code:`TASK_ERROR`,id:n?.id,details:{taskType:n?.taskType,taskIndex:n?.taskIndex,...n?.details},cause:n?.cause}),Object.setPrototypeOf(this,e.prototype)}};function X(e,t,n={}){if(!Number.isInteger(e))throw Error(`${t} must be an integer`);if(n.min!==void 0&&e<n.min)throw Error(`${t} must be an integer greater than or equal to ${n.min}`);return e}function wt(e){if(e==null)return{type:`error`,error:{type:`Undetermined`,message:`Unknown error occurred`},usage:{in:0,out:0},raw:e};if(e instanceof Error)return{type:`error`,error:{type:e.name||`Error`,message:e.message||`Unexpected error`},usage:{in:0,out:0},raw:e};if(typeof e==`object`){let t=e,n=t?.error?.error?.type||t?.error?.type||t?.type||t?.code||t?.status||`Undetermined`,r=t?.error?.error?.message||t?.error?.message||t?.message||t?.error||`Unexpected error`;return{type:`error`,error:{type:String(n),message:String(r)},usage:{in:0,out:0},raw:e}}return{type:`error`,error:{type:`Undetermined`,message:String(e)},usage:{in:0,out:0},raw:e}}function Z(e,t=`Operation aborted`){if(e?.aborted)throw new M(t,{reason:e.reason})}function Tt(e,t,n=`Operation aborted`){return t?t.aborted?Promise.reject(new M(n,{reason:t.reason})):new Promise((r,i)=>{let a=()=>{t.removeEventListener(`abort`,a),i(new M(n,{reason:t.reason}))};t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,a),r(e)},e=>{t.removeEventListener(`abort`,a),i(e)})}):e}function Et(e,t,n=`[redacted]`){return Dt(e,null,t,n)}function Dt(e,t,n,r){if(typeof e!=`object`||!e)return typeof e==`string`&&t&&n.has(t)?r:e;if(Array.isArray(e))return e.map(e=>Dt(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=Dt(a,t,n,r);return i}const Ot=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function kt(e){return Et(e,Ot,`[redacted-file-value]`)}const At=20*1024*1024;async function Q(e,t){if(t.signal?.aborted)throw new DOMException(`File resolution aborted`,`AbortError`);let{source:n}=e;if(n.type===`base64`)return jt({type:`base64`,data:n.data},e,t);if(n.type===`text`)return jt({type:`text`,content:n.content},e,t);if(n.type===`url`)return jt({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return jt(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function jt(e,t,n){if(n.accepted.includes(e.type))return{...e,mimeType:e.mimeType??t.mimeType,name:e.name??t.name};throw Error(`File source '${e.type}' is not supported for ${n.provider} ${t.kind} file '${t.name}'. Accepted: ${n.accepted.join(`, `)}`)}const Mt=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function Nt(e){return e.startsWith(`text/`)||Mt.has(e)}function Pt(e){let t=h.getType(e);if(!t){let t=y(e).toLowerCase();throw Error(`Unsupported file type: ${t||`(no extension)`}`)}if(t.startsWith(`image/`))return{kind:`image`,mimeType:t};if(t===`application/pdf`)return{kind:`document`,mimeType:t};if(Nt(t))return{kind:`text`,mimeType:t};{let n=y(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function Ft(e,t){let n=b(e);try{await g(n)}catch{throw Error(`File not found: ${e}`)}let r=await v(n);if(r.size>At)throw Error(`File too large: ${r.size} bytes. Maximum allowed: ${At} bytes`);let i=n.split(`/`).pop()||``,a=Pt(n);if((t||(a.kind===`text`?`utf-8`:`base64`))===`utf-8`){if(a.kind!==`text`)throw Error(`Cannot read ${a.kind} file as text: ${e}`);let t=await _(n,`utf-8`);return{kind:`text`,mimeType:a.mimeType,size:r.size,name:i,source:{type:`text`,content:t}}}else{if(a.kind===`text`)throw Error(`Cannot read text file as binary: ${e}`);let t=(await _(n)).toString(`base64`);return{kind:a.kind,mimeType:a.mimeType,size:r.size,name:i,source:{type:`base64`,data:t}}}}async function It(e,t={model:``}){return Promise.all(e.map(e=>Lt(e,t)))}async function Lt(e,t){if(e.role===`assistant`){let t=[];for(let n of e.content)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`thinking`){let e=n.continuity?.provider===`anthropic`?n.continuity:void 0;n.redacted?t.push({type:`redacted_thinking`,data:e?.redactedData??n.text??``}):e?.signature&&t.push({type:`thinking`,thinking:n.text??``,signature:e.signature})}else n.type===`tool-call`?t.push({type:`tool_use`,id:n.id,name:n.name,input:n.parameters}):n.type===`provider-tool`&&(t.push({type:`server_tool_use`,id:n.id,name:n.name,input:n.input??{}}),n.output!=null&&t.push({type:`web_search_tool_result`,tool_use_id:n.id,content:n.output}));return{role:`assistant`,content:t}}if(e.role===`tool`)return{role:`user`,content:await Promise.all(e.content.map(async e=>({type:`tool_result`,tool_use_id:e.id,content:typeof e.content==`string`?e.content:await $t(e.content,t),...e.isError?{is_error:!0}:{}})))};if(typeof e.content==`string`)return{role:`user`,content:e.content};{let n=[];for(let r of e.content)r.type===`text`?n.push({type:`text`,text:r.text}):r.type===`file`&&n.push(await Rt(r.file,t,`user-message`));return{role:`user`,content:n}}}async function Rt(e,t,n){if(e.kind===`image`)return{type:`image`,source:Bt(await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`Anthropic only supports PDF document files. Received ${e.mimeType}`);let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`document`,source:Vt(r),title:r.name??e.name,citations:{enabled:!0}}}let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Anthropic text source: ${r.type}`);return n===`tool-result`?{type:`text`,text:r.content}:{type:`document`,source:{type:`text`,media_type:`text/plain`,data:r.content},title:r.name??e.name,citations:{enabled:!0}}}function zt(e){if(e===`image/jpeg`||e===`image/png`||e===`image/gif`||e===`image/webp`)return e;throw Error(`Anthropic does not support image MIME type: ${e}. Supported types: image/jpeg, image/png, image/gif, image/webp.`)}function Bt(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:zt(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function Vt(e){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:`application/pdf`,data:e.data};throw Error(`Unsupported Anthropic PDF source: ${e.type}`)}function Ht(e,t=``){return e===!0?Ut(t)?{thinking:{type:`adaptive`},output_config:{effort:`high`}}:{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function Ut(e){let t=e.toLowerCase().match(/claude-(opus|sonnet)-(\d+)-(\d+)/);if(!t)return!1;let[,n,r,i]=t,a=Number(r),o=Number(i);return!Number.isFinite(a)||!Number.isFinite(o)?!1:n===`opus`||n===`sonnet`?a>4||a===4&&o>=6:!1}function Wt(e){return e.map(e=>{let t=l.toJSONSchema(e.schema);if(!Qt(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}const Gt={web_search:`web_search_20250305`};function Kt(e){return Gt[e]??e}function qt(e){return(e??[]).map(e=>({type:e.nativeName??Kt(e.name),name:e.name,...e.config}))}function Jt(e,t,n,r){if(e===void 0&&t!==!1)return{};let i=t===!1?{disable_parallel_tool_use:!0}:{};if(e===void 0||e===`auto`)return{tool_choice:{type:`auto`,...i}};if(e===`required`)return{tool_choice:{type:`any`,...i}};if(e===`none`)return{tool_choice:{type:`none`}};if(!(n?.some(t=>t.name===e.name)||r?.some(t=>t.name===e.name)))throw Error(`Tool choice references an unavailable tool: ${e.name}`);return{tool_choice:{type:`tool`,name:e.name,...i}}}function Yt(e){let t=[];for(let n of e)if(n.type===`text`){let e=n.citations?.map(Xt);t.push({type:`text`,text:n.text,...e&&e.length>0?{citations:e}:{}})}else if(n.type===`thinking`){let e=n.thinking.length===0&&!!n.signature;t.push({type:`thinking`,...n.thinking?{text:n.thinking}:{},redacted:e,continuity:{provider:`anthropic`,signature:n.signature}})}else if(n.type===`redacted_thinking`)t.push({type:`thinking`,redacted:!0,continuity:{provider:`anthropic`,redactedData:n.data}});else if(n.type===`tool_use`){if(typeof n.input!=`object`||n.input===null||Array.isArray(n.input))throw Error(`Invalid tool call input for ${n.name}: expected object, got ${typeof n.input}`);t.push({type:`tool-call`,id:n.id,name:n.name,parameters:n.input})}return t}function Xt(e){switch(e.type){case`char_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`char`,start:e.start_char_index,end:e.end_char_index}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`page_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`page`,start:e.start_page_number,end:e.end_page_number}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`content_block_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`block`,start:e.start_block_index,end:e.end_block_index}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`web_search_result_location`:return{source:{type:`web`,title:e.title??void 0,url:e.url,citedText:e.cited_text},providerMetadata:{type:e.type,encryptedIndex:e.encrypted_index}};case`search_result_location`:return{source:{type:`search-result`,title:e.title??void 0,url:e.source,citedText:e.cited_text,locator:{type:`block`,start:e.start_block_index,end:e.end_block_index}},providerMetadata:{type:e.type,searchResultIndex:e.search_result_index}}}}function Zt(e){switch(e){case`max_tokens`:return`length`;case`end_turn`:return`stop`;case`stop_sequence`:return`stop`;case`tool_use`:return`function_call`;default:return`error`}}function Qt(e){return e&&typeof e==`object`&&e.type===`object`}async function $t(e,t){return Promise.all(e.map(async e=>e.type===`text`?{type:`text`,text:e.text}:Rt(e.file,t,`tool-result`)))}async function en(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v;try{Z(g,`Generate aborted`);let e=await It(r,{model:n,fileResolver:s?.fileResolver,signal:g}),y={model:n,max_tokens:l??16e3,messages:e,...i&&{system:i},...f&&{stop_sequences:qe(f)},...(a||o)&&{tools:[...a?Wt(a):[],...qt(o)]},...Ht(c,n),...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Jt(p,m,a,o),...h};_?.debug(`Anthropic request`,{request:kt(y)});let b=await Tt(t.messages.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);Z(g,`Generate aborted`),v=tn(b)}catch(e){Z(g,`Generate aborted`),v=wt(e)}return _?.debug(`Anthropic response`,{result:v}),v}function tn(e){let t=Zt(e.stop_reason);if(t===`error`)return{type:`error`,error:{type:`Uncaught error`,message:`Stop reason is not recognized or unhandled: ${e.stop_reason}`},usage:rn(e.usage),raw:e};if(t===`function_call`){let t=Yt(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:I(t),usage:rn(e.usage),raw:e}}if(e.type==`message`){let n=Yt(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:I(n),usage:rn(e.usage),raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:rn(e.usage),raw:e}}function nn(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)}function rn(e){return be({in:nn(e),out:e.output_tokens},{cachedIn:e.cache_read_input_tokens??void 0,cacheWriteIn:e.cache_creation_input_tokens??void 0})}function an(){let e=new Map,t=new Map,n=0,r=0,i=0,a=0,o=new Map;function s(s){let c=[];switch(s.type){case`message_start`:n=(s.message.usage?.input_tokens??0)+(s.message.usage?.cache_creation_input_tokens??0)+(s.message.usage?.cache_read_input_tokens??0),a=s.message.usage?.cache_creation_input_tokens??0,i=s.message.usage?.cache_read_input_tokens??0,c.push({type:`start`,id:s.message.id,data:{model:s.message.model,timestamp:Date.now()}});break;case`message_delta`:s.usage&&(r=s.usage.output_tokens??r,s.usage.input_tokens!=null&&(n=s.usage.input_tokens+(s.usage.cache_creation_input_tokens??a)+(s.usage.cache_read_input_tokens??i)),a=s.usage.cache_creation_input_tokens??a,i=s.usage.cache_read_input_tokens??i),s.delta.stop_reason&&c.push({type:`complete`,data:{finishReason:Zt(s.delta.stop_reason),usage:be({in:n,out:r},{cachedIn:i,cacheWriteIn:a})}});case`message_stop`:break;case`content_block_start`:if(s.content_block.type===`text`)e.set(s.index,`text`),c.push({type:`text-start`,data:{index:s.index}});else if(s.content_block.type===`tool_use`){e.set(s.index,`tool`);let t=s.content_block;o.set(s.index,{id:t.id,name:t.name,argumentsBuffer:``}),c.push({type:`tool-call-start`,data:{index:s.index,id:t.id,name:t.name}})}else if(s.content_block.type===`thinking`){e.set(s.index,`thinking`);let t=s.content_block.thinking.length===0&&!!s.content_block.signature;c.push({type:`thinking-start`,data:{index:s.index,redacted:t,continuity:{provider:`anthropic`,signature:s.content_block.signature}}})}else if(s.content_block.type===`redacted_thinking`)e.set(s.index,`thinking`),c.push({type:`thinking-start`,data:{index:s.index,redacted:!0,continuity:{provider:`anthropic`,redactedData:s.content_block.data}}});else if(s.content_block.type===`server_tool_use`){e.set(s.index,`provider-tool`);let n=s.content_block;t.set(n.id,{index:s.index,name:n.name}),c.push({type:`provider-tool-start`,data:{index:s.index,id:n.id,name:n.name}})}else if(s.content_block.type===`web_search_tool_result`){let e=s.content_block,n=t.get(e.tool_use_id);n&&(c.push({type:`provider-tool-complete`,data:{index:n.index,id:e.tool_use_id,name:n.name,output:e.content}}),t.delete(e.tool_use_id))}break;case`content_block_delta`:if(s.delta.type===`text_delta`)c.push({type:`text-delta`,data:{text:s.delta.text,index:s.index}});else if(s.delta.type===`input_json_delta`){let e=o.get(s.index);e&&(e.argumentsBuffer+=s.delta.partial_json,c.push({type:`tool-call-args-delta`,data:{index:s.index,id:e.id,name:e.name,delta:s.delta.partial_json,accumulated:e.argumentsBuffer}}))}else s.delta.type===`thinking_delta`?c.push({type:`thinking-delta`,data:{text:s.delta.thinking,index:s.index}}):s.delta.type===`signature_delta`?c.push({type:`thinking-metadata`,data:{index:s.index,continuity:{provider:`anthropic`,signature:s.delta.signature}}}):s.delta.type===`citations_delta`&&(e.get(s.index)!==`text`&&console.warn(`[Anthropic] received citation delta outside a text block`,{index:s.index,blockType:e.get(s.index)}),c.push({type:`text-citation`,data:{index:s.index,citation:Xt(s.delta.citation)}}));break;case`content_block_stop`:{let t=e.get(s.index);if(t===`text`)c.push({type:`text-complete`,data:{index:s.index}});else if(t===`thinking`)c.push({type:`thinking-complete`,data:{index:s.index}});else if(t!==`provider-tool`&&t===`tool`){let e=o.get(s.index);if(e){try{let t=e.argumentsBuffer?JSON.parse(e.argumentsBuffer):{};c.push({type:`tool-call-complete`,data:{index:s.index,id:e.id,name:e.name,arguments:t}})}catch(t){throw Error(`Failed to parse tool call arguments for ${e.name}: ${t instanceof Error?t.message:String(t)}\nRaw buffer: ${z(e.argumentsBuffer)}`)}o.delete(s.index)}}e.delete(s.index);break}}return c}return{handleEvent:s}}async function*on(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span,v=[...a?Wt(a):[],...qt(o)],y=an();try{let e=await It(r,{model:n,fileResolver:s?.fileResolver,signal:c}),b={model:n,max_tokens:u??sn(n),messages:e,...i&&{system:i},...p&&{stop_sequences:qe(p)},...v.length>0&&{tools:v},...Ht(l,n),...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Jt(m,h,a,o),...g};_?.debug(`Anthropic streaming request`,{request:kt(b)});let x=await t.messages.create({...b,stream:!0},{signal:c});for await(let e of x){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function sn(e){return e in t?t[e]:e.includes(`opus`)?e.match(/opus-4-[6-9]|opus-[5-9]/)?128e3:64e3:e.includes(`sonnet`)||e.includes(`haiku`)?e.match(/claude-3-[0-5]-/)?8192:64e3:16384}function cn(e,t={}){let n=new m({apiKey:e,maxRetries:X(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`anthropic`,resolveProviderToolName(e){return Kt(e)},async createGenerationRequest(e,t){return await en({client:n,model:e,...t})},createStreamingRequest(e,t){return on({client:n,model:e,...t})}}}const ln={Models:i,DefaultModel:s};async function un(e,t={}){let n=X(t.maxRetries??2,`maxRetries`,{min:0}),r=t.timeoutMs===void 0?void 0:X(t.timeoutMs,`timeoutMs`,{min:1}),i=0;for(;;){Z(t.signal,`Request aborted`);let a=dn(t.signal,r);try{let r=await Tt(e({signal:a.signal}),a.signal,`Request aborted`);if(!fn(r.status)||i>=n)return r;let o=pn(r,i);t.onRetry?.({attempt:i+1,delayMs:o,status:r.status}),await hn(o,t.signal),i+=1}catch(e){if(Z(t.signal,`Request aborted`),i>=n)throw e;let r=pn(void 0,i);t.onRetry?.({attempt:i+1,delayMs:r,error:e}),await hn(r,t.signal),i+=1}finally{a.cleanup()}}}function dn(e,t){if(t===void 0)return{signal:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>{n.abort(new DOMException(`Request timed out after ${t}ms`,`TimeoutError`))},t),i=()=>{n.abort(e?.reason)};return e?.aborted?i():e?.addEventListener(`abort`,i,{once:!0}),{signal:n.signal,cleanup:()=>{clearTimeout(r),e?.removeEventListener(`abort`,i)}}}function fn(e){return e===408||e===409||e===429||e>=500}function pn(e,t){let n=mn(e);if(n!==void 0)return n;let r=Math.min(500*2**t,8e3);return r+Math.floor(Math.random()*r*.25)}function mn(e){let t=e?.headers.get(`retry-after-ms`);if(t){let e=Number.parseFloat(t);if(Number.isFinite(e)&&e>=0)return e}let n=e?.headers.get(`retry-after`);if(!n)return;let r=Number.parseFloat(n);if(Number.isFinite(r)&&r>=0)return r*1e3;let i=Date.parse(n);if(Number.isFinite(i))return Math.max(i-Date.now(),0)}async function hn(e,t){if(e<=0){Z(t,`Request aborted`);return}await new Promise((n,r)=>{let i,a=()=>{clearTimeout(i),t?.removeEventListener(`abort`,o)},o=()=>{a(),r(new DOMException(`Request aborted`,`AbortError`))},s=()=>{a(),n()};if(t?.aborted){o();return}i=setTimeout(s,e),t?.addEventListener(`abort`,o,{once:!0})}),Z(t,`Request aborted`)}const gn={web_search:`openrouter:web_search`};function _n(e){return gn[e]}function vn(e,t){let n=[];for(let r of e){let e=r.nativeName??_n(r.name);if(!e){t?.(`providerTool not supported by ChatCompletions provider vendor`,{vendor:`openrouter`,name:r.name});continue}n.push({type:e,...r.config?{parameters:r.config}:{}})}return n.length>0?n:void 0}function yn(e){switch(e.type){case`url_citation`:{let t=e.url_citation;return t?.url?{source:{type:`web`,title:t.title,url:t.url,citedText:t.content},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:e.type}}:null}default:return null}}function bn(e){let t=e.outputSpan;return!t||t.start===void 0&&t.end===void 0?!1:t.start!==0||t.end!==0}function xn(e,t){switch(t){case`openrouter`:return _n(e);default:return}}async function Sn(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>kn(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function Cn(e,t){return t===`together`?e===!0?{reasoning:{enabled:!0}}:e===!1?{reasoning:{enabled:!1}}:{}:e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`none`}:{}}function wn(e){return be({in:e?.prompt_tokens||0,out:e?.completion_tokens||0},{cachedIn:e?.prompt_tokens_details?.cached_tokens??e?.input_tokens_details?.cached_tokens,cacheWriteIn:e?.prompt_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.input_tokens_details?.cache_creation_tokens,reasoningOut:e?.completion_tokens_details?.reasoning_tokens??e?.output_tokens_details?.reasoning_tokens})}function Tn(e){if(e&&e.length>0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}))}function En(e,t,n){if(!(!e||e.length===0)){if(!t){n?.(`providerTools not supported by ChatCompletions provider`);return}switch(t){case`openrouter`:return vn(e,n)}}}function Dn(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,function:{name:e.name}}};throw n?.some(t=>t.name===e.name)?Error(`ChatCompletions does not support provider tool choice: ${e.name}`):Error(`Tool choice references an unavailable tool: ${e.name}`)}function On(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`function_call`;case`content_filter`:case`error`:return`error`;default:return`stop`}}async function kn(e,t){switch(e.role){case`tool`:return An(e,t);case`assistant`:return jn(e);default:return Mn(e,t)}}async function An(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await Pn(e.content,t),tool_call_id:e.id})))}function jn(e){let t=e.content.filter(e=>e.type===`tool-call`),n=e.content.filter(e=>e.type===`text`),r=t.length>0?t.map(e=>({type:`function`,id:e.id,function:{name:e.name,arguments:JSON.stringify(e.parameters)}})):void 0;return{role:`assistant`,content:n.map(e=>e.text).join(``),...r&&{tool_calls:r}}}async function Mn(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>Nn(e,t)))).filter(e=>e!==null);return n.every(e=>e.type===`text`)?{role:`user`,content:n.map(e=>e.text).join(``)}:{role:`user`,content:n}}async function Nn(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?Fn(e.file,t,`user-message`):null}async function Pn(e,t){let n=[];for(let r of e){if(r.type===`text`){n.push(r.text);continue}if(r.file.kind===`text`){let e=await Q(r.file,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:`tool-result`,resolver:t.fileResolver,signal:t.signal});if(e.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${e.type}`);n.push(Rn(r.file,e.content,e.name,e.mimeType));continue}t.warn?.(`ChatCompletions omitted unsupported tool-result file`,{model:t.model,kind:r.file.kind,name:r.file.name,mimeType:r.file.mimeType}),n.push(zn(r.file))}return n.join(`
13
- `)}async function Fn(e,t,n){if(e.kind===`text`){let r=await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${r.type}`);return{type:`text`,text:Rn(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`){if(t.providerDialect===`together`)throw Error(`Together Chat Completions does not support PDF file parts`);if(e.mimeType!==`application/pdf`)throw Error(`ChatCompletions document file inputs currently support PDF only. Received ${e.mimeType}`);let r=await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`file`,file:{filename:r.name??e.name,file_data:Ln(r,e)}}}return{type:`image_url`,image_url:{url:In(await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}}}function In(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions image source: ${e.type}`)}function Ln(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions file source: ${e.type}`)}function Rn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function zn(e){return[`Tool result attachment unavailable.`,`File: ${e.name}`,`MIME type: ${e.mimeType}`,``,`This tool returned a file of kind "${e.kind}", but Chat Completions tool-result messages support text only. The file content was not included. Continue without the file or ask for it to be attached in a user message.`].join(`
14
- `)}async function Bn(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,apiKey:c,providerDialect:l,providerToolVendor:u,maxRetries:d,timeoutMs:f,reasoning:p,maxOutputTokens:m,temperature:h,topP:g,stop:_,toolChoice:v,parallelToolCalls:y,providerOptions:b,signal:x}=e,S=s?.span,C;try{Z(x,`Generate aborted`);let e=await Sn(r,i,{model:n,providerDialect:l,fileResolver:s?.fileResolver,signal:x,warn:S?.warn.bind(S)}),w=Tn(a),T=En(o,u,S?.warn.bind(S)),E=[...w??[],...T??[]],D={model:n,messages:e,...E.length>0?{tools:E}:{},...Cn(p,l),...m===void 0?{}:{max_tokens:m},...h===void 0?{}:{temperature:h},...g===void 0?{}:{top_p:g},..._===void 0?{}:{stop:_},...Dn(v,a,o),...y===void 0?{}:{parallel_tool_calls:y},...b};S?.debug(`ChatCompletions request`,{model:D.model,messages:D.messages.length,tools:D.tools?.length??0}),S?.trace(`ChatCompletions request body`,{request:kt(D)});let O={"Content-Type":`application/json`};c&&(O.Authorization=`Bearer ${c}`);let k=await un(({signal:e})=>fetch(`${t}/chat/completions`,{method:`POST`,headers:O,body:JSON.stringify(D),signal:e}),{maxRetries:d,timeoutMs:f,signal:x,onRetry:e=>S?.warn(`ChatCompletions request retry`,{attempt:e.attempt,maxRetries:d,timeoutMs:f,delayMs:e.delayMs,status:e.status,error:e.error instanceof Error?e.error.message:void 0})});if(!k.ok){let e=await k.text().catch(()=>``);throw Error(`HTTP error! status: ${k.status}${e?` - ${e}`:``}`)}let A=await Tt(k.json(),x,`Generate aborted`);Z(x,`Generate aborted`),C=Vn(A)}catch(e){Z(x,`Generate aborted`),S?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),C=wt(e)}return S?.trace(`ChatCompletions response`,{result:C}),C}function Vn(e){let t=e.choices?.[0];if(!t)return{type:`error`,error:{type:`ChatCompletionsError`,message:`No choices in response`},usage:{in:0,out:0},raw:e};let n=[],r=t.message.reasoning_content??t.message.reasoning;r&&n.push({type:`thinking`,text:r});let i=(t.message.annotations??[]).map(yn).filter(e=>e!==null),a=i.filter(bn),o=i.filter(e=>!bn(e));if(t.message.content&&n.push({type:`text`,text:t.message.content,...a.length>0?{citations:a}:{}}),o.length>0&&n.push({type:`citation`,citations:o}),t.message.tool_calls)for(let e of t.message.tool_calls){let t;try{t=JSON.parse(e.function.arguments)}catch(t){throw Error(`Invalid tool call arguments for ${e.function.name}: ${t instanceof Error?t.message:String(t)}`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Invalid tool call arguments for ${e.function.name}: expected object, got ${typeof t}`);n.push({type:`tool-call`,id:e.id,name:e.function.name,parameters:t})}let s=n.some(e=>e.type===`tool-call`)?On(`tool_calls`):On(t.finish_reason);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:s,content:n,text:I(n),usage:wn(e.usage),raw:e}}function Hn(){let e=new Map,t=0,n=-1,r=``,i=``,a=null,o,s;function c(e){n<0||(a===`text`?e.push({type:`text-complete`,data:{index:n}}):a===`thinking`&&e.push({type:`thinking-complete`,data:{index:n}}),a=null,n=-1)}function l(l){let u=[];l.usage&&(s=wn(l.usage));let d=l.choices?.[0];if(!d)return u;r||(r=l.id,i=l.model,u.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}}));let f=d.delta,p=f.reasoning_content??f.reasoning;if(p&&(a!==`thinking`&&(c(u),n=t++,a=`thinking`,u.push({type:`thinking-start`,data:{index:n}})),u.push({type:`thinking-delta`,data:{index:n,text:p}})),f.content&&(a!==`text`&&(c(u),n=t++,a=`text`,u.push({type:`text-start`,data:{index:n}})),u.push({type:`text-delta`,data:{text:f.content,index:n}})),f.annotations){let e=f.annotations.map(yn).filter(e=>e!==null),r=a===`text`?e.filter(bn):[];for(let e of r)u.push({type:`text-citation`,data:{index:n,citation:e}});let i=e.filter(e=>!r.includes(e));i.length>0&&(c(u),u.push({type:`citation`,data:{index:t++,citations:i}}))}if(f.tool_calls){c(u);for(let n of f.tool_calls){let r=n.index;if(!e.has(r)){let i=t++,a=n.id||`tool-${i}`;e.set(r,{id:a,name:n.function?.name||``,argumentsBuffer:``,partIdx:i}),u.push({type:`tool-call-start`,data:{index:i,id:a,name:n.function?.name||``}})}let i=e.get(r);n.id&&(i.id=n.id),n.function?.name&&(i.name=n.function.name),n.function?.arguments&&(i.argumentsBuffer+=n.function.arguments,u.push({type:`tool-call-args-delta`,data:{index:i.partIdx,id:i.id,name:i.name,delta:n.function.arguments,accumulated:i.argumentsBuffer}}))}}if(d.finish_reason&&o===void 0){c(u);for(let[,t]of e)try{let e=t.argumentsBuffer?JSON.parse(t.argumentsBuffer):{};u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.id,name:t.name,arguments:e}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw buffer: ${z(t.argumentsBuffer)}`)}e.clear(),o=On(d.finish_reason)}return u}function u(){return o===void 0?e.size===0?[]:[{type:`error`,data:{type:`IncompleteStream`,message:`Stream ended without a completion signal while tool call arguments were still buffering for ${[...e.values()].map(e=>`${e.name||`unknown tool`} (${e.id})`).join(`, `)}; arguments were likely truncated or incomplete.`}}]:[{type:`complete`,data:{finishReason:o,usage:s??{in:0,out:0}}}]}return{handleChunk:l,finalize:u}}async function*Un(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,apiKey:l,providerDialect:u,providerToolVendor:d,maxRetries:f,timeoutMs:p,reasoning:m,maxOutputTokens:h,temperature:g,topP:_,stop:v,toolChoice:y,parallelToolCalls:b,providerOptions:x}=e,S=s?.span,C=Hn();try{let e=await Sn(r,i,{model:n,providerDialect:u,fileResolver:s?.fileResolver,signal:c,warn:S?.warn.bind(S)}),w=Tn(a),T=En(o,d,S?.warn.bind(S)),E=[...w??[],...T??[]],D={model:n,messages:e,stream:!0,stream_options:{include_usage:!0},...E.length>0?{tools:E}:{},...Cn(m,u),...h===void 0?{}:{max_tokens:h},...g===void 0?{}:{temperature:g},..._===void 0?{}:{top_p:_},...v===void 0?{}:{stop:v},...Dn(y,a,o),...b===void 0?{}:{parallel_tool_calls:b},...x};S?.debug(`ChatCompletions request`,{model:D.model,messages:D.messages.length,tools:D.tools?.length??0,stream:!0}),S?.trace(`ChatCompletions request body`,{request:kt(D)});let O={"Content-Type":`application/json`};l&&(O.Authorization=`Bearer ${l}`);let k=await un(({signal:e})=>fetch(`${t}/chat/completions`,{method:`POST`,headers:O,body:JSON.stringify(D),signal:e}),{maxRetries:f,timeoutMs:p,signal:c,onRetry:e=>S?.warn(`ChatCompletions streaming request retry`,{attempt:e.attempt,maxRetries:f,timeoutMs:p,delayMs:e.delayMs,status:e.status,error:e.error instanceof Error?e.error.message:void 0})});if(!k.ok){let e=await k.text().catch(()=>``);throw Error(`HTTP error! status: ${k.status}${e?` - ${e}`:``}`)}if(!k.body)throw Error(`Response body is null`);let A=k.body.getReader(),j=new TextDecoder,M=``;for(;;){let{done:e,value:t}=await A.read();if(e)break;M+=j.decode(t,{stream:!0});let n=M.split(`
15
- `);M=n.pop()||``;for(let e of n){let t=e.trim();if(!t||t.startsWith(`:`)||!t.startsWith(`data: `))continue;let n=t.slice(6);if(n===`[DONE]`)continue;let r;try{r=JSON.parse(n)}catch(e){S?.error(`Error parsing ChatCompletions stream chunk`,{error:e instanceof Error?e.message:String(e),line:t});continue}if(r.error){let e=Wn(r.error);yield{type:`error`,data:{type:e.type,message:e.message,raw:r.error}};return}let i=C.handleChunk(r);for(let e of i)yield e}}for(let e of C.finalize())yield e}catch(e){if(c?.aborted)return;S?.error(`Error in ChatCompletions streaming request`,{error:e instanceof Error?e.message:String(e)}),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function Wn(e){if(typeof e==`string`)return{type:`UPSTREAM_STREAM_ERROR`,message:e};let t=e.type??(e.code===void 0?void 0:String(e.code))??`UPSTREAM_STREAM_ERROR`;return{type:t,message:e.message??t}}function Gn(e,t,n){let r=typeof t==`string`?t:t?.apiKey,i=typeof t==`string`?n:t,a=X(i?.maxRetries??2,`maxRetries`,{min:0}),o=i?.timeoutMs===void 0?void 0:X(i.timeoutMs,`timeoutMs`,{min:1}),s=i?.providerToolVendor,c=i?.providerDialect;return{name:`ChatCompletions`,resolveProviderToolName(e){return xn(e,s)},async createGenerationRequest(t,n){return await Bn({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,providerDialect:c,providerToolVendor:s,...n})},createStreamingRequest(t,n){return Un({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,providerDialect:c,providerToolVendor:s,...n})}}}function Kn(e,t,n){let r={};return t&&(r.systemInstruction=t),e&&e.length>0&&(r.tools=e.map(e=>({functionDeclarations:[{name:e.name,description:e.description,parametersJsonSchema:l.toJSONSchema(e.schema)}]}))),n&&Object.assign(r,n),r}const qn={web_search:`googleSearch`,code_execution:`codeExecution`};function Jn(e){return qn[e]??e}function Yn(e,t){if(!(!t||t.length===0)){e.tools||=[];for(let n of t){let t=n.nativeName??Jn(n.name);e.tools.push({[t]:n.config??{}})}}}function Xn(e,t,n,r){if(t===!1)throw Error(`Gemini does not support disabling parallel tool calls`);if(e===void 0)return{};if(e===`auto`)return{toolConfig:{functionCallingConfig:{mode:S.AUTO}}};if(e===`none`)return{toolConfig:{functionCallingConfig:{mode:S.NONE}}};if(e===`required`){if(!n||n.length===0)throw Error(`Gemini requires function tools for required tool choice`);return{toolConfig:{functionCallingConfig:{mode:S.ANY}}}}if(n?.some(t=>t.name===e.name))return{toolConfig:{functionCallingConfig:{mode:S.ANY,allowedFunctionNames:[e.name]}}};throw r?.some(t=>t.name===e.name)?Error(`Gemini does not support provider tool choice: ${e.name}`):Error(`Tool choice references an unavailable tool: ${e.name}`)}function Zn(e){return e===!0?{thinkingConfig:{thinkingBudget:8192,includeThoughts:!0}}:e===!1?{thinkingConfig:{thinkingBudget:0}}:{}}async function Qn(e,t={model:``}){return(await Promise.all(e.map(e=>$n(e,t)))).filter(e=>e!==void 0)}async function $n(e,t){switch(e.role){case`tool`:return er(e,t);case`assistant`:return tr(e);case`user`:return nr(e,t)}}async function er(e,t){return{role:`user`,parts:(await Promise.all(e.content.map(async e=>{let n=typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
16
- `),r={functionResponse:{id:e.id??void 0,name:e.name,response:{output:n}}};return typeof e.content==`string`?[r]:[r,...await Promise.all(e.content.filter(e=>e.type===`file`).map(e=>ir(e.file,t,`tool-result`)))]}))).flat(1)}}function tr(e){let t=[],n=e.content.filter(e=>e.type===`text`);if(n.length>0)for(let e of n){let n=e.text;if(!n)continue;let r={text:n};e.providerMetadata?.thoughtSignature&&(r.thoughtSignature=e.providerMetadata.thoughtSignature),t.push(r)}let r=e.content.filter(e=>e.type===`tool-call`);return r.length>0&&t.push(...r.map(e=>{let t={functionCall:{id:e.id??void 0,name:e.name,args:e.parameters}};return e.providerMetadata?.thoughtSignature&&(t.thoughtSignature=e.providerMetadata.thoughtSignature),t})),{role:`model`,parts:t}}async function nr(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>rr(e,t)))).filter(e=>e!==null)}}async function rr(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?ir(e.file,t,`user-message`):null}async function ir(e,t,n){if(e.kind===`text`){let r=await Q(e,{provider:`gemini`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Gemini text source: ${r.type}`);return{text:or(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`&&e.mimeType!==`application/pdf`)throw Error(`Gemini document file support is limited to PDFs. Received ${e.mimeType}`);return ar(await Q(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function ar(e,t){if(e.type===`base64`)return{inlineData:{mimeType:e.mimeType??t.mimeType,data:e.data}};if(e.type===`url`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.url}};if(e.type===`gemini-file-uri`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.uri}};throw Error(`Unsupported Gemini file source: ${e.type}`)}function or(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function sr(e){switch(e){case x.STOP:return[!0,`stop`];case x.MAX_TOKENS:return[!0,`length`];case x.FINISH_REASON_UNSPECIFIED:case x.SAFETY:case x.RECITATION:case x.LANGUAGE:case x.OTHER:case x.BLOCKLIST:case x.PROHIBITED_CONTENT:case x.SPII:case x.MALFORMED_FUNCTION_CALL:case x.IMAGE_SAFETY:return[!1,`error`]}return[!1,`error`]}async function cr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v={...Zn(c),...l===void 0?{}:{maxOutputTokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{topP:d},...f===void 0?{}:{stopSequences:Array.isArray(f)?f:[f]},...Xn(p,m,a,o),...h},y;try{Z(g,`Generate aborted`);let e=await Qn(r,{model:n,fileResolver:s?.fileResolver,signal:g}),c=Kn(a,i,v);p!==`none`&&Yn(c,o);let l={contents:e,config:c};_?.debug(`Gemini request`,{request:kt(l)});let u=await Tt(t.models.generateContent({model:n,...l}),g,`Generate aborted`);Z(g,`Generate aborted`),y=lr(u,{span:_})}catch(e){Z(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),y=wt(e)}return _?.debug(`Gemini response`,{result:y}),y}function lr(e,t){let{span:n}=t,r=e.usageMetadata?.promptTokenCount??0,i=be({in:r,out:(e.usageMetadata?.totalTokenCount??r)-r},{cachedIn:e.usageMetadata?.cachedContentTokenCount,reasoningOut:e.usageMetadata?.thoughtsTokenCount});if(!e)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};if(e.promptFeedback&&e.promptFeedback.blockReason)return{type:`error`,error:{type:`Blocked`,message:`Response blocked by Google AI: ${e.promptFeedback.blockReason}, ${e.promptFeedback.blockReasonMessage}`},usage:i,raw:e};if(!e.candidates||e.candidates.length===0)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};e.candidates.length>1&&n?.warn(`We received ${e.candidates.length} response candidates`);let a=e.candidates[0],o=a.content?.parts||[],[s,c]=sr(a.finishReason);if(s){let t=[];for(let e=0;e<o.length;e++){let n=o[e];if(n.text)if(n.thought)t.push({type:`thinking`,summary:n.text,...n.thoughtSignature?{continuity:{provider:`gemini`,thoughtSignature:n.thoughtSignature}}:{}});else{let r=dr(a,e);ur(t,{type:`text`,text:n.text,...r.length>0?{citations:r}:{},...n.thoughtSignature?{providerMetadata:{thoughtSignature:n.thoughtSignature}}:{}})}}let n=o.filter(e=>e.functionCall),r=n.length>0?n.map(e=>({call:e.functionCall,thoughtSignature:e.thoughtSignature})):(e.functionCalls??[]).map(e=>({call:e,thoughtSignature:void 0}));if(r.length>0)for(let{call:e,thoughtSignature:n}of r)if(e.args==null)t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:{},...n?{providerMetadata:{thoughtSignature:n}}:{}});else if(typeof e.args!=`object`||Array.isArray(e.args))throw Error(`Invalid tool call arguments for ${e.name}: expected object, got ${typeof e.args}`);else t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:e.args,...n?{providerMetadata:{thoughtSignature:n}}:{}});return{type:`success`,id:e.responseId??``,model:e.modelVersion??``,role:`assistant`,finishReason:r.length>0?`function_call`:c,content:t,text:I(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function ur(e,t){let n=e[e.length-1];if(n?.type===`text`&&!n.citations?.length&&!n.providerMetadata&&!t.citations?.length&&!t.providerMetadata){n.text+=t.text;return}e.push(t)}function dr(e,t){let n=[],r=e.groundingMetadata,i=r?.groundingChunks??[];for(let e of r?.groundingSupports??[])if(!(e.segment?.partIndex!==void 0&&e.segment.partIndex!==t))for(let t of e.groundingChunkIndices??[]){let r=i[t];r&&n.push(fr(r,e))}for(let t of e.citationMetadata?.citations??[])n.push({source:t.uri?{type:`web`,title:t.title,url:t.uri}:{type:`unknown`},outputSpan:{start:t.startIndex,end:t.endIndex},providerMetadata:{license:t.license,publicationDate:t.publicationDate}});return n}function fr(e,t){let n=t.segment;return e.web?{source:{type:`web`,title:e.web.title,url:e.web.uri},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{outputText:n?.text,confidenceScores:t.confidenceScores}}:e.retrievedContext?{source:{type:`retrieved-context`,title:e.retrievedContext.title,uri:e.retrievedContext.uri,citedText:e.retrievedContext.text,locator:{type:`page`,start:e.retrievedContext.pageNumber,end:e.retrievedContext.pageNumber}},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{documentName:e.retrievedContext.documentName,outputText:n?.text,confidenceScores:t.confidenceScores}}:e.maps?{source:{type:`web`,title:e.maps.title,url:e.maps.uri,citedText:e.maps.text},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{placeId:e.maps.placeId,outputText:n?.text,confidenceScores:t.confidenceScores}}:{source:{type:`unknown`},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{chunk:e,outputText:n?.text,confidenceScores:t.confidenceScores}}}function pr(){let e=0,t=-1,n=!1,r=``,i=``,a=0,o=0,s=0,c=0,l=null,u=new Map;function d(e){t<0||(l===`text`?e.push({type:`text-complete`,data:{index:t}}):l===`thinking`&&e.push({type:`thinking-complete`,data:{index:t}}),l=null,t=-1)}function f(f){let p=[];r||(r=f.responseId||`gemini-${Date.now()}`,i=f.modelVersion||`gemini`,p.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}})),f.usageMetadata&&(a=f.usageMetadata.promptTokenCount||0,o=(f.usageMetadata.totalTokenCount||0)-a,s=f.usageMetadata.cachedContentTokenCount||0,c=f.usageMetadata.thoughtsTokenCount||0);let m=f.candidates?.[0];if(!m)return p;let h=m.content?.parts||[];for(let r=0;r<h.length;r++){let i=h[r],a=`thought`in i&&i.thought===!0,o=Object.keys(i),s=o.length===1&&`text`in i&&!i.text;if(!(`thoughtSignature`in i&&!i.text&&!i.functionCall||o.length===2&&`text`in i&&`thoughtSignature`in i&&!i.text||s)&&(a&&i.text?(l!==`thinking`&&(d(p),t=e++,l=`thinking`,p.push({type:`thinking-start`,data:{index:t,...i.thoughtSignature?{continuity:{provider:`gemini`,thoughtSignature:i.thoughtSignature}}:{}}})),p.push({type:`thinking-summary-delta`,data:{index:t,text:i.text}})):i.text&&!a?(l!==`text`&&(d(p),t=e++,l=`text`,p.push({type:`text-start`,data:{index:t}})),u.set(r,t),p.push({type:`text-delta`,data:{text:i.text,index:t}})):i.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(i))}`),i.functionCall)){d(p),n=!0;let t=e++,r=i.functionCall.id||`tool-${t}`,a=i.functionCall.name??``;p.push({type:`tool-call-start`,data:{index:t,id:r,name:a}});let o=i.functionCall.args??{},s=JSON.stringify(o);p.push({type:`tool-call-args-delta`,data:{index:t,id:r,name:a,delta:s,accumulated:s}});let c={index:t,id:r,name:a,arguments:o},l=i;l.thoughtSignature&&(c.providerMetadata={thoughtSignature:l.thoughtSignature}),p.push({type:`tool-call-complete`,data:c})}}for(let{partIndex:e,citation:n}of mr(m)){let r=e===void 0?t:u.get(e);if(r===void 0||r<0){console.warn(`[Gemini] received citation without a resolvable text part`,{citation:n});continue}p.push({type:`text-citation`,data:{index:r,citation:n}})}if(m.finishReason&&m.finishReason!==x.FINISH_REASON_UNSPECIFIED){d(p);let[e,t]=sr(m.finishReason),r=n?`function_call`:t;!e&&!n?p.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${m.finishReason}`,usage:be({in:a,out:o},{cachedIn:s,reasoningOut:c}),raw:f}}):p.push({type:`complete`,data:{finishReason:r,usage:be({in:a,out:o},{cachedIn:s,reasoningOut:c})}})}return p}return{handleChunk:f}}function mr(e){let t=[],n=e.groundingMetadata,r=n?.groundingChunks??[];for(let e of n?.groundingSupports??[])for(let n of e.groundingChunkIndices??[]){let i=r[n];i&&t.push({partIndex:e.segment?.partIndex,citation:hr(i,e)})}for(let n of e.citationMetadata?.citations??[])t.push({citation:{source:n.uri?{type:`web`,title:n.title,url:n.uri}:{type:`unknown`},outputSpan:{start:n.startIndex,end:n.endIndex},providerMetadata:{license:n.license,publicationDate:n.publicationDate}}});return t}function hr(e,t){let n=t.segment;return e.web?{source:{type:`web`,title:e.web.title,url:e.web.uri},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{outputText:n?.text,confidenceScores:t.confidenceScores}}:e.retrievedContext?{source:{type:`retrieved-context`,title:e.retrievedContext.title,uri:e.retrievedContext.uri,citedText:e.retrievedContext.text,locator:{type:`page`,start:e.retrievedContext.pageNumber,end:e.retrievedContext.pageNumber}},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{documentName:e.retrievedContext.documentName,outputText:n?.text,confidenceScores:t.confidenceScores}}:{source:{type:`unknown`},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{chunk:e,outputText:n?.text,confidenceScores:t.confidenceScores}}}async function*gr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span,v=Kn(a,i,{...Zn(l),...u===void 0?{}:{maxOutputTokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{topP:f},...p===void 0?{}:{stopSequences:Array.isArray(p)?p:[p]},...Xn(m,h,a,o),...g});m!==`none`&&Yn(v,o);let y=pr();try{let e={contents:await Qn(r,{model:n,fileResolver:s?.fileResolver,signal:c}),config:v};_?.debug(`Gemini streaming request`,{request:kt(e)});let i=await t.models.generateContentStream({model:n,...e});for await(let e of i){let t=y.handleChunk(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;_?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function _r(e,t={}){let n=new C({apiKey:e,httpOptions:{retryOptions:{attempts:vr(t.maxRetries)},...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}}});return{name:`Gemini`,resolveProviderToolName(e){return Jn(e)},async createGenerationRequest(e,t){return await cr({client:n,model:e,...t})},createStreamingRequest(e,t){return gr({client:n,model:e,...t})}}}function vr(e=2){return X(e,`maxRetries`,{min:0})+1}const yr={Models:r,DefaultModel:n};async function br(e){let{provider:t,model:n,messages:r,system:i,tools:a,providerTools:o,span:s,fileResolver:c,...l}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,providerTools:o,runtime:{span:s,fileResolver:c},...l})}async function xr(e){if(`instruct`in e){let{instruct:t,messages:n,...r}=e,i=he(t),a=await Sr({...r,messages:[...n??[],i.message]},k());if(!a.ok)return a;try{return{...a,response:i.parse(a.final)}}catch(e){return{ok:!1,messages:a.messages,final:a.final,usage:a.usage,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)}}}}return Sr(e,k())}async function Sr(e,t){let{provider:n,model:r,messages:i,system:a,onToolCall:o,maxIterations:s,span:c,fileResolver:l,reasoning:u,maxOutputTokens:d,temperature:f,topP:p,stop:m,toolChoice:h,parallelToolCalls:g,providerOptions:_,signal:v=new AbortController().signal}=e,y=Ie(Fe(e),{provider:n,model:r,span:c,configuration:t}),b=[...i],x=[],S=K(),C=0,w,T=e=>{b.push(e),x.push(e)},E=e=>(c?.setResult({kind:`llm`,model:r,request:{messages:i},response:{content:e.ok?e.final.content:null},usage:xe(e.usage),finishReason:e.ok?e.final.finishReason:void 0}),c?.end(e.ok?`ok`:`error`),e),D=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??r,request:{messages:b},response:{content:t.content},usage:xe(t.usage),finishReason:t.finishReason}),e.end()};try{for(;;){if(Z(v,`Generate aborted`),s!==void 0&&C>=s)return E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${s})`}}},usage:S});C+=1;let e=c?.startSpan(`turn-${C}`,{type:`llm`}),t=y.executable(),i=t.length>0?t.map(e=>({name:e.name,description:e.description,schema:e.schema})):void 0,O=y.provider(),k;try{k=await br({provider:n,model:r,messages:b,system:a,tools:i,providerTools:O.length>0?O:void 0,span:e,fileResolver:l,reasoning:u,maxOutputTokens:d,temperature:f,topP:p,stop:m,toolChoice:h,parallelToolCalls:g,providerOptions:_,signal:v}),Z(v,`Generate aborted`)}catch(t){throw t instanceof Error&&t.name===`AbortError`&&e?.end(`ok`),t}if(ke(S,k,{provider:n.name,model:k.type===`error`?r:k.model??r}),k.type!==`error`&&Ae(e,k.content),D(e,k),k.type===`error`)return E({ok:!1,messages:x,error:{kind:`model`,error:k},usage:S});let A={role:`assistant`,id:k.id,model:k.model,content:k.content,finishReason:k.finishReason};if(T(A),w=A,k.finishReason!==`function_call`)return E({ok:!0,response:w,messages:x,final:w,usage:S});let j=L(k.content);if(j.length===0)return E({ok:!0,response:w,messages:x,final:w,usage:S});let{results:M,usage:N}=await Le(j,o,v,y,c);q(S,N),Z(v,`Generate aborted`),M.length>0&&T({role:`tool`,id:crypto.randomUUID(),content:M})}}catch(e){throw e instanceof P?(c?.end(`error`),new P(e.message,{toolName:e.toolName,messages:e.messages??x,partial:e.partial??w,usage:_e(S,e.usage),cause:e.cause})):e instanceof M?(c?.end(`ok`),new M(`Generate aborted`,{reason:e.reason,messages:e.messages??x,partial:e.partial,usage:_e(S,e.usage)})):e instanceof Error&&e.name===`AbortError`?(c?.end(`ok`),new M(`Generate aborted`,{reason:v.reason,messages:x,usage:S})):e}}function Cr(e){if(e&&e.length>0)return e.map(e=>({type:`function`,strict:!0,name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}))}const wr={web_search:`web_search_preview`,code_execution:`code_interpreter`};function Tr(e){return wr[e]??e}function Er(e){return e?.map(e=>({type:e.nativeName??Tr(e.name),...e.config}))}function Dr(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,name:e.name}};let r=n?.find(t=>t.name===e.name);if(r)return{tool_choice:{type:r.nativeName??Tr(r.name)}};throw Error(`Tool choice references an unavailable tool: ${e.name}`)}function Or(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`none`}}:{}}async function kr(e,t={model:``}){return(await Promise.all(e.map(e=>Ar(e,t)))).flat(1)}async function Ar(e,t){switch(e.role){case`tool`:return jr(e,t);case`assistant`:return Mr(e);default:return Nr(e,t)}}async function jr(e,t){return Promise.all(e.content.map(async e=>({type:`function_call_output`,call_id:e.id,output:typeof e.content==`string`?e.content:await Promise.all(e.content.map(e=>e.type===`text`?Promise.resolve({type:`input_text`,text:e.text}):Fr(e.file,t,`tool-result`)))})))}function Mr(e){let t=[],n=I(e.content);n&&t.push({role:e.role,content:n});let r=e.content.filter(e=>e.type===`thinking`);for(let e of r)e.continuity?.provider===`openai`&&t.push({type:`reasoning`,id:e.id,summary:e.summary?[{type:`summary_text`,text:e.summary}]:[],...e.text?{content:[{type:`reasoning_text`,text:e.text}]}:{},encrypted_content:e.continuity.encrypted});let i=e.content.filter(e=>e.type===`tool-call`);for(let e of i)t.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.parameters)});let a=e.content.filter(e=>e.type===`provider-tool`);for(let e of a)e.output!=null&&t.push(e.output);return t}async function Nr(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>Pr(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function Pr(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?Fr(e.file,t,`user-message`):(e.type,null)}async function Fr(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:Ir(await Q(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e),detail:`auto`};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`OpenAI file inputs currently support PDF documents. Received ${e.mimeType}`);return Lr(await Q(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}let r=await Q(e,{provider:`openai`,model:t.model,accepted:[`text`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return r.type===`text`?{type:`input_text`,text:r.content}:Lr(r,e)}function Ir(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported OpenAI image source: ${e.type}`)}function Lr(e,t){if(e.type===`url`)return{type:`input_file`,filename:e.name??t.name,file_url:e.url};if(e.type===`base64`)return{type:`input_file`,filename:e.name??t.name,file_data:`data:${e.mimeType??t.mimeType};base64,${e.data}`};throw Error(`Unsupported OpenAI file source: ${e.type}`)}async function Rr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v;try{if(Z(g,`Generate aborted`),f!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let e=[...Cr(a)??[],...Er(o)??[]],y={model:n,input:await kr(r,{model:n,fileResolver:s?.fileResolver,signal:g}),...i&&{instructions:i},...e.length>0?{tools:e}:{},...Or(c),...l===void 0?{}:{max_output_tokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Dr(p,a,o),...m===void 0?{}:{parallel_tool_calls:m},...h};_?.debug(`OpenAI ResponsesAPI request`,{request:kt(y)});let b=await Tt(t.responses.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);Z(g,`Generate aborted`),v=zr(b)}catch(e){Z(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),v=wt(e)}return _?.debug(`OpenAI ResponsesAPI response`,{result:v}),v}function zr(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:Hr(e.usage),raw:e};let t=e.output?.filter(e=>e.type===`reasoning`)?.map(e=>e),n=[];if(t&&t.length>0)for(let e of t)(e.summary?.[0]?.text||e.content?.[0]?.text||e.encrypted_content)&&n.push({type:`thinking`,id:e.id,...e.content?.[0]?.text?{text:e.content[0].text}:{},...e.summary?.[0]?.text?{summary:e.summary[0].text}:{},...e.encrypted_content?{continuity:{provider:`openai`,encrypted:e.encrypted_content}}:{}});let r=Br(e);r.length>0?n.push(...r):e.output_text&&n.push({type:`text`,text:e.output_text});let i=e.output?.filter(e=>e.type===`function_call`);if(i&&i.length>0)for(let e of i){let t=e;try{n.push({type:`tool-call`,id:t.call_id||t.id||``,name:t.name||``,parameters:t.arguments?JSON.parse(t.arguments):{}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${t.arguments}`)}}return{type:`success`,id:e.id,model:e.model||``,role:`assistant`,finishReason:e.incomplete_details?`error`:i&&i.length>0?`function_call`:`stop`,content:n,text:I(n),usage:Hr(e.usage),raw:e}}function Br(e){let t=[];for(let n of e.output??[])if(n.type===`message`)for(let e of n.content??[]){if(e.type!==`output_text`)continue;let n=(e.annotations??[]).map(Vr).filter(e=>e!==null);t.push({type:`text`,text:e.text,...n.length>0?{citations:n}:{}})}return t}function Vr(e){if(!e||typeof e!=`object`)return null;let t=e;switch(t.type){case`url_citation`:return{source:{type:`web`,title:t.title,url:t.url},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type}};case`file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};case`container_file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type,containerId:t.container_id}};case`file_path`:return{source:{type:`document`,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};default:return{source:{type:`unknown`},providerMetadata:t}}}function Hr(e){return be({in:e?.input_tokens??0,out:e?.output_tokens??0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}function Ur(){let e=``,t=``,n=0,r=-1,i=!1,a=new Map,o=new Map,s=new Map,c=new Set([`web_search_call`,`file_search_call`,`code_interpreter_call`]),l=new Map;function u(u){let d=[];switch(u.type){case`response.created`:e=u.response.id||`openai-${Date.now()}`,t=u.response.model,d.push({type:`start`,id:e,data:{model:t,timestamp:Date.now()}});break;case`response.output_text.delta`:{let e=Wr(u.item_id,u.content_index);r===-1&&(r=n++,a.set(e,r),d.push({type:`text-start`,data:{index:r}})),d.push({type:`text-delta`,data:{text:u.delta,index:r}});break}case`response.output_text.done`:{let e=Wr(u.item_id,u.content_index);a.set(e,r),r>=0&&(d.push({type:`text-complete`,data:{index:r}}),r=-1);break}case`response.output_text.annotation.added`:{let e=Gr(u.annotation);if(!e)break;let t=a.get(Wr(u.item_id,u.content_index));t===void 0&&console.warn(`[OpenAI] received text annotation without a resolved text part; falling back to current part`,{itemId:u.item_id,contentIndex:u.content_index}),d.push({type:`text-citation`,data:{index:t??r,citation:e}});break}case`response.function_call_arguments.delta`:{let e=u.item_id;if(!l.has(e)){let t=o.get(e),r=t?.name||``,i=t?.callId||e,a=n++;l.set(e,{id:e,callId:i,name:r,argumentsBuffer:``,partIdx:a}),d.push({type:`tool-call-start`,data:{index:a,id:i,name:r}})}let t=l.get(e);t.argumentsBuffer+=u.delta,d.push({type:`tool-call-args-delta`,data:{index:t.partIdx,id:t.callId,name:t.name,delta:u.delta,accumulated:t.argumentsBuffer}});break}case`response.function_call_arguments.done`:{i=!0;let e=u.item_id,t=l.get(e),n=u.name||t?.name||``;if(t){try{let e=u.arguments?JSON.parse(u.arguments):{};d.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.callId,name:n,arguments:e}})}catch(e){throw Error(`Failed to parse function call arguments for ${n}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${u.arguments}`)}l.delete(e)}break}case`response.completed`:{let e=u.response.usage;d.push({type:`complete`,data:{finishReason:u.response.incomplete_details?`error`:i?`function_call`:`stop`,usage:be({in:e?.input_tokens||0,out:e?.output_tokens||0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}});break}case`response.failed`:d.push({type:`error`,data:{type:`RESPONSES_API_ERROR`,message:`Response failed: ${u.response.status}`,raw:u}});break;case`response.output_item.added`:if(u.item?.type===`reasoning`){let e=u.item;r=n++,d.push({type:`thinking-start`,data:{index:r,id:e.id,...e.encrypted_content?{continuity:{provider:`openai`,encrypted:e.encrypted_content}}:{}}})}else if(u.item?.type===`function_call`){let e=u.item,t=e.id||e.call_id;t&&o.set(t,{name:e.name||``,callId:e.call_id||t})}else if(u.item&&c.has(u.item.type)){let e=u.item,t=n++;s.set(e.id,t),d.push({type:`provider-tool-start`,data:{index:t,id:e.id,name:e.type}})}break;case`response.output_item.done`:if(u.item?.type===`reasoning`&&r>=0)d.push({type:`thinking-complete`,data:{index:r}}),r=-1;else if(u.item&&c.has(u.item.type)){let e=u.item,t=s.get(e.id);t!==void 0&&(d.push({type:`provider-tool-complete`,data:{index:t,id:e.id,name:e.type,output:u.item}}),s.delete(e.id))}break;case`response.reasoning_text.delta`:u.delta&&d.push({type:`thinking-delta`,data:{index:r,text:u.delta}});break;case`response.reasoning_summary_text.delta`:u.delta&&d.push({type:`thinking-summary-delta`,data:{index:r,text:u.delta}});break;case`response.in_progress`:case`response.content_part.added`:case`response.content_part.done`:case`response.reasoning_summary_part.added`:case`response.reasoning_summary_part.done`:case`response.reasoning_summary_text.done`:case`response.reasoning_text.done`:case`response.web_search_call.in_progress`:case`response.web_search_call.searching`:case`response.web_search_call.completed`:break;default:console.log(`[OpenAI] unhandled stream event: ${u.type}`)}return d}return{handleEvent:u}}function Wr(e,t){return`${e}:${t}`}function Gr(e){if(!e||typeof e!=`object`)return null;let t=e;switch(t.type){case`url_citation`:return{source:{type:`web`,title:t.title,url:t.url},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type}};case`file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};case`container_file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type,containerId:t.container_id}};case`file_path`:return{source:{type:`document`,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};default:return{source:{type:`unknown`},providerMetadata:t}}}async function*Kr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span;if(p!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let v=[...Cr(a)??[],...Er(o)??[]],y=Ur();try{let e={model:n,input:await kr(r,{model:n,fileResolver:s?.fileResolver,signal:c}),...i&&{instructions:i},stream:!0,...v.length>0?{tools:v}:{},...Or(l),...u===void 0?{}:{max_output_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Dr(m,a,o),...h===void 0?{}:{parallel_tool_calls:h},...g};_?.debug(`OpenAI ResponsesAPI streaming request`,{request:kt(e)});let p=t.responses.stream(e,...c?[{signal:c}]:[]);for await(let e of p){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;_?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function qr(e,t={}){let n=new w({apiKey:e,maxRetries:X(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`OpenAI`,resolveProviderToolName(e){return Tr(e)},async createGenerationRequest(e,t){return await Rr({client:n,model:e,...t})},createStreamingRequest(e,t){return Kr({client:n,model:e,...t})}}}const Jr={Models:a,DefaultModel:o};function Yr(e){return{kind:`agent`,name:e.name,description:e.description,schema:e.schema,async execute(t,n){let r=await e.createAgent(t,n),i=Xr(e.prompt,t),a=r.on(e=>n.emit({type:`turn-event`,event:e})),o;try{o=await r.send(i,{...e.request,signal:n.signal}).final}catch(t){throw Zr(t,e.name)}finally{a()}if(o.usage&&n.reportUsage?.(o.usage),!o.ok)throw Error(`Subagent failed: ${JSON.stringify(o.error)}`);let s=o.response;return typeof s==`string`?s:JSON.stringify(s)}}}function Xr(e,t){return typeof e==`function`?e(t):typeof e==`string`?e:`Complete this delegated task. Input: ${JSON.stringify(t)}`}function Zr(e,t){return e instanceof P?new P(e.message,{toolName:t,usage:e.usage,cause:e}):e instanceof M?new M(e.message,{reason:e.reason,usage:e.usage}):e}function Qr(e,t={}){let n=t.maxItems??50,r=Math.max(1,t.maxConcurrency??8),i=u.object({items:u.array(e.schema).min(1).max(n).describe(`Inputs to run through ${e.name}. Results are returned in the same order.`)});return{...e.kind?{kind:e.kind}:{},name:t.name??`${e.name}_batch`,description:t.description??`Run ${e.name} for multiple inputs concurrently and return ordered per-item results.`,schema:i,async execute(t,n){let i=await $r(t.items,r,n.signal,async(t,r)=>{try{return{index:r,input:t,ok:!0,output:await e.execute(t,n)}}catch(e){if(e instanceof P||e instanceof M)throw e;return{index:r,input:t,ok:!1,error:{type:`execution`,message:e instanceof Error?e.message:String(e)}}}});return JSON.stringify({results:i})}}}async function $r(e,t,n,r){let i=Array(e.length),a=0,o=!1,s=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:s},async()=>{for(;!o&&a<e.length;){if(n.aborted)throw o=!0,new M(`Operation aborted`,{reason:n.reason});let t=a++;try{i[t]=await r(e[t],t)}catch(e){throw o=!0,e}}})),i}const ei={trace:0,debug:1,info:2,warn:3,error:4};var ti=class{minLevel;showInternal;showTimestamp;showDuration;markdown;output;spans=new Map;visibleDepths=new Map;constructor(e={}){this.minLevel=e.minLevel??`info`,this.showInternal=e.showInternal??!1,this.showTimestamp=e.showTimestamp??!0,this.showDuration=e.showDuration??!0,this.markdown=e.markdown??!1,this.output=e.output??console.log}shouldShowEvent(e){return ei[e]>=ei[this.minLevel]}isSpanVisible(e){return!(e.type===`internal`&&!this.showInternal)}findVisibleAncestor(e){let t=e.parentSpanId;for(;t;){let e=this.spans.get(t);if(!e)break;if(this.isSpanVisible(e))return e;t=e.parentSpanId}return null}calculateVisibleDepth(e){if(!this.isSpanVisible(e))return-1;let t=this.findVisibleAncestor(e);return t?(this.visibleDepths.get(t.spanId)??0)+1:0}formatTimestamp(){if(!this.showTimestamp)return``;let e=new Date;return`[${e.toTimeString().slice(0,8)}.${e.getMilliseconds().toString().padStart(3,`0`)}] `}formatDuration(e){if(!this.showDuration||!e.endTime)return``;let t=e.endTime-e.startTime;return t<1e3?` (${Math.round(t)}ms)`:` (${(t/1e3).toFixed(2)}s)`}formatIndent(e){return` `.repeat(e)}formatSpanName(e){return e.type?`[${e.type}] ${e.name}`:e.name}renderMarkdown(e){return ni(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,t);let n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatSpanName(e);this.output(`${r}${n}START ${i}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.visibleDepths.get(e.spanId)??0,n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatDuration(e),a=this.formatSpanName(e),o=e.status===`error`?` [ERROR]`:``;if(this.output(`${r}${n}END ${a}${i}${o}`),e.result?.kind===`llm`){let t=e.result,i=[`model=${t.model}`];if(t.finishReason&&i.push(`finishReason=${t.finishReason}`),t.usage&&(t.usage.inputTokens!==void 0&&i.push(`inputTokens=${t.usage.inputTokens}`),t.usage.outputTokens!==void 0&&i.push(`outputTokens=${t.usage.outputTokens}`),t.usage.cachedInputTokens!==void 0&&i.push(`cachedInputTokens=${t.usage.cachedInputTokens}`),t.usage.cacheWriteInputTokens!==void 0&&i.push(`cacheWriteInputTokens=${t.usage.cacheWriteInputTokens}`),t.usage.reasoningOutputTokens!==void 0&&i.push(`reasoningOutputTokens=${t.usage.reasoningOutputTokens}`)),this.output(`${r}${n} INFO LLM complete ${i.join(` `)}`),this.shouldShowEvent(`debug`)&&t.response.content){let e=(typeof t.response.content==`string`?t.response.content:JSON.stringify(t.response.content,null,2)).split(`
17
- `);for(let t of e)this.output(`${r}${n} DEBUG ${t}`)}}}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,t){if(!this.shouldShowEvent(t.level))return;this.spans.set(e.spanId,e);let n;if(this.isSpanVisible(e))n=this.visibleDepths.get(e.spanId)??0;else{let t=this.findVisibleAncestor(e);n=t?this.visibleDepths.get(t.spanId)??0:0}let r=this.formatIndent(n+1),i=this.formatTimestamp(),a=t.level.toUpperCase().padEnd(5),o=this.markdown&&t.attributes?.markdown===!0,s=t.attributes?Object.entries(t.attributes).filter(([e])=>e!==`markdown`):[],c=t.name;o&&(c=this.renderMarkdown(c));let l=`${i}${r}${a} ${c}`;if(s.length>0){let e=s.map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(` `);l+=` ${e}`}this.output(l)}};function ni(e){return ri(E.lexer(e))}function ri(e=[]){return e.map(e=>ii(e)).filter(e=>e.length>0).join(`
18
- `)}function ii(e){switch(e.type){case`space`:return``;case`heading`:return T.bold($(e.tokens));case`paragraph`:return $(e.tokens);case`blockquote`:return ui(ri(e.tokens),`> `);case`code`:return(e.lang?T.dim(`${e.lang}\n`):``)+T.yellow(e.text);case`list`:return oi(e)?ci(e):e.raw;case`hr`:return T.dim(`-`.repeat(40));case`table`:return si(e)?li(e):e.raw;case`html`:return e.text;case`text`:return e.tokens?$(e.tokens):fi(e.text);default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function $(e=[]){return e.map(e=>ai(e)).join(``)}function ai(e){switch(e.type){case`text`:case`escape`:return fi(e.text);case`strong`:return T.bold($(e.tokens));case`em`:return T.italic($(e.tokens));case`codespan`:return T.yellow(e.text);case`del`:return T.strikethrough($(e.tokens));case`link`:{let t=$(e.tokens);return e.href&&e.href!==e.text?`${T.blue.underline(t)} ${T.dim(`(${e.href})`)}`:T.blue.underline(t)}case`image`:return e.text?`${e.text} (${e.href})`:e.href;case`br`:return`
19
- `;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function oi(e){return e.type===`list`&&`items`in e&&Array.isArray(e.items)}function si(e){return e.type===`table`&&`header`in e&&`rows`in e}function ci(e){return e.items.map((t,n)=>{let r=e.ordered?`${Number(e.start||1)+n}. `:`- `,i=t.task?`[${t.checked?`x`:` `}] `:``,a=ri(t.tokens).trimEnd();return r+i+di(a,r.length+i.length)}).join(`
20
- `)}function li(e){let t=e.header.map(e=>$(e.tokens)).join(` | `),n=e.rows.map(e=>e.map(e=>$(e.tokens)).join(` | `));return[T.bold(t),...n].join(`
21
- `)}function ui(e,t){return e.split(`
12
+ `,[,r]=ue(this.schema);for(let[e,t]of de(this.schema))n+=`\n- ${e}: ${t}`;return n+=`\n\nExample:\n${JSON.stringify(r,null,2)}\n\n`,n+t}};function Ct(e){let t=Math.max(0,...Array.from(e.matchAll(/`+/g),e=>e[0].length));return"`".repeat(Math.max(3,t+1))}var wt=class e extends A{constructor(t,n){super(t,{code:`TASK_ERROR`,id:n?.id,details:{taskType:n?.taskType,taskIndex:n?.taskIndex,...n?.details},cause:n?.cause}),Object.setPrototypeOf(this,e.prototype)}};function X(e,t,n={}){if(!Number.isInteger(e))throw Error(`${t} must be an integer`);if(n.min!==void 0&&e<n.min)throw Error(`${t} must be an integer greater than or equal to ${n.min}`);return e}function Tt(e){if(e==null)return{type:`error`,error:{type:`Undetermined`,message:`Unknown error occurred`},usage:{in:0,out:0},raw:e};if(e instanceof Error)return{type:`error`,error:{type:e.name||`Error`,message:e.message||`Unexpected error`},usage:{in:0,out:0},raw:e};if(typeof e==`object`){let t=e,n=t?.error?.error?.type||t?.error?.type||t?.type||t?.code||t?.status||`Undetermined`,r=t?.error?.error?.message||t?.error?.message||t?.message||t?.error||`Unexpected error`;return{type:`error`,error:{type:String(n),message:String(r)},usage:{in:0,out:0},raw:e}}return{type:`error`,error:{type:`Undetermined`,message:String(e)},usage:{in:0,out:0},raw:e}}function Z(e,t=`Operation aborted`){if(e?.aborted)throw new M(t,{reason:e.reason})}function Et(e,t,n=`Operation aborted`){return t?t.aborted?Promise.reject(new M(n,{reason:t.reason})):new Promise((r,i)=>{let a=()=>{t.removeEventListener(`abort`,a),i(new M(n,{reason:t.reason}))};t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,a),r(e)},e=>{t.removeEventListener(`abort`,a),i(e)})}):e}function Dt(e,t,n=`[redacted]`){return Ot(e,null,t,n)}function Ot(e,t,n,r){if(typeof e!=`object`||!e)return typeof e==`string`&&t&&n.has(t)?r:e;if(Array.isArray(e))return e.map(e=>Ot(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=Ot(a,t,n,r);return i}const kt=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function At(e){return Dt(e,kt,`[redacted-file-value]`)}const jt=20*1024*1024;async function Q(e,t){if(t.signal?.aborted)throw new DOMException(`File resolution aborted`,`AbortError`);let{source:n}=e;if(n.type===`base64`)return Mt({type:`base64`,data:n.data},e,t);if(n.type===`text`)return Mt({type:`text`,content:n.content},e,t);if(n.type===`url`)return Mt({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return Mt(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function Mt(e,t,n){if(n.accepted.includes(e.type))return{...e,mimeType:e.mimeType??t.mimeType,name:e.name??t.name};throw Error(`File source '${e.type}' is not supported for ${n.provider} ${t.kind} file '${t.name}'. Accepted: ${n.accepted.join(`, `)}`)}const Nt=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function Pt(e){return e.startsWith(`text/`)||Nt.has(e)}function Ft(e){let t=h.getType(e);if(!t){let t=y(e).toLowerCase();throw Error(`Unsupported file type: ${t||`(no extension)`}`)}if(t.startsWith(`image/`))return{kind:`image`,mimeType:t};if(t===`application/pdf`)return{kind:`document`,mimeType:t};if(Pt(t))return{kind:`text`,mimeType:t};{let n=y(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function It(e,t){let n=b(e);try{await g(n)}catch{throw Error(`File not found: ${e}`)}let r=await v(n);if(r.size>jt)throw Error(`File too large: ${r.size} bytes. Maximum allowed: ${jt} bytes`);let i=n.split(`/`).pop()||``,a=Ft(n);if((t||(a.kind===`text`?`utf-8`:`base64`))===`utf-8`){if(a.kind!==`text`)throw Error(`Cannot read ${a.kind} file as text: ${e}`);let t=await _(n,`utf-8`);return{kind:`text`,mimeType:a.mimeType,size:r.size,name:i,source:{type:`text`,content:t}}}else{if(a.kind===`text`)throw Error(`Cannot read text file as binary: ${e}`);let t=(await _(n)).toString(`base64`);return{kind:a.kind,mimeType:a.mimeType,size:r.size,name:i,source:{type:`base64`,data:t}}}}async function Lt(e,t={model:``}){return Promise.all(e.map(e=>Rt(e,t)))}async function Rt(e,t){if(e.role===`assistant`){let t=[];for(let n of e.content)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`thinking`){let e=n.continuity?.provider===`anthropic`?n.continuity:void 0;n.redacted?t.push({type:`redacted_thinking`,data:e?.redactedData??n.text??``}):e?.signature&&t.push({type:`thinking`,thinking:n.text??``,signature:e.signature})}else n.type===`tool-call`?t.push({type:`tool_use`,id:n.id,name:n.name,input:n.parameters}):n.type===`provider-tool`&&(t.push({type:`server_tool_use`,id:n.id,name:n.name,input:n.input??{}}),n.output!=null&&t.push({type:`web_search_tool_result`,tool_use_id:n.id,content:n.output}));return{role:`assistant`,content:t}}if(e.role===`tool`)return{role:`user`,content:await Promise.all(e.content.map(async e=>({type:`tool_result`,tool_use_id:e.id,content:typeof e.content==`string`?e.content:await en(e.content,t),...e.isError?{is_error:!0}:{}})))};if(typeof e.content==`string`)return{role:`user`,content:e.content};{let n=[];for(let r of e.content)r.type===`text`?n.push({type:`text`,text:r.text}):r.type===`file`&&n.push(await zt(r.file,t,`user-message`));return{role:`user`,content:n}}}async function zt(e,t,n){if(e.kind===`image`)return{type:`image`,source:Vt(await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`Anthropic only supports PDF document files. Received ${e.mimeType}`);let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`document`,source:Ht(r),title:r.name??e.name,citations:{enabled:!0}}}let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Anthropic text source: ${r.type}`);return n===`tool-result`?{type:`text`,text:r.content}:{type:`document`,source:{type:`text`,media_type:`text/plain`,data:r.content},title:r.name??e.name,citations:{enabled:!0}}}function Bt(e){if(e===`image/jpeg`||e===`image/png`||e===`image/gif`||e===`image/webp`)return e;throw Error(`Anthropic does not support image MIME type: ${e}. Supported types: image/jpeg, image/png, image/gif, image/webp.`)}function Vt(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:Bt(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function Ht(e){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:`application/pdf`,data:e.data};throw Error(`Unsupported Anthropic PDF source: ${e.type}`)}function Ut(e,t=``){return e===!0?Wt(t)?{thinking:{type:`adaptive`},output_config:{effort:`high`}}:{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function Wt(e){let t=e.toLowerCase().match(/claude-(opus|sonnet)-(\d+)-(\d+)/);if(!t)return!1;let[,n,r,i]=t,a=Number(r),o=Number(i);return!Number.isFinite(a)||!Number.isFinite(o)?!1:n===`opus`||n===`sonnet`?a>4||a===4&&o>=6:!1}function Gt(e){return e.map(e=>{let t=l.toJSONSchema(e.schema);if(!$t(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}const Kt={web_search:`web_search_20250305`};function qt(e){return Kt[e]??e}function Jt(e){return(e??[]).map(e=>({type:e.nativeName??qt(e.name),name:e.name,...e.config}))}function Yt(e,t,n,r){if(e===void 0&&t!==!1)return{};let i=t===!1?{disable_parallel_tool_use:!0}:{};if(e===void 0||e===`auto`)return{tool_choice:{type:`auto`,...i}};if(e===`required`)return{tool_choice:{type:`any`,...i}};if(e===`none`)return{tool_choice:{type:`none`}};if(!(n?.some(t=>t.name===e.name)||r?.some(t=>t.name===e.name)))throw Error(`Tool choice references an unavailable tool: ${e.name}`);return{tool_choice:{type:`tool`,name:e.name,...i}}}function Xt(e){let t=[];for(let n of e)if(n.type===`text`){let e=n.citations?.map(Zt);t.push({type:`text`,text:n.text,...e&&e.length>0?{citations:e}:{}})}else if(n.type===`thinking`){let e=n.thinking.length===0&&!!n.signature;t.push({type:`thinking`,...n.thinking?{text:n.thinking}:{},redacted:e,continuity:{provider:`anthropic`,signature:n.signature}})}else if(n.type===`redacted_thinking`)t.push({type:`thinking`,redacted:!0,continuity:{provider:`anthropic`,redactedData:n.data}});else if(n.type===`tool_use`){if(typeof n.input!=`object`||n.input===null||Array.isArray(n.input))throw Error(`Invalid tool call input for ${n.name}: expected object, got ${typeof n.input}`);t.push({type:`tool-call`,id:n.id,name:n.name,parameters:n.input})}return t}function Zt(e){switch(e.type){case`char_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`char`,start:e.start_char_index,end:e.end_char_index}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`page_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`page`,start:e.start_page_number,end:e.end_page_number}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`content_block_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`block`,start:e.start_block_index,end:e.end_block_index}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`web_search_result_location`:return{source:{type:`web`,title:e.title??void 0,url:e.url,citedText:e.cited_text},providerMetadata:{type:e.type,encryptedIndex:e.encrypted_index}};case`search_result_location`:return{source:{type:`search-result`,title:e.title??void 0,url:e.source,citedText:e.cited_text,locator:{type:`block`,start:e.start_block_index,end:e.end_block_index}},providerMetadata:{type:e.type,searchResultIndex:e.search_result_index}}}}function Qt(e){switch(e){case`max_tokens`:return`length`;case`end_turn`:return`stop`;case`stop_sequence`:return`stop`;case`tool_use`:return`function_call`;default:return`error`}}function $t(e){return e&&typeof e==`object`&&e.type===`object`}async function en(e,t){return Promise.all(e.map(async e=>e.type===`text`?{type:`text`,text:e.text}:zt(e.file,t,`tool-result`)))}async function tn(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v;try{Z(g,`Generate aborted`);let e=await Lt(r,{model:n,fileResolver:s?.fileResolver,signal:g}),y={model:n,max_tokens:l??16e3,messages:e,...i&&{system:i},...f&&{stop_sequences:Je(f)},...(a||o)&&{tools:[...a?Gt(a):[],...Jt(o)]},...Ut(c,n),...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Yt(p,m,a,o),...h};_?.debug(`Anthropic request`,{request:At(y)});let b=await Et(t.messages.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);Z(g,`Generate aborted`),v=nn(b)}catch(e){Z(g,`Generate aborted`),v=Tt(e)}return _?.debug(`Anthropic response`,{result:v}),v}function nn(e){let t=Qt(e.stop_reason);if(t===`error`)return{type:`error`,error:{type:`Uncaught error`,message:`Stop reason is not recognized or unhandled: ${e.stop_reason}`},usage:an(e.usage),raw:e};if(t===`function_call`){let t=Xt(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:F(t),usage:an(e.usage),raw:e}}if(e.type==`message`){let n=Xt(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:F(n),usage:an(e.usage),raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:an(e.usage),raw:e}}function rn(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)}function an(e){return be({in:rn(e),out:e.output_tokens},{cachedIn:e.cache_read_input_tokens??void 0,cacheWriteIn:e.cache_creation_input_tokens??void 0})}function on(){let e=new Map,t=new Map,n=0,r=0,i=0,a=0,o=new Map;function s(s){let c=[];switch(s.type){case`message_start`:n=(s.message.usage?.input_tokens??0)+(s.message.usage?.cache_creation_input_tokens??0)+(s.message.usage?.cache_read_input_tokens??0),a=s.message.usage?.cache_creation_input_tokens??0,i=s.message.usage?.cache_read_input_tokens??0,c.push({type:`start`,id:s.message.id,data:{model:s.message.model,timestamp:Date.now()}});break;case`message_delta`:s.usage&&(r=s.usage.output_tokens??r,s.usage.input_tokens!=null&&(n=s.usage.input_tokens+(s.usage.cache_creation_input_tokens??a)+(s.usage.cache_read_input_tokens??i)),a=s.usage.cache_creation_input_tokens??a,i=s.usage.cache_read_input_tokens??i),s.delta.stop_reason&&c.push({type:`complete`,data:{finishReason:Qt(s.delta.stop_reason),usage:be({in:n,out:r},{cachedIn:i,cacheWriteIn:a})}});case`message_stop`:break;case`content_block_start`:if(s.content_block.type===`text`)e.set(s.index,`text`),c.push({type:`text-start`,data:{index:s.index}});else if(s.content_block.type===`tool_use`){e.set(s.index,`tool`);let t=s.content_block;o.set(s.index,{id:t.id,name:t.name,argumentsBuffer:``}),c.push({type:`tool-call-start`,data:{index:s.index,id:t.id,name:t.name}})}else if(s.content_block.type===`thinking`){e.set(s.index,`thinking`);let t=s.content_block.thinking.length===0&&!!s.content_block.signature;c.push({type:`thinking-start`,data:{index:s.index,redacted:t,continuity:{provider:`anthropic`,signature:s.content_block.signature}}})}else if(s.content_block.type===`redacted_thinking`)e.set(s.index,`thinking`),c.push({type:`thinking-start`,data:{index:s.index,redacted:!0,continuity:{provider:`anthropic`,redactedData:s.content_block.data}}});else if(s.content_block.type===`server_tool_use`){e.set(s.index,`provider-tool`);let n=s.content_block;t.set(n.id,{index:s.index,name:n.name}),c.push({type:`provider-tool-start`,data:{index:s.index,id:n.id,name:n.name}})}else if(s.content_block.type===`web_search_tool_result`){let e=s.content_block,n=t.get(e.tool_use_id);n&&(c.push({type:`provider-tool-complete`,data:{index:n.index,id:e.tool_use_id,name:n.name,output:e.content}}),t.delete(e.tool_use_id))}break;case`content_block_delta`:if(s.delta.type===`text_delta`)c.push({type:`text-delta`,data:{text:s.delta.text,index:s.index}});else if(s.delta.type===`input_json_delta`){let e=o.get(s.index);e&&(e.argumentsBuffer+=s.delta.partial_json,c.push({type:`tool-call-args-delta`,data:{index:s.index,id:e.id,name:e.name,delta:s.delta.partial_json,accumulated:e.argumentsBuffer}}))}else s.delta.type===`thinking_delta`?c.push({type:`thinking-delta`,data:{text:s.delta.thinking,index:s.index}}):s.delta.type===`signature_delta`?c.push({type:`thinking-metadata`,data:{index:s.index,continuity:{provider:`anthropic`,signature:s.delta.signature}}}):s.delta.type===`citations_delta`&&(e.get(s.index)!==`text`&&console.warn(`[Anthropic] received citation delta outside a text block`,{index:s.index,blockType:e.get(s.index)}),c.push({type:`text-citation`,data:{index:s.index,citation:Zt(s.delta.citation)}}));break;case`content_block_stop`:{let t=e.get(s.index);if(t===`text`)c.push({type:`text-complete`,data:{index:s.index}});else if(t===`thinking`)c.push({type:`thinking-complete`,data:{index:s.index}});else if(t!==`provider-tool`&&t===`tool`){let e=o.get(s.index);if(e){try{let t=e.argumentsBuffer?JSON.parse(e.argumentsBuffer):{};c.push({type:`tool-call-complete`,data:{index:s.index,id:e.id,name:e.name,arguments:t}})}catch(t){throw Error(`Failed to parse tool call arguments for ${e.name}: ${t instanceof Error?t.message:String(t)}\nRaw buffer: ${re(e.argumentsBuffer)}`)}o.delete(s.index)}}e.delete(s.index);break}}return c}return{handleEvent:s}}async function*sn(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span,v=[...a?Gt(a):[],...Jt(o)],y=on();try{let e=await Lt(r,{model:n,fileResolver:s?.fileResolver,signal:c}),b={model:n,max_tokens:u??cn(n),messages:e,...i&&{system:i},...p&&{stop_sequences:Je(p)},...v.length>0&&{tools:v},...Ut(l,n),...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Yt(m,h,a,o),...g};_?.debug(`Anthropic streaming request`,{request:At(b)});let x=await t.messages.create({...b,stream:!0},{signal:c});for await(let e of x){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function cn(e){return e in t?t[e]:e.includes(`opus`)?e.match(/opus-4-[6-9]|opus-[5-9]/)?128e3:64e3:e.includes(`sonnet`)||e.includes(`haiku`)?e.match(/claude-3-[0-5]-/)?8192:64e3:16384}function ln(e,t={}){let n=new m({apiKey:e,maxRetries:X(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`anthropic`,resolveProviderToolName(e){return qt(e)},async createGenerationRequest(e,t){return await tn({client:n,model:e,...t})},createStreamingRequest(e,t){return sn({client:n,model:e,...t})}}}const un={Models:i,DefaultModel:s};async function dn(e,t={}){let n=X(t.maxRetries??2,`maxRetries`,{min:0}),r=t.timeoutMs===void 0?void 0:X(t.timeoutMs,`timeoutMs`,{min:1}),i=0;for(;;){Z(t.signal,`Request aborted`);let a=fn(t.signal,r);try{let r=await Et(e({signal:a.signal}),a.signal,`Request aborted`);if(!pn(r.status)||i>=n)return r;let o=mn(r,i);t.onRetry?.({attempt:i+1,delayMs:o,status:r.status}),await gn(o,t.signal),i+=1}catch(e){if(Z(t.signal,`Request aborted`),i>=n)throw e;let r=mn(void 0,i);t.onRetry?.({attempt:i+1,delayMs:r,error:e}),await gn(r,t.signal),i+=1}finally{a.cleanup()}}}function fn(e,t){if(t===void 0)return{signal:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>{n.abort(new DOMException(`Request timed out after ${t}ms`,`TimeoutError`))},t),i=()=>{n.abort(e?.reason)};return e?.aborted?i():e?.addEventListener(`abort`,i,{once:!0}),{signal:n.signal,cleanup:()=>{clearTimeout(r),e?.removeEventListener(`abort`,i)}}}function pn(e){return e===408||e===409||e===429||e>=500}function mn(e,t){let n=hn(e);if(n!==void 0)return n;let r=Math.min(500*2**t,8e3);return r+Math.floor(Math.random()*r*.25)}function hn(e){let t=e?.headers.get(`retry-after-ms`);if(t){let e=Number.parseFloat(t);if(Number.isFinite(e)&&e>=0)return e}let n=e?.headers.get(`retry-after`);if(!n)return;let r=Number.parseFloat(n);if(Number.isFinite(r)&&r>=0)return r*1e3;let i=Date.parse(n);if(Number.isFinite(i))return Math.max(i-Date.now(),0)}async function gn(e,t){if(e<=0){Z(t,`Request aborted`);return}await new Promise((n,r)=>{let i,a=()=>{clearTimeout(i),t?.removeEventListener(`abort`,o)},o=()=>{a(),r(new DOMException(`Request aborted`,`AbortError`))},s=()=>{a(),n()};if(t?.aborted){o();return}i=setTimeout(s,e),t?.addEventListener(`abort`,o,{once:!0})}),Z(t,`Request aborted`)}const _n={web_search:`openrouter:web_search`};function vn(e){return _n[e]}function yn(e,t){let n=[];for(let r of e){let e=r.nativeName??vn(r.name);if(!e){t?.(`providerTool not supported by ChatCompletions provider vendor`,{vendor:`openrouter`,name:r.name});continue}n.push({type:e,...r.config?{parameters:r.config}:{}})}return n.length>0?n:void 0}function bn(e){switch(e.type){case`url_citation`:{let t=e.url_citation;return t?.url?{source:{type:`web`,title:t.title,url:t.url,citedText:t.content},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:e.type}}:null}default:return null}}function xn(e){let t=e.outputSpan;return!t||t.start===void 0&&t.end===void 0?!1:t.start!==0||t.end!==0}function Sn(e){return e===!0?{reasoning:{enabled:!0}}:e===!1?{reasoning:{enabled:!1}}:{}}function Cn(e){if(e.kind===`document`)throw Error(`Together Chat Completions does not support PDF file parts`)}function wn(e,t){switch(t){case`openrouter`:return vn(e);default:return}}async function Tn(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>Nn(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function En(e,t){return t===`together`?Sn(e):Dn(e)}function Dn(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`none`}:{}}function On(e){return be({in:e?.prompt_tokens||0,out:e?.completion_tokens||0},{cachedIn:e?.prompt_tokens_details?.cached_tokens??e?.input_tokens_details?.cached_tokens,cacheWriteIn:e?.prompt_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.input_tokens_details?.cache_creation_tokens,reasoningOut:e?.completion_tokens_details?.reasoning_tokens??e?.output_tokens_details?.reasoning_tokens})}function kn(e){if(e&&e.length>0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}))}function An(e,t,n){if(!(!e||e.length===0)){if(!t){n?.(`providerTools not supported by ChatCompletions provider`);return}switch(t){case`openrouter`:return yn(e,n)}}}function jn(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,function:{name:e.name}}};throw n?.some(t=>t.name===e.name)?Error(`ChatCompletions does not support provider tool choice: ${e.name}`):Error(`Tool choice references an unavailable tool: ${e.name}`)}function Mn(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`function_call`;case`content_filter`:case`error`:return`error`;default:return`stop`}}async function Nn(e,t){switch(e.role){case`tool`:return Pn(e,t);case`assistant`:return Fn(e);default:return In(e,t)}}async function Pn(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await Rn(e.content,t),tool_call_id:e.id})))}function Fn(e){let t=e.content.filter(e=>e.type===`tool-call`),n=e.content.filter(e=>e.type===`text`),r=t.length>0?t.map(e=>({type:`function`,id:e.id,function:{name:e.name,arguments:JSON.stringify(e.parameters)}})):void 0;return{role:`assistant`,content:n.map(e=>e.text).join(``),...r&&{tool_calls:r}}}async function In(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>Ln(e,t)))).filter(e=>e!==null);return n.every(e=>e.type===`text`)?{role:`user`,content:n.map(e=>e.text).join(``)}:{role:`user`,content:n}}async function Ln(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?zn(e.file,t,`user-message`):null}async function Rn(e,t){let n=[];for(let r of e){if(r.type===`text`){n.push(r.text);continue}if(r.file.kind===`text`){let e=await Q(r.file,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:`tool-result`,resolver:t.fileResolver,signal:t.signal});if(e.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${e.type}`);n.push(Hn(r.file,e.content,e.name,e.mimeType));continue}t.warn?.(`ChatCompletions omitted unsupported tool-result file`,{model:t.model,kind:r.file.kind,name:r.file.name,mimeType:r.file.mimeType}),n.push(Un(r.file))}return n.join(`
13
+ `)}async function zn(e,t,n){if(t.vendor===`together`&&Cn(e),e.kind===`text`){let r=await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${r.type}`);return{type:`text`,text:Hn(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`ChatCompletions document file inputs currently support PDF only. Received ${e.mimeType}`);let r=await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`file`,file:{filename:r.name??e.name,file_data:Vn(r,e)}}}return{type:`image_url`,image_url:{url:Bn(await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}}}function Bn(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions image source: ${e.type}`)}function Vn(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions file source: ${e.type}`)}function Hn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function Un(e){return[`Tool result attachment unavailable.`,`File: ${e.name}`,`MIME type: ${e.mimeType}`,``,`This tool returned a file of kind "${e.kind}", but Chat Completions tool-result messages support text only. The file content was not included. Continue without the file or ask for it to be attached in a user message.`].join(`
14
+ `)}async function Wn(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,apiKey:c,vendor:l,maxRetries:u,timeoutMs:d,reasoning:f,maxOutputTokens:p,temperature:m,topP:h,stop:g,toolChoice:_,parallelToolCalls:v,providerOptions:y,signal:b}=e,x=s?.span,S;try{Z(b,`Generate aborted`);let e=await Tn(r,i,{model:n,vendor:l,fileResolver:s?.fileResolver,signal:b,warn:x?.warn.bind(x)}),C=kn(a),w=An(o,l,x?.warn.bind(x)),T=[...C??[],...w??[]],E={model:n,messages:e,...T.length>0?{tools:T}:{},...En(f,l),...p===void 0?{}:{max_tokens:p},...m===void 0?{}:{temperature:m},...h===void 0?{}:{top_p:h},...g===void 0?{}:{stop:g},...jn(_,a,o),...v===void 0?{}:{parallel_tool_calls:v},...y};x?.debug(`ChatCompletions request`,{model:E.model,messages:E.messages.length,tools:E.tools?.length??0}),x?.trace(`ChatCompletions request body`,{request:At(E)});let D={"Content-Type":`application/json`};c&&(D.Authorization=`Bearer ${c}`);let O=await dn(({signal:e})=>fetch(`${t}/chat/completions`,{method:`POST`,headers:D,body:JSON.stringify(E),signal:e}),{maxRetries:u,timeoutMs:d,signal:b,onRetry:e=>x?.warn(`ChatCompletions request retry`,{attempt:e.attempt,maxRetries:u,timeoutMs:d,delayMs:e.delayMs,status:e.status,error:e.error instanceof Error?e.error.message:void 0})});if(!O.ok){let e=await O.text().catch(()=>``);throw Error(`HTTP error! status: ${O.status}${e?` - ${e}`:``}`)}let k=await Et(O.json(),b,`Generate aborted`);Z(b,`Generate aborted`),S=Gn(k)}catch(e){Z(b,`Generate aborted`),x?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),S=Tt(e)}return x?.trace(`ChatCompletions response`,{result:S}),S}function Gn(e){let t=e.choices?.[0];if(!t)return{type:`error`,error:{type:`ChatCompletionsError`,message:`No choices in response`},usage:{in:0,out:0},raw:e};let n=[],r=t.message.reasoning_content??t.message.reasoning;r&&n.push({type:`thinking`,text:r});let i=(t.message.annotations??[]).map(bn).filter(e=>e!==null),a=i.filter(xn),o=i.filter(e=>!xn(e));if(t.message.content&&n.push({type:`text`,text:t.message.content,...a.length>0?{citations:a}:{}}),o.length>0&&n.push({type:`citation`,citations:o}),t.message.tool_calls)for(let e of t.message.tool_calls){let t;try{t=JSON.parse(e.function.arguments)}catch(t){throw Error(`Invalid tool call arguments for ${e.function.name}: ${t instanceof Error?t.message:String(t)}`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Invalid tool call arguments for ${e.function.name}: expected object, got ${typeof t}`);n.push({type:`tool-call`,id:e.id,name:e.function.name,parameters:t})}let s=n.some(e=>e.type===`tool-call`)?Mn(`tool_calls`):Mn(t.finish_reason);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:s,content:n,text:F(n),usage:On(e.usage),raw:e}}function Kn(){let e=new Map,t=0,n=-1,r=``,i=``,a=null,o,s;function c(e){n<0||(a===`text`?e.push({type:`text-complete`,data:{index:n}}):a===`thinking`&&e.push({type:`thinking-complete`,data:{index:n}}),a=null,n=-1)}function l(l){let u=[];l.usage&&(s=On(l.usage));let d=l.choices?.[0];if(!d)return u;r||(r=l.id,i=l.model,u.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}}));let f=d.delta,p=f.reasoning_content??f.reasoning;if(p&&(a!==`thinking`&&(c(u),n=t++,a=`thinking`,u.push({type:`thinking-start`,data:{index:n}})),u.push({type:`thinking-delta`,data:{index:n,text:p}})),f.content&&(a!==`text`&&(c(u),n=t++,a=`text`,u.push({type:`text-start`,data:{index:n}})),u.push({type:`text-delta`,data:{text:f.content,index:n}})),f.annotations){let e=f.annotations.map(bn).filter(e=>e!==null),r=a===`text`?e.filter(xn):[];for(let e of r)u.push({type:`text-citation`,data:{index:n,citation:e}});let i=e.filter(e=>!r.includes(e));i.length>0&&(c(u),u.push({type:`citation`,data:{index:t++,citations:i}}))}if(f.tool_calls){c(u);for(let n of f.tool_calls){let r=n.index;if(!e.has(r)){let i=t++,a=n.id||`tool-${i}`;e.set(r,{id:a,name:n.function?.name||``,argumentsBuffer:``,partIdx:i}),u.push({type:`tool-call-start`,data:{index:i,id:a,name:n.function?.name||``}})}let i=e.get(r);n.id&&(i.id=n.id),n.function?.name&&(i.name=n.function.name),n.function?.arguments&&(i.argumentsBuffer+=n.function.arguments,u.push({type:`tool-call-args-delta`,data:{index:i.partIdx,id:i.id,name:i.name,delta:n.function.arguments,accumulated:i.argumentsBuffer}}))}}if(d.finish_reason&&o===void 0){c(u);for(let[,t]of e)try{let e=t.argumentsBuffer?JSON.parse(t.argumentsBuffer):{};u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.id,name:t.name,arguments:e}})}catch(e){let n=e instanceof Error?e.message:String(e);u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.id,name:t.name,arguments:{},error:{type:`invalid-arguments`,message:`Failed to parse tool call arguments for ${t.name}: ${n}`,raw:re(t.argumentsBuffer)}}})}e.clear(),o=Mn(d.finish_reason)}return u}function u(){return o===void 0?e.size===0?[]:[{type:`error`,data:{type:`IncompleteStream`,message:`Stream ended without a completion signal while tool call arguments were still buffering for ${[...e.values()].map(e=>`${e.name||`unknown tool`} (${e.id})`).join(`, `)}; arguments were likely truncated or incomplete.`}}]:[{type:`complete`,data:{finishReason:o,usage:s??{in:0,out:0}}}]}return{handleChunk:l,finalize:u}}async function*qn(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,apiKey:l,vendor:u,maxRetries:d,timeoutMs:f,reasoning:p,maxOutputTokens:m,temperature:h,topP:g,stop:_,toolChoice:v,parallelToolCalls:y,providerOptions:b}=e,x=s?.span,S=Kn();try{let e=await Tn(r,i,{model:n,vendor:u,fileResolver:s?.fileResolver,signal:c,warn:x?.warn.bind(x)}),C=kn(a),w=An(o,u,x?.warn.bind(x)),T=[...C??[],...w??[]],E={model:n,messages:e,stream:!0,stream_options:{include_usage:!0},...T.length>0?{tools:T}:{},...En(p,u),...m===void 0?{}:{max_tokens:m},...h===void 0?{}:{temperature:h},...g===void 0?{}:{top_p:g},..._===void 0?{}:{stop:_},...jn(v,a,o),...y===void 0?{}:{parallel_tool_calls:y},...b};x?.debug(`ChatCompletions request`,{model:E.model,messages:E.messages.length,tools:E.tools?.length??0,stream:!0}),x?.trace(`ChatCompletions request body`,{request:At(E)});let D={"Content-Type":`application/json`};l&&(D.Authorization=`Bearer ${l}`);let O=await dn(({signal:e})=>fetch(`${t}/chat/completions`,{method:`POST`,headers:D,body:JSON.stringify(E),signal:e}),{maxRetries:d,timeoutMs:f,signal:c,onRetry:e=>x?.warn(`ChatCompletions streaming request retry`,{attempt:e.attempt,maxRetries:d,timeoutMs:f,delayMs:e.delayMs,status:e.status,error:e.error instanceof Error?e.error.message:void 0})});if(!O.ok){let e=await O.text().catch(()=>``);throw Error(`HTTP error! status: ${O.status}${e?` - ${e}`:``}`)}if(!O.body)throw Error(`Response body is null`);let k=O.body.getReader(),A=new TextDecoder,j=``;for(;;){let{done:e,value:t}=await k.read();if(e)break;j+=A.decode(t,{stream:!0});let n=j.split(`
15
+ `);j=n.pop()||``;for(let e of n){let t=e.trim();if(!t||t.startsWith(`:`)||!t.startsWith(`data: `))continue;let n=t.slice(6);if(n===`[DONE]`)continue;let r;try{r=JSON.parse(n)}catch(e){x?.error(`Error parsing ChatCompletions stream chunk`,{error:e instanceof Error?e.message:String(e),line:t});continue}if(r.error){let e=Jn(r.error);yield{type:`error`,data:{type:e.type,message:e.message,raw:r.error}};return}let i=S.handleChunk(r);for(let e of i)yield e}}for(let e of S.finalize())yield e}catch(e){if(c?.aborted)return;x?.error(`Error in ChatCompletions streaming request`,{error:e instanceof Error?e.message:String(e)}),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function Jn(e){if(typeof e==`string`)return{type:`UPSTREAM_STREAM_ERROR`,message:e};let t=e.type??(e.code===void 0?void 0:String(e.code))??`UPSTREAM_STREAM_ERROR`;return{type:t,message:e.message??t}}const Yn={"api.openrouter.ai":`openrouter`,"api.together.ai":`together`,"api.together.xyz":`together`,"openrouter.ai":`openrouter`};function Xn(e,t,n){let r=typeof t==`string`?t:t?.apiKey,i=typeof t==`string`?n:t,a=X(i?.maxRetries??2,`maxRetries`,{min:0}),o=i?.timeoutMs===void 0?void 0:X(i.timeoutMs,`timeoutMs`,{min:1}),s=i?.vendor??Zn(e);return{name:`ChatCompletions`,resolveProviderToolName(e){return wn(e,s)},async createGenerationRequest(t,n){return await Wn({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,vendor:s,...n})},createStreamingRequest(t,n){return qn({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,vendor:s,...n})}}}function Zn(e){try{return Yn[new URL(e).hostname.toLowerCase()]}catch{return}}function Qn(e,t,n){let r={};return t&&(r.systemInstruction=t),e&&e.length>0&&(r.tools=e.map(e=>({functionDeclarations:[{name:e.name,description:e.description,parametersJsonSchema:l.toJSONSchema(e.schema)}]}))),n&&Object.assign(r,n),r}const $n={web_search:`googleSearch`,code_execution:`codeExecution`};function er(e){return $n[e]??e}function tr(e,t){if(!(!t||t.length===0)){e.tools||=[];for(let n of t){let t=n.nativeName??er(n.name);e.tools.push({[t]:n.config??{}})}}}function nr(e,t,n,r){if(t===!1)throw Error(`Gemini does not support disabling parallel tool calls`);if(e===void 0)return{};if(e===`auto`)return{toolConfig:{functionCallingConfig:{mode:S.AUTO}}};if(e===`none`)return{toolConfig:{functionCallingConfig:{mode:S.NONE}}};if(e===`required`){if(!n||n.length===0)throw Error(`Gemini requires function tools for required tool choice`);return{toolConfig:{functionCallingConfig:{mode:S.ANY}}}}if(n?.some(t=>t.name===e.name))return{toolConfig:{functionCallingConfig:{mode:S.ANY,allowedFunctionNames:[e.name]}}};throw r?.some(t=>t.name===e.name)?Error(`Gemini does not support provider tool choice: ${e.name}`):Error(`Tool choice references an unavailable tool: ${e.name}`)}function rr(e){return e===!0?{thinkingConfig:{thinkingBudget:8192,includeThoughts:!0}}:e===!1?{thinkingConfig:{thinkingBudget:0}}:{}}async function ir(e,t={model:``}){return(await Promise.all(e.map(e=>ar(e,t)))).filter(e=>e!==void 0)}async function ar(e,t){switch(e.role){case`tool`:return or(e,t);case`assistant`:return sr(e);case`user`:return cr(e,t)}}async function or(e,t){return{role:`user`,parts:(await Promise.all(e.content.map(async e=>{let n=typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
16
+ `),r={functionResponse:{id:e.id??void 0,name:e.name,response:{output:n}}};return typeof e.content==`string`?[r]:[r,...await Promise.all(e.content.filter(e=>e.type===`file`).map(e=>ur(e.file,t,`tool-result`)))]}))).flat(1)}}function sr(e){let t=[],n=e.content.filter(e=>e.type===`text`);if(n.length>0)for(let e of n){let n=e.text;if(!n)continue;let r={text:n};e.providerMetadata?.thoughtSignature&&(r.thoughtSignature=e.providerMetadata.thoughtSignature),t.push(r)}let r=e.content.filter(e=>e.type===`tool-call`);return r.length>0&&t.push(...r.map(e=>{let t={functionCall:{id:e.id??void 0,name:e.name,args:e.parameters}};return e.providerMetadata?.thoughtSignature&&(t.thoughtSignature=e.providerMetadata.thoughtSignature),t})),{role:`model`,parts:t}}async function cr(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>lr(e,t)))).filter(e=>e!==null)}}async function lr(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?ur(e.file,t,`user-message`):null}async function ur(e,t,n){if(e.kind===`text`){let r=await Q(e,{provider:`gemini`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Gemini text source: ${r.type}`);return{text:fr(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`&&e.mimeType!==`application/pdf`)throw Error(`Gemini document file support is limited to PDFs. Received ${e.mimeType}`);return dr(await Q(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function dr(e,t){if(e.type===`base64`)return{inlineData:{mimeType:e.mimeType??t.mimeType,data:e.data}};if(e.type===`url`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.url}};if(e.type===`gemini-file-uri`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.uri}};throw Error(`Unsupported Gemini file source: ${e.type}`)}function fr(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function pr(e){switch(e){case x.STOP:return[!0,`stop`];case x.MAX_TOKENS:return[!0,`length`];case x.FINISH_REASON_UNSPECIFIED:case x.SAFETY:case x.RECITATION:case x.LANGUAGE:case x.OTHER:case x.BLOCKLIST:case x.PROHIBITED_CONTENT:case x.SPII:case x.MALFORMED_FUNCTION_CALL:case x.IMAGE_SAFETY:return[!1,`error`]}return[!1,`error`]}async function mr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v={...rr(c),...l===void 0?{}:{maxOutputTokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{topP:d},...f===void 0?{}:{stopSequences:Array.isArray(f)?f:[f]},...nr(p,m,a,o),...h},y;try{Z(g,`Generate aborted`);let e=await ir(r,{model:n,fileResolver:s?.fileResolver,signal:g}),c=Qn(a,i,v);p!==`none`&&tr(c,o);let l={contents:e,config:c};_?.debug(`Gemini request`,{request:At(l)});let u=await Et(t.models.generateContent({model:n,...l}),g,`Generate aborted`);Z(g,`Generate aborted`),y=hr(u,{span:_})}catch(e){Z(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),y=Tt(e)}return _?.debug(`Gemini response`,{result:y}),y}function hr(e,t){let{span:n}=t,r=e.usageMetadata?.promptTokenCount??0,i=be({in:r,out:(e.usageMetadata?.totalTokenCount??r)-r},{cachedIn:e.usageMetadata?.cachedContentTokenCount,reasoningOut:e.usageMetadata?.thoughtsTokenCount});if(!e)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};if(e.promptFeedback&&e.promptFeedback.blockReason)return{type:`error`,error:{type:`Blocked`,message:`Response blocked by Google AI: ${e.promptFeedback.blockReason}, ${e.promptFeedback.blockReasonMessage}`},usage:i,raw:e};if(!e.candidates||e.candidates.length===0)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};e.candidates.length>1&&n?.warn(`We received ${e.candidates.length} response candidates`);let a=e.candidates[0],o=a.content?.parts||[],[s,c]=pr(a.finishReason);if(s){let t=[];for(let e=0;e<o.length;e++){let n=o[e];if(n.text)if(n.thought)t.push({type:`thinking`,summary:n.text,...n.thoughtSignature?{continuity:{provider:`gemini`,thoughtSignature:n.thoughtSignature}}:{}});else{let r=_r(a,e);gr(t,{type:`text`,text:n.text,...r.length>0?{citations:r}:{},...n.thoughtSignature?{providerMetadata:{thoughtSignature:n.thoughtSignature}}:{}})}}let n=o.filter(e=>e.functionCall),r=n.length>0?n.map(e=>({call:e.functionCall,thoughtSignature:e.thoughtSignature})):(e.functionCalls??[]).map(e=>({call:e,thoughtSignature:void 0}));if(r.length>0)for(let{call:e,thoughtSignature:n}of r)if(e.args==null)t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:{},...n?{providerMetadata:{thoughtSignature:n}}:{}});else if(typeof e.args!=`object`||Array.isArray(e.args))throw Error(`Invalid tool call arguments for ${e.name}: expected object, got ${typeof e.args}`);else t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:e.args,...n?{providerMetadata:{thoughtSignature:n}}:{}});return{type:`success`,id:e.responseId??``,model:e.modelVersion??``,role:`assistant`,finishReason:r.length>0?`function_call`:c,content:t,text:F(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function gr(e,t){let n=e[e.length-1];if(n?.type===`text`&&!n.citations?.length&&!n.providerMetadata&&!t.citations?.length&&!t.providerMetadata){n.text+=t.text;return}e.push(t)}function _r(e,t){let n=[],r=e.groundingMetadata,i=r?.groundingChunks??[];for(let e of r?.groundingSupports??[])if(!(e.segment?.partIndex!==void 0&&e.segment.partIndex!==t))for(let t of e.groundingChunkIndices??[]){let r=i[t];r&&n.push(vr(r,e))}for(let t of e.citationMetadata?.citations??[])n.push({source:t.uri?{type:`web`,title:t.title,url:t.uri}:{type:`unknown`},outputSpan:{start:t.startIndex,end:t.endIndex},providerMetadata:{license:t.license,publicationDate:t.publicationDate}});return n}function vr(e,t){let n=t.segment;return e.web?{source:{type:`web`,title:e.web.title,url:e.web.uri},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{outputText:n?.text,confidenceScores:t.confidenceScores}}:e.retrievedContext?{source:{type:`retrieved-context`,title:e.retrievedContext.title,uri:e.retrievedContext.uri,citedText:e.retrievedContext.text,locator:{type:`page`,start:e.retrievedContext.pageNumber,end:e.retrievedContext.pageNumber}},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{documentName:e.retrievedContext.documentName,outputText:n?.text,confidenceScores:t.confidenceScores}}:e.maps?{source:{type:`web`,title:e.maps.title,url:e.maps.uri,citedText:e.maps.text},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{placeId:e.maps.placeId,outputText:n?.text,confidenceScores:t.confidenceScores}}:{source:{type:`unknown`},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{chunk:e,outputText:n?.text,confidenceScores:t.confidenceScores}}}function yr(){let e=0,t=-1,n=!1,r=``,i=``,a=0,o=0,s=0,c=0,l=null,u=new Map;function d(e){t<0||(l===`text`?e.push({type:`text-complete`,data:{index:t}}):l===`thinking`&&e.push({type:`thinking-complete`,data:{index:t}}),l=null,t=-1)}function f(f){let p=[];r||(r=f.responseId||`gemini-${Date.now()}`,i=f.modelVersion||`gemini`,p.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}})),f.usageMetadata&&(a=f.usageMetadata.promptTokenCount||0,o=(f.usageMetadata.totalTokenCount||0)-a,s=f.usageMetadata.cachedContentTokenCount||0,c=f.usageMetadata.thoughtsTokenCount||0);let m=f.candidates?.[0];if(!m)return p;let h=m.content?.parts||[];for(let r=0;r<h.length;r++){let i=h[r],a=`thought`in i&&i.thought===!0,o=Object.keys(i),s=o.length===1&&`text`in i&&!i.text;if(!(`thoughtSignature`in i&&!i.text&&!i.functionCall||o.length===2&&`text`in i&&`thoughtSignature`in i&&!i.text||s)&&(a&&i.text?(l!==`thinking`&&(d(p),t=e++,l=`thinking`,p.push({type:`thinking-start`,data:{index:t,...i.thoughtSignature?{continuity:{provider:`gemini`,thoughtSignature:i.thoughtSignature}}:{}}})),p.push({type:`thinking-summary-delta`,data:{index:t,text:i.text}})):i.text&&!a?(l!==`text`&&(d(p),t=e++,l=`text`,p.push({type:`text-start`,data:{index:t}})),u.set(r,t),p.push({type:`text-delta`,data:{text:i.text,index:t}})):i.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(i))}`),i.functionCall)){d(p),n=!0;let t=e++,r=i.functionCall.id||`tool-${t}`,a=i.functionCall.name??``;p.push({type:`tool-call-start`,data:{index:t,id:r,name:a}});let o=i.functionCall.args??{},s=JSON.stringify(o);p.push({type:`tool-call-args-delta`,data:{index:t,id:r,name:a,delta:s,accumulated:s}});let c={index:t,id:r,name:a,arguments:o},l=i;l.thoughtSignature&&(c.providerMetadata={thoughtSignature:l.thoughtSignature}),p.push({type:`tool-call-complete`,data:c})}}for(let{partIndex:e,citation:n}of br(m)){let r=e===void 0?t:u.get(e);if(r===void 0||r<0){console.warn(`[Gemini] received citation without a resolvable text part`,{citation:n});continue}p.push({type:`text-citation`,data:{index:r,citation:n}})}if(m.finishReason&&m.finishReason!==x.FINISH_REASON_UNSPECIFIED){d(p);let[e,t]=pr(m.finishReason),r=n?`function_call`:t;!e&&!n?p.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${m.finishReason}`,usage:be({in:a,out:o},{cachedIn:s,reasoningOut:c}),raw:f}}):p.push({type:`complete`,data:{finishReason:r,usage:be({in:a,out:o},{cachedIn:s,reasoningOut:c})}})}return p}return{handleChunk:f}}function br(e){let t=[],n=e.groundingMetadata,r=n?.groundingChunks??[];for(let e of n?.groundingSupports??[])for(let n of e.groundingChunkIndices??[]){let i=r[n];i&&t.push({partIndex:e.segment?.partIndex,citation:xr(i,e)})}for(let n of e.citationMetadata?.citations??[])t.push({citation:{source:n.uri?{type:`web`,title:n.title,url:n.uri}:{type:`unknown`},outputSpan:{start:n.startIndex,end:n.endIndex},providerMetadata:{license:n.license,publicationDate:n.publicationDate}}});return t}function xr(e,t){let n=t.segment;return e.web?{source:{type:`web`,title:e.web.title,url:e.web.uri},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{outputText:n?.text,confidenceScores:t.confidenceScores}}:e.retrievedContext?{source:{type:`retrieved-context`,title:e.retrievedContext.title,uri:e.retrievedContext.uri,citedText:e.retrievedContext.text,locator:{type:`page`,start:e.retrievedContext.pageNumber,end:e.retrievedContext.pageNumber}},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{documentName:e.retrievedContext.documentName,outputText:n?.text,confidenceScores:t.confidenceScores}}:{source:{type:`unknown`},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{chunk:e,outputText:n?.text,confidenceScores:t.confidenceScores}}}async function*Sr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span,v=Qn(a,i,{...rr(l),...u===void 0?{}:{maxOutputTokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{topP:f},...p===void 0?{}:{stopSequences:Array.isArray(p)?p:[p]},...nr(m,h,a,o),...g});m!==`none`&&tr(v,o);let y=yr();try{let e={contents:await ir(r,{model:n,fileResolver:s?.fileResolver,signal:c}),config:v};_?.debug(`Gemini streaming request`,{request:At(e)});let i=await t.models.generateContentStream({model:n,...e});for await(let e of i){let t=y.handleChunk(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;_?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function Cr(e,t={}){let n=new C({apiKey:e,httpOptions:{retryOptions:{attempts:wr(t.maxRetries)},...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}}});return{name:`Gemini`,resolveProviderToolName(e){return er(e)},async createGenerationRequest(e,t){return await mr({client:n,model:e,...t})},createStreamingRequest(e,t){return Sr({client:n,model:e,...t})}}}function wr(e=2){return X(e,`maxRetries`,{min:0})+1}const Tr={Models:r,DefaultModel:n};async function Er(e){let{provider:t,model:n,messages:r,system:i,tools:a,providerTools:o,span:s,fileResolver:c,...l}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,providerTools:o,runtime:{span:s,fileResolver:c},...l})}async function Dr(e){if(`instruct`in e){let{instruct:t,messages:n,...r}=e,i=he(t),a=await Or({...r,messages:[...n??[],i.message]},k());if(!a.ok)return a;try{return{...a,response:i.parse(a.final)}}catch(e){return{ok:!1,messages:a.messages,final:a.final,usage:a.usage,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)}}}}return Or(e,k())}async function Or(e,t){let{provider:n,model:r,messages:i,system:a,onToolCall:o,maxIterations:s,span:c,fileResolver:l,reasoning:u,maxOutputTokens:d,temperature:f,topP:p,stop:m,toolChoice:h,parallelToolCalls:g,providerOptions:_,signal:v=new AbortController().signal}=e,y=Ie(Fe(e),{provider:n,model:r,span:c,configuration:t}),b=[...i],x=[],S=K(),C=0,w,T=e=>{b.push(e),x.push(e)},E=e=>(c?.setResult({kind:`llm`,model:r,request:{messages:i},response:{content:e.ok?e.final.content:null},usage:xe(e.usage),finishReason:e.ok?e.final.finishReason:void 0}),c?.end(e.ok?`ok`:`error`),e),D=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??r,request:{messages:b},response:{content:t.content},usage:xe(t.usage),finishReason:t.finishReason}),e.end()};try{for(;;){if(Z(v,`Generate aborted`),s!==void 0&&C>=s)return E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${s})`}}},usage:S});C+=1;let e=c?.startSpan(`turn-${C}`,{type:`llm`}),t=y.executable(),i=t.length>0?t.map(e=>({name:e.name,description:e.description,schema:e.schema})):void 0,O=y.provider(),k;try{k=await Er({provider:n,model:r,messages:b,system:a,tools:i,providerTools:O.length>0?O:void 0,span:e,fileResolver:l,reasoning:u,maxOutputTokens:d,temperature:f,topP:p,stop:m,toolChoice:h,parallelToolCalls:g,providerOptions:_,signal:v}),Z(v,`Generate aborted`)}catch(t){throw t instanceof Error&&t.name===`AbortError`&&e?.end(`ok`),t}if(ke(S,k,{provider:n.name,model:k.type===`error`?r:k.model??r}),k.type!==`error`&&Ae(e,k.content),D(e,k),k.type===`error`)return E({ok:!1,messages:x,error:{kind:`model`,error:k},usage:S});let A={role:`assistant`,id:k.id,model:k.model,content:k.content,finishReason:k.finishReason};if(T(A),w=A,k.finishReason!==`function_call`)return E({ok:!0,response:w,messages:x,final:w,usage:S});let j=I(k.content);if(j.length===0)return E({ok:!0,response:w,messages:x,final:w,usage:S});let{results:M,usage:N}=await Le(j,o,v,y,c);q(S,N),Z(v,`Generate aborted`),M.length>0&&T({role:`tool`,id:crypto.randomUUID(),content:M})}}catch(e){throw e instanceof P?(c?.end(`error`),new P(e.message,{toolName:e.toolName,messages:e.messages??x,partial:e.partial??w,usage:_e(S,e.usage),cause:e.cause})):e instanceof M?(c?.end(`ok`),new M(`Generate aborted`,{reason:e.reason,messages:e.messages??x,partial:e.partial,usage:_e(S,e.usage)})):e instanceof Error&&e.name===`AbortError`?(c?.end(`ok`),new M(`Generate aborted`,{reason:v.reason,messages:x,usage:S})):e}}function kr(e){if(e&&e.length>0)return e.map(e=>({type:`function`,strict:!0,name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}))}const Ar={web_search:`web_search_preview`,code_execution:`code_interpreter`};function jr(e){return Ar[e]??e}function Mr(e){return e?.map(e=>({type:e.nativeName??jr(e.name),...e.config}))}function Nr(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,name:e.name}};let r=n?.find(t=>t.name===e.name);if(r)return{tool_choice:{type:r.nativeName??jr(r.name)}};throw Error(`Tool choice references an unavailable tool: ${e.name}`)}function Pr(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`none`}}:{}}async function Fr(e,t={model:``}){return(await Promise.all(e.map(e=>Ir(e,t)))).flat(1)}async function Ir(e,t){switch(e.role){case`tool`:return Lr(e,t);case`assistant`:return Rr(e);default:return zr(e,t)}}async function Lr(e,t){return Promise.all(e.content.map(async e=>({type:`function_call_output`,call_id:e.id,output:typeof e.content==`string`?e.content:await Promise.all(e.content.map(e=>e.type===`text`?Promise.resolve({type:`input_text`,text:e.text}):Vr(e.file,t,`tool-result`)))})))}function Rr(e){let t=[],n=F(e.content);n&&t.push({role:e.role,content:n});let r=e.content.filter(e=>e.type===`thinking`);for(let e of r)e.continuity?.provider===`openai`&&t.push({type:`reasoning`,id:e.id,summary:e.summary?[{type:`summary_text`,text:e.summary}]:[],...e.text?{content:[{type:`reasoning_text`,text:e.text}]}:{},encrypted_content:e.continuity.encrypted});let i=e.content.filter(e=>e.type===`tool-call`);for(let e of i)t.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.parameters)});let a=e.content.filter(e=>e.type===`provider-tool`);for(let e of a)e.output!=null&&t.push(e.output);return t}async function zr(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>Br(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function Br(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?Vr(e.file,t,`user-message`):(e.type,null)}async function Vr(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:Hr(await Q(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e),detail:`auto`};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`OpenAI file inputs currently support PDF documents. Received ${e.mimeType}`);return Ur(await Q(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}let r=await Q(e,{provider:`openai`,model:t.model,accepted:[`text`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return r.type===`text`?{type:`input_text`,text:r.content}:Ur(r,e)}function Hr(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported OpenAI image source: ${e.type}`)}function Ur(e,t){if(e.type===`url`)return{type:`input_file`,filename:e.name??t.name,file_url:e.url};if(e.type===`base64`)return{type:`input_file`,filename:e.name??t.name,file_data:`data:${e.mimeType??t.mimeType};base64,${e.data}`};throw Error(`Unsupported OpenAI file source: ${e.type}`)}async function Wr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v;try{if(Z(g,`Generate aborted`),f!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let e=[...kr(a)??[],...Mr(o)??[]],y={model:n,input:await Fr(r,{model:n,fileResolver:s?.fileResolver,signal:g}),...i&&{instructions:i},...e.length>0?{tools:e}:{},...Pr(c),...l===void 0?{}:{max_output_tokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Nr(p,a,o),...m===void 0?{}:{parallel_tool_calls:m},...h};_?.debug(`OpenAI ResponsesAPI request`,{request:At(y)});let b=await Et(t.responses.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);Z(g,`Generate aborted`),v=Gr(b)}catch(e){Z(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),v=Tt(e)}return _?.debug(`OpenAI ResponsesAPI response`,{result:v}),v}function Gr(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:Jr(e.usage),raw:e};let t=e.output?.filter(e=>e.type===`reasoning`)?.map(e=>e),n=[];if(t&&t.length>0)for(let e of t)(e.summary?.[0]?.text||e.content?.[0]?.text||e.encrypted_content)&&n.push({type:`thinking`,id:e.id,...e.content?.[0]?.text?{text:e.content[0].text}:{},...e.summary?.[0]?.text?{summary:e.summary[0].text}:{},...e.encrypted_content?{continuity:{provider:`openai`,encrypted:e.encrypted_content}}:{}});let r=Kr(e);r.length>0?n.push(...r):e.output_text&&n.push({type:`text`,text:e.output_text});let i=e.output?.filter(e=>e.type===`function_call`);if(i&&i.length>0)for(let e of i){let t=e;try{n.push({type:`tool-call`,id:t.call_id||t.id||``,name:t.name||``,parameters:t.arguments?JSON.parse(t.arguments):{}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${t.arguments}`)}}return{type:`success`,id:e.id,model:e.model||``,role:`assistant`,finishReason:e.incomplete_details?`error`:i&&i.length>0?`function_call`:`stop`,content:n,text:F(n),usage:Jr(e.usage),raw:e}}function Kr(e){let t=[];for(let n of e.output??[])if(n.type===`message`)for(let e of n.content??[]){if(e.type!==`output_text`)continue;let n=(e.annotations??[]).map(qr).filter(e=>e!==null);t.push({type:`text`,text:e.text,...n.length>0?{citations:n}:{}})}return t}function qr(e){if(!e||typeof e!=`object`)return null;let t=e;switch(t.type){case`url_citation`:return{source:{type:`web`,title:t.title,url:t.url},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type}};case`file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};case`container_file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type,containerId:t.container_id}};case`file_path`:return{source:{type:`document`,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};default:return{source:{type:`unknown`},providerMetadata:t}}}function Jr(e){return be({in:e?.input_tokens??0,out:e?.output_tokens??0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}function Yr(){let e=``,t=``,n=0,r=-1,i=!1,a=new Map,o=new Map,s=new Map,c=new Set([`web_search_call`,`file_search_call`,`code_interpreter_call`]),l=new Map;function u(u){let d=[];switch(u.type){case`response.created`:e=u.response.id||`openai-${Date.now()}`,t=u.response.model,d.push({type:`start`,id:e,data:{model:t,timestamp:Date.now()}});break;case`response.output_text.delta`:{let e=Xr(u.item_id,u.content_index);r===-1&&(r=n++,a.set(e,r),d.push({type:`text-start`,data:{index:r}})),d.push({type:`text-delta`,data:{text:u.delta,index:r}});break}case`response.output_text.done`:{let e=Xr(u.item_id,u.content_index);a.set(e,r),r>=0&&(d.push({type:`text-complete`,data:{index:r}}),r=-1);break}case`response.output_text.annotation.added`:{let e=Zr(u.annotation);if(!e)break;let t=a.get(Xr(u.item_id,u.content_index));t===void 0&&console.warn(`[OpenAI] received text annotation without a resolved text part; falling back to current part`,{itemId:u.item_id,contentIndex:u.content_index}),d.push({type:`text-citation`,data:{index:t??r,citation:e}});break}case`response.function_call_arguments.delta`:{let e=u.item_id;if(!l.has(e)){let t=o.get(e),r=t?.name||``,i=t?.callId||e,a=n++;l.set(e,{id:e,callId:i,name:r,argumentsBuffer:``,partIdx:a}),d.push({type:`tool-call-start`,data:{index:a,id:i,name:r}})}let t=l.get(e);t.argumentsBuffer+=u.delta,d.push({type:`tool-call-args-delta`,data:{index:t.partIdx,id:t.callId,name:t.name,delta:u.delta,accumulated:t.argumentsBuffer}});break}case`response.function_call_arguments.done`:{i=!0;let e=u.item_id,t=l.get(e),n=u.name||t?.name||``;if(t){try{let e=u.arguments?JSON.parse(u.arguments):{};d.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.callId,name:n,arguments:e}})}catch(e){throw Error(`Failed to parse function call arguments for ${n}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${u.arguments}`)}l.delete(e)}break}case`response.completed`:{let e=u.response.usage;d.push({type:`complete`,data:{finishReason:u.response.incomplete_details?`error`:i?`function_call`:`stop`,usage:be({in:e?.input_tokens||0,out:e?.output_tokens||0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}});break}case`response.failed`:d.push({type:`error`,data:{type:`RESPONSES_API_ERROR`,message:`Response failed: ${u.response.status}`,raw:u}});break;case`response.output_item.added`:if(u.item?.type===`reasoning`){let e=u.item;r=n++,d.push({type:`thinking-start`,data:{index:r,id:e.id,...e.encrypted_content?{continuity:{provider:`openai`,encrypted:e.encrypted_content}}:{}}})}else if(u.item?.type===`function_call`){let e=u.item,t=e.id||e.call_id;t&&o.set(t,{name:e.name||``,callId:e.call_id||t})}else if(u.item&&c.has(u.item.type)){let e=u.item,t=n++;s.set(e.id,t),d.push({type:`provider-tool-start`,data:{index:t,id:e.id,name:e.type}})}break;case`response.output_item.done`:if(u.item?.type===`reasoning`&&r>=0)d.push({type:`thinking-complete`,data:{index:r}}),r=-1;else if(u.item&&c.has(u.item.type)){let e=u.item,t=s.get(e.id);t!==void 0&&(d.push({type:`provider-tool-complete`,data:{index:t,id:e.id,name:e.type,output:u.item}}),s.delete(e.id))}break;case`response.reasoning_text.delta`:u.delta&&d.push({type:`thinking-delta`,data:{index:r,text:u.delta}});break;case`response.reasoning_summary_text.delta`:u.delta&&d.push({type:`thinking-summary-delta`,data:{index:r,text:u.delta}});break;case`response.in_progress`:case`response.content_part.added`:case`response.content_part.done`:case`response.reasoning_summary_part.added`:case`response.reasoning_summary_part.done`:case`response.reasoning_summary_text.done`:case`response.reasoning_text.done`:case`response.web_search_call.in_progress`:case`response.web_search_call.searching`:case`response.web_search_call.completed`:break;default:console.log(`[OpenAI] unhandled stream event: ${u.type}`)}return d}return{handleEvent:u}}function Xr(e,t){return`${e}:${t}`}function Zr(e){if(!e||typeof e!=`object`)return null;let t=e;switch(t.type){case`url_citation`:return{source:{type:`web`,title:t.title,url:t.url},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type}};case`file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};case`container_file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type,containerId:t.container_id}};case`file_path`:return{source:{type:`document`,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};default:return{source:{type:`unknown`},providerMetadata:t}}}async function*Qr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span;if(p!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let v=[...kr(a)??[],...Mr(o)??[]],y=Yr();try{let e={model:n,input:await Fr(r,{model:n,fileResolver:s?.fileResolver,signal:c}),...i&&{instructions:i},stream:!0,...v.length>0?{tools:v}:{},...Pr(l),...u===void 0?{}:{max_output_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Nr(m,a,o),...h===void 0?{}:{parallel_tool_calls:h},...g};_?.debug(`OpenAI ResponsesAPI streaming request`,{request:At(e)});let p=t.responses.stream(e,...c?[{signal:c}]:[]);for await(let e of p){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;_?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function $r(e,t={}){let n=new w({apiKey:e,maxRetries:X(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`OpenAI`,resolveProviderToolName(e){return jr(e)},async createGenerationRequest(e,t){return await Wr({client:n,model:e,...t})},createStreamingRequest(e,t){return Qr({client:n,model:e,...t})}}}const ei={Models:a,DefaultModel:o};function ti(e){return{kind:`agent`,name:e.name,description:e.description,schema:e.schema,async execute(t,n){let r=await e.createAgent(t,n),i=ni(e.prompt,t),a=r.on(e=>n.emit({type:`turn-event`,event:e})),o;try{o=await r.send(i,{...e.request,signal:n.signal}).final}catch(t){throw ri(t,e.name)}finally{a()}if(o.usage&&n.reportUsage?.(o.usage),!o.ok)throw Error(`Subagent failed: ${JSON.stringify(o.error)}`);let s=o.response;return typeof s==`string`?s:JSON.stringify(s)}}}function ni(e,t){return typeof e==`function`?e(t):typeof e==`string`?e:`Complete this delegated task. Input: ${JSON.stringify(t)}`}function ri(e,t){return e instanceof P?new P(e.message,{toolName:t,usage:e.usage,cause:e}):e instanceof M?new M(e.message,{reason:e.reason,usage:e.usage}):e}function ii(e,t={}){let n=t.maxItems??50,r=Math.max(1,t.maxConcurrency??8),i=u.object({items:u.array(e.schema).min(1).max(n).describe(`Inputs to run through ${e.name}. Results are returned in the same order.`)});return{...e.kind?{kind:e.kind}:{},name:t.name??`${e.name}_batch`,description:t.description??`Run ${e.name} for multiple inputs concurrently and return ordered per-item results.`,schema:i,async execute(t,n){let i=await ai(t.items,r,n.signal,async(t,r)=>{try{return{index:r,input:t,ok:!0,output:await e.execute(t,n)}}catch(e){if(e instanceof P||e instanceof M)throw e;return{index:r,input:t,ok:!1,error:{type:`execution`,message:e instanceof Error?e.message:String(e)}}}});return JSON.stringify({results:i})}}}async function ai(e,t,n,r){let i=Array(e.length),a=0,o=!1,s=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:s},async()=>{for(;!o&&a<e.length;){if(n.aborted)throw o=!0,new M(`Operation aborted`,{reason:n.reason});let t=a++;try{i[t]=await r(e[t],t)}catch(e){throw o=!0,e}}})),i}const oi={trace:0,debug:1,info:2,warn:3,error:4};var si=class{minLevel;showInternal;showTimestamp;showDuration;markdown;output;spans=new Map;visibleDepths=new Map;constructor(e={}){this.minLevel=e.minLevel??`info`,this.showInternal=e.showInternal??!1,this.showTimestamp=e.showTimestamp??!0,this.showDuration=e.showDuration??!0,this.markdown=e.markdown??!1,this.output=e.output??console.log}shouldShowEvent(e){return oi[e]>=oi[this.minLevel]}isSpanVisible(e){return!(e.type===`internal`&&!this.showInternal)}findVisibleAncestor(e){let t=e.parentSpanId;for(;t;){let e=this.spans.get(t);if(!e)break;if(this.isSpanVisible(e))return e;t=e.parentSpanId}return null}calculateVisibleDepth(e){if(!this.isSpanVisible(e))return-1;let t=this.findVisibleAncestor(e);return t?(this.visibleDepths.get(t.spanId)??0)+1:0}formatTimestamp(){if(!this.showTimestamp)return``;let e=new Date;return`[${e.toTimeString().slice(0,8)}.${e.getMilliseconds().toString().padStart(3,`0`)}] `}formatDuration(e){if(!this.showDuration||!e.endTime)return``;let t=e.endTime-e.startTime;return t<1e3?` (${Math.round(t)}ms)`:` (${(t/1e3).toFixed(2)}s)`}formatIndent(e){return` `.repeat(e)}formatSpanName(e){return e.type?`[${e.type}] ${e.name}`:e.name}renderMarkdown(e){return ci(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,t);let n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatSpanName(e);this.output(`${r}${n}START ${i}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.visibleDepths.get(e.spanId)??0,n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatDuration(e),a=this.formatSpanName(e),o=e.status===`error`?` [ERROR]`:``;if(this.output(`${r}${n}END ${a}${i}${o}`),e.result?.kind===`llm`){let t=e.result,i=[`model=${t.model}`];if(t.finishReason&&i.push(`finishReason=${t.finishReason}`),t.usage&&(t.usage.inputTokens!==void 0&&i.push(`inputTokens=${t.usage.inputTokens}`),t.usage.outputTokens!==void 0&&i.push(`outputTokens=${t.usage.outputTokens}`),t.usage.cachedInputTokens!==void 0&&i.push(`cachedInputTokens=${t.usage.cachedInputTokens}`),t.usage.cacheWriteInputTokens!==void 0&&i.push(`cacheWriteInputTokens=${t.usage.cacheWriteInputTokens}`),t.usage.reasoningOutputTokens!==void 0&&i.push(`reasoningOutputTokens=${t.usage.reasoningOutputTokens}`)),this.output(`${r}${n} INFO LLM complete ${i.join(` `)}`),this.shouldShowEvent(`debug`)&&t.response.content){let e=(typeof t.response.content==`string`?t.response.content:JSON.stringify(t.response.content,null,2)).split(`
17
+ `);for(let t of e)this.output(`${r}${n} DEBUG ${t}`)}}}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,t){if(!this.shouldShowEvent(t.level))return;this.spans.set(e.spanId,e);let n;if(this.isSpanVisible(e))n=this.visibleDepths.get(e.spanId)??0;else{let t=this.findVisibleAncestor(e);n=t?this.visibleDepths.get(t.spanId)??0:0}let r=this.formatIndent(n+1),i=this.formatTimestamp(),a=t.level.toUpperCase().padEnd(5),o=this.markdown&&t.attributes?.markdown===!0,s=t.attributes?Object.entries(t.attributes).filter(([e])=>e!==`markdown`):[],c=t.name;o&&(c=this.renderMarkdown(c));let l=`${i}${r}${a} ${c}`;if(s.length>0){let e=s.map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(` `);l+=` ${e}`}this.output(l)}};function ci(e){return li(E.lexer(e))}function li(e=[]){return e.map(e=>ui(e)).filter(e=>e.length>0).join(`
18
+ `)}function ui(e){switch(e.type){case`space`:return``;case`heading`:return T.bold($(e.tokens));case`paragraph`:return $(e.tokens);case`blockquote`:return gi(li(e.tokens),`> `);case`code`:return(e.lang?T.dim(`${e.lang}\n`):``)+T.yellow(e.text);case`list`:return fi(e)?mi(e):e.raw;case`hr`:return T.dim(`-`.repeat(40));case`table`:return pi(e)?hi(e):e.raw;case`html`:return e.text;case`text`:return e.tokens?$(e.tokens):vi(e.text);default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function $(e=[]){return e.map(e=>di(e)).join(``)}function di(e){switch(e.type){case`text`:case`escape`:return vi(e.text);case`strong`:return T.bold($(e.tokens));case`em`:return T.italic($(e.tokens));case`codespan`:return T.yellow(e.text);case`del`:return T.strikethrough($(e.tokens));case`link`:{let t=$(e.tokens);return e.href&&e.href!==e.text?`${T.blue.underline(t)} ${T.dim(`(${e.href})`)}`:T.blue.underline(t)}case`image`:return e.text?`${e.text} (${e.href})`:e.href;case`br`:return`
19
+ `;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function fi(e){return e.type===`list`&&`items`in e&&Array.isArray(e.items)}function pi(e){return e.type===`table`&&`header`in e&&`rows`in e}function mi(e){return e.items.map((t,n)=>{let r=e.ordered?`${Number(e.start||1)+n}. `:`- `,i=t.task?`[${t.checked?`x`:` `}] `:``,a=li(t.tokens).trimEnd();return r+i+_i(a,r.length+i.length)}).join(`
20
+ `)}function hi(e){let t=e.header.map(e=>$(e.tokens)).join(` | `),n=e.rows.map(e=>e.map(e=>$(e.tokens)).join(` | `));return[T.bold(t),...n].join(`
21
+ `)}function gi(e,t){return e.split(`
22
22
  `).map(e=>t+e).join(`
23
- `)}function di(e,t){let[n=``,...r]=e.split(`
23
+ `)}function _i(e,t){let[n=``,...r]=e.split(`
24
24
  `);if(r.length===0)return n;let i=` `.repeat(t);return[n,...r.map(e=>i+e)].join(`
25
- `)}function fi(e){return e.replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/g,`&`)}export{ot as Agent,ln as Anthropic,M as AxleAbortError,N as AxleAgentAbortError,A as AxleError,Ve as AxleStopReason,P as AxleToolFatalError,yr as Gemini,Xe as History,xt as Instruct,gt as InstructVariableError,B as LogWriter,pt as MCP,Jr as OpenAI,ti as SimpleWriter,Ct as TaskError,we as ToolRegistry,et as Tracer,e as TurnAccumulator,Ke as TurnEventBuilder,q as addStats,cn as anthropic,De as braveWebSearch,Gn as chatCompletions,O as configureAxle,ht as createAgentConfig,Yr as createAgentTool,Ye as createHandle,K as createStats,ie as estimateContextUsage,_r as gemini,xr as generate,br as generateTurn,Ft as loadFileContent,_e as mergeStats,qr as openai,Qr as parallelize,pe as parseResponse,Ue as stream};
25
+ `)}function vi(e){return e.replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/g,`&`)}export{st as Agent,un as Anthropic,M as AxleAbortError,N as AxleAgentAbortError,A as AxleError,Ve as AxleStopReason,P as AxleToolFatalError,Tr as Gemini,Ze as History,St as Instruct,_t as InstructVariableError,z as LogWriter,mt as MCP,ei as OpenAI,si as SimpleWriter,wt as TaskError,we as ToolRegistry,tt as Tracer,e as TurnAccumulator,qe as TurnEventBuilder,q as addStats,ln as anthropic,De as braveWebSearch,Xn as chatCompletions,O as configureAxle,gt as createAgentConfig,ti as createAgentTool,Xe as createHandle,K as createStats,ie as estimateContextUsage,Cr as gemini,Dr as generate,Er as generateTurn,It as loadFileContent,_e as mergeStats,$r as openai,ii as parallelize,pe as parseResponse,We as stream};
package/dist/ui.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as TurnPart, C as SubagentAction, D as ToolAction, E as TimingInfo, L as Citation, O as Turn, R as CitationOutputSpan, S as ProviderToolAction, T as ThinkingPart, Y as ThinkingContinuity, _ as Annotation, _t as TokenStats, a as UnknownEvent, b as CitationPart, ct as FileInfo, f as AnnotationEvent, g as ActionResult, gt as Stats, h as ActionPart, i as TurnAccumulatorState, j as TurnStatus, k as TurnMetadata, m as TurnEvent, n as TurnAccumulator, p as AnnotationTarget, q as DocumentLocator, r as TurnAccumulatorResult, t as AccumulatableEvent, v as AnnotationPlacement, vt as UsageEntry, w as TextPart, x as FilePart, y as AnnotationStatus, z as CitationSource } from "./accumulator-j9h_1Eyk.js";
1
+ import { A as TurnPart, C as SubagentAction, D as ToolAction, E as TimingInfo, L as Citation, O as Turn, R as CitationOutputSpan, S as ProviderToolAction, T as ThinkingPart, Y as ThinkingContinuity, _ as Annotation, _t as TokenStats, a as UnknownEvent, b as CitationPart, ct as FileInfo, f as AnnotationEvent, g as ActionResult, gt as Stats, h as ActionPart, i as TurnAccumulatorState, j as TurnStatus, k as TurnMetadata, m as TurnEvent, n as TurnAccumulator, p as AnnotationTarget, q as DocumentLocator, r as TurnAccumulatorResult, t as AccumulatableEvent, v as AnnotationPlacement, vt as UsageEntry, w as TextPart, x as FilePart, y as AnnotationStatus, z as CitationSource } from "./accumulator-yYlD8Bfm.js";
2
2
  export { type AccumulatableEvent, type ActionPart, type ActionResult, type Annotation, type AnnotationEvent, type AnnotationPlacement, type AnnotationStatus, type AnnotationTarget, type Citation, type CitationOutputSpan, type CitationPart, type CitationSource, type DocumentLocator, type FileInfo, type FilePart, type ProviderToolAction, type Stats, type SubagentAction, type TextPart, type ThinkingContinuity, type ThinkingPart, type TimingInfo, type TokenStats, type ToolAction, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, type TurnMetadata, type TurnPart, type TurnStatus, type UnknownEvent, type UsageEntry };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fifthrevision/axle",
3
- "version": "0.25.0",
3
+ "version": "0.25.2",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/johncch/axle.git"