@fifthrevision/axle 0.21.0 → 0.22.1
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.
|
@@ -2,7 +2,7 @@ import { ZodObject, z } from "zod";
|
|
|
2
2
|
|
|
3
3
|
//#region src/types.d.ts
|
|
4
4
|
/**
|
|
5
|
-
*
|
|
5
|
+
* Usage reported by a provider response.
|
|
6
6
|
*/
|
|
7
7
|
interface Stats {
|
|
8
8
|
/** Total effective input tokens. Includes `cachedIn` and `cacheWriteIn` when reported. */
|
|
@@ -19,7 +19,7 @@ interface Stats {
|
|
|
19
19
|
//#endregion
|
|
20
20
|
//#region src/messages/stream.d.ts
|
|
21
21
|
interface StreamChunk {
|
|
22
|
-
type: "start" | "text-start" | "text-delta" | "text-citation" | "text-complete" | "tool-call-start" | "tool-call-args-delta" | "tool-call-complete" | "thinking-start" | "thinking-delta" | "thinking-summary-delta" | "thinking-metadata" | "thinking-complete" | "provider-tool-start" | "provider-tool-complete" | "complete" | "error";
|
|
22
|
+
type: "start" | "text-start" | "text-delta" | "text-citation" | "citation" | "text-complete" | "tool-call-start" | "tool-call-args-delta" | "tool-call-complete" | "thinking-start" | "thinking-delta" | "thinking-summary-delta" | "thinking-metadata" | "thinking-complete" | "provider-tool-start" | "provider-tool-complete" | "complete" | "error";
|
|
23
23
|
id?: string;
|
|
24
24
|
data?: any;
|
|
25
25
|
}
|
|
@@ -67,6 +67,14 @@ interface StreamTextCitationChunk extends StreamChunk {
|
|
|
67
67
|
citation: Citation;
|
|
68
68
|
};
|
|
69
69
|
}
|
|
70
|
+
interface StreamCitationChunk extends StreamChunk {
|
|
71
|
+
type: "citation";
|
|
72
|
+
data: {
|
|
73
|
+
index: number;
|
|
74
|
+
citations: Citation[];
|
|
75
|
+
providerMetadata?: Record<string, unknown>;
|
|
76
|
+
};
|
|
77
|
+
}
|
|
70
78
|
interface StreamTextCompleteChunk extends StreamChunk {
|
|
71
79
|
type: "text-complete";
|
|
72
80
|
data: {
|
|
@@ -157,7 +165,7 @@ interface StreamProviderToolCompleteChunk extends StreamChunk {
|
|
|
157
165
|
output?: unknown;
|
|
158
166
|
};
|
|
159
167
|
}
|
|
160
|
-
type AnyStreamChunk = StreamStartChunk | StreamCompleteChunk | StreamErrorChunk | StreamTextStartChunk | StreamTextDeltaChunk | StreamTextCitationChunk | StreamTextCompleteChunk | StreamThinkingStartChunk | StreamThinkingDeltaChunk | StreamThinkingSummaryDeltaChunk | StreamThinkingMetadataChunk | StreamThinkingCompleteChunk | StreamToolCallStartChunk | StreamToolCallArgsDeltaChunk | StreamToolCallCompleteChunk | StreamProviderToolStartChunk | StreamProviderToolCompleteChunk;
|
|
168
|
+
type AnyStreamChunk = StreamStartChunk | StreamCompleteChunk | StreamErrorChunk | StreamTextStartChunk | StreamTextDeltaChunk | StreamTextCitationChunk | StreamCitationChunk | StreamTextCompleteChunk | StreamThinkingStartChunk | StreamThinkingDeltaChunk | StreamThinkingSummaryDeltaChunk | StreamThinkingMetadataChunk | StreamThinkingCompleteChunk | StreamToolCallStartChunk | StreamToolCallArgsDeltaChunk | StreamToolCallCompleteChunk | StreamProviderToolStartChunk | StreamProviderToolCompleteChunk;
|
|
161
169
|
//#endregion
|
|
162
170
|
//#region src/tracer/types.d.ts
|
|
163
171
|
type SpanStatus = "ok" | "error";
|
|
@@ -429,7 +437,7 @@ interface ModelResponse {
|
|
|
429
437
|
id: string;
|
|
430
438
|
model: string;
|
|
431
439
|
text: string;
|
|
432
|
-
content: Array<ContentPartText | ContentPartThinking | ContentPartToolCall>;
|
|
440
|
+
content: Array<ContentPartText | ContentPartThinking | ContentPartToolCall | ContentPartCitation>;
|
|
433
441
|
finishReason: AxleStopReason;
|
|
434
442
|
usage: Stats;
|
|
435
443
|
raw: any;
|
|
@@ -535,7 +543,7 @@ interface AxleAssistantMessage {
|
|
|
535
543
|
/** Model identifier that produced this message, when known. */
|
|
536
544
|
model?: string;
|
|
537
545
|
/** Assistant content parts in model order. */
|
|
538
|
-
content: Array<ContentPartText | ContentPartThinking | ContentPartToolCall | ContentPartProviderTool>;
|
|
546
|
+
content: Array<ContentPartText | ContentPartThinking | ContentPartToolCall | ContentPartProviderTool | ContentPartCitation>;
|
|
539
547
|
/** Provider-normalized reason the assistant message stopped. */
|
|
540
548
|
finishReason?: AxleStopReason;
|
|
541
549
|
}
|
|
@@ -566,7 +574,7 @@ interface AxleToolCallResult {
|
|
|
566
574
|
/**
|
|
567
575
|
* Any content part Axle can carry in a user or assistant message.
|
|
568
576
|
*/
|
|
569
|
-
type ContentPart = ContentPartText | ContentPartFile | ContentPartToolCall | ContentPartThinking | ContentPartProviderTool;
|
|
577
|
+
type ContentPart = ContentPartText | ContentPartFile | ContentPartToolCall | ContentPartThinking | ContentPartProviderTool | ContentPartCitation;
|
|
570
578
|
/**
|
|
571
579
|
* Plain text content.
|
|
572
580
|
*/
|
|
@@ -725,6 +733,20 @@ interface ContentPartProviderTool {
|
|
|
725
733
|
/** Provider-specific tool output. */
|
|
726
734
|
output?: unknown;
|
|
727
735
|
}
|
|
736
|
+
/**
|
|
737
|
+
* Unanchored provider citations or sources associated with the assistant output.
|
|
738
|
+
*
|
|
739
|
+
* Text-span citations remain attached to `ContentPartText.citations`. This part
|
|
740
|
+
* is for source lists that the provider emits as their own ordered stream item.
|
|
741
|
+
*/
|
|
742
|
+
interface ContentPartCitation {
|
|
743
|
+
/** Part discriminator. */
|
|
744
|
+
type: "citation";
|
|
745
|
+
/** Source citations carried by this ordered part. */
|
|
746
|
+
citations: Citation[];
|
|
747
|
+
/** Provider-specific metadata that is not part of Axle's normalized contract. */
|
|
748
|
+
providerMetadata?: Record<string, unknown>;
|
|
749
|
+
}
|
|
728
750
|
//#endregion
|
|
729
751
|
//#region src/tools/registry.d.ts
|
|
730
752
|
declare class ToolRegistry {
|
|
@@ -771,6 +793,7 @@ interface ExecutableTool<TSchema extends ZodObject<any> = ZodObject<any>> {
|
|
|
771
793
|
interface ProviderTool {
|
|
772
794
|
type: "provider";
|
|
773
795
|
name: string;
|
|
796
|
+
/** Provider-specific passthrough config. Field names and placement are not portable. */
|
|
774
797
|
config?: Record<string, unknown>;
|
|
775
798
|
}
|
|
776
799
|
type ToolDefinition = Pick<ExecutableTool, "name" | "description" | "schema">;
|
|
@@ -865,7 +888,7 @@ interface Turn<TAnnotation extends Annotation = Annotation> {
|
|
|
865
888
|
/**
|
|
866
889
|
* Any renderable part within a turn.
|
|
867
890
|
*/
|
|
868
|
-
type TurnPart<TAnnotation extends Annotation = Annotation> = TextPart<TAnnotation> | FilePart<TAnnotation> | ThinkingPart<TAnnotation> | ActionPart<TAnnotation>;
|
|
891
|
+
type TurnPart<TAnnotation extends Annotation = Annotation> = TextPart<TAnnotation> | CitationPart<TAnnotation> | FilePart<TAnnotation> | ThinkingPart<TAnnotation> | ActionPart<TAnnotation>;
|
|
869
892
|
/**
|
|
870
893
|
* Assistant or user text content.
|
|
871
894
|
*/
|
|
@@ -885,6 +908,23 @@ interface TextPart<TAnnotation extends Annotation = Annotation> {
|
|
|
885
908
|
/** Optional timing metadata. */
|
|
886
909
|
timing?: TimingInfo;
|
|
887
910
|
}
|
|
911
|
+
/**
|
|
912
|
+
* Unanchored citations or source list emitted as an ordered renderable part.
|
|
913
|
+
*/
|
|
914
|
+
interface CitationPart<TAnnotation extends Annotation = Annotation> {
|
|
915
|
+
/** Stable part id. */
|
|
916
|
+
id: string;
|
|
917
|
+
/** Part discriminator. */
|
|
918
|
+
type: "citation";
|
|
919
|
+
/** Source citations carried by this part. */
|
|
920
|
+
citations: Citation[];
|
|
921
|
+
/** Provider-specific metadata that is not part of Axle's normalized contract. */
|
|
922
|
+
providerMetadata?: Record<string, unknown>;
|
|
923
|
+
/** Annotations attached to this part. */
|
|
924
|
+
annotations?: TAnnotation[];
|
|
925
|
+
/** Optional timing metadata. */
|
|
926
|
+
timing?: TimingInfo;
|
|
927
|
+
}
|
|
888
928
|
/**
|
|
889
929
|
* File content attached to a user turn.
|
|
890
930
|
*/
|
|
@@ -1153,4 +1193,4 @@ declare class TurnAccumulator<TAnnotation extends Annotation = Annotation, THost
|
|
|
1153
1193
|
private handled;
|
|
1154
1194
|
}
|
|
1155
1195
|
//#endregion
|
|
1156
|
-
export {
|
|
1196
|
+
export { ContextUsage as $, ToolRegistry as A, ContentPartCitation as B, TurnMetadata as C, ProviderTool as D, ExecutableTool as E, AxleUserMessage as F, ContentPartToolCall as G, ContentPartProviderTool as H, Citation as I, ThinkingContinuity as J, DocumentLocator as K, CitationOutputSpan as L, AxleMessage as M, AxleToolCallMessage as N, ToolContext as O, AxleToolCallResult as P, AxleStopReason as Q, CitationSource as R, Turn as S, TurnStatus as T, ContentPartText as U, ContentPartFile as V, ContentPartThinking as W, AIProvider as X, ToolResultPart as Y, AxleModelRequestOptions as Z, SubagentAction as _, SpanOptions as _t, UnknownEvent as a, DeferredFileInfo as at, TimingInfo as b, TracingContext as bt, TurnEvent as c, FileProviderId as ct, Annotation as d, FileResolver as dt, ModelError as et, AnnotationPlacement as f, ResolvedFileSource as ft, ProviderToolAction as g, SpanEvent as gt, FilePart as h, SpanData as ht, TurnAccumulatorState as i, ToolChoice as it, AxleAssistantMessage as j, ToolDefinition as k, ActionPart as l, FileResolveFormat as lt, CitationPart as m, EventLevel as mt, TurnAccumulator as n, ProviderClientOptions as nt, AnnotationEvent as o, FileInfo as ot, AnnotationStatus as p, loadFileContent as pt, MessageMetadata as q, TurnAccumulatorResult as r, ProviderOptions as rt, AnnotationTarget as s, FileKind as st, AccumulatableEvent as t, ModelResult as tt, ActionResult as u, FileResolveRequest as ut, TextPart as v, SpanType as vt, TurnPart as w, ToolAction as x, Stats as xt, ThinkingPart as y, TraceWriter as yt, ContentPart as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as ContextUsage, A as ToolRegistry, B as ContentPartCitation, C as TurnMetadata, D as ProviderTool, E as ExecutableTool, F as AxleUserMessage, G as ContentPartToolCall, H as ContentPartProviderTool, I as Citation, J as ThinkingContinuity, K as DocumentLocator, L as CitationOutputSpan, M as AxleMessage, N as AxleToolCallMessage, O as ToolContext, P as AxleToolCallResult, Q as AxleStopReason, R as CitationSource, S as Turn, T as TurnStatus, U as ContentPartText, V as ContentPartFile, W as ContentPartThinking, X as AIProvider, Y as ToolResultPart, Z as AxleModelRequestOptions, _ as SubagentAction, _t as SpanOptions, at as DeferredFileInfo, bt as TracingContext, c as TurnEvent, ct as FileProviderId, d as Annotation, dt as FileResolver, et as ModelError, f as AnnotationPlacement, ft as ResolvedFileSource, g as ProviderToolAction, gt as SpanEvent, h as FilePart, ht as SpanData, i as TurnAccumulatorState, it as ToolChoice, j as AxleAssistantMessage, k as ToolDefinition, l as ActionPart, lt as FileResolveFormat, m as CitationPart, mt as EventLevel, n as TurnAccumulator, nt as ProviderClientOptions, o as AnnotationEvent, ot as FileInfo, p as AnnotationStatus, pt as loadFileContent, q as MessageMetadata, r as TurnAccumulatorResult, rt as ProviderOptions, s as AnnotationTarget, st as FileKind, t as AccumulatableEvent, tt as ModelResult, u as ActionResult, ut as FileResolveRequest, v as TextPart, vt as SpanType, w as TurnPart, x as ToolAction, xt as Stats, y as ThinkingPart, yt as TraceWriter, z as ContentPart } from "./accumulator-BNYePirr.js";
|
|
2
2
|
import * as z$2 from "zod";
|
|
3
3
|
|
|
4
4
|
//#region src/mcp/MCP.d.ts
|
|
@@ -593,9 +593,11 @@ declare const Anthropic: {
|
|
|
593
593
|
//#region src/providers/chatcompletions/provider.d.ts
|
|
594
594
|
interface ChatCompletionsOptions extends ProviderClientOptions {
|
|
595
595
|
apiKey?: string;
|
|
596
|
+
providerToolVendor?: "openrouter";
|
|
596
597
|
}
|
|
597
598
|
declare function chatCompletions(baseUrl: string, options?: ChatCompletionsOptions): AIProvider;
|
|
598
599
|
declare function chatCompletions(baseUrl: string, apiKey?: string): AIProvider;
|
|
600
|
+
declare function chatCompletions(baseUrl: string, apiKey: string, options?: Omit<ChatCompletionsOptions, "apiKey">): AIProvider;
|
|
599
601
|
//#endregion
|
|
600
602
|
//#region src/providers/context.d.ts
|
|
601
603
|
interface ContextEstimateInput {
|
|
@@ -705,6 +707,11 @@ type StreamEvent = {
|
|
|
705
707
|
type: "text:end";
|
|
706
708
|
index: number;
|
|
707
709
|
final: string;
|
|
710
|
+
} | {
|
|
711
|
+
type: "citation";
|
|
712
|
+
index: number;
|
|
713
|
+
citations: Citation[];
|
|
714
|
+
providerMetadata?: Record<string, unknown>;
|
|
708
715
|
} | {
|
|
709
716
|
type: "thinking:start";
|
|
710
717
|
index: number;
|
|
@@ -966,4 +973,4 @@ interface FileStore {
|
|
|
966
973
|
declare function createStats(): Stats;
|
|
967
974
|
declare function addStats(total: Stats, usage?: Stats): void;
|
|
968
975
|
//#endregion
|
|
969
|
-
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, AxleError, type AxleMessage, type AxleModelRequestOptions, AxleStopReason, type AxleToolCallMessage, type AxleToolCallResult, AxleToolFatalError, type AxleUserMessage, type ChatCompletionsOptions, type Citation, type CitationOutputSpan, type CitationSource, type ContentPart, type ContentPartFile, type ContentPartProviderTool, type ContentPartText, type ContentPartThinking, type ContentPartToolCall, type ContextUsage, 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 InstructInputs, type InstructOptions, type InstructResponse, InstructVariableError, type InstructVarsMode, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MaybePromise, type MemoryContext, type MessageMetadata, OpenAI, type OutputSchema, 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 SpanData, type SpanOptions, 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 ToolAction, type ToolChoice, type ToolContext, type ToolDefinition, type ToolDefinitionRef, ToolRegistry, type ToolResultPart, type TraceWriter, Tracer, type TracingContext, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, TurnEventBuilder, type TurnEventCallback, type TurnMetadata, type TurnPart, type TurnStatus, addStats, anthropic, chatCompletions, createAgentConfig, createHandle, createStats, estimateContextUsage, gemini, generate, generateTurn, loadFileContent, openai, parseResponse, stream };
|
|
976
|
+
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, AxleError, type AxleMessage, type AxleModelRequestOptions, AxleStopReason, type AxleToolCallMessage, type AxleToolCallResult, AxleToolFatalError, type AxleUserMessage, 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 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 InstructInputs, type InstructOptions, type InstructResponse, InstructVariableError, type InstructVarsMode, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MaybePromise, type MemoryContext, type MessageMetadata, OpenAI, type OutputSchema, 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 SpanData, type SpanOptions, 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 ToolAction, type ToolChoice, type ToolContext, type ToolDefinition, type ToolDefinitionRef, ToolRegistry, type ToolResultPart, type TraceWriter, Tracer, type TracingContext, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, TurnEventBuilder, type TurnEventCallback, type TurnMetadata, type TurnPart, type TurnStatus, addStats, anthropic, chatCompletions, createAgentConfig, createHandle, createStats, estimateContextUsage, gemini, generate, generateTurn, loadFileContent, openai, parseResponse, stream };
|
package/dist/index.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import{t as e}from"./accumulator-BLjnX0uz.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 from"zod";import{Client as u}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as d}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as f}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import p from"@anthropic-ai/sdk";import"glob";import m from"mime";import{access as h,readFile as g,stat as _}from"node:fs/promises";import{extname as v,resolve as y}from"node:path";import{FinishReason as b,FunctionCallingConfigMode as x,GoogleGenAI as S}from"@google/genai";import C from"openai";import w from"chalk";import{marked as T}from"marked";var E=class e extends Error{code;id;details;constructor(t,n){super(t,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||`AXLE_ERROR`,this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id?{id:this.id}:{},...this.details?{details:this.details}:{},...this.cause?{cause:D(this.cause)}:{}}}};function D(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:D(e.cause)}:{}}:e}var O=class e extends E{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}:{}}}},k=class e extends O{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}:{}}}},A=class e extends E{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 j(e){let t=R(e.system??``),n=ne(e.tools),r=ne(e.mcpTools),i=F(e.providerTools),a=e.messages.reduce((e,t)=>e+ee(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 ee(e){switch(e.role){case`user`:return M(e.content);case`assistant`:return M(e.content);case`tool`:return e.content.reduce((e,t)=>e+N(t),0)}}function M(e){return typeof e==`string`?R(e):e.reduce((e,t)=>e+te(t),0)}function te(e){switch(e.type){case`text`:return R(e.text);case`thinking`:return R(e.summary??e.text??``);case`tool-call`:return R(e.name)+L(e.parameters);case`provider-tool`:return R(e.name)+L(e.input)+L(e.output);case`file`:return L(e.file)}}function N(e){return R(e.name)+P(e.content)}function P(e){return typeof e==`string`?R(e):e.reduce((e,t)=>t.type===`text`?e+R(t.text):e+L(t.file),0)}function ne(e){let t=e?.map(I)??[];return t.length===0?0:L({tools:t})}function F(e){return!e||e.length===0?0:L({providerTools:e})}function I(e){try{return{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}catch{return{name:e.name,description:e.description}}}function L(e){return e==null?0:R(JSON.stringify(e))}function R(e){return e?Math.ceil(e.length/3):0}function z(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 B(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
1
|
+
import{t as e}from"./accumulator-BLjnX0uz.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 from"zod";import{Client as u}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as d}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as f}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import p from"@anthropic-ai/sdk";import"glob";import m from"mime";import{access as h,readFile as g,stat as _}from"node:fs/promises";import{extname as v,resolve as y}from"node:path";import{FinishReason as b,FunctionCallingConfigMode as x,GoogleGenAI as S}from"@google/genai";import C from"openai";import w from"chalk";import{marked as T}from"marked";var E=class e extends Error{code;id;details;constructor(t,n){super(t,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||`AXLE_ERROR`,this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id?{id:this.id}:{},...this.details?{details:this.details}:{},...this.cause?{cause:D(this.cause)}:{}}}};function D(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:D(e.cause)}:{}}:e}var O=class e extends E{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}:{}}}},k=class e extends O{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}:{}}}},A=class e extends E{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 j(e){let t=R(e.system??``),n=ne(e.tools),r=ne(e.mcpTools),i=F(e.providerTools),a=e.messages.reduce((e,t)=>e+ee(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 ee(e){switch(e.role){case`user`:return M(e.content);case`assistant`:return M(e.content);case`tool`:return e.content.reduce((e,t)=>e+N(t),0)}}function M(e){return typeof e==`string`?R(e):e.reduce((e,t)=>e+te(t),0)}function te(e){switch(e.type){case`text`:return R(e.text);case`thinking`:return R(e.summary??e.text??``);case`tool-call`:return R(e.name)+L(e.parameters);case`provider-tool`:return R(e.name)+L(e.input)+L(e.output);case`citation`:return L(e.citations);case`file`:return L(e.file)}}function N(e){return R(e.name)+P(e.content)}function P(e){return typeof e==`string`?R(e):e.reduce((e,t)=>t.type===`text`?e+R(t.text):e+L(t.file),0)}function ne(e){let t=e?.map(I)??[];return t.length===0?0:L({tools:t})}function F(e){return!e||e.length===0?0:L({providerTools:e})}function I(e){try{return{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}catch{return{name:e.name,description:e.description}}}function L(e){return e==null?0:R(JSON.stringify(e))}function R(e){return e?Math.ceil(e.length/3):0}function z(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 B(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
2
|
|
|
3
|
-
`)}function V(e){return e.filter(e=>e.type===`tool-call`)}function H(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(U).join(` | `),t[0]]}if(e instanceof c.ZodLiteral){let t=e.value;return[U(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]=H(t);return[`object array`,[e,e]]}else if(t instanceof c.ZodEnum||t instanceof c.ZodLiteral){let[e,n]=H(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]=H(r);n[e]=t}return[`JSON object`,n]}if(e instanceof c.ZodOptional){let[t,n]=H(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function re(e){if(e instanceof c.ZodObject)return Object.entries(e.shape).map(([e,t])=>{let[n]=H(t);return[e,n]});let[t]=H(e);return[[`response`,t]]}function U(e){return typeof e==`string`?JSON.stringify(e):String(e)}function ie(e,t){if(!t)return e;let n=ae(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 ae(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 oe(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=>se(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:z({text:n,files:r}),...a?{metadata:a}:{}},parse:e=>se(e,i)}}function se(e,t){return e?ie(B(e.content),t):null}function W(){return{in:0,out:0}}function ce(e,t){t&&(e.in+=t.in??0,e.out+=t.out??0,ue(e,`cachedIn`,t.cachedIn),ue(e,`cacheWriteIn`,t.cacheWriteIn),ue(e,`reasoningOut`,t.reasoningOut))}function G(e,t){return{...e,...de(`cachedIn`,t.cachedIn),...de(`cacheWriteIn`,t.cacheWriteIn),...de(`reasoningOut`,t.reasoningOut)}}function le(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 ue(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function de(e,t){return typeof t==`number`?{[e]:t}:{}}var fe=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 E(`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 E(`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 E(`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}};function pe(e,t){ce(e,t.usage)}function me(e){return JSON.stringify({error:e})}function he(e){let t=e.tools!==void 0||e.providerTools!==void 0;if(e.registry&&t)throw new E("Cannot specify both `registry` and `tools` / `providerTools`. Use one or the other.",{code:`TOOL_OPTIONS_CONFLICT`});return e.registry?e.registry:new fe({tools:e.tools,providerTools:e.providerTools})}async function ge(e,t=async()=>null,n,r,i){let a=[],o=()=>{throw new O(`Operation aborted`,{reason:n.reason})};for(let s of e){n.aborted&&o();let e=i?.startSpan(s.name,{type:`tool`}),c={signal:n,tracer:e,registry:r,emit:()=>{}},l;try{l=await t(s.name,s.parameters,c),n.aborted&&(e?.end(`ok`),o())}catch(t){if(t instanceof A)throw e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`fatal`,message:t.message}}),e?.end(`error`),t;(n.aborted||t instanceof O||t instanceof Error&&t.name===`AbortError`)&&(e?.end(`ok`),o()),l={type:`error`,error:{type:`exception`,message:t instanceof Error?t.message:String(t)}}}if(l==null){let t=r.get(s.name);if(t)try{let n=await t.execute(s.parameters,c);e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:n}),e?.end(`ok`),a.push({id:s.id,name:s.name,content:n});continue}catch(t){if(t instanceof A)throw e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`fatal`,message:t.message}}),e?.end(`error`),t;(n.aborted||t instanceof O||t instanceof Error&&t.name===`AbortError`)&&(e?.end(`ok`),o()),l={type:`error`,error:{type:`execution`,message:t instanceof Error?t.message:String(t)}}}}if(l==null){let t=`Tool not found: ${s.name}`;e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`not-found`,message:t}}),e?.end(`error`),a.push({id:s.id,name:s.name,content:me({type:`not-found`,message:t}),isError:!0});continue}l.type===`success`?(e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:l.content}),e?.end(`ok`),a.push({id:s.id,name:s.name,content:l.content})):(e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:l.error}),e?.end(`error`),a.push({id:s.id,name:s.name,content:me(l.error),isError:!0}))}return{results:a}}let _e=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function K(e,t){for(let n of e)n(t)}function ve(e){return{type:`error`,error:{type:`not-found`,message:`Tool not found: ${e}`}}}function ye(e){return{name:e.name,description:e.description,schema:e.schema}}function be(e){let t=[],n,r;if(`instruct`in e){let{instruct:t,messages:i,...a}=e,o=oe(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();return Promise.resolve().then(()=>xe(n,a,t).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 xe(e,t,n){let{provider:r,model:i,messages:a,system:o,onToolCall:s,maxIterations:c,tracer:l,fileResolver:u,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}=e,y=he(e),b=[...a],x=[],S=W(),C=0,w=0,T=e=>{b.push(e),x.push(e)},E=e=>{e.ok||K(n,{type:`error`,error:e.error});let t=e.ok?e.final.content:null,r=e.ok?e.final.finishReason:void 0;return l?.setResult({kind:`llm`,model:i,request:{messages:a},response:{content:t??null},usage:le(e.usage),finishReason:r}),l?.end(e.ok?`ok`:`error`),e},D=(e,n,r,i)=>{i();let a=e.length?{role:`assistant`,id:n,model:r,content:e,finishReason:`cancelled`}:void 0;throw a&&T(a),l?.end(`ok`),new O(`Stream aborted`,{reason:t.reason,messages:x,partial:a,usage:S})};for(;;){if(t.aborted&&D([],``,``,()=>{}),c!==void 0&&w>=c)return E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${c})`}}},usage:S});w+=1;let e=l?.startSpan(`turn-${w}`,{type:`llm`}),a=y?.executable()??[],k=a.length>0?a.map(ye):void 0,j=y?.provider()??[],ee=r.createStreamingRequest(i,{messages:b,system:o,tools:k,providerTools:j.length>0?j:void 0,runtime:{tracer:e,fileResolver:u},signal:t,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}),M=[],te=``,N=``,P=null,ne=W(),F=-1,I=null,L=``,R=new Map,z=new Map,B=new Map,V=-1,H=()=>{I!==null&&F>=0&&(K(n,{type:I===`text`?`text:end`:`thinking:end`,index:F,final:L}),I=null,L=``,F=-1)};for await(let r of ee){switch(r.type){case`start`:te=r.id,N=r.data.model,K(n,{type:`turn:start`,id:te,model:N});break;case`text-start`:H(),M.push({type:`text`,text:``}),V=M.length-1,F=C++,z.set(r.data.index,V),B.set(r.data.index,F),I=`text`,L=``,K(n,{type:`text:start`,index:F});break;case`text-delta`:{let e=M[V];e.text+=r.data.text,L=e.text,K(n,{type:`text:delta`,index:F,delta:r.data.text,accumulated:L});break}case`text-citation`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??F,i=M[e];if(!i||i.type!==`text`)break;i.citations=[...i.citations??[],r.data.citation],K(n,{type:`text:citation`,index:t,citation:r.data.citation,citations:i.citations});break}case`text-complete`:H();break;case`thinking-start`:H(),M.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=M.length-1,F=C++,z.set(r.data.index,V),B.set(r.data.index,F),I=`thinking`,L=``,K(n,{type:`thinking:start`,index:F,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break;case`thinking-delta`:{let e=M[V];e.text=(e.text??``)+r.data.text,L=e.text,K(n,{type:`thinking:delta`,index:F,delta:r.data.text,accumulated:L});break}case`thinking-summary-delta`:{let e=M[V];e.summary=(e.summary??``)+r.data.text,L=e.summary,K(n,{type:`thinking:summary-delta`,index:F,delta:r.data.text,accumulated:L});break}case`thinking-metadata`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??F,i=M[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),K(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=C++;M.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),V=M.length-1,z.set(r.data.index,V),B.set(r.data.index,e),R.set(r.data.id,e),K(n,{type:`tool:request`,index:e,id:r.data.id,name:r.data.name});break}case`tool-call-args-delta`:K(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=M[V];r.data.id&&(e.id=r.data.id),r.data.name&&(e.name=r.data.name),e.parameters=r.data.arguments,r.data.providerMetadata&&(e.providerMetadata=r.data.providerMetadata);break}case`provider-tool-start`:{H();let e=C++;M.push({type:`provider-tool`,id:r.data.id,name:r.data.name}),V=M.length-1,z.set(r.data.index,V),B.set(r.data.index,e),K(n,{type:`provider-tool:start`,index:e,id:r.data.id,name:r.data.name});break}case`provider-tool-complete`:{let e=M[V];r.data.output!=null&&(e.output=r.data.output),K(n,{type:`provider-tool:complete`,index:r.data.index,id:r.data.id,name:r.data.name,output:r.data.output});break}case`complete`:H(),P=r.data.finishReason,ne=r.data.usage;break;case`error`:return H(),ce(S,r.data.usage),e?.end(`error`),E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:r.data.type,message:r.data.message}}},usage:S});default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.aborted)break}if(t.aborted&&(e?.end(`ok`),D(M,te,N,H)),P===null)return H(),e?.end(`error`),E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:S});ce(S,ne);let re={kind:`llm`,model:N,request:{messages:b},response:{content:M},usage:le(ne),finishReason:P};e?.setResult(re),e?.end();let U={role:`assistant`,id:te,model:N,content:M,finishReason:P};if(T(U),K(n,{type:`turn:complete`,message:U,usage:ne}),P!==`function_call`)return E({ok:!0,response:U,messages:x,final:U,usage:S});let ie=M.filter(e=>e.type===`tool-call`);if(ie.length===0)return E({ok:!0,response:U,messages:x,final:U,usage:S});if(t.aborted)throw l?.end(`ok`),new O(`Stream aborted`,{reason:t.reason,messages:x,usage:S});let ae=crypto.randomUUID();K(n,{type:`tool-results:start`,id:ae});let oe=0,se=async(e,t,r)=>{let i=ie[oe++],a=R.get(i.id)??-1;K(n,{type:`tool:exec-start`,index:a,id:i.id,name:e,parameters:t});let o={...r,emit:t=>{K(n,{type:`tool:exec-delta`,index:a,id:i.id,name:e,chunk:t})}},c=y.get(e),l=(s?await s(e,t,o):c?{type:`success`,content:await c.execute(t,o)}:null)??ve(e);return K(n,{type:`tool:exec-complete`,index:a,id:i.id,name:e,result:l}),l},G;try{({results:G}=await ge(ie,se,t,y,l))}catch(e){throw e instanceof A?(l?.end(`error`),new A(e.message,{toolName:e.toolName,messages:e.messages??x,partial:e.partial??U,usage:e.usage??S,cause:e.cause})):e instanceof O?(l?.end(`ok`),new O(`Stream aborted`,{reason:e.reason,messages:e.messages??x,partial:e.partial,usage:e.usage??S})):e}if(G.length>0){let e={role:`tool`,id:ae,content:G};T(e),K(n,{type:`tool-results:complete`,message:e})}}}function q(e=new Date){return{start:e.toISOString()}}function J(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var Se=class{currentTurnId=null;currentTurnTiming;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage=W();createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=J(q(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=q(),this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage=W(),{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:q()};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=J(this.currentTextPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:e}),this.currentTextPart=null}break;case`thinking:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i={id:r,type:`thinking`,text:``,timing:q(),...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=J(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=q(),a={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}),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&&n.push({type:`action:progress`,turnId:t,partId:r.partId,chunk:e.chunk});break}case`tool:exec-complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=J(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`provider-tool:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=q(),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=J(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),ce(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=J(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:J(this.currentTextPart.timing)}),null),this.currentThinkingPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:J(this.currentThinkingPart.timing)}),null))}};function Ce(e){return Array.isArray(e)?e:[e]}function we(e){return e.then(()=>{},()=>{})}function Te(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:we(a)}}var Ee=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})}};function De(e,t){return{...e,...t,providerOptions:e?.providerOptions||t?.providerOptions?{...e?.providerOptions,...t?.providerOptions}:void 0}}var Oe=class{provider;model;history;tracer;name;fileResolver;requestOptions;registry;sessionId;system;mcps=[];resolvedMcps=new WeakSet;memory;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e,t){if(this.provider=e.provider,this.model=e.model,this.sessionId=e.sessionId??crypto.randomUUID(),this.history=new Ee,this.tracer=e.tracer,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 fe({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){this.eventCallbacks.push(e)}context(){return j({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 E(`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=oe(e,{metadata:r}),o=De(this.requestOptions,i),{handle:s,settled:c}=Te(this.sendQueue,e=>this.run(a,e,n,o),i.signal);return this.sendQueue=c,s}async resolveMcpTools(e){for(let t of this.mcps){if(this.resolvedMcps.has(t))continue;let n=await t.listTools({prefix:t.name,tracer:this.tracer,signal:e});this.registry.addMcp(n),this.resolvedMcps.add(t)}}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,r,i){let a=new Se,o=new e({turns:this.history.turns,sessionAnnotations:this.history.sessionAnnotations}),s,c=e=>{let t=o.apply(e);t.handled&&(this.history.replaceTurns(t.state.turns),this.history.replaceSessionAnnotations(t.state.sessionAnnotations??[])),this.emitEvent(e)},l=()=>s?o.state.turns.find(e=>e.id===s):void 0,u=W();if(n.aborted)throw new k(`Agent send aborted`,{reason:n.reason,usage:u});try{await this.resolveMcpTools(n)}catch(e){throw n.aborted||e instanceof O||e instanceof Error&&e.name===`AbortError`?new k(`Agent send aborted`,{reason:e instanceof O?e.reason:n.reason,usage:u}):e}let d=this.system,f=[...this.history.log,t.message];if(this.memory){let e=await this.memory.recall({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:f,tracer:this.tracer});e.systemSuffix&&(d=(d??``)+`
|
|
3
|
+
`)}function V(e){return e.filter(e=>e.type===`tool-call`)}function H(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(U).join(` | `),t[0]]}if(e instanceof c.ZodLiteral){let t=e.value;return[U(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]=H(t);return[`object array`,[e,e]]}else if(t instanceof c.ZodEnum||t instanceof c.ZodLiteral){let[e,n]=H(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]=H(r);n[e]=t}return[`JSON object`,n]}if(e instanceof c.ZodOptional){let[t,n]=H(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function re(e){if(e instanceof c.ZodObject)return Object.entries(e.shape).map(([e,t])=>{let[n]=H(t);return[e,n]});let[t]=H(e);return[[`response`,t]]}function U(e){return typeof e==`string`?JSON.stringify(e):String(e)}function ie(e,t){if(!t)return e;let n=ae(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 ae(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 oe(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=>se(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:z({text:n,files:r}),...a?{metadata:a}:{}},parse:e=>se(e,i)}}function se(e,t){return e?ie(B(e.content),t):null}function W(){return{in:0,out:0}}function ce(e,t){t&&(e.in+=t.in??0,e.out+=t.out??0,ue(e,`cachedIn`,t.cachedIn),ue(e,`cacheWriteIn`,t.cacheWriteIn),ue(e,`reasoningOut`,t.reasoningOut))}function G(e,t){return{...e,...de(`cachedIn`,t.cachedIn),...de(`cacheWriteIn`,t.cacheWriteIn),...de(`reasoningOut`,t.reasoningOut)}}function le(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 ue(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function de(e,t){return typeof t==`number`?{[e]:t}:{}}var fe=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 E(`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 E(`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 E(`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}};function pe(e,t){ce(e,t.usage)}function me(e){return JSON.stringify({error:e})}function he(e){let t=e.tools!==void 0||e.providerTools!==void 0;if(e.registry&&t)throw new E("Cannot specify both `registry` and `tools` / `providerTools`. Use one or the other.",{code:`TOOL_OPTIONS_CONFLICT`});return e.registry?e.registry:new fe({tools:e.tools,providerTools:e.providerTools})}async function ge(e,t=async()=>null,n,r,i){let a=[],o=()=>{throw new O(`Operation aborted`,{reason:n.reason})};for(let s of e){n.aborted&&o();let e=i?.startSpan(s.name,{type:`tool`}),c={signal:n,tracer:e,registry:r,emit:()=>{}},l;try{l=await t(s.name,s.parameters,c),n.aborted&&(e?.end(`ok`),o())}catch(t){if(t instanceof A)throw e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`fatal`,message:t.message}}),e?.end(`error`),t;(n.aborted||t instanceof O||t instanceof Error&&t.name===`AbortError`)&&(e?.end(`ok`),o()),l={type:`error`,error:{type:`exception`,message:t instanceof Error?t.message:String(t)}}}if(l==null){let t=r.get(s.name);if(t)try{let n=await t.execute(s.parameters,c);e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:n}),e?.end(`ok`),a.push({id:s.id,name:s.name,content:n});continue}catch(t){if(t instanceof A)throw e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`fatal`,message:t.message}}),e?.end(`error`),t;(n.aborted||t instanceof O||t instanceof Error&&t.name===`AbortError`)&&(e?.end(`ok`),o()),l={type:`error`,error:{type:`execution`,message:t instanceof Error?t.message:String(t)}}}}if(l==null){let t=`Tool not found: ${s.name}`;e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`not-found`,message:t}}),e?.end(`error`),a.push({id:s.id,name:s.name,content:me({type:`not-found`,message:t}),isError:!0});continue}l.type===`success`?(e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:l.content}),e?.end(`ok`),a.push({id:s.id,name:s.name,content:l.content})):(e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:l.error}),e?.end(`error`),a.push({id:s.id,name:s.name,content:me(l.error),isError:!0}))}return{results:a}}let _e=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function K(e,t){for(let n of e)n(t)}function ve(e){return{type:`error`,error:{type:`not-found`,message:`Tool not found: ${e}`}}}function ye(e){return{name:e.name,description:e.description,schema:e.schema}}function be(e){let t=[],n,r;if(`instruct`in e){let{instruct:t,messages:i,...a}=e,o=oe(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();return Promise.resolve().then(()=>xe(n,a,t).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 xe(e,t,n){let{provider:r,model:i,messages:a,system:o,onToolCall:s,maxIterations:c,tracer:l,fileResolver:u,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}=e,y=he(e),b=[...a],x=[],S=W(),C=0,w=0,T=e=>{b.push(e),x.push(e)},E=e=>{e.ok||K(n,{type:`error`,error:e.error});let t=e.ok?e.final.content:null,r=e.ok?e.final.finishReason:void 0;return l?.setResult({kind:`llm`,model:i,request:{messages:a},response:{content:t??null},usage:le(e.usage),finishReason:r}),l?.end(e.ok?`ok`:`error`),e},D=(e,n,r,i)=>{i();let a=e.length?{role:`assistant`,id:n,model:r,content:e,finishReason:`cancelled`}:void 0;throw a&&T(a),l?.end(`ok`),new O(`Stream aborted`,{reason:t.reason,messages:x,partial:a,usage:S})};for(;;){if(t.aborted&&D([],``,``,()=>{}),c!==void 0&&w>=c)return E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${c})`}}},usage:S});w+=1;let e=l?.startSpan(`turn-${w}`,{type:`llm`}),a=y?.executable()??[],k=a.length>0?a.map(ye):void 0,j=y?.provider()??[],ee=r.createStreamingRequest(i,{messages:b,system:o,tools:k,providerTools:j.length>0?j:void 0,runtime:{tracer:e,fileResolver:u},signal:t,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}),M=[],te=``,N=``,P=null,ne=W(),F=-1,I=null,L=``,R=new Map,z=new Map,B=new Map,V=-1,H=()=>{I!==null&&F>=0&&(K(n,{type:I===`text`?`text:end`:`thinking:end`,index:F,final:L}),I=null,L=``,F=-1)};for await(let r of ee){switch(r.type){case`start`:te=r.id,N=r.data.model,K(n,{type:`turn:start`,id:te,model:N});break;case`text-start`:H(),M.push({type:`text`,text:``}),V=M.length-1,F=C++,z.set(r.data.index,V),B.set(r.data.index,F),I=`text`,L=``,K(n,{type:`text:start`,index:F});break;case`text-delta`:{let e=M[V];e.text+=r.data.text,L=e.text,K(n,{type:`text:delta`,index:F,delta:r.data.text,accumulated:L});break}case`text-citation`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??F,i=M[e];if(!i||i.type!==`text`)break;i.citations=[...i.citations??[],r.data.citation],K(n,{type:`text:citation`,index:t,citation:r.data.citation,citations:i.citations});break}case`citation`:{H();let e=C++;M.push({type:`citation`,citations:r.data.citations,...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),V=M.length-1,z.set(r.data.index,V),B.set(r.data.index,e),K(n,{type:`citation`,index:e,citations:r.data.citations,providerMetadata:r.data.providerMetadata});break}case`text-complete`:H();break;case`thinking-start`:H(),M.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=M.length-1,F=C++,z.set(r.data.index,V),B.set(r.data.index,F),I=`thinking`,L=``,K(n,{type:`thinking:start`,index:F,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break;case`thinking-delta`:{let e=M[V];e.text=(e.text??``)+r.data.text,L=e.text,K(n,{type:`thinking:delta`,index:F,delta:r.data.text,accumulated:L});break}case`thinking-summary-delta`:{let e=M[V];e.summary=(e.summary??``)+r.data.text,L=e.summary,K(n,{type:`thinking:summary-delta`,index:F,delta:r.data.text,accumulated:L});break}case`thinking-metadata`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??F,i=M[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),K(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=C++;M.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),V=M.length-1,z.set(r.data.index,V),B.set(r.data.index,e),R.set(r.data.id,e),K(n,{type:`tool:request`,index:e,id:r.data.id,name:r.data.name});break}case`tool-call-args-delta`:K(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=M[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);break}case`provider-tool-start`:{H();let e=C++;M.push({type:`provider-tool`,id:r.data.id,name:r.data.name}),V=M.length-1,z.set(r.data.index,V),B.set(r.data.index,e),K(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=M[e];i&&i.type===`provider-tool`&&r.data.output!=null&&(i.output=r.data.output),K(n,{type:`provider-tool:complete`,index:t,id:r.data.id,name:r.data.name,output:r.data.output});break}case`complete`:H(),P=r.data.finishReason,ne=r.data.usage;break;case`error`:return H(),ce(S,r.data.usage),e?.end(`error`),E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:r.data.type,message:r.data.message}}},usage:S});default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.aborted)break}if(t.aborted&&(e?.end(`ok`),D(M,te,N,H)),P===null)return H(),e?.end(`error`),E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:S});ce(S,ne);let re={kind:`llm`,model:N,request:{messages:b},response:{content:M},usage:le(ne),finishReason:P};e?.setResult(re),e?.end();let U={role:`assistant`,id:te,model:N,content:M,finishReason:P};if(T(U),K(n,{type:`turn:complete`,message:U,usage:ne}),P!==`function_call`)return E({ok:!0,response:U,messages:x,final:U,usage:S});let ie=M.filter(e=>e.type===`tool-call`);if(ie.length===0)return E({ok:!0,response:U,messages:x,final:U,usage:S});if(t.aborted)throw l?.end(`ok`),new O(`Stream aborted`,{reason:t.reason,messages:x,usage:S});let ae=crypto.randomUUID();K(n,{type:`tool-results:start`,id:ae});let oe=0,se=async(e,t,r)=>{let i=ie[oe++],a=R.get(i.id)??-1;K(n,{type:`tool:exec-start`,index:a,id:i.id,name:e,parameters:t});let o={...r,emit:t=>{K(n,{type:`tool:exec-delta`,index:a,id:i.id,name:e,chunk:t})}},c=y.get(e),l=(s?await s(e,t,o):c?{type:`success`,content:await c.execute(t,o)}:null)??ve(e);return K(n,{type:`tool:exec-complete`,index:a,id:i.id,name:e,result:l}),l},G;try{({results:G}=await ge(ie,se,t,y,l))}catch(e){throw e instanceof A?(l?.end(`error`),new A(e.message,{toolName:e.toolName,messages:e.messages??x,partial:e.partial??U,usage:e.usage??S,cause:e.cause})):e instanceof O?(l?.end(`ok`),new O(`Stream aborted`,{reason:e.reason,messages:e.messages??x,partial:e.partial,usage:e.usage??S})):e}if(G.length>0){let e={role:`tool`,id:ae,content:G};T(e),K(n,{type:`tool-results:complete`,message:e})}}}function q(e=new Date){return{start:e.toISOString()}}function J(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var Se=class{currentTurnId=null;currentTurnTiming;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage=W();createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=J(q(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=q(),this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage=W(),{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:q()};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=J(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=J(q()),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:q(),...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=J(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=q(),a={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}),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&&n.push({type:`action:progress`,turnId:t,partId:r.partId,chunk:e.chunk});break}case`tool:exec-complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=J(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`provider-tool:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=q(),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=J(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),ce(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=J(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:J(this.currentTextPart.timing)}),null),this.currentThinkingPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:J(this.currentThinkingPart.timing)}),null))}};function Ce(e){return Array.isArray(e)?e:[e]}function we(e){return e.then(()=>{},()=>{})}function Te(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:we(a)}}var Ee=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})}};function De(e,t){return{...e,...t,providerOptions:e?.providerOptions||t?.providerOptions?{...e?.providerOptions,...t?.providerOptions}:void 0}}var Oe=class{provider;model;history;tracer;name;fileResolver;requestOptions;registry;sessionId;system;mcps=[];resolvedMcps=new WeakSet;memory;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e,t){if(this.provider=e.provider,this.model=e.model,this.sessionId=e.sessionId??crypto.randomUUID(),this.history=new Ee,this.tracer=e.tracer,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 fe({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){this.eventCallbacks.push(e)}context(){return j({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 E(`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=oe(e,{metadata:r}),o=De(this.requestOptions,i),{handle:s,settled:c}=Te(this.sendQueue,e=>this.run(a,e,n,o),i.signal);return this.sendQueue=c,s}async resolveMcpTools(e){for(let t of this.mcps){if(this.resolvedMcps.has(t))continue;let n=await t.listTools({prefix:t.name,tracer:this.tracer,signal:e});this.registry.addMcp(n),this.resolvedMcps.add(t)}}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,r,i){let a=new Se,o=new e({turns:this.history.turns,sessionAnnotations:this.history.sessionAnnotations}),s,c=e=>{let t=o.apply(e);t.handled&&(this.history.replaceTurns(t.state.turns),this.history.replaceSessionAnnotations(t.state.sessionAnnotations??[])),this.emitEvent(e)},l=()=>s?o.state.turns.find(e=>e.id===s):void 0,u=W();if(n.aborted)throw new k(`Agent send aborted`,{reason:n.reason,usage:u});try{await this.resolveMcpTools(n)}catch(e){throw n.aborted||e instanceof O||e instanceof Error&&e.name===`AbortError`?new k(`Agent send aborted`,{reason:e instanceof O?e.reason:n.reason,usage:u}):e}let d=this.system,f=[...this.history.log,t.message];if(this.memory){let e=await this.memory.recall({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:f,tracer:this.tracer});e.systemSuffix&&(d=(d??``)+`
|
|
4
4
|
|
|
5
5
|
`+e.systemSuffix)}if(n.aborted)throw new k(`Agent send aborted`,{reason:n.reason,usage:u});this.history.appendToLog(t.message);for(let e of a.createUserTurn(t.message))c(e);let p=a.startAgentTurn();s=p.turnId,c(p);let{signal:m,...h}=i??{},g=be({provider:this.provider,model:this.model,messages:f,system:d,registry:this.registry,tracer:this.tracer,fileResolver:r??this.fileResolver,...h,signal:n,onToolCall:async(e,t,n)=>{let r=this.registry.get(e);if(!r)return null;try{return{type:`success`,content:await r.execute(t,n)}}catch(e){if(e instanceof A)throw e;return{type:`error`,error:{type:`execution`,message:e instanceof Error?e.message:String(e)}}}}});g.on(e=>{let t=a.handleStreamEvent(e);for(let e of t)c(e)});let _;try{_=await g.final}catch(e){if(e instanceof A){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=a.finalizeTurn(`error`);for(let e of t)c(e);throw new A(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:e.usage??u,cause:e.cause})}if(e instanceof O){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=a.finalizeTurn(`cancelled`);for(let e of t)c(e);throw new k(`Agent send aborted`,{reason:e.reason,messages:e.messages,partial:e.partial,turn:l(),usage:e.usage??u})}throw e}let v=_.ok?`complete`:`error`;_.messages.length>0&&this.history.appendToLog(_.messages);let y=a.finalizeTurn(v);for(let e of y)c(e);let b=_.usage??u,x=l();if(!_.ok)return{ok:!1,error:_.error,turn:x,usage:b};let S;try{S=t.parse(_.final)}catch(e){return{ok:!1,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)},turn:x,usage:b}}if(!x)throw new E(`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:_.messages,tracer:this.tracer})}catch(e){this.tracer?.warn(`memory record failed`,{error:e instanceof Error?e.message:String(e)})}return{ok:!0,response:S,turn:x,usage:b}}};function ke(e){try{let t=l.fromJSONSchema(e);return t instanceof l.ZodObject?t.strict():l.object({}).passthrough()}catch{return l.object({}).passthrough()}}function Ae(e,t,n){return e.map(e=>Me(e,t,n))}function je(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=ke(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function Me(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=ke(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 A(`MCP tool call failed: ${e.name}`,{toolName:r,cause:t})}if(`isError`in a&&a.isError)throw Error(Pe(a.content));return Ne(a.content)}}}function Ne(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(`
|
|
6
6
|
`)}function Pe(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
7
7
|
`)||`MCP tool execution error`}var Fe=class{config;client;transport;cachedMcpTools;_connected=!1;constructor(e){this.config=e}get name(){return this.config.name??this.client?.getServerVersion()?.name}get connected(){return this._connected}async connect(e){if(this._connected)return;let t=e?.tracer?.startSpan(`mcp:connect`,{type:`internal`});this.client=new u({name:`axle`,version:`1.0.0`}),this.config.transport===`stdio`?this.transport=new d({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new f(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 Ae(await this.fetchTools(t,e?.tracer,e?.signal),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return je(await this.fetchTools(t,e?.tracer,e?.signal),e?.prefix)}async refreshTools(){return this.assertConnected(),this.cachedMcpTools=void 0,this.listTools()}async close(e){this._connected&&(e?.tracer?.debug(`mcp:close`),await this.client?.close(),this._connected=!1,this.client=void 0,this.transport=void 0,this.cachedMcpTools=void 0)}async fetchTools(e,t,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 Ie(e){return e?.map(e=>({type:`provider`,name:e.name,config:e.config}))}async function Le(e,t){if(e.version!==1)throw new E(`Unsupported agent definition version: ${e.version}`);let n=await t(e),r=e.model??n.model;if(!r)throw new E(`AgentDefinition requires a model or model resolver`);if(e.tools?.length&&!n.tools)throw new E(`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??Ie(e.providerTools),mcps:n.mcps??e.mcps?.map(e=>new Fe(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 Re=class e extends E{missingVariables;constructor(t){super(ze(t),{code:`INSTRUCT_VARIABLE_ERROR`,details:{missingVariables:t}}),this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),missingVariables:this.missingVariables}}};function ze(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var Be=class e extends Error{missingVariables;constructor(t){super(He(t)),this.name=`MissingVariablesError`,this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}};function Ve(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 Be(e)}return e}function He(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var Ue=class e{prompt;inputs={};files=[];textReferences=[];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}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)}hasFiles(){return this.files.length>0}render(e={}){let t;try{t=Ve(this.prompt,this.inputs,{strict:(e.vars??this.vars)===`required`})}catch(e){throw e instanceof Be?new Re(e.missingVariables):e}if(this.textReferences.length>0)for(let[e,n]of this.textReferences.entries()){let r=n.name?`: ${n.name}`:``;t+=`\n\n## Reference ${e+1}${r}\n\n\`\`\`${n.content}'''`}if(!this.schema)return t;let n=`# Output Format Instructions
|
|
8
8
|
|
|
9
9
|
Return only valid JSON matching this schema. Do not wrap it in markdown. Do not include prose before or after the JSON.
|
|
10
|
-
`,[,r]=H(this.schema);for(let[e,t]of re(this.schema))n+=`\n- ${e}: ${t}`;return n+=`\n\nExample:\n${JSON.stringify(r,null,2)}\n\n`,n+t}},We=class e extends E{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 Y(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 Ge(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 X(e,t=`Operation aborted`){if(e?.aborted)throw new O(t,{reason:e.reason})}function Ke(e,t,n=`Operation aborted`){return t?t.aborted?Promise.reject(new O(n,{reason:t.reason})):new Promise((r,i)=>{let a=()=>{t.removeEventListener(`abort`,a),i(new O(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 qe(e,t,n=`[redacted]`){return Je(e,null,t,n)}function Je(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=>Je(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=Je(a,t,n,r);return i}const Ye=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function Z(e){return qe(e,Ye,`[redacted-file-value]`)}const Xe=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 Ze({type:`base64`,data:n.data},e,t);if(n.type===`text`)return Ze({type:`text`,content:n.content},e,t);if(n.type===`url`)return Ze({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return Ze(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function Ze(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 Qe=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function $e(e){return e.startsWith(`text/`)||Qe.has(e)}function et(e){let t=m.getType(e);if(!t){let t=v(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($e(t))return{kind:`text`,mimeType:t};{let n=v(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function tt(e,t){let n=y(e);try{await h(n)}catch{throw Error(`File not found: ${e}`)}let r=await _(n);if(r.size>Xe)throw Error(`File too large: ${r.size} bytes. Maximum allowed: ${Xe} bytes`);let i=n.split(`/`).pop()||``,a=et(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 g(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 g(n)).toString(`base64`);return{kind:a.kind,mimeType:a.mimeType,size:r.size,name:i,source:{type:`base64`,data:t}}}}async function nt(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 _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 it(r.file,t,`user-message`));return{role:`user`,content:n}}}async function it(e,t,n){if(e.kind===`image`)return{type:`image`,source:ot(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:st(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 at(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 ot(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:at(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function st(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 ct(e){return e===!0?{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function lt(e){return e.map(e=>{let t=l.toJSONSchema(e.schema);if(!gt(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}const ut={web_search:`web_search_20250305`};function dt(e){return(e??[]).map(e=>({type:ut[e.name]??e.name,name:e.name,...e.config}))}function ft(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 pt(e){let t=[];for(let n of e)if(n.type===`text`){let e=n.citations?.map(mt);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 mt(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 ht(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 gt(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}:it(e.file,t,`tool-result`)))}async function vt(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?.tracer,v;try{X(g,`Generate aborted`);let e=await nt(r,{model:n,fileResolver:s?.fileResolver,signal:g}),y={model:n,max_tokens:l??16e3,messages:e,...i&&{system:i},...f&&{stop_sequences:Ce(f)},...(a||o)&&{tools:[...a?lt(a):[],...dt(o)]},...ct(c),...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...ft(p,m,a,o),...h};_?.debug(`Anthropic request`,{request:Z(y)});let b=await Ke(t.messages.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=yt(b)}catch(e){X(g,`Generate aborted`),v=Ge(e)}return _?.debug(`Anthropic response`,{result:v}),v}function yt(e){let t=ht(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:xt(e.usage),raw:e};if(t===`function_call`){let t=pt(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:B(t),usage:xt(e.usage),raw:e}}if(e.type==`message`){let n=pt(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:B(n),usage:xt(e.usage),raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:xt(e.usage),raw:e}}function bt(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)}function xt(e){return G({in:bt(e),out:e.output_tokens},{cachedIn:e.cache_read_input_tokens??void 0,cacheWriteIn:e.cache_creation_input_tokens??void 0})}function St(){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:ht(s.delta.stop_reason),usage:G({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`&&c.push({type:`text-citation`,data:{index:s.index,citation:mt(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: ${e.argumentsBuffer}`)}o.delete(s.index)}}e.delete(s.index);break}}return c}return{handleEvent:s}}async function*Ct(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?.tracer,v=[...a?lt(a):[],...dt(o)],y=St();try{let e=await nt(r,{model:n,fileResolver:s?.fileResolver,signal:c}),b={model:n,max_tokens:u??wt(n),messages:e,...i&&{system:i},...p&&{stop_sequences:Ce(p)},...v.length>0&&{tools:v},...ct(l),...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...ft(m,h,a,o),...g};_?.debug(`Anthropic streaming request`,{request:Z(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 wt(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 Tt(e,t={}){let n=new p({apiKey:e,maxRetries:Y(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`anthropic`,async createGenerationRequest(e,t){return await vt({client:n,model:e,...t})},createStreamingRequest(e,t){return Ct({client:n,model:e,...t})}}}const Et={Models:i,DefaultModel:s};async function Dt(e,t={}){let n=Y(t.maxRetries??2,`maxRetries`,{min:0}),r=t.timeoutMs===void 0?void 0:Y(t.timeoutMs,`timeoutMs`,{min:1}),i=0;for(;;){X(t.signal,`Request aborted`);let a=Ot(t.signal,r);try{let r=await Ke(e({signal:a.signal}),a.signal,`Request aborted`);if(!kt(r.status)||i>=n)return r;let o=At(r,i);t.onRetry?.({attempt:i+1,delayMs:o,status:r.status}),await Mt(o,t.signal),i+=1}catch(e){if(X(t.signal,`Request aborted`),i>=n)throw e;let r=At(void 0,i);t.onRetry?.({attempt:i+1,delayMs:r,error:e}),await Mt(r,t.signal),i+=1}finally{a.cleanup()}}}function Ot(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 kt(e){return e===408||e===409||e===429||e>=500}function At(e,t){let n=jt(e);if(n!==void 0)return n;let r=Math.min(500*2**t,8e3);return r+Math.floor(Math.random()*r*.25)}function jt(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 Mt(e,t){if(e<=0){X(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})}),X(t,`Request aborted`)}async function Nt(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>zt(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function Pt(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`none`}:{}}function Ft(e){return G({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 It(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 Lt(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 Rt(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`function_call`;case`content_filter`:return`error`;default:return`stop`}}async function zt(e,t){switch(e.role){case`tool`:return Bt(e,t);case`assistant`:return Vt(e);default:return Ht(e,t)}}async function Bt(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await Wt(e.content,t),tool_call_id:e.id})))}function Vt(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 Ht(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>Ut(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 Ut(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?Gt(e.file,t,`user-message`):null}async function Wt(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(Jt(r.file,e.content,e.name,e.mimeType));continue}throw Error(`ChatCompletions tool results do not support file parts other than text`)}return n.join(`
|
|
11
|
-
`)}async function
|
|
12
|
-
`);
|
|
13
|
-
`),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=>fn(e.file,t,`tool-result`)))]}))).flat(1)}}function ln(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 un(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>dn(e,t)))).filter(e=>e!==null)}}async function dn(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?fn(e.file,t,`user-message`):null}async function fn(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:mn(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 pn(await Q(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function pn(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 mn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function hn(e){switch(e){case b.STOP:return[!0,`stop`];case b.MAX_TOKENS:return[!0,`length`];case b.FINISH_REASON_UNSPECIFIED:case b.SAFETY:case b.RECITATION:case b.LANGUAGE:case b.OTHER:case b.BLOCKLIST:case b.PROHIBITED_CONTENT:case b.SPII:case b.MALFORMED_FUNCTION_CALL:case b.IMAGE_SAFETY:return[!1,`error`]}return[!1,`error`]}async function gn(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?.tracer,v={...an(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]},...rn(p,m,a,o),...h},y;try{X(g,`Generate aborted`);let e=await on(r,{model:n,fileResolver:s?.fileResolver,signal:g}),c=en(a,i,v);p!==`none`&&nn(c,o);let l={contents:e,config:c};_?.debug(`Gemini request`,{request:Z(l)});let u=await Ke(t.models.generateContent({model:n,...l}),g,`Generate aborted`);X(g,`Generate aborted`),y=_n(u,{tracer:_})}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),y=Ge(e)}return _?.debug(`Gemini response`,{result:y}),y}function _n(e,t){let{tracer:n}=t,r=e.usageMetadata?.promptTokenCount??0,i=G({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]=hn(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=yn(a,e);vn(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:B(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function vn(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 yn(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(bn(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 bn(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 xn(){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 Sn(m)){let r=e===void 0?t:u.get(e);r===void 0||r<0||p.push({type:`text-citation`,data:{index:r,citation:n}})}if(m.finishReason&&m.finishReason!==b.FINISH_REASON_UNSPECIFIED){d(p);let[e,t]=hn(m.finishReason),r=n?`function_call`:t;!e&&!n?p.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${m.finishReason}`,usage:G({in:a,out:o},{cachedIn:s,reasoningOut:c}),raw:f}}):p.push({type:`complete`,data:{finishReason:r,usage:G({in:a,out:o},{cachedIn:s,reasoningOut:c})}})}return p}return{handleChunk:f}}function Sn(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:Cn(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 Cn(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*wn(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?.tracer,v=en(a,i,{...an(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]},...rn(m,h,a,o),...g});m!==`none`&&nn(v,o);let y=xn();try{let e={contents:await on(r,{model:n,fileResolver:s?.fileResolver,signal:c}),config:v};_?.debug(`Gemini streaming request`,{request:Z(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 Tn(e,t={}){let n=new S({apiKey:e,httpOptions:{retryOptions:{attempts:En(t.maxRetries)},...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}}});return{name:`Gemini`,async createGenerationRequest(e,t){return await gn({client:n,model:e,...t})},createStreamingRequest(e,t){return wn({client:n,model:e,...t})}}}function En(e=2){return Y(e,`maxRetries`,{min:0})+1}const Dn={Models:r,DefaultModel:n};async function On(e){let{provider:t,model:n,messages:r,system:i,tools:a,providerTools:o,tracer:s,fileResolver:c,...l}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,providerTools:o,runtime:{tracer:s,fileResolver:c},...l})}async function kn(e){if(`instruct`in e){let{instruct:t,messages:n,...r}=e,i=oe(t),a=await An({...r,messages:[...n??[],i.message]});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 An(e)}async function An(e){let{provider:t,model:n,messages:r,system:i,onToolCall:a,maxIterations:o,tracer:s,fileResolver:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_=new AbortController().signal}=e,v=he(e),y=[...r],b=[],x=W(),S=0,C,w=e=>{y.push(e),b.push(e)},T=e=>(s?.setResult({kind:`llm`,model:n,request:{messages:r},response:{content:e.ok?e.final.content:null},usage:le(e.usage),finishReason:e.ok?e.final.finishReason:void 0}),s?.end(e.ok?`ok`:`error`),e),E=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??n,request:{messages:y},response:{content:t.content},usage:le(t.usage),finishReason:t.finishReason}),e.end()};try{for(;;){if(X(_,`Generate aborted`),o!==void 0&&S>=o)return T({ok:!1,messages:b,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${o})`}}},usage:x});S+=1;let e=s?.startSpan(`turn-${S}`,{type:`llm`}),r=v.executable(),D=r.length>0?r.map(e=>({name:e.name,description:e.description,schema:e.schema})):void 0,O=v.provider(),k;try{k=await On({provider:t,model:n,messages:y,system:i,tools:D,providerTools:O.length>0?O:void 0,tracer:e,fileResolver:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_}),X(_,`Generate aborted`)}catch(t){throw t instanceof Error&&t.name===`AbortError`&&e?.end(`ok`),t}if(pe(x,k),E(e,k),k.type===`error`)return T({ok:!1,messages:b,error:{kind:`model`,error:k},usage:x});let A={role:`assistant`,id:k.id,model:k.model,content:k.content,finishReason:k.finishReason};if(w(A),C=A,k.finishReason!==`function_call`)return T({ok:!0,response:C,messages:b,final:C,usage:x});let j=V(k.content);if(j.length===0)return T({ok:!0,response:C,messages:b,final:C,usage:x});let{results:ee}=await ge(j,a,_,v,s);X(_,`Generate aborted`),ee.length>0&&w({role:`tool`,id:crypto.randomUUID(),content:ee})}}catch(e){throw e instanceof A?(s?.end(`error`),new A(e.message,{toolName:e.toolName,messages:e.messages??b,partial:e.partial??C,usage:e.usage??x,cause:e.cause})):e instanceof O?(s?.end(`ok`),new O(`Generate aborted`,{reason:e.reason,messages:e.messages??b,partial:e.partial,usage:e.usage??x})):e instanceof Error&&e.name===`AbortError`?(s?.end(`ok`),new O(`Generate aborted`,{reason:_.reason,messages:b,usage:x})):e}}function jn(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 Mn={web_search:`web_search_preview`,code_execution:`code_interpreter`};function Nn(e){return e?.map(e=>({type:Mn[e.name]??e.name,...e.config}))}function Pn(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:Mn[r.name]??r.name}};throw Error(`Tool choice references an unavailable tool: ${e.name}`)}function Fn(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`none`}}:{}}async function In(e,t={model:``}){return(await Promise.all(e.map(e=>Ln(e,t)))).flat(1)}async function Ln(e,t){switch(e.role){case`tool`:return Rn(e,t);case`assistant`:return zn(e);default:return Bn(e,t)}}async function Rn(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}):Hn(e.file,t,`tool-result`)))})))}function zn(e){let t=[],n=B(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 Bn(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>Vn(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function Vn(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?Hn(e.file,t,`user-message`):(e.type,null)}async function Hn(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:Un(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 Wn(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}:Wn(r,e)}function Un(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 Wn(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 Gn(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?.tracer,v;try{if(X(g,`Generate aborted`),f!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let e=[...jn(a)??[],...Nn(o)??[]],y={model:n,input:await In(r,{model:n,fileResolver:s?.fileResolver,signal:g}),...i&&{instructions:i},...e.length>0?{tools:e}:{},...Fn(c),...l===void 0?{}:{max_output_tokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Pn(p,a,o),...m===void 0?{}:{parallel_tool_calls:m},...h};_?.debug(`OpenAI ResponsesAPI request`,{request:Z(y)});let b=await Ke(t.responses.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=Kn(b)}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),v=Ge(e)}return _?.debug(`OpenAI ResponsesAPI response`,{result:v}),v}function Kn(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:Yn(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=qn(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:B(n),usage:Yn(e.usage),raw:e}}function qn(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(Jn).filter(e=>e!==null);t.push({type:`text`,text:e.text,...n.length>0?{citations:n}:{}})}return t}function Jn(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 Yn(e){return G({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 Xn(){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=Zn(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=Zn(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=Qn(u.annotation);if(!e)break;let t=a.get(Zn(u.item_id,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:G({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 Zn(e,t){return`${e}:${t}`}function Qn(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*$n(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?.tracer;if(p!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let v=[...jn(a)??[],...Nn(o)??[]],y=Xn();try{let e={model:n,input:await In(r,{model:n,fileResolver:s?.fileResolver,signal:c}),...i&&{instructions:i},stream:!0,...v.length>0?{tools:v}:{},...Fn(l),...u===void 0?{}:{max_output_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Pn(m,a,o),...h===void 0?{}:{parallel_tool_calls:h},...g};_?.debug(`OpenAI ResponsesAPI streaming request`,{request:Z(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 er(e,t={}){let n=new C({apiKey:e,maxRetries:Y(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`OpenAI`,async createGenerationRequest(e,t){return await Gn({client:n,model:e,...t})},createStreamingRequest(e,t){return $n({client:n,model:e,...t})}}}const tr={Models:a,DefaultModel:o},nr={debug:0,info:1,warn:2,error:3};var rr=class{writers=[];_minLevel=`info`;get minLevel(){return this._minLevel}set minLevel(e){this._minLevel=e}addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.writers.forEach(e=>e.onSpanStart(n)),new ir(n,this)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}_notifySpanEnd(e){this.writers.forEach(t=>t.onSpanEnd(e))}_notifySpanUpdate(e){this.writers.forEach(t=>t.onSpanUpdate?.(e))}_notifyEvent(e,t){this.writers.forEach(n=>n.onEvent?.(e,t))}_notifySpanStart(e){this.writers.forEach(t=>t.onSpanStart(e))}_shouldLog(e){return nr[e]>=nr[this._minLevel]}},ir=class e{data;tracer;ended=!1;constructor(e,t){this.data=e,this.tracer=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.tracer._notifySpanStart(r),new e(r,this.tracer)}end(e=`ok`){this.ended||(this.ended=!0,this.data.endTime=performance.now(),this.data.status=e,this.tracer._notifySpanEnd(this.data))}addEvent(e,t,n){if(this.ended||!this.tracer._shouldLog(t))return;let r={name:e,timestamp:performance.now(),level:t,attributes:n};this.data.events.push(r),this.tracer._notifyEvent(this.data,r)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,this.tracer._notifySpanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.tracer._notifySpanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.tracer._notifySpanUpdate(this.data))}};const ar={debug:0,info:1,warn:2,error:3};var or=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 ar[e]>=ar[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 sr(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(`
|
|
14
|
-
`);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
|
|
15
|
-
`)}function
|
|
16
|
-
`;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function
|
|
17
|
-
`)}function
|
|
18
|
-
`)}function
|
|
10
|
+
`,[,r]=H(this.schema);for(let[e,t]of re(this.schema))n+=`\n- ${e}: ${t}`;return n+=`\n\nExample:\n${JSON.stringify(r,null,2)}\n\n`,n+t}},We=class e extends E{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 Y(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 Ge(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 X(e,t=`Operation aborted`){if(e?.aborted)throw new O(t,{reason:e.reason})}function Ke(e,t,n=`Operation aborted`){return t?t.aborted?Promise.reject(new O(n,{reason:t.reason})):new Promise((r,i)=>{let a=()=>{t.removeEventListener(`abort`,a),i(new O(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 qe(e,t,n=`[redacted]`){return Je(e,null,t,n)}function Je(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=>Je(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=Je(a,t,n,r);return i}const Ye=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function Z(e){return qe(e,Ye,`[redacted-file-value]`)}const Xe=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 Ze({type:`base64`,data:n.data},e,t);if(n.type===`text`)return Ze({type:`text`,content:n.content},e,t);if(n.type===`url`)return Ze({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return Ze(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function Ze(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 Qe=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function $e(e){return e.startsWith(`text/`)||Qe.has(e)}function et(e){let t=m.getType(e);if(!t){let t=v(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($e(t))return{kind:`text`,mimeType:t};{let n=v(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function tt(e,t){let n=y(e);try{await h(n)}catch{throw Error(`File not found: ${e}`)}let r=await _(n);if(r.size>Xe)throw Error(`File too large: ${r.size} bytes. Maximum allowed: ${Xe} bytes`);let i=n.split(`/`).pop()||``,a=et(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 g(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 g(n)).toString(`base64`);return{kind:a.kind,mimeType:a.mimeType,size:r.size,name:i,source:{type:`base64`,data:t}}}}async function nt(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 _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 it(r.file,t,`user-message`));return{role:`user`,content:n}}}async function it(e,t,n){if(e.kind===`image`)return{type:`image`,source:ot(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:st(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 at(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 ot(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:at(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function st(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 ct(e){return e===!0?{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function lt(e){return e.map(e=>{let t=l.toJSONSchema(e.schema);if(!gt(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}const ut={web_search:`web_search_20250305`};function dt(e){return(e??[]).map(e=>({type:ut[e.name]??e.name,name:e.name,...e.config}))}function ft(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 pt(e){let t=[];for(let n of e)if(n.type===`text`){let e=n.citations?.map(mt);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 mt(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 ht(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 gt(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}:it(e.file,t,`tool-result`)))}async function vt(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?.tracer,v;try{X(g,`Generate aborted`);let e=await nt(r,{model:n,fileResolver:s?.fileResolver,signal:g}),y={model:n,max_tokens:l??16e3,messages:e,...i&&{system:i},...f&&{stop_sequences:Ce(f)},...(a||o)&&{tools:[...a?lt(a):[],...dt(o)]},...ct(c),...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...ft(p,m,a,o),...h};_?.debug(`Anthropic request`,{request:Z(y)});let b=await Ke(t.messages.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=yt(b)}catch(e){X(g,`Generate aborted`),v=Ge(e)}return _?.debug(`Anthropic response`,{result:v}),v}function yt(e){let t=ht(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:xt(e.usage),raw:e};if(t===`function_call`){let t=pt(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:B(t),usage:xt(e.usage),raw:e}}if(e.type==`message`){let n=pt(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:B(n),usage:xt(e.usage),raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:xt(e.usage),raw:e}}function bt(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)}function xt(e){return G({in:bt(e),out:e.output_tokens},{cachedIn:e.cache_read_input_tokens??void 0,cacheWriteIn:e.cache_creation_input_tokens??void 0})}function St(){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:ht(s.delta.stop_reason),usage:G({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:mt(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: ${e.argumentsBuffer}`)}o.delete(s.index)}}e.delete(s.index);break}}return c}return{handleEvent:s}}async function*Ct(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?.tracer,v=[...a?lt(a):[],...dt(o)],y=St();try{let e=await nt(r,{model:n,fileResolver:s?.fileResolver,signal:c}),b={model:n,max_tokens:u??wt(n),messages:e,...i&&{system:i},...p&&{stop_sequences:Ce(p)},...v.length>0&&{tools:v},...ct(l),...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...ft(m,h,a,o),...g};_?.debug(`Anthropic streaming request`,{request:Z(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 wt(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 Tt(e,t={}){let n=new p({apiKey:e,maxRetries:Y(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`anthropic`,async createGenerationRequest(e,t){return await vt({client:n,model:e,...t})},createStreamingRequest(e,t){return Ct({client:n,model:e,...t})}}}const Et={Models:i,DefaultModel:s};async function Dt(e,t={}){let n=Y(t.maxRetries??2,`maxRetries`,{min:0}),r=t.timeoutMs===void 0?void 0:Y(t.timeoutMs,`timeoutMs`,{min:1}),i=0;for(;;){X(t.signal,`Request aborted`);let a=Ot(t.signal,r);try{let r=await Ke(e({signal:a.signal}),a.signal,`Request aborted`);if(!kt(r.status)||i>=n)return r;let o=At(r,i);t.onRetry?.({attempt:i+1,delayMs:o,status:r.status}),await Mt(o,t.signal),i+=1}catch(e){if(X(t.signal,`Request aborted`),i>=n)throw e;let r=At(void 0,i);t.onRetry?.({attempt:i+1,delayMs:r,error:e}),await Mt(r,t.signal),i+=1}finally{a.cleanup()}}}function Ot(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 kt(e){return e===408||e===409||e===429||e>=500}function At(e,t){let n=jt(e);if(n!==void 0)return n;let r=Math.min(500*2**t,8e3);return r+Math.floor(Math.random()*r*.25)}function jt(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 Mt(e,t){if(e<=0){X(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})}),X(t,`Request aborted`)}const Nt={web_search:`openrouter:web_search`};function Pt(e,t){let n=[];for(let r of e){let e=Nt[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 Ft(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 It(e){let t=e.outputSpan;return!t||t.start===void 0&&t.end===void 0?!1:t.start!==0||t.end!==0}async function Lt(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>Wt(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function Rt(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`none`}:{}}function zt(e){return G({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 Bt(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 Vt(e,t,n){if(!(!e||e.length===0)){if(!t){n?.(`providerTools not supported by ChatCompletions provider`);return}switch(t){case`openrouter`:return Pt(e,n)}}}function Ht(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 Ut(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 Wt(e,t){switch(e.role){case`tool`:return Gt(e,t);case`assistant`:return Kt(e);default:return qt(e,t)}}async function Gt(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await Yt(e.content,t),tool_call_id:e.id})))}function Kt(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 qt(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>Jt(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 Jt(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?Xt(e.file,t,`user-message`):null}async function Yt(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($t(r.file,e.content,e.name,e.mimeType));continue}throw Error(`ChatCompletions tool results do not support file parts other than text`)}return n.join(`
|
|
11
|
+
`)}async function Xt(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:$t(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:Qt(r,e)}}}return{type:`image_url`,image_url:{url:Zt(await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}}}function Zt(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 Qt(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 $t(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}async function en(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,apiKey:c,providerToolVendor: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?.tracer,S;try{X(b,`Generate aborted`);let e=await Lt(r,i,{model:n,fileResolver:s?.fileResolver,signal:b}),C=Bt(a),w=Vt(o,l,x?.warn.bind(x)),T=[...C??[],...w??[]],E={model:n,messages:e,...T.length>0?{tools:T}:{},...Rt(f),...p===void 0?{}:{max_tokens:p},...m===void 0?{}:{temperature:m},...h===void 0?{}:{top_p:h},...g===void 0?{}:{stop:g},...Ht(_,a,o),...v===void 0?{}:{parallel_tool_calls:v},...y};x?.debug(`ChatCompletions request`,{request:Z(E)});let D={"Content-Type":`application/json`};c&&(D.Authorization=`Bearer ${c}`);let O=await Dt(({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?.debug(`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 Ke(O.json(),b,`Generate aborted`);X(b,`Generate aborted`),S=tn(k)}catch(e){X(b,`Generate aborted`),x?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),S=Ge(e)}return x?.debug(`ChatCompletions response`,{result:S}),S}function tn(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(Ft).filter(e=>e!==null),a=i.filter(It),o=i.filter(e=>!It(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`)?Ut(`tool_calls`):Ut(t.finish_reason);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:s,content:n,text:B(n),usage:zt(e.usage),raw:e}}function nn(){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=zt(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(Ft).filter(e=>e!==null),r=a===`text`?e.filter(It):[];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: ${t.argumentsBuffer}`)}e.clear(),o=Ut(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*rn(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,apiKey:l,providerToolVendor:u,maxRetries:d,timeoutMs:f,reasoning:p,maxOutputTokens:m,temperature:h,topP:g,stop:_,toolChoice:v,parallelToolCalls:y,providerOptions:b}=e,x=s?.tracer,S=nn();try{let e=await Lt(r,i,{model:n,fileResolver:s?.fileResolver,signal:c}),C=Bt(a),w=Vt(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}:{},...Rt(p),...m===void 0?{}:{max_tokens:m},...h===void 0?{}:{temperature:h},...g===void 0?{}:{top_p:g},..._===void 0?{}:{stop:_},...Ht(v,a,o),...y===void 0?{}:{parallel_tool_calls:y},...b};x?.debug(`ChatCompletions streaming request`,{request:Z(E)});let D={"Content-Type":`application/json`};l&&(D.Authorization=`Bearer ${l}`);let O=await Dt(({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?.debug(`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(`
|
|
12
|
+
`);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=an(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 an(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 on(e,t,n){let r=typeof t==`string`?t:t?.apiKey,i=typeof t==`string`?n:t,a=Y(i?.maxRetries??2,`maxRetries`,{min:0}),o=i?.timeoutMs===void 0?void 0:Y(i.timeoutMs,`timeoutMs`,{min:1}),s=i?.providerToolVendor;return{name:`ChatCompletions`,async createGenerationRequest(t,n){return await en({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,providerToolVendor:s,...n})},createStreamingRequest(t,n){return rn({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,providerToolVendor:s,...n})}}}function sn(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 cn={web_search:`googleSearch`,code_execution:`codeExecution`};function ln(e,t){if(!(!t||t.length===0)){e.tools||=[];for(let n of t){let t=cn[n.name]??n.name;e.tools.push({[t]:n.config??{}})}}}function un(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:x.AUTO}}};if(e===`none`)return{toolConfig:{functionCallingConfig:{mode:x.NONE}}};if(e===`required`){if(!n||n.length===0)throw Error(`Gemini requires function tools for required tool choice`);return{toolConfig:{functionCallingConfig:{mode:x.ANY}}}}if(n?.some(t=>t.name===e.name))return{toolConfig:{functionCallingConfig:{mode:x.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 dn(e){return e===!0?{thinkingConfig:{thinkingBudget:8192,includeThoughts:!0}}:e===!1?{thinkingConfig:{thinkingBudget:0}}:{}}async function fn(e,t={model:``}){return(await Promise.all(e.map(e=>pn(e,t)))).filter(e=>e!==void 0)}async function pn(e,t){switch(e.role){case`tool`:return mn(e,t);case`assistant`:return hn(e);case`user`:return gn(e,t)}}async function mn(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(`
|
|
13
|
+
`),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=>vn(e.file,t,`tool-result`)))]}))).flat(1)}}function hn(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 gn(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>_n(e,t)))).filter(e=>e!==null)}}async function _n(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?vn(e.file,t,`user-message`):null}async function vn(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:bn(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 yn(await Q(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function yn(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 bn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function xn(e){switch(e){case b.STOP:return[!0,`stop`];case b.MAX_TOKENS:return[!0,`length`];case b.FINISH_REASON_UNSPECIFIED:case b.SAFETY:case b.RECITATION:case b.LANGUAGE:case b.OTHER:case b.BLOCKLIST:case b.PROHIBITED_CONTENT:case b.SPII:case b.MALFORMED_FUNCTION_CALL:case b.IMAGE_SAFETY:return[!1,`error`]}return[!1,`error`]}async function Sn(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?.tracer,v={...dn(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]},...un(p,m,a,o),...h},y;try{X(g,`Generate aborted`);let e=await fn(r,{model:n,fileResolver:s?.fileResolver,signal:g}),c=sn(a,i,v);p!==`none`&&ln(c,o);let l={contents:e,config:c};_?.debug(`Gemini request`,{request:Z(l)});let u=await Ke(t.models.generateContent({model:n,...l}),g,`Generate aborted`);X(g,`Generate aborted`),y=Cn(u,{tracer:_})}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),y=Ge(e)}return _?.debug(`Gemini response`,{result:y}),y}function Cn(e,t){let{tracer:n}=t,r=e.usageMetadata?.promptTokenCount??0,i=G({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]=xn(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=Tn(a,e);wn(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:B(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function wn(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 Tn(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(En(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 En(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 Dn(){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 On(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!==b.FINISH_REASON_UNSPECIFIED){d(p);let[e,t]=xn(m.finishReason),r=n?`function_call`:t;!e&&!n?p.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${m.finishReason}`,usage:G({in:a,out:o},{cachedIn:s,reasoningOut:c}),raw:f}}):p.push({type:`complete`,data:{finishReason:r,usage:G({in:a,out:o},{cachedIn:s,reasoningOut:c})}})}return p}return{handleChunk:f}}function On(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:kn(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 kn(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*An(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?.tracer,v=sn(a,i,{...dn(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]},...un(m,h,a,o),...g});m!==`none`&&ln(v,o);let y=Dn();try{let e={contents:await fn(r,{model:n,fileResolver:s?.fileResolver,signal:c}),config:v};_?.debug(`Gemini streaming request`,{request:Z(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 jn(e,t={}){let n=new S({apiKey:e,httpOptions:{retryOptions:{attempts:Mn(t.maxRetries)},...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}}});return{name:`Gemini`,async createGenerationRequest(e,t){return await Sn({client:n,model:e,...t})},createStreamingRequest(e,t){return An({client:n,model:e,...t})}}}function Mn(e=2){return Y(e,`maxRetries`,{min:0})+1}const Nn={Models:r,DefaultModel:n};async function Pn(e){let{provider:t,model:n,messages:r,system:i,tools:a,providerTools:o,tracer:s,fileResolver:c,...l}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,providerTools:o,runtime:{tracer:s,fileResolver:c},...l})}async function Fn(e){if(`instruct`in e){let{instruct:t,messages:n,...r}=e,i=oe(t),a=await In({...r,messages:[...n??[],i.message]});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 In(e)}async function In(e){let{provider:t,model:n,messages:r,system:i,onToolCall:a,maxIterations:o,tracer:s,fileResolver:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_=new AbortController().signal}=e,v=he(e),y=[...r],b=[],x=W(),S=0,C,w=e=>{y.push(e),b.push(e)},T=e=>(s?.setResult({kind:`llm`,model:n,request:{messages:r},response:{content:e.ok?e.final.content:null},usage:le(e.usage),finishReason:e.ok?e.final.finishReason:void 0}),s?.end(e.ok?`ok`:`error`),e),E=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??n,request:{messages:y},response:{content:t.content},usage:le(t.usage),finishReason:t.finishReason}),e.end()};try{for(;;){if(X(_,`Generate aborted`),o!==void 0&&S>=o)return T({ok:!1,messages:b,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${o})`}}},usage:x});S+=1;let e=s?.startSpan(`turn-${S}`,{type:`llm`}),r=v.executable(),D=r.length>0?r.map(e=>({name:e.name,description:e.description,schema:e.schema})):void 0,O=v.provider(),k;try{k=await Pn({provider:t,model:n,messages:y,system:i,tools:D,providerTools:O.length>0?O:void 0,tracer:e,fileResolver:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_}),X(_,`Generate aborted`)}catch(t){throw t instanceof Error&&t.name===`AbortError`&&e?.end(`ok`),t}if(pe(x,k),E(e,k),k.type===`error`)return T({ok:!1,messages:b,error:{kind:`model`,error:k},usage:x});let A={role:`assistant`,id:k.id,model:k.model,content:k.content,finishReason:k.finishReason};if(w(A),C=A,k.finishReason!==`function_call`)return T({ok:!0,response:C,messages:b,final:C,usage:x});let j=V(k.content);if(j.length===0)return T({ok:!0,response:C,messages:b,final:C,usage:x});let{results:ee}=await ge(j,a,_,v,s);X(_,`Generate aborted`),ee.length>0&&w({role:`tool`,id:crypto.randomUUID(),content:ee})}}catch(e){throw e instanceof A?(s?.end(`error`),new A(e.message,{toolName:e.toolName,messages:e.messages??b,partial:e.partial??C,usage:e.usage??x,cause:e.cause})):e instanceof O?(s?.end(`ok`),new O(`Generate aborted`,{reason:e.reason,messages:e.messages??b,partial:e.partial,usage:e.usage??x})):e instanceof Error&&e.name===`AbortError`?(s?.end(`ok`),new O(`Generate aborted`,{reason:_.reason,messages:b,usage:x})):e}}function Ln(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 Rn={web_search:`web_search_preview`,code_execution:`code_interpreter`};function zn(e){return e?.map(e=>({type:Rn[e.name]??e.name,...e.config}))}function Bn(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:Rn[r.name]??r.name}};throw Error(`Tool choice references an unavailable tool: ${e.name}`)}function Vn(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`none`}}:{}}async function Hn(e,t={model:``}){return(await Promise.all(e.map(e=>Un(e,t)))).flat(1)}async function Un(e,t){switch(e.role){case`tool`:return Wn(e,t);case`assistant`:return Gn(e);default:return Kn(e,t)}}async function Wn(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}):Jn(e.file,t,`tool-result`)))})))}function Gn(e){let t=[],n=B(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 Kn(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>qn(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function qn(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?Jn(e.file,t,`user-message`):(e.type,null)}async function Jn(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:Yn(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 Xn(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}:Xn(r,e)}function Yn(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 Xn(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 Zn(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?.tracer,v;try{if(X(g,`Generate aborted`),f!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let e=[...Ln(a)??[],...zn(o)??[]],y={model:n,input:await Hn(r,{model:n,fileResolver:s?.fileResolver,signal:g}),...i&&{instructions:i},...e.length>0?{tools:e}:{},...Vn(c),...l===void 0?{}:{max_output_tokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Bn(p,a,o),...m===void 0?{}:{parallel_tool_calls:m},...h};_?.debug(`OpenAI ResponsesAPI request`,{request:Z(y)});let b=await Ke(t.responses.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=Qn(b)}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),v=Ge(e)}return _?.debug(`OpenAI ResponsesAPI response`,{result:v}),v}function Qn(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:tr(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=$n(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:B(n),usage:tr(e.usage),raw:e}}function $n(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(er).filter(e=>e!==null);t.push({type:`text`,text:e.text,...n.length>0?{citations:n}:{}})}return t}function er(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 tr(e){return G({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 nr(){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=rr(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=rr(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=ir(u.annotation);if(!e)break;let t=a.get(rr(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:G({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 rr(e,t){return`${e}:${t}`}function ir(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*ar(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?.tracer;if(p!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let v=[...Ln(a)??[],...zn(o)??[]],y=nr();try{let e={model:n,input:await Hn(r,{model:n,fileResolver:s?.fileResolver,signal:c}),...i&&{instructions:i},stream:!0,...v.length>0?{tools:v}:{},...Vn(l),...u===void 0?{}:{max_output_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Bn(m,a,o),...h===void 0?{}:{parallel_tool_calls:h},...g};_?.debug(`OpenAI ResponsesAPI streaming request`,{request:Z(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 or(e,t={}){let n=new C({apiKey:e,maxRetries:Y(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`OpenAI`,async createGenerationRequest(e,t){return await Zn({client:n,model:e,...t})},createStreamingRequest(e,t){return ar({client:n,model:e,...t})}}}const sr={Models:a,DefaultModel:o},cr={debug:0,info:1,warn:2,error:3};var lr=class{writers=[];_minLevel=`info`;get minLevel(){return this._minLevel}set minLevel(e){this._minLevel=e}addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.writers.forEach(e=>e.onSpanStart(n)),new ur(n,this)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}_notifySpanEnd(e){this.writers.forEach(t=>t.onSpanEnd(e))}_notifySpanUpdate(e){this.writers.forEach(t=>t.onSpanUpdate?.(e))}_notifyEvent(e,t){this.writers.forEach(n=>n.onEvent?.(e,t))}_notifySpanStart(e){this.writers.forEach(t=>t.onSpanStart(e))}_shouldLog(e){return cr[e]>=cr[this._minLevel]}},ur=class e{data;tracer;ended=!1;constructor(e,t){this.data=e,this.tracer=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.tracer._notifySpanStart(r),new e(r,this.tracer)}end(e=`ok`){this.ended||(this.ended=!0,this.data.endTime=performance.now(),this.data.status=e,this.tracer._notifySpanEnd(this.data))}addEvent(e,t,n){if(this.ended||!this.tracer._shouldLog(t))return;let r={name:e,timestamp:performance.now(),level:t,attributes:n};this.data.events.push(r),this.tracer._notifyEvent(this.data,r)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,this.tracer._notifySpanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.tracer._notifySpanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.tracer._notifySpanUpdate(this.data))}};const dr={debug:0,info:1,warn:2,error:3};var fr=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 dr[e]>=dr[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 pr(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(`
|
|
14
|
+
`);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 pr(e){return mr(T.lexer(e))}function mr(e=[]){return e.map(e=>hr(e)).filter(e=>e.length>0).join(`
|
|
15
|
+
`)}function hr(e){switch(e.type){case`space`:return``;case`heading`:return w.bold($(e.tokens));case`paragraph`:return $(e.tokens);case`blockquote`:return xr(mr(e.tokens),`> `);case`code`:return(e.lang?w.dim(`${e.lang}\n`):``)+w.yellow(e.text);case`list`:return _r(e)?yr(e):e.raw;case`hr`:return w.dim(`-`.repeat(40));case`table`:return vr(e)?br(e):e.raw;case`html`:return e.text;case`text`:return e.tokens?$(e.tokens):Cr(e.text);default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function $(e=[]){return e.map(e=>gr(e)).join(``)}function gr(e){switch(e.type){case`text`:case`escape`:return Cr(e.text);case`strong`:return w.bold($(e.tokens));case`em`:return w.italic($(e.tokens));case`codespan`:return w.yellow(e.text);case`del`:return w.strikethrough($(e.tokens));case`link`:{let t=$(e.tokens);return e.href&&e.href!==e.text?`${w.blue.underline(t)} ${w.dim(`(${e.href})`)}`:w.blue.underline(t)}case`image`:return e.text?`${e.text} (${e.href})`:e.href;case`br`:return`
|
|
16
|
+
`;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function _r(e){return e.type===`list`&&`items`in e&&Array.isArray(e.items)}function vr(e){return e.type===`table`&&`header`in e&&`rows`in e}function yr(e){return e.items.map((t,n)=>{let r=e.ordered?`${Number(e.start||1)+n}. `:`- `,i=t.task?`[${t.checked?`x`:` `}] `:``,a=mr(t.tokens).trimEnd();return r+i+Sr(a,r.length+i.length)}).join(`
|
|
17
|
+
`)}function br(e){let t=e.header.map(e=>$(e.tokens)).join(` | `),n=e.rows.map(e=>e.map(e=>$(e.tokens)).join(` | `));return[w.bold(t),...n].join(`
|
|
18
|
+
`)}function xr(e,t){return e.split(`
|
|
19
19
|
`).map(e=>t+e).join(`
|
|
20
|
-
`)}function
|
|
20
|
+
`)}function Sr(e,t){let[n=``,...r]=e.split(`
|
|
21
21
|
`);if(r.length===0)return n;let i=` `.repeat(t);return[n,...r.map(e=>i+e)].join(`
|
|
22
|
-
`)}function
|
|
22
|
+
`)}function Cr(e){return e.replace(/"/g,`"`).replace(/'/g,`'`).replace(/</g,`<`).replace(/>/g,`>`).replace(/&/g,`&`)}export{Oe as Agent,Et as Anthropic,O as AxleAbortError,k as AxleAgentAbortError,E as AxleError,_e as AxleStopReason,A as AxleToolFatalError,Nn as Gemini,Ee as History,Ue as Instruct,Re as InstructVariableError,Fe as MCP,sr as OpenAI,fr as SimpleWriter,We as TaskError,fe as ToolRegistry,lr as Tracer,e as TurnAccumulator,Se as TurnEventBuilder,ce as addStats,Tt as anthropic,on as chatCompletions,Le as createAgentConfig,Te as createHandle,W as createStats,j as estimateContextUsage,jn as gemini,Fn as generate,Pn as generateTurn,tt as loadFileContent,or as openai,ie as parseResponse,be as stream};
|
package/dist/ui.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as
|
|
2
|
-
export { type AccumulatableEvent, type ActionPart, type ActionResult, type Annotation, type AnnotationEvent, type AnnotationPlacement, type AnnotationStatus, type AnnotationTarget, type Citation, type CitationOutputSpan, type CitationSource, type DocumentLocator, type FileInfo, type FilePart, type ProviderToolAction, type Stats, type SubagentAction, type TextPart, type ThinkingContinuity, type ThinkingPart, type TimingInfo, type ToolAction, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, type TurnMetadata, type TurnPart, type TurnStatus, type UnknownEvent };
|
|
1
|
+
import { C as TurnMetadata, I as Citation, J as ThinkingContinuity, K as DocumentLocator, L as CitationOutputSpan, R as CitationSource, S as Turn, T as TurnStatus, _ as SubagentAction, a as UnknownEvent, b as TimingInfo, c as TurnEvent, d as Annotation, f as AnnotationPlacement, g as ProviderToolAction, h as FilePart, i as TurnAccumulatorState, l as ActionPart, m as CitationPart, n as TurnAccumulator, o as AnnotationEvent, ot as FileInfo, p as AnnotationStatus, r as TurnAccumulatorResult, s as AnnotationTarget, t as AccumulatableEvent, u as ActionResult, v as TextPart, w as TurnPart, x as ToolAction, xt as Stats, y as ThinkingPart } from "./accumulator-BNYePirr.js";
|
|
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 ToolAction, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, type TurnMetadata, type TurnPart, type TurnStatus, type UnknownEvent };
|