@fifthrevision/axle 0.23.0 → 0.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/accumulator-BnFn9yqM.js +1 -0
- package/dist/{accumulator-C4O3UCxY.d.ts → accumulator-CblCRkql.d.ts} +86 -66
- package/dist/index.d.ts +165 -78
- package/dist/index.js +17 -17
- package/dist/ui.d.ts +2 -2
- package/dist/ui.js +1 -1
- package/package.json +1 -1
- package/dist/accumulator-BLjnX0uz.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class e{_state;constructor(e){this._state={turns:e?.turns??[],sessionAnnotations:e?.sessionAnnotations}}get state(){return this._state}apply(t){let n=t;switch(t.type){case`session:restore`:return this.replaceState({turns:n.turns??[],sessionAnnotations:n.sessionAnnotations},t);case`turn:user`:return this.replaceTurns([...this._state.turns,n.turn],t);case`turn:start`:{let e={id:n.turnId,owner:`agent`,parts:[],status:`streaming`,...n.timing?{timing:n.timing}:{}};return this.replaceTurns([...this._state.turns,e],t)}case`part:start`:return this.updateTurn(n.turnId,t,e=>({...e,parts:[...e.parts,n.part]}));case`text:delta`:return this.updatePart(n.turnId,n.partId,t,e=>e.type===`text`?{...e,text:e.text+n.delta}:e);case`text:citation`:return this.updatePart(n.turnId,n.partId,t,e=>e.type===`text`?{...e,citations:[...e.citations??[],n.citation]}:e);case`thinking:delta`:return this.updatePart(n.turnId,n.partId,t,e=>e.type===`thinking`?{...e,text:(e.text??``)+n.delta}:e);case`thinking:summary-delta`:return this.updatePart(n.turnId,n.partId,t,e=>e.type===`thinking`?{...e,summary:(e.summary??``)+n.delta}:e);case`thinking:update`:return this.updatePart(n.turnId,n.partId,t,e=>e.type===`thinking`?{...e,...n.redacted===void 0?{}:{redacted:n.redacted},...n.continuity?{continuity:n.continuity}:{},...n.providerMetadata?{providerMetadata:n.providerMetadata}:{}}:e);case`part:end`:return this.updatePart(n.turnId,n.partId,t,e=>({...e,timing:n.timing??e.timing}));case`action:args-delta`:return this.updatePart(n.turnId,n.partId,t,e=>e.type!==`action`||e.kind!==`tool`?e:{...e,detail:{...e.detail,pendingArgs:n.accumulated}});case`action:running`:return this.updatePart(n.turnId,n.partId,t,e=>{if(e.type!==`action`)return e;if(e.kind===`tool`){let{pendingArgs:t,...r}=e.detail;return{...e,status:`running`,detail:n.parameters?{...r,parameters:n.parameters}:r}}return{...e,status:`running`}});case`action:progress`:return this.updatePart(n.turnId,n.partId,t,e=>{if(e.type!==`action`)return e;let t=e.detail.result,r=t?.type===`in-progress`?t.content:``;return{...e,detail:{...e.detail,result:{type:`in-progress`,content:r+n.chunk}}}});case`action:complete`:return this.updatePart(n.turnId,n.partId,t,e=>e.type===`action`?{...e,status:`complete`,detail:{...e.detail,result:n.result},timing:n.timing??e.timing}:e);case`action:error`:return this.updatePart(n.turnId,n.partId,t,e=>e.type===`action`?{...e,status:`error`,detail:{...e.detail,result:{type:`error`,error:n.error}},timing:n.timing??e.timing}:e);case`turn:end`:return this.updateTurn(n.turnId,t,e=>({...e,status:n.status,usage:n.usage,timing:n.timing??e.timing}));case`annotation:start`:return this.addAnnotation(t);case`annotation:update`:return this.replaceAnnotation(t,!1);case`annotation:end`:return this.replaceAnnotation(t,!0);case`error`:return this.handled(t);case`action:child-event`:return this.updatePart(n.turnId,n.partId,t,t=>{if(t.type!==`action`||t.kind!==`agent`)return t;let r=new e({turns:t.detail.children}).apply(n.event);return{...t,detail:{...t.detail,children:r.state.turns}}});default:return{handled:!1,state:this._state,event:t}}}replaceState(e,t){return this._state=e,this.handled(t)}replaceTurns(e,t){return this.replaceState({...this._state,turns:e},t)}updateTurn(e,t,n){let r=!1,i=this._state.turns.map(t=>{if(t.id!==e)return t;let i=n(t);return i===t?t:(r=!0,i)});return r?this.replaceTurns(i,t):this.handled(t)}updatePart(e,t,n,r){return this.updateTurn(e,n,e=>{let n=!1,i=e.parts.map(e=>{if(e.id!==t)return e;let i=r(e);return i===e?e:(n=!0,i)});return n?{...e,parts:i}:e})}addAnnotation(e){let n=e,r=n.target,i=t(n.annotation);return!r||!i?this.handled(e):r.type===`session`?this.replaceState({...this._state,sessionAnnotations:[...this._state.sessionAnnotations??[],i]},e):r.type===`turn`?this.updateTurn(r.turnId,e,e=>({...e,annotations:[...e.annotations??[],i]})):r.type===`part`?this.updatePart(r.turnId,r.partId,e,e=>({...e,annotations:[...e.annotations??[],i]})):this.handled(e)}replaceAnnotation(e,r){let i=e,a=i.target,o=t(i.annotation,r);if(!a||!o)return this.handled(e);if(a.type===`session`){let t=n(this._state.sessionAnnotations,o);return t?this.replaceState({...this._state,sessionAnnotations:t},e):this.handled(e)}return a.type===`turn`?this.updateTurn(a.turnId,e,e=>{let t=n(e.annotations,o);return t?{...e,annotations:t}:e}):a.type===`part`?this.updatePart(a.turnId,a.partId,e,e=>{let t=n(e.annotations,o);return t?{...e,annotations:t}:e}):this.handled(e)}handled(e){return{handled:!0,state:this._state,event:e}}};function t(e,t=!1){if(!e)return;let n=t?e.status??`complete`:e.status,r={...e,placement:e.placement??`after`};return n?{...r,status:n}:r}function n(e,t){if(!e)return;let n=!1,r=e.map(e=>e.id===t.id?(n=!0,t):e);return n?r:void 0}export{e as t};
|
|
@@ -83,10 +83,7 @@ interface Span {
|
|
|
83
83
|
}
|
|
84
84
|
//#endregion
|
|
85
85
|
//#region src/types.d.ts
|
|
86
|
-
|
|
87
|
-
* Usage reported by a provider response.
|
|
88
|
-
*/
|
|
89
|
-
interface Stats {
|
|
86
|
+
interface TokenStats {
|
|
90
87
|
/** Total effective input tokens. Includes `cachedIn` and `cacheWriteIn` when reported. */
|
|
91
88
|
in: number;
|
|
92
89
|
/** Total output tokens. Includes `reasoningOut` when reported. */
|
|
@@ -98,6 +95,24 @@ interface Stats {
|
|
|
98
95
|
/** Output tokens spent on reasoning/thinking. Included in `out`. */
|
|
99
96
|
reasoningOut?: number;
|
|
100
97
|
}
|
|
98
|
+
interface UsageEntry extends TokenStats {
|
|
99
|
+
/** Provider identifier. */
|
|
100
|
+
provider: string;
|
|
101
|
+
/** Model identifier. */
|
|
102
|
+
model: string;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Aggregate usage reported by an Axle operation.
|
|
106
|
+
*
|
|
107
|
+
* `breakdown` holds one entry per provider+model pair so cost can be
|
|
108
|
+
* reconstructed when an operation spans models (for example subagent tools).
|
|
109
|
+
* Entries explain the aggregate numeric fields and must not be added to them
|
|
110
|
+
* again.
|
|
111
|
+
*/
|
|
112
|
+
interface Stats extends TokenStats {
|
|
113
|
+
/** @experimental The entry shape may gain dimensions in a minor release. */
|
|
114
|
+
breakdown?: UsageEntry[];
|
|
115
|
+
}
|
|
101
116
|
//#endregion
|
|
102
117
|
//#region src/messages/stream.d.ts
|
|
103
118
|
interface StreamChunk {
|
|
@@ -303,15 +318,6 @@ type DeferredFileInfo = FileInfo & {
|
|
|
303
318
|
ref: unknown;
|
|
304
319
|
};
|
|
305
320
|
};
|
|
306
|
-
type ConcreteFileInfo = FileInfo & {
|
|
307
|
-
source: {
|
|
308
|
-
type: "text";
|
|
309
|
-
} | {
|
|
310
|
-
type: "base64";
|
|
311
|
-
} | {
|
|
312
|
-
type: "url";
|
|
313
|
-
};
|
|
314
|
-
};
|
|
315
321
|
type FileProviderId = "anthropic" | "openai" | "gemini" | "chatcompletions";
|
|
316
322
|
type FileResolveFormat = "base64" | "url" | "text" | "gemini-file-uri";
|
|
317
323
|
type ResolvedFileSource = {
|
|
@@ -510,14 +516,15 @@ type MessageMetadata = Record<string, unknown>;
|
|
|
510
516
|
* Content returned by a tool call.
|
|
511
517
|
*
|
|
512
518
|
* Tool results may be simple text or structured parts when the result includes
|
|
513
|
-
* file data.
|
|
519
|
+
* file data. Deferred file sources remain authored in history and are resolved
|
|
520
|
+
* at each provider conversion boundary so expiring URLs are not persisted.
|
|
514
521
|
*/
|
|
515
522
|
type ToolResultPart = {
|
|
516
523
|
type: "text";
|
|
517
524
|
text: string;
|
|
518
525
|
} | {
|
|
519
526
|
type: "file";
|
|
520
|
-
file:
|
|
527
|
+
file: FileInfo;
|
|
521
528
|
};
|
|
522
529
|
/**
|
|
523
530
|
* Message authored by the user or host application.
|
|
@@ -750,56 +757,6 @@ interface ContentPartCitation {
|
|
|
750
757
|
providerMetadata?: Record<string, unknown>;
|
|
751
758
|
}
|
|
752
759
|
//#endregion
|
|
753
|
-
//#region src/tools/registry.d.ts
|
|
754
|
-
declare class ToolRegistry {
|
|
755
|
-
private tools;
|
|
756
|
-
private mcpTools;
|
|
757
|
-
private providerTools;
|
|
758
|
-
constructor(init?: {
|
|
759
|
-
tools?: ExecutableTool[];
|
|
760
|
-
providerTools?: ProviderTool[];
|
|
761
|
-
});
|
|
762
|
-
add(tool: ExecutableTool): void;
|
|
763
|
-
add(tools: ExecutableTool[]): void;
|
|
764
|
-
addMcp(tool: ExecutableTool): void;
|
|
765
|
-
addMcp(tools: ExecutableTool[]): void;
|
|
766
|
-
addProvider(tool: ProviderTool): void;
|
|
767
|
-
addProvider(tools: ProviderTool[]): void;
|
|
768
|
-
remove(name: string): boolean;
|
|
769
|
-
has(name: string): boolean;
|
|
770
|
-
get(name: string): ExecutableTool | undefined;
|
|
771
|
-
getProvider(name: string): ProviderTool | undefined;
|
|
772
|
-
executable(): ExecutableTool[];
|
|
773
|
-
local(): ExecutableTool[];
|
|
774
|
-
mcp(): ExecutableTool[];
|
|
775
|
-
provider(): ProviderTool[];
|
|
776
|
-
get size(): number;
|
|
777
|
-
}
|
|
778
|
-
//#endregion
|
|
779
|
-
//#region src/tools/types.d.ts
|
|
780
|
-
interface ToolContext {
|
|
781
|
-
registry: ToolRegistry;
|
|
782
|
-
signal: AbortSignal;
|
|
783
|
-
emit: (chunk: string) => void;
|
|
784
|
-
span?: Span;
|
|
785
|
-
}
|
|
786
|
-
interface ExecutableTool<TSchema extends ZodObject<any> = ZodObject<any>> {
|
|
787
|
-
type?: "function";
|
|
788
|
-
name: string;
|
|
789
|
-
description: string;
|
|
790
|
-
schema: TSchema;
|
|
791
|
-
execute(input: z.infer<TSchema>, ctx: ToolContext): Promise<string | ToolResultPart[]>;
|
|
792
|
-
configure?(config: Record<string, any>): void;
|
|
793
|
-
summarize?(input: z.infer<TSchema>): string;
|
|
794
|
-
}
|
|
795
|
-
interface ProviderTool {
|
|
796
|
-
type: "provider";
|
|
797
|
-
name: string;
|
|
798
|
-
/** Provider-specific passthrough config. Field names and placement are not portable. */
|
|
799
|
-
config?: Record<string, unknown>;
|
|
800
|
-
}
|
|
801
|
-
type ToolDefinition = Pick<ExecutableTool, "name" | "description" | "schema">;
|
|
802
|
-
//#endregion
|
|
803
760
|
//#region src/turns/types.d.ts
|
|
804
761
|
/**
|
|
805
762
|
* Lifecycle state for a renderable turn.
|
|
@@ -1163,6 +1120,69 @@ type TurnEvent<TAnnotation extends Annotation = Annotation> = {
|
|
|
1163
1120
|
};
|
|
1164
1121
|
};
|
|
1165
1122
|
//#endregion
|
|
1123
|
+
//#region src/tools/registry.d.ts
|
|
1124
|
+
declare class ToolRegistry {
|
|
1125
|
+
private tools;
|
|
1126
|
+
private mcpTools;
|
|
1127
|
+
private providerTools;
|
|
1128
|
+
constructor(init?: {
|
|
1129
|
+
tools?: ExecutableTool[];
|
|
1130
|
+
providerTools?: ProviderTool[];
|
|
1131
|
+
});
|
|
1132
|
+
add(tool: ExecutableTool): void;
|
|
1133
|
+
add(tools: ExecutableTool[]): void;
|
|
1134
|
+
addMcp(tool: ExecutableTool): void;
|
|
1135
|
+
addMcp(tools: ExecutableTool[]): void;
|
|
1136
|
+
addProvider(tool: ProviderTool): void;
|
|
1137
|
+
addProvider(tools: ProviderTool[]): void;
|
|
1138
|
+
remove(name: string): boolean;
|
|
1139
|
+
has(name: string): boolean;
|
|
1140
|
+
get(name: string): ExecutableTool | undefined;
|
|
1141
|
+
getProvider(name: string): ProviderTool | undefined;
|
|
1142
|
+
executable(): ExecutableTool[];
|
|
1143
|
+
local(): ExecutableTool[];
|
|
1144
|
+
mcp(): ExecutableTool[];
|
|
1145
|
+
provider(): ProviderTool[];
|
|
1146
|
+
get size(): number;
|
|
1147
|
+
}
|
|
1148
|
+
//#endregion
|
|
1149
|
+
//#region src/tools/types.d.ts
|
|
1150
|
+
type ToolProgressChunk = string | {
|
|
1151
|
+
type: "turn-event";
|
|
1152
|
+
event: TurnEvent;
|
|
1153
|
+
};
|
|
1154
|
+
interface ToolContext {
|
|
1155
|
+
registry: ToolRegistry;
|
|
1156
|
+
signal: AbortSignal;
|
|
1157
|
+
emit: (chunk: ToolProgressChunk) => void;
|
|
1158
|
+
/**
|
|
1159
|
+
* Report model usage incurred while executing this tool (for example a
|
|
1160
|
+
* subagent's tokens) so it is rolled into the parent operation's totals.
|
|
1161
|
+
*
|
|
1162
|
+
* @experimental
|
|
1163
|
+
*/
|
|
1164
|
+
reportUsage?: (usage: Stats) => void;
|
|
1165
|
+
span?: Span;
|
|
1166
|
+
}
|
|
1167
|
+
interface ExecutableTool<TSchema extends ZodObject<any> = ZodObject<any>> {
|
|
1168
|
+
type?: "function";
|
|
1169
|
+
/** Presentation metadata. Agent-backed tools set "agent"; execution is identical. */
|
|
1170
|
+
kind?: "tool" | "agent";
|
|
1171
|
+
name: string;
|
|
1172
|
+
description: string;
|
|
1173
|
+
schema: TSchema;
|
|
1174
|
+
execute(input: z.infer<TSchema>, ctx: ToolContext): Promise<string | ToolResultPart[]>;
|
|
1175
|
+
configure?(config: Record<string, any>): void;
|
|
1176
|
+
summarize?(input: z.infer<TSchema>): string;
|
|
1177
|
+
}
|
|
1178
|
+
interface ProviderTool {
|
|
1179
|
+
type: "provider";
|
|
1180
|
+
name: string;
|
|
1181
|
+
/** Provider-specific passthrough config. Field names and placement are not portable. */
|
|
1182
|
+
config?: Record<string, unknown>;
|
|
1183
|
+
}
|
|
1184
|
+
type ToolDefinition = Pick<ExecutableTool, "name" | "description" | "schema">;
|
|
1185
|
+
//#endregion
|
|
1166
1186
|
//#region src/turns/accumulator.d.ts
|
|
1167
1187
|
interface TurnAccumulatorState<TAnnotation extends Annotation = Annotation> {
|
|
1168
1188
|
turns: Turn<TAnnotation>[];
|
|
@@ -1195,4 +1215,4 @@ declare class TurnAccumulator<TAnnotation extends Annotation = Annotation, THost
|
|
|
1195
1215
|
private handled;
|
|
1196
1216
|
}
|
|
1197
1217
|
//#endregion
|
|
1198
|
-
export {
|
|
1218
|
+
export { AxleStopReason as $, TurnPart as A, ToolResult as At, ContentPart as B, SubagentAction as C, SpanData as Ct, ToolAction as D, SpanStatus as Dt, TimingInfo as E, SpanResult as Et, AxleToolCallResult as F, ContentPartThinking as G, ContentPartFile as H, AxleUserMessage as I, MessageMetadata as J, ContentPartToolCall as K, Citation as L, AxleAssistantMessage as M, AxleMessage as N, Turn as O, SpanType as Ot, AxleToolCallMessage as P, AxleModelRequestOptions as Q, CitationOutputSpan as R, ProviderToolAction as S, Span as St, ThinkingPart as T, SpanOptions as Tt, ContentPartProviderTool as U, ContentPartCitation as V, ContentPartText as W, ToolResultPart as X, ThinkingContinuity as Y, AIProvider as Z, Annotation as _, UsageEntry as _t, UnknownEvent as a, ToolChoice as at, CitationPart as b, LLMResponse as bt, ToolContext as c, FileKind as ct, ToolRegistry as d, FileResolveRequest as dt, ContextUsage as et, AnnotationEvent as f, FileResolver as ft, ActionResult as g, TokenStats as gt, ActionPart as h, Stats as ht, TurnAccumulatorState as i, ProviderOptions as it, TurnStatus as j, TraceWriter as jt, TurnMetadata as k, TokenUsage as kt, ToolDefinition as l, FileProviderId as lt, TurnEvent as m, loadFileContent as mt, TurnAccumulator as n, ModelResult as nt, ExecutableTool as o, DeferredFileInfo as ot, AnnotationTarget as p, ResolvedFileSource as pt, DocumentLocator as q, TurnAccumulatorResult as r, ProviderClientOptions as rt, ProviderTool as s, FileInfo as st, AccumulatableEvent as t, ModelError as tt, ToolProgressChunk as u, FileResolveFormat as ut, AnnotationPlacement as v, EventLevel as vt, TextPart as w, SpanEvent as wt, FilePart as x, LLMResult as xt, AnnotationStatus as y, LLMRequest as yt, CitationSource as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { $ as
|
|
1
|
+
import { $ as AxleStopReason, A as TurnPart, At as ToolResult, B as ContentPart, C as SubagentAction, Ct as SpanData, D as ToolAction, Dt as SpanStatus, Et as SpanResult, F as AxleToolCallResult, G as ContentPartThinking, H as ContentPartFile, I as AxleUserMessage, J as MessageMetadata, K as ContentPartToolCall, L as Citation, M as AxleAssistantMessage, N as AxleMessage, O as Turn, Ot as SpanType, P as AxleToolCallMessage, Q as AxleModelRequestOptions, R as CitationOutputSpan, S as ProviderToolAction, St as Span, T as ThinkingPart, Tt as SpanOptions, U as ContentPartProviderTool, V as ContentPartCitation, W as ContentPartText, X as ToolResultPart, Y as ThinkingContinuity, Z as AIProvider, _ as Annotation, _t as UsageEntry, at as ToolChoice, b as CitationPart, bt as LLMResponse, c as ToolContext, ct as FileKind, d as ToolRegistry, dt as FileResolveRequest, et as ContextUsage, f as AnnotationEvent, ft as FileResolver, g as ActionResult, gt as TokenStats, h as ActionPart, ht as Stats, i as TurnAccumulatorState, it as ProviderOptions, j as TurnStatus, jt as TraceWriter, k as TurnMetadata, kt as TokenUsage, l as ToolDefinition, lt as FileProviderId, m as TurnEvent, mt as loadFileContent, n as TurnAccumulator, nt as ModelResult, o as ExecutableTool, ot as DeferredFileInfo, p as AnnotationTarget, pt as ResolvedFileSource, q as DocumentLocator, r as TurnAccumulatorResult, rt as ProviderClientOptions, s as ProviderTool, st as FileInfo, t as AccumulatableEvent, tt as ModelError, u as ToolProgressChunk, ut as FileResolveFormat, v as AnnotationPlacement, vt as EventLevel, w as TextPart, wt as SpanEvent, x as FilePart, xt as LLMResult, y as AnnotationStatus, yt as LLMRequest, z as CitationSource } from "./accumulator-CblCRkql.js";
|
|
2
2
|
import * as z$2 from "zod";
|
|
3
|
+
import { ZodObject, z } from "zod";
|
|
3
4
|
|
|
4
5
|
//#region src/mcp/MCP.d.ts
|
|
5
6
|
interface MCPStdioConfig {
|
|
@@ -55,6 +56,10 @@ declare function parseResponse<T extends OutputSchema>(rawValue: string, schema?
|
|
|
55
56
|
//#region src/core/Instruct.d.ts
|
|
56
57
|
type InstructInputs = Record<string, unknown>;
|
|
57
58
|
type InstructVarsMode = "required" | "optional";
|
|
59
|
+
interface InstructContextSection {
|
|
60
|
+
content: string;
|
|
61
|
+
title?: string;
|
|
62
|
+
}
|
|
58
63
|
interface InstructOptions<TSchema extends OutputSchema | undefined = OutputSchema | undefined> {
|
|
59
64
|
prompt: string;
|
|
60
65
|
schema?: TSchema;
|
|
@@ -69,6 +74,7 @@ declare class Instruct<TSchema extends OutputSchema | undefined = undefined> {
|
|
|
69
74
|
content: string;
|
|
70
75
|
name?: string;
|
|
71
76
|
}>;
|
|
77
|
+
contextSections: InstructContextSection[];
|
|
72
78
|
vars: InstructVarsMode;
|
|
73
79
|
metadata?: MessageMetadata;
|
|
74
80
|
schema: TSchema;
|
|
@@ -81,6 +87,10 @@ declare class Instruct<TSchema extends OutputSchema | undefined = undefined> {
|
|
|
81
87
|
addFile(file: FileInfo | string, options?: {
|
|
82
88
|
name?: string;
|
|
83
89
|
}): void;
|
|
90
|
+
/** Append host-supplied supporting material without modifying the authored prompt. */
|
|
91
|
+
addContext(content: string, options?: {
|
|
92
|
+
title?: string;
|
|
93
|
+
}): this;
|
|
84
94
|
hasFiles(): boolean;
|
|
85
95
|
render(options?: {
|
|
86
96
|
vars?: InstructVarsMode;
|
|
@@ -179,6 +189,80 @@ declare class Tracer {
|
|
|
179
189
|
flush(): Promise<void>;
|
|
180
190
|
}
|
|
181
191
|
//#endregion
|
|
192
|
+
//#region src/errors/AxleError.d.ts
|
|
193
|
+
declare class AxleError extends Error {
|
|
194
|
+
readonly code: string;
|
|
195
|
+
readonly id?: string;
|
|
196
|
+
readonly details?: Record<string, any>;
|
|
197
|
+
constructor(message: string, options?: {
|
|
198
|
+
code?: string;
|
|
199
|
+
id?: string;
|
|
200
|
+
details?: Record<string, any>;
|
|
201
|
+
cause?: unknown;
|
|
202
|
+
});
|
|
203
|
+
toJSON(): {
|
|
204
|
+
cause?: unknown;
|
|
205
|
+
details?: Record<string, any> | undefined;
|
|
206
|
+
id?: string | undefined;
|
|
207
|
+
name: string;
|
|
208
|
+
message: string;
|
|
209
|
+
code: string;
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
//#endregion
|
|
213
|
+
//#region src/errors/AxleAbortError.d.ts
|
|
214
|
+
declare class AxleAbortError extends AxleError {
|
|
215
|
+
readonly reason: unknown;
|
|
216
|
+
readonly messages?: AxleMessage[];
|
|
217
|
+
readonly partial?: AxleAssistantMessage;
|
|
218
|
+
readonly usage?: Stats;
|
|
219
|
+
constructor(message?: string, options?: {
|
|
220
|
+
reason?: unknown;
|
|
221
|
+
messages?: AxleMessage[];
|
|
222
|
+
partial?: AxleAssistantMessage;
|
|
223
|
+
usage?: Stats;
|
|
224
|
+
});
|
|
225
|
+
toJSON(): {
|
|
226
|
+
usage?: Stats | undefined;
|
|
227
|
+
partial?: AxleAssistantMessage | undefined;
|
|
228
|
+
messages?: AxleMessage[] | undefined;
|
|
229
|
+
reason: unknown;
|
|
230
|
+
cause?: unknown;
|
|
231
|
+
details?: Record<string, any> | undefined;
|
|
232
|
+
id?: string | undefined;
|
|
233
|
+
name: string;
|
|
234
|
+
message: string;
|
|
235
|
+
code: string;
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
//#endregion
|
|
239
|
+
//#region src/errors/AxleToolFatalError.d.ts
|
|
240
|
+
declare class AxleToolFatalError extends AxleError {
|
|
241
|
+
readonly toolName?: string;
|
|
242
|
+
readonly messages?: AxleMessage[];
|
|
243
|
+
readonly partial?: AxleAssistantMessage;
|
|
244
|
+
readonly usage?: Stats;
|
|
245
|
+
constructor(message?: string, options?: {
|
|
246
|
+
toolName?: string;
|
|
247
|
+
messages?: AxleMessage[];
|
|
248
|
+
partial?: AxleAssistantMessage;
|
|
249
|
+
usage?: Stats;
|
|
250
|
+
cause?: unknown;
|
|
251
|
+
});
|
|
252
|
+
toJSON(): {
|
|
253
|
+
usage?: Stats | undefined;
|
|
254
|
+
partial?: AxleAssistantMessage | undefined;
|
|
255
|
+
messages?: AxleMessage[] | undefined;
|
|
256
|
+
toolName?: string | undefined;
|
|
257
|
+
cause?: unknown;
|
|
258
|
+
details?: Record<string, any> | undefined;
|
|
259
|
+
id?: string | undefined;
|
|
260
|
+
name: string;
|
|
261
|
+
message: string;
|
|
262
|
+
code: string;
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
//#endregion
|
|
182
266
|
//#region src/providers/helpers.d.ts
|
|
183
267
|
type ToolCallResult = {
|
|
184
268
|
type: "success";
|
|
@@ -455,7 +539,7 @@ declare class Agent {
|
|
|
455
539
|
addMcp(mcp: MCP): void;
|
|
456
540
|
addMcps(mcps: MCP[]): void;
|
|
457
541
|
hasTools(): boolean;
|
|
458
|
-
on(callback: TurnEventCallback): void;
|
|
542
|
+
on(callback: TurnEventCallback): () => void;
|
|
459
543
|
context(): ContextUsage;
|
|
460
544
|
/**
|
|
461
545
|
* Capture the serializable session state for later continuation.
|
|
@@ -495,53 +579,6 @@ declare function createAgentConfig(definition: AgentDefinition, resolver: AgentD
|
|
|
495
579
|
//#region src/core/userTurn.d.ts
|
|
496
580
|
type InstructResponse<TSchema extends OutputSchema | undefined> = TSchema extends OutputSchema ? ParsedSchema<TSchema> : string;
|
|
497
581
|
//#endregion
|
|
498
|
-
//#region src/errors/AxleError.d.ts
|
|
499
|
-
declare class AxleError extends Error {
|
|
500
|
-
readonly code: string;
|
|
501
|
-
readonly id?: string;
|
|
502
|
-
readonly details?: Record<string, any>;
|
|
503
|
-
constructor(message: string, options?: {
|
|
504
|
-
code?: string;
|
|
505
|
-
id?: string;
|
|
506
|
-
details?: Record<string, any>;
|
|
507
|
-
cause?: unknown;
|
|
508
|
-
});
|
|
509
|
-
toJSON(): {
|
|
510
|
-
cause?: unknown;
|
|
511
|
-
details?: Record<string, any> | undefined;
|
|
512
|
-
id?: string | undefined;
|
|
513
|
-
name: string;
|
|
514
|
-
message: string;
|
|
515
|
-
code: string;
|
|
516
|
-
};
|
|
517
|
-
}
|
|
518
|
-
//#endregion
|
|
519
|
-
//#region src/errors/AxleAbortError.d.ts
|
|
520
|
-
declare class AxleAbortError extends AxleError {
|
|
521
|
-
readonly reason: unknown;
|
|
522
|
-
readonly messages?: AxleMessage[];
|
|
523
|
-
readonly partial?: AxleAssistantMessage;
|
|
524
|
-
readonly usage?: Stats;
|
|
525
|
-
constructor(message?: string, options?: {
|
|
526
|
-
reason?: unknown;
|
|
527
|
-
messages?: AxleMessage[];
|
|
528
|
-
partial?: AxleAssistantMessage;
|
|
529
|
-
usage?: Stats;
|
|
530
|
-
});
|
|
531
|
-
toJSON(): {
|
|
532
|
-
usage?: Stats | undefined;
|
|
533
|
-
partial?: AxleAssistantMessage | undefined;
|
|
534
|
-
messages?: AxleMessage[] | undefined;
|
|
535
|
-
reason: unknown;
|
|
536
|
-
cause?: unknown;
|
|
537
|
-
details?: Record<string, any> | undefined;
|
|
538
|
-
id?: string | undefined;
|
|
539
|
-
name: string;
|
|
540
|
-
message: string;
|
|
541
|
-
code: string;
|
|
542
|
-
};
|
|
543
|
-
}
|
|
544
|
-
//#endregion
|
|
545
582
|
//#region src/errors/AxleAgentAbortError.d.ts
|
|
546
583
|
declare class AxleAgentAbortError extends AxleAbortError {
|
|
547
584
|
readonly turn?: Turn;
|
|
@@ -567,33 +604,6 @@ declare class AxleAgentAbortError extends AxleAbortError {
|
|
|
567
604
|
};
|
|
568
605
|
}
|
|
569
606
|
//#endregion
|
|
570
|
-
//#region src/errors/AxleToolFatalError.d.ts
|
|
571
|
-
declare class AxleToolFatalError extends AxleError {
|
|
572
|
-
readonly toolName?: string;
|
|
573
|
-
readonly messages?: AxleMessage[];
|
|
574
|
-
readonly partial?: AxleAssistantMessage;
|
|
575
|
-
readonly usage?: Stats;
|
|
576
|
-
constructor(message?: string, options?: {
|
|
577
|
-
toolName?: string;
|
|
578
|
-
messages?: AxleMessage[];
|
|
579
|
-
partial?: AxleAssistantMessage;
|
|
580
|
-
usage?: Stats;
|
|
581
|
-
cause?: unknown;
|
|
582
|
-
});
|
|
583
|
-
toJSON(): {
|
|
584
|
-
usage?: Stats | undefined;
|
|
585
|
-
partial?: AxleAssistantMessage | undefined;
|
|
586
|
-
messages?: AxleMessage[] | undefined;
|
|
587
|
-
toolName?: string | undefined;
|
|
588
|
-
cause?: unknown;
|
|
589
|
-
details?: Record<string, any> | undefined;
|
|
590
|
-
id?: string | undefined;
|
|
591
|
-
name: string;
|
|
592
|
-
message: string;
|
|
593
|
-
code: string;
|
|
594
|
-
};
|
|
595
|
-
}
|
|
596
|
-
//#endregion
|
|
597
607
|
//#region src/errors/InstructVariableError.d.ts
|
|
598
608
|
declare class InstructVariableError extends AxleError {
|
|
599
609
|
readonly missingVariables: string[];
|
|
@@ -799,6 +809,7 @@ type StreamEvent = {
|
|
|
799
809
|
index: number;
|
|
800
810
|
id: string;
|
|
801
811
|
name: string;
|
|
812
|
+
kind?: "tool" | "agent";
|
|
802
813
|
} | {
|
|
803
814
|
type: "tool:args-delta";
|
|
804
815
|
index: number;
|
|
@@ -817,13 +828,24 @@ type StreamEvent = {
|
|
|
817
828
|
index: number;
|
|
818
829
|
id: string;
|
|
819
830
|
name: string;
|
|
820
|
-
chunk:
|
|
831
|
+
chunk: ToolProgressChunk;
|
|
821
832
|
} | {
|
|
822
833
|
type: "tool:exec-complete";
|
|
823
834
|
index: number;
|
|
824
835
|
id: string;
|
|
825
836
|
name: string;
|
|
826
837
|
result: ToolCallResult;
|
|
838
|
+
usage?: Stats;
|
|
839
|
+
} | {
|
|
840
|
+
type: "tool:exec-error";
|
|
841
|
+
index: number;
|
|
842
|
+
id: string;
|
|
843
|
+
name: string;
|
|
844
|
+
error: {
|
|
845
|
+
type: "fatal" | "aborted";
|
|
846
|
+
message: string;
|
|
847
|
+
};
|
|
848
|
+
usage?: Stats;
|
|
827
849
|
} | {
|
|
828
850
|
type: "provider-tool:start";
|
|
829
851
|
index: number;
|
|
@@ -927,6 +949,70 @@ declare const OpenAI: {
|
|
|
927
949
|
readonly DefaultModel: "gpt-5.4-mini";
|
|
928
950
|
};
|
|
929
951
|
//#endregion
|
|
952
|
+
//#region src/tools/agentTool.d.ts
|
|
953
|
+
interface CreateAgentToolOptions<TSchema extends ZodObject<any>> {
|
|
954
|
+
name: string;
|
|
955
|
+
description: string;
|
|
956
|
+
schema: TSchema;
|
|
957
|
+
/** Create the child agent for this tool call. Fresh agents are recommended. */
|
|
958
|
+
createAgent: (input: z.infer<TSchema>, ctx: ToolContext) => MaybePromise<Agent>;
|
|
959
|
+
/**
|
|
960
|
+
* Convert tool input into the child-agent user prompt. Defaults to a compact
|
|
961
|
+
* JSON task payload.
|
|
962
|
+
*/
|
|
963
|
+
prompt?: string | ((input: z.infer<TSchema>) => string);
|
|
964
|
+
/** Per-send request overrides for the child agent. */
|
|
965
|
+
request?: AxleModelRequestOptions;
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* Expose an Agent as a normal executable tool.
|
|
969
|
+
*
|
|
970
|
+
* This lets a parent model delegate bounded work to a child agent while only
|
|
971
|
+
* receiving the child agent's final response. The child's turn events are
|
|
972
|
+
* forwarded through `ctx.emit` and its token usage through `ctx.reportUsage`,
|
|
973
|
+
* so parents can render live progress and reconstruct cost.
|
|
974
|
+
*
|
|
975
|
+
* @experimental Shapes related to subagent rendering may change in a minor
|
|
976
|
+
* release.
|
|
977
|
+
*/
|
|
978
|
+
declare function createAgentTool<TSchema extends ZodObject<any>>(options: CreateAgentToolOptions<TSchema>): ExecutableTool<TSchema>;
|
|
979
|
+
//#endregion
|
|
980
|
+
//#region src/tools/parallelize.d.ts
|
|
981
|
+
interface ParallelizeOptions {
|
|
982
|
+
/** Name of the generated batch tool. Defaults to `${tool.name}_batch`. */
|
|
983
|
+
name?: string;
|
|
984
|
+
/** Description of the generated batch tool. */
|
|
985
|
+
description?: string;
|
|
986
|
+
/** Maximum items accepted by the generated tool schema. */
|
|
987
|
+
maxItems?: number;
|
|
988
|
+
/** Maximum inner tool calls to run concurrently. */
|
|
989
|
+
maxConcurrency?: number;
|
|
990
|
+
}
|
|
991
|
+
interface ParallelToolResult<TInput = unknown> {
|
|
992
|
+
index: number;
|
|
993
|
+
input: TInput;
|
|
994
|
+
ok: boolean;
|
|
995
|
+
output?: string | ToolResultPart[];
|
|
996
|
+
error?: {
|
|
997
|
+
type: "execution";
|
|
998
|
+
message: string;
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
/**
|
|
1002
|
+
* Create a batch tool that runs a tool over many input items concurrently.
|
|
1003
|
+
*
|
|
1004
|
+
* The generated tool preserves result order and reports per-item failures
|
|
1005
|
+
* instead of failing the whole batch for ordinary execution errors. Fatal
|
|
1006
|
+
* and abort errors are not demoted: they propagate and terminate the run,
|
|
1007
|
+
* matching the unbatched tool contract.
|
|
1008
|
+
*
|
|
1009
|
+
* @experimental The generated tool's result JSON (`ParallelToolResult`) may
|
|
1010
|
+
* change in a minor release.
|
|
1011
|
+
*/
|
|
1012
|
+
declare function parallelize<TSchema extends ZodObject<any>>(tool: ExecutableTool<TSchema>, options?: ParallelizeOptions): ExecutableTool<ZodObject<{
|
|
1013
|
+
items: z.ZodArray<TSchema>;
|
|
1014
|
+
}>>;
|
|
1015
|
+
//#endregion
|
|
930
1016
|
//#region src/turns/eventBuilder.d.ts
|
|
931
1017
|
declare class TurnEventBuilder {
|
|
932
1018
|
private currentTurnId;
|
|
@@ -1001,5 +1087,6 @@ interface FileStore {
|
|
|
1001
1087
|
//#region src/utils/stats.d.ts
|
|
1002
1088
|
declare function createStats(): Stats;
|
|
1003
1089
|
declare function addStats(total: Stats, usage?: Stats): void;
|
|
1090
|
+
declare function mergeStats(...usages: Array<Stats | undefined>): Stats;
|
|
1004
1091
|
//#endregion
|
|
1005
|
-
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, type LLMRequest, type LLMResponse, type LLMResult, type LogEntry, type LogFn, LogWriter, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MaybePromise, type MemoryContext, type MessageMetadata, type ObservabilityOptions, OpenAI, type OutputSchema, type ParsedSchema, type ProviderClientOptions, type ProviderDefinition, type ProviderOptions, type ProviderTool, type ProviderToolAction, type ProviderToolDefinitionRef, type RecallResult, type ResolvedAgentDefinition, type ResolvedFileSource, type SavedAgent, type SendMessageOptions, SimpleWriter, type SimpleWriterOptions, type Span, type SpanData, type SpanEvent, type SpanOptions, type SpanResult, type SpanStatus, type SpanType, type Stats, type StreamEvent, type StreamEventCallback, type StreamHandle, type StreamInstructHandle, type StreamInstructParams, type StreamInstructResult, type StreamParams, type StreamResult, type SubagentAction, TaskError, type TextPart, type ThinkingContinuity, type ThinkingPart, type TokenUsage, type ToolAction, type ToolChoice, type ToolContext, type ToolDefinition, type ToolDefinitionRef, ToolRegistry, type ToolResult, type ToolResultPart, type TraceWriter, Tracer, type TracerOptions, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, TurnEventBuilder, type TurnEventCallback, type TurnMetadata, type TurnPart, type TurnStatus, addStats, anthropic, chatCompletions, createAgentConfig, createHandle, createStats, estimateContextUsage, gemini, generate, generateTurn, loadFileContent, openai, parseResponse, stream };
|
|
1092
|
+
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 CreateAgentToolOptions, type DeferredFileInfo, type DocumentLocator, type EventLevel, type ExecutableTool, type FileInfo, type FileKind, type FilePart, type FileProviderId, type FileResolveFormat, type FileResolveRequest, type FileResolver, type FileStore, Gemini, type GenerateInstructParams, type GenerateInstructResult, type GenerateParams, type Handle, History, Instruct, type InstructContextSection, type InstructInputs, type InstructOptions, type InstructResponse, InstructVariableError, type InstructVarsMode, type LLMRequest, type LLMResponse, type LLMResult, type LogEntry, type LogFn, LogWriter, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MaybePromise, type MemoryContext, type MessageMetadata, type ObservabilityOptions, OpenAI, type OutputSchema, type ParallelToolResult, type ParallelizeOptions, type ParsedSchema, type ProviderClientOptions, type ProviderDefinition, type ProviderOptions, type ProviderTool, type ProviderToolAction, type ProviderToolDefinitionRef, type RecallResult, type ResolvedAgentDefinition, type ResolvedFileSource, type SavedAgent, type SendMessageOptions, SimpleWriter, type SimpleWriterOptions, type Span, type SpanData, type SpanEvent, type SpanOptions, type SpanResult, type SpanStatus, type SpanType, type Stats, type StreamEvent, type StreamEventCallback, type StreamHandle, type StreamInstructHandle, type StreamInstructParams, type StreamInstructResult, type StreamParams, type StreamResult, type SubagentAction, TaskError, type TextPart, type ThinkingContinuity, type ThinkingPart, type TokenStats, type TokenUsage, type ToolAction, type ToolChoice, type ToolContext, type ToolDefinition, type ToolDefinitionRef, type ToolProgressChunk, ToolRegistry, type ToolResult, type ToolResultPart, type TraceWriter, Tracer, type TracerOptions, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, TurnEventBuilder, type TurnEventCallback, type TurnMetadata, type TurnPart, type TurnStatus, type UsageEntry, addStats, anthropic, chatCompletions, createAgentConfig, createAgentTool, createHandle, createStats, estimateContextUsage, gemini, generate, generateTurn, loadFileContent, mergeStats, openai, parallelize, parseResponse, stream };
|
package/dist/index.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
import{t as e}from"./accumulator-
|
|
1
|
+
import{t as e}from"./accumulator-BnFn9yqM.js";import{d as t,i as n,o as r,p as i,r as a,t as o,u as s}from"./models-Cx50YJNx.js";import*as c from"zod";import l,{z as u}from"zod";import{Client as d}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as f}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as p}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import m from"@anthropic-ai/sdk";import"glob";import h from"mime";import{access as g,readFile as _,stat as v}from"node:fs/promises";import{extname as y,resolve as b}from"node:path";import{FinishReason as x,FunctionCallingConfigMode as S,GoogleGenAI as C}from"@google/genai";import w from"openai";import T from"chalk";import{marked as E}from"marked";var D=class e extends Error{code;id;details;constructor(t,n){super(t,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||`AXLE_ERROR`,this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id?{id:this.id}:{},...this.details?{details:this.details}:{},...this.cause?{cause:O(this.cause)}:{}}}};function O(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:O(e.cause)}:{}}:e}var k=class e extends D{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}:{}}}},A=class e extends k{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}:{}}}},j=class e extends D{toolName;messages;partial;usage;constructor(t=`Fatal tool error`,n){super(t,{code:`TOOL_FATAL_ERROR`,details:{toolName:n?.toolName,usage:n?.usage},cause:n?.cause}),this.toolName=n?.toolName,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.toolName?{toolName:this.toolName}:{},...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}};function ee(e){let{text:t,files:n}=e,r=[];if(t&&r.push({type:`text`,text:t}),n)for(let e of n)r.push({type:`file`,file:e});return r}function M(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
2
|
|
|
3
|
-
`)}function
|
|
3
|
+
`)}function te(e){return e.filter(e=>e.type===`thinking`).map(e=>e.text??``).join(`
|
|
4
4
|
|
|
5
|
-
`)}function ee(e){return e.filter(e=>e.type===`tool-call`)}function te(e){return e.filter(e=>e.type===`provider-tool`)}function ne(e){let t=[];for(let n of e)(n.type===`text`&&n.citations||n.type===`citation`)&&t.push(...n.citations);return t}function re(e,t=500){return e.length>t?`${e.slice(0,t)}… (${e.length} chars)`:e}function P(e,t=600){if(e.length<=t)return e;let n=Math.floor(t/2);return`${e.slice(0,n)}…[${e.length} chars]…${e.slice(-n)}`}var F=class{log;constructor(e){this.log=e}onSpanStart(){}onSpanEnd(e){let t=e.status===`error`?`error`:e.type===`tool`||e.type===`workflow`?`info`:`debug`;this.log({level:t,message:e.name,fields:{...e.attributes,type:e.type,status:e.status,traceId:e.traceId,spanId:e.spanId,...e.parentSpanId?{parentSpanId:e.parentSpanId}:{},...e.endTime===void 0?{}:{durationMs:Math.round(e.endTime-e.startTime)}}})}onEvent(e,t){this.log({level:t.level,message:t.name,fields:{traceId:e.traceId,spanId:e.spanId,name:e.name,...t.attributes}})}};function I(e,t,n){if(!n)return;let r=re(n);e?.info(t,{text:r}),r!==n&&e?.debug(t,{text:n})}function ie(e){let t=U(e.system??``),n=V(e.tools),r=V(e.mcpTools),i=oe(e.providerTools),a=e.messages.reduce((e,t)=>e+L(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 L(e){switch(e.role){case`user`:return R(e.content);case`assistant`:return R(e.content);case`tool`:return e.content.reduce((e,t)=>e+B(t),0)}}function R(e){return typeof e==`string`?U(e):e.reduce((e,t)=>e+z(t),0)}function z(e){switch(e.type){case`text`:return U(e.text);case`thinking`:return U(e.summary??e.text??``);case`tool-call`:return U(e.name)+H(e.parameters);case`provider-tool`:return U(e.name)+H(e.input)+H(e.output);case`citation`:return H(e.citations);case`file`:return H(e.file)}}function B(e){return U(e.name)+ae(e.content)}function ae(e){return typeof e==`string`?U(e):e.reduce((e,t)=>t.type===`text`?e+U(t.text):e+H(t.file),0)}function V(e){let t=e?.map(se)??[];return t.length===0?0:H({tools:t})}function oe(e){return!e||e.length===0?0:H({providerTools:e})}function se(e){try{return{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}catch{return{name:e.name,description:e.description}}}function H(e){return e==null?0:U(JSON.stringify(e))}function U(e){return e?Math.ceil(e.length/3):0}function W(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(le).join(` | `),t[0]]}if(e instanceof c.ZodLiteral){let t=e.value;return[le(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]=W(t);return[`object array`,[e,e]]}else if(t instanceof c.ZodEnum||t instanceof c.ZodLiteral){let[e,n]=W(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]=W(r);n[e]=t}return[`JSON object`,n]}if(e instanceof c.ZodOptional){let[t,n]=W(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function ce(e){if(e instanceof c.ZodObject)return Object.entries(e.shape).map(([e,t])=>{let[n]=W(t);return[e,n]});let[t]=W(e);return[[`response`,t]]}function le(e){return typeof e==`string`?JSON.stringify(e):String(e)}function ue(e,t){if(!t)return e;let n=de(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 de(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 fe(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=>pe(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:j({text:n,files:r}),...a?{metadata:a}:{}},parse:e=>pe(e,i)}}function pe(e,t){return e?ue(M(e.content),t):null}function G(){return{in:0,out:0}}function me(e,t){t&&(e.in+=t.in??0,e.out+=t.out??0,ge(e,`cachedIn`,t.cachedIn),ge(e,`cacheWriteIn`,t.cacheWriteIn),ge(e,`reasoningOut`,t.reasoningOut))}function K(e,t){return{...e,..._e(`cachedIn`,t.cachedIn),..._e(`cacheWriteIn`,t.cacheWriteIn),..._e(`reasoningOut`,t.reasoningOut)}}function he(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 ge(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function _e(e,t){return typeof t==`number`?{[e]:t}:{}}var ve=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 ye(e,t){me(e,t.usage)}function be(e,t){if(!e)return;I(e,`text`,M(t));let n=N(t);n&&e.debug(`thinking`,{thinking:n});for(let n of te(t))e.info(n.name,{type:`provider-tool`,input:n.input}),n.output!==void 0&&e.trace(n.name,{type:`provider-tool`,output:n.output});xe(e,ne(t))}function xe(e,t){if(t.length===0)return;let n=Se(t);e.info(`citations`,{count:t.length,sources:n.slice(0,8),...n.length>8?{more:n.length-8}:{}}),n.length>8&&e.debug(`citations`,{sources:n}),e.setAttribute(`citationCount`,t.length)}function Se(e){let t=new Set,n=[];for(let{source:r}of e){let e=Ce(r),i=`title`in r?r.title:void 0,a=e??i??r.type;t.has(a)||(t.add(a),n.push({type:r.type,...i?{title:i}:{},...e?{url:e}:{}}))}return n}function Ce(e){switch(e.type){case`web`:case`search-result`:return e.url;case`retrieved-context`:return e.uri;case`document`:return e.fileId;default:return}}function we(e){return JSON.stringify({error:e})}function Te(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 ve({tools:e.tools,providerTools:e.providerTools})}async function Ee(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,span: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:we({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:we(l.error),isError:!0}))}return{results:a}}let De=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function q(e,t){for(let n of e)n(t)}function Oe(e){return{type:`error`,error:{type:`not-found`,message:`Tool not found: ${e}`}}}function ke(e){return{name:e.name,description:e.description,schema:e.schema}}function Ae(e){let t=[],n,r;if(`instruct`in e){let{instruct:t,messages:i,...a}=e,o=fe(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(()=>je(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 je(e,t,n){let{provider:r,model:i,messages:a,system:o,onToolCall:s,maxIterations:c,span:l,fileResolver:u,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}=e,y=Te(e),b=[...a],x=[],S=G(),C=0,w=0,T=e=>{b.push(e),x.push(e)},E=e=>{e.ok||q(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:he(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(ke):void 0,j=y?.provider()??[],M=r.createStreamingRequest(i,{messages:b,system:o,tools:k,providerTools:j.length>0?j:void 0,runtime:{span:e,fileResolver:u},signal:t,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}),N=[],ee=``,te=``,ne=null,re=G(),P=-1,F=null,I=``,ie=new Map,L=new Map,R=new Map,z=-1,B=()=>{F!==null&&P>=0&&(q(n,{type:F===`text`?`text:end`:`thinking:end`,index:P,final:I}),F=null,I=``,P=-1)};for await(let r of M){switch(r.type){case`start`:ee=r.id,te=r.data.model,q(n,{type:`turn:start`,id:ee,model:te});break;case`text-start`:B(),N.push({type:`text`,text:``}),z=N.length-1,P=C++,L.set(r.data.index,z),R.set(r.data.index,P),F=`text`,I=``,q(n,{type:`text:start`,index:P});break;case`text-delta`:{let e=N[z];e.text+=r.data.text,I=e.text,q(n,{type:`text:delta`,index:P,delta:r.data.text,accumulated:I});break}case`text-citation`:{let e=L.get(r.data.index)??z,t=R.get(r.data.index)??P,i=N[e];if(!i||i.type!==`text`)break;i.citations=[...i.citations??[],r.data.citation],q(n,{type:`text:citation`,index:t,citation:r.data.citation,citations:i.citations});break}case`citation`:{B();let e=C++;N.push({type:`citation`,citations:r.data.citations,...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),z=N.length-1,L.set(r.data.index,z),R.set(r.data.index,e),q(n,{type:`citation`,index:e,citations:r.data.citations,providerMetadata:r.data.providerMetadata});break}case`text-complete`:B();break;case`thinking-start`:B(),N.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}:{}}),z=N.length-1,P=C++,L.set(r.data.index,z),R.set(r.data.index,P),F=`thinking`,I=``,q(n,{type:`thinking:start`,index:P,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break;case`thinking-delta`:{let e=N[z];e.text=(e.text??``)+r.data.text,I=e.text,q(n,{type:`thinking:delta`,index:P,delta:r.data.text,accumulated:I});break}case`thinking-summary-delta`:{let e=N[z];e.summary=(e.summary??``)+r.data.text,I=e.summary,q(n,{type:`thinking:summary-delta`,index:P,delta:r.data.text,accumulated:I});break}case`thinking-metadata`:{let e=L.get(r.data.index)??z,t=R.get(r.data.index)??P,i=N[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),q(n,{type:`thinking:update`,index:t,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break}case`thinking-complete`:B();break;case`tool-call-start`:{B();let e=C++;N.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),z=N.length-1,L.set(r.data.index,z),R.set(r.data.index,e),ie.set(r.data.id,e),q(n,{type:`tool:request`,index:e,id:r.data.id,name:r.data.name});break}case`tool-call-args-delta`:q(n,{type:`tool:args-delta`,index:ie.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=N[L.get(r.data.index)??z];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`:{B();let e=C++;N.push({type:`provider-tool`,id:r.data.id,name:r.data.name}),z=N.length-1,L.set(r.data.index,z),R.set(r.data.index,e),q(n,{type:`provider-tool:start`,index:e,id:r.data.id,name:r.data.name});break}case`provider-tool-complete`:{let e=L.get(r.data.index)??z,t=R.get(r.data.index)??r.data.index,i=N[e];i&&i.type===`provider-tool`&&r.data.output!=null&&(i.output=r.data.output),q(n,{type:`provider-tool:complete`,index:t,id:r.data.id,name:r.data.name,output:r.data.output});break}case`complete`:B(),ne=r.data.finishReason,re=r.data.usage;break;case`error`:return B(),me(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(N,ee,te,B)),ne===null)return B(),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});me(S,re);let ae={kind:`llm`,model:te,request:{messages:b},response:{content:N},usage:he(re),finishReason:ne};be(e,N),e?.setResult(ae),e?.end();let V={role:`assistant`,id:ee,model:te,content:N,finishReason:ne};if(T(V),q(n,{type:`turn:complete`,message:V,usage:re}),ne!==`function_call`)return E({ok:!0,response:V,messages:x,final:V,usage:S});let oe=N.filter(e=>e.type===`tool-call`);if(oe.length===0)return E({ok:!0,response:V,messages:x,final:V,usage:S});if(t.aborted)throw l?.end(`ok`),new O(`Stream aborted`,{reason:t.reason,messages:x,usage:S});let se=crypto.randomUUID();q(n,{type:`tool-results:start`,id:se});let H=0,U=async(e,t,r)=>{let i=oe[H++],a=ie.get(i.id)??-1;q(n,{type:`tool:exec-start`,index:a,id:i.id,name:e,parameters:t});let o={...r,emit:t=>{q(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)??Oe(e);return q(n,{type:`tool:exec-complete`,index:a,id:i.id,name:e,result:l}),l},W;try{({results:W}=await Ee(oe,U,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??V,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(W.length>0){let e={role:`tool`,id:se,content:W};T(e),q(n,{type:`tool-results:complete`,message:e})}}}function Me(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 Ne=class{currentTurnId=null;currentTurnTiming;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage=G();createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=J(Me(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=Me(),this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage=G(),{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:Me()};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(Me()),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:Me(),...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=Me(),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=Me(),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),me(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 Pe(e){return Array.isArray(e)?e:[e]}function Fe(e){return e.then(()=>{},()=>{})}function Ie(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:Fe(a)}}var Le=class{_turns=[];_log=[];_sessionAnnotations=[];constructor(e){e?.turns&&(this._turns=[...e.turns]),e?.log&&(this._log=[...e.log]),e?.sessionAnnotations&&(this._sessionAnnotations=[...e.sessionAnnotations])}get turns(){return[...this._turns]}get log(){return[...this._log]}get sessionAnnotations(){return[...this._sessionAnnotations]}addTurn(e){this._turns.push(e)}replaceTurns(e){this._turns=[...e]}replaceLog(e){this._log=[...e]}replaceSessionAnnotations(e=[]){this._sessionAnnotations=[...e]}appendToLog(e){Array.isArray(e)?this._log.push(...e):this._log.push(e)}latestTurn(){return this._turns[this._turns.length-1]}toString(){return JSON.stringify({turns:this._turns,sessionAnnotations:this._sessionAnnotations})}};const Re={trace:0,debug:1,info:2,warn:3,error:4},ze=()=>performance.timeOrigin+performance.now();var Be=class{writers=[];minLevel=`info`;addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}shouldLog(e){return Re[e]>=Re[this.minLevel]}spanStart(e){for(let t of this.writers)t.onSpanStart(e)}spanEnd(e){for(let t of this.writers)t.onSpanEnd(e)}spanUpdate(e){for(let t of this.writers)t.onSpanUpdate?.(e)}event(e,t){for(let n of this.writers)n.onEvent?.(e,t)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}},Ve=class{rec=new Be;constructor(e){e?.minLevel&&(this.rec.minLevel=e.minLevel);for(let t of e?.writers??[])this.rec.addWriter(t)}get minLevel(){return this.rec.minLevel}set minLevel(e){this.rec.minLevel=e}addWriter(e){this.rec.addWriter(e)}removeWriter(e){this.rec.removeWriter(e)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:ze(),status:`ok`,attributes:{...t?.attributes??{}},events:[]};return this.rec.spanStart(n),new He(n,this.rec)}flush(){return this.rec.flush()}},He=class e{data;rec;ended=!1;constructor(e,t){this.data=e,this.rec=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:ze(),status:`ok`,attributes:{...n?.attributes??{}},events:[]};return this.rec.spanStart(r),new e(r,this.rec)}end(e=`ok`){this.ended||(this.ended=!0,this.data.endTime=ze(),this.data.status=e,this.rec.spanEnd(this.data))}addEvent(e,t,n){if(this.ended||!this.rec.shouldLog(t))return;let r={name:e,timestamp:ze(),level:t,attributes:n};this.data.events.push(r),this.rec.event(this.data,r)}trace(e,t){this.addEvent(e,`trace`,t)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,this.rec.spanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.rec.spanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.rec.spanUpdate(this.data))}};function Ue(e){if(!e)return{};let{trace:t,log:n,level:r}=e;if(t)return n&&console.warn(`[axle] observability.log is ignored when observability.trace is set; add a LogWriter to your tracer's writers instead`),{parent:t};if(n){let e=new Ve({minLevel:r,writers:[new F(n)]});return{parent:e,owned:e}}return{}}function We(e){return Ge(e)?`cancelled`:`error`}function Ge(e){return e instanceof O||e instanceof k||e instanceof Error&&e.name===`AbortError`}function Ke(e,t){return{...e,...t,providerOptions:e?.providerOptions||t?.providerOptions?{...e?.providerOptions,...t?.providerOptions}:void 0}}var qe=class{provider;model;history;name;fileResolver;requestOptions;registry;sessionId;system;mcps=[];resolvedMcps=new WeakSet;memory;spanParent;ownedTracer;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e,t){this.provider=e.provider,this.model=e.model,this.sessionId=e.sessionId??crypto.randomUUID(),this.history=new Le;let n=Ue(e.observability);if(this.spanParent=n.parent,this.ownedTracer=n.owned,this.system=e.system,this.name=e.name,this.fileResolver=e.fileResolver,this.requestOptions={reasoning:e.reasoning,maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,stop:e.stop,toolChoice:e.toolChoice,parallelToolCalls:e.parallelToolCalls,providerOptions:e.providerOptions},this.registry=new ve({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 ie({system:this.system,messages:this.history.log,tools:this.toToolDefinitions(this.registry.local()),providerTools:this.registry.provider(),mcpTools:this.toToolDefinitions(this.registry.mcp())})}snapshot(){let e=this.history.sessionAnnotations;return{version:1,sessionId:this.sessionId,messages:this.history.log,turns:this.history.turns,sessionAnnotations:e.length>0?e:void 0}}restore(e){if(e.version!==1)throw new 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=fe(e,{metadata:r}),o=Ke(this.requestOptions,i),{handle:s,settled:c}=Ie(this.sendQueue,async e=>{let t=this.spanParent?.startSpan(`agent.send`,{type:`workflow`,attributes:{sessionId:this.sessionId,...this.name?{agentName:this.name}:{}}});I(t,`message`,M(a.message.content));let r=`ok`;try{let i=await this.run(a,{signal:e,fileResolver:n,requestOptions:o,span:t});return i.ok||(r=`error`),t?.setAttributes({inputTokens:i.usage.in,outputTokens:i.usage.out}),i}catch(e){throw r=We(e),t?.error(e instanceof Error?e.message:String(e)),e}finally{t?.end(r),await this.ownedTracer?.flush()}},i.signal);return this.sendQueue=c,s}async resolveMcpTools(e,t){for(let n of this.mcps){if(this.resolvedMcps.has(n))continue;let r=await n.listTools({prefix:n.name,span:t,signal:e});this.registry.addMcp(r),this.resolvedMcps.add(n)}}emitEvent(e){for(let t of this.eventCallbacks)t(e)}toToolDefinitions(e){return e.map(e=>({name:e.name,description:e.description,schema:e.schema}))}async run(t,n){let{signal:r,fileResolver:i,requestOptions:a}=n,o=n.span,s=new Ne,c=new e({turns:this.history.turns,sessionAnnotations:this.history.sessionAnnotations}),l,u=e=>{let t=c.apply(e);t.handled&&(this.history.replaceTurns(t.state.turns),this.history.replaceSessionAnnotations(t.state.sessionAnnotations??[])),this.emitEvent(e)},d=()=>l?c.state.turns.find(e=>e.id===l):void 0,f=G();if(r.aborted)throw new k(`Agent send aborted`,{reason:r.reason,usage:f});try{await this.resolveMcpTools(r,o)}catch(e){throw r.aborted||e instanceof O||e instanceof Error&&e.name===`AbortError`?new k(`Agent send aborted`,{reason:e instanceof O?e.reason:r.reason,usage:f}):e}let p=this.system,m=[...this.history.log,t.message];if(this.memory){let e=await this.memory.recall({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:m,span:o});e.systemSuffix&&(p=(p??``)+`
|
|
5
|
+
`)}function N(e){return e.filter(e=>e.type===`tool-call`)}function ne(e){return e.filter(e=>e.type===`provider-tool`)}function re(e){let t=[];for(let n of e)(n.type===`text`&&n.citations||n.type===`citation`)&&t.push(...n.citations);return t}function P(e,t=500){return e.length>t?`${e.slice(0,t)}… (${e.length} chars)`:e}function ie(e,t=600){if(e.length<=t)return e;let n=Math.floor(t/2);return`${e.slice(0,n)}…[${e.length} chars]…${e.slice(-n)}`}var F=class{log;constructor(e){this.log=e}onSpanStart(){}onSpanEnd(e){let t=e.status===`error`?`error`:e.type===`tool`||e.type===`workflow`?`info`:`debug`;this.log({level:t,message:e.name,fields:{...e.attributes,type:e.type,status:e.status,traceId:e.traceId,spanId:e.spanId,...e.parentSpanId?{parentSpanId:e.parentSpanId}:{},...e.endTime===void 0?{}:{durationMs:Math.round(e.endTime-e.startTime)}}})}onEvent(e,t){this.log({level:t.level,message:t.name,fields:{traceId:e.traceId,spanId:e.spanId,name:e.name,...t.attributes}})}};function I(e,t,n){if(!n)return;let r=P(n);e?.info(t,{text:r}),r!==n&&e?.debug(t,{text:n})}function L(e){let t=U(e.system??``),n=se(e.tools),r=se(e.mcpTools),i=ce(e.providerTools),a=e.messages.reduce((e,t)=>e+R(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 R(e){switch(e.role){case`user`:return ae(e.content);case`assistant`:return ae(e.content);case`tool`:return e.content.reduce((e,t)=>e+z(t),0)}}function ae(e){return typeof e==`string`?U(e):e.reduce((e,t)=>e+oe(t),0)}function oe(e){switch(e.type){case`text`:return U(e.text);case`thinking`:return U(e.summary??e.text??``);case`tool-call`:return U(e.name)+H(e.parameters);case`provider-tool`:return U(e.name)+H(e.input)+H(e.output);case`citation`:return H(e.citations);case`file`:return H(e.file)}}function z(e){return U(e.name)+B(e.content)}function B(e){return typeof e==`string`?U(e):e.reduce((e,t)=>t.type===`text`?e+U(t.text):e+H(t.file),0)}function se(e){let t=e?.map(V)??[];return t.length===0?0:H({tools:t})}function ce(e){return!e||e.length===0?0:H({providerTools:e})}function V(e){try{return{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}catch{return{name:e.name,description:e.description}}}function H(e){return e==null?0:U(JSON.stringify(e))}function U(e){return e?Math.ceil(e.length/3):0}function W(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(ue).join(` | `),t[0]]}if(e instanceof c.ZodLiteral){let t=e.value;return[ue(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]=W(t);return[`object array`,[e,e]]}else if(t instanceof c.ZodEnum||t instanceof c.ZodLiteral){let[e,n]=W(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]=W(r);n[e]=t}return[`JSON object`,n]}if(e instanceof c.ZodOptional){let[t,n]=W(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function le(e){if(e instanceof c.ZodObject)return Object.entries(e.shape).map(([e,t])=>{let[n]=W(t);return[e,n]});let[t]=W(e);return[[`response`,t]]}function ue(e){return typeof e==`string`?JSON.stringify(e):String(e)}function de(e,t){if(!t)return e;let n=fe(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 fe(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 pe(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=>me(e,void 0)};let n=e.render(),r=e.files,i=e.schema,a=t.metadata??e.metadata;return{message:{role:`user`,id:crypto.randomUUID(),content:ee({text:n,files:r}),...a?{metadata:a}:{}},parse:e=>me(e,i)}}function me(e,t){return e?de(M(e.content),t):null}function G(){return{in:0,out:0}}function K(e,t){t&&(e.in+=t.in??0,e.out+=t.out??0,ye(e,`cachedIn`,t.cachedIn),ye(e,`cacheWriteIn`,t.cacheWriteIn),ye(e,`reasoningOut`,t.reasoningOut),t.breakdown?.length&&(e.breakdown=_e(e.breakdown,t.breakdown)))}function he(...e){let t=G();for(let n of e)K(t,n);return t}function ge(e,t){return{...e,breakdown:[{provider:t.provider,model:t.model,in:e.in,out:e.out,...e.cachedIn===void 0?{}:{cachedIn:e.cachedIn},...e.cacheWriteIn===void 0?{}:{cacheWriteIn:e.cacheWriteIn},...e.reasoningOut===void 0?{}:{reasoningOut:e.reasoningOut}}]}}function _e(e,t){let n=e?[...e]:[];for(let e of t){let t=n.find(t=>t.provider===e.provider&&t.model===e.model);if(!t){n.push({...e});continue}t.in+=e.in,t.out+=e.out,ye(t,`cachedIn`,e.cachedIn),ye(t,`cacheWriteIn`,e.cacheWriteIn),ye(t,`reasoningOut`,e.reasoningOut)}return n}function q(e,t){return{...e,...be(`cachedIn`,t.cachedIn),...be(`cacheWriteIn`,t.cacheWriteIn),...be(`reasoningOut`,t.reasoningOut)}}function ve(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 ye(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function be(e,t){return typeof t==`number`?{[e]:t}:{}}var xe=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 D(`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 D(`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 D(`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 Se(e,t,n){t.usage&&K(e,n?ge(t.usage,n):t.usage)}function Ce(e,t){if(!e)return;I(e,`text`,M(t));let n=te(t);n&&e.debug(`thinking`,{thinking:n});for(let n of ne(t))e.info(n.name,{type:`provider-tool`,input:n.input}),n.output!==void 0&&e.trace(n.name,{type:`provider-tool`,output:n.output});we(e,re(t))}function we(e,t){if(t.length===0)return;let n=Te(t);e.info(`citations`,{count:t.length,sources:n.slice(0,8),...n.length>8?{more:n.length-8}:{}}),n.length>8&&e.debug(`citations`,{sources:n}),e.setAttribute(`citationCount`,t.length)}function Te(e){let t=new Set,n=[];for(let{source:r}of e){let e=Ee(r),i=`title`in r?r.title:void 0,a=e??i??r.type;t.has(a)||(t.add(a),n.push({type:r.type,...i?{title:i}:{},...e?{url:e}:{}}))}return n}function Ee(e){switch(e.type){case`web`:case`search-result`:return e.url;case`retrieved-context`:return e.uri;case`document`:return e.fileId;default:return}}function De(e){return JSON.stringify({error:e})}function Oe(e){let t=e.tools!==void 0||e.providerTools!==void 0;if(e.registry&&t)throw new D("Cannot specify both `registry` and `tools` / `providerTools`. Use one or the other.",{code:`TOOL_OPTIONS_CONFLICT`});return e.registry?e.registry:new xe({tools:e.tools,providerTools:e.providerTools})}async function ke(e,t=async()=>null,n,r,i,a){let o=[],s=G(),c=!1;for(let l of e){let e;try{e=await je(l,t,n,r,i,a)}catch(e){throw c?Ae(e,s):e}o.push(e.result),e.usage&&(K(s,e.usage),c=!0)}return{results:o,...c?{usage:s}:{}}}function Ae(e,t){return e instanceof j?new j(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:he(t,e.usage),cause:e.cause}):e instanceof k?new k(e.message,{reason:e.reason,messages:e.messages,partial:e.partial,usage:he(t,e.usage)}):e}async function je(e,t,n,r,i,a){if(n.aborted)throw new k(`Operation aborted`,{reason:n.reason});let o=r.get(e.name),s=i?.startSpan(e.name,{type:`tool`}),c,l={signal:n,span:s,registry:r,emit:t=>a?.onDelta?.(e,t),reportUsage:e=>{c??=G(),K(c,e)}};a?.onStart?.(e);let u,d=`exception`;try{if(u=await t(e.name,e.parameters,l),u==null&&o&&(d=`execution`,u={type:`success`,content:await o.execute(e.parameters,l)}),n.aborted)throw new k(`Operation aborted`,{reason:n.reason})}catch(t){let r=Me(t,n);if(r){s?.setResult({kind:`tool`,name:e.name,input:e.parameters,output:{type:r instanceof j?`fatal`:`aborted`,message:r.message}}),s?.end(r instanceof j?`error`:`ok`);let t=c?Ae(r,c):r;throw a?.onError?.(e,t),t}u={type:`error`,error:{type:d,message:t instanceof Error?t.message:String(t)}}}u??={type:`error`,error:{type:`not-found`,message:`Tool not found: ${e.name}`}};let f={result:u,...c?{usage:c}:{}};a?.onComplete?.(e,f);let p=u.type===`success`?u.content:De(u.error);return s?.setResult({kind:`tool`,name:e.name,input:e.parameters,output:u.type===`success`?u.content:u.error}),s?.end(u.type===`success`?`ok`:`error`),{result:{id:e.id,name:e.name,content:p,...u.type===`error`?{isError:!0}:{}},...c?{usage:c}:{}}}function Me(e,t){if(e instanceof j||e instanceof k)return e;if(t.aborted)return new k(`Operation aborted`,{reason:t.reason})}let Ne=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function J(e,t){for(let n of e)n(t)}function Pe(e){return{name:e.name,description:e.description,schema:e.schema}}function Fe(e){let t=[],n,r;if(`instruct`in e){let{instruct:t,messages:i,...a}=e,o=pe(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(()=>Ie(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 Ie(e,t,n){let{provider:r,model:i,messages:a,system:o,onToolCall:s,maxIterations:c,span:l,fileResolver:u,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}=e,y=Oe(e),b=[...a],x=[],S=G(),C=0,w=0,T=e=>{b.push(e),x.push(e)},E=e=>{e.ok||J(n,{type:`error`,error:e.error});let t=e.ok?e.final.content:null,r=e.ok?e.final.finishReason:void 0;return l?.setResult({kind:`llm`,model:i,request:{messages:a},response:{content:t??null},usage:ve(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 k(`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()??[],O=a.length>0?a.map(Pe):void 0,A=y?.provider()??[],ee=r.createStreamingRequest(i,{messages:b,system:o,tools:O,providerTools:A.length>0?A:void 0,runtime:{span:e,fileResolver:u},signal:t,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}),M=[],te=``,N=``,ne=null,re=G(),P=-1,ie=null,F=``,I=new Map,L=new Map,R=new Map,ae=new Set,oe=(e,t)=>{J(n,{type:`tool:request`,index:I.get(e)??-1,id:e,name:t,kind:y.get(t)?.kind??`tool`})},z=-1,B=()=>{ie!==null&&P>=0&&(J(n,{type:ie===`text`?`text:end`:`thinking:end`,index:P,final:F}),ie=null,F=``,P=-1)};for await(let a of ee){switch(a.type){case`start`:te=a.id,N=a.data.model,J(n,{type:`turn:start`,id:te,model:N});break;case`text-start`:B(),M.push({type:`text`,text:``}),z=M.length-1,P=C++,L.set(a.data.index,z),R.set(a.data.index,P),ie=`text`,F=``,J(n,{type:`text:start`,index:P});break;case`text-delta`:{let e=M[z];e.text+=a.data.text,F=e.text,J(n,{type:`text:delta`,index:P,delta:a.data.text,accumulated:F});break}case`text-citation`:{let e=L.get(a.data.index)??z,t=R.get(a.data.index)??P,r=M[e];if(!r||r.type!==`text`)break;r.citations=[...r.citations??[],a.data.citation],J(n,{type:`text:citation`,index:t,citation:a.data.citation,citations:r.citations});break}case`citation`:{B();let e=C++;M.push({type:`citation`,citations:a.data.citations,...a.data.providerMetadata?{providerMetadata:a.data.providerMetadata}:{}}),z=M.length-1,L.set(a.data.index,z),R.set(a.data.index,e),J(n,{type:`citation`,index:e,citations:a.data.citations,providerMetadata:a.data.providerMetadata});break}case`text-complete`:B();break;case`thinking-start`:B(),M.push({type:`thinking`,text:``,...a.data.id?{id:a.data.id}:{},...a.data.redacted===void 0?{}:{redacted:a.data.redacted},...a.data.continuity?{continuity:a.data.continuity}:{},...a.data.providerMetadata?{providerMetadata:a.data.providerMetadata}:{}}),z=M.length-1,P=C++,L.set(a.data.index,z),R.set(a.data.index,P),ie=`thinking`,F=``,J(n,{type:`thinking:start`,index:P,redacted:a.data.redacted,continuity:a.data.continuity,providerMetadata:a.data.providerMetadata});break;case`thinking-delta`:{let e=M[z];e.text=(e.text??``)+a.data.text,F=e.text,J(n,{type:`thinking:delta`,index:P,delta:a.data.text,accumulated:F});break}case`thinking-summary-delta`:{let e=M[z];e.summary=(e.summary??``)+a.data.text,F=e.summary,J(n,{type:`thinking:summary-delta`,index:P,delta:a.data.text,accumulated:F});break}case`thinking-metadata`:{let e=L.get(a.data.index)??z,t=R.get(a.data.index)??P,r=M[e];if(!r||r.type!==`thinking`)break;a.data.redacted!==void 0&&(r.redacted=a.data.redacted),a.data.continuity&&(r.continuity=a.data.continuity),a.data.providerMetadata&&(r.providerMetadata=a.data.providerMetadata),J(n,{type:`thinking:update`,index:t,redacted:a.data.redacted,continuity:a.data.continuity,providerMetadata:a.data.providerMetadata});break}case`thinking-complete`:B();break;case`tool-call-start`:{B();let e=C++;M.push({type:`tool-call`,id:a.data.id,name:a.data.name,parameters:{}}),z=M.length-1,L.set(a.data.index,z),R.set(a.data.index,e),I.set(a.data.id,e),a.data.name?oe(a.data.id,a.data.name):ae.add(a.data.id);break}case`tool-call-args-delta`:ae.has(a.data.id)&&a.data.name&&(ae.delete(a.data.id),oe(a.data.id,a.data.name)),J(n,{type:`tool:args-delta`,index:I.get(a.data.id)??-1,id:a.data.id,name:a.data.name,delta:a.data.delta,accumulated:a.data.accumulated});break;case`tool-call-complete`:{let e=M[L.get(a.data.index)??z];if(!e||e.type!==`tool-call`)break;a.data.id&&(e.id=a.data.id),a.data.name&&(e.name=a.data.name),e.parameters=a.data.arguments,a.data.providerMetadata&&(e.providerMetadata=a.data.providerMetadata),ae.has(e.id)&&e.name&&(ae.delete(e.id),oe(e.id,e.name));break}case`provider-tool-start`:{B();let e=C++;M.push({type:`provider-tool`,id:a.data.id,name:a.data.name}),z=M.length-1,L.set(a.data.index,z),R.set(a.data.index,e),J(n,{type:`provider-tool:start`,index:e,id:a.data.id,name:a.data.name});break}case`provider-tool-complete`:{let e=L.get(a.data.index)??z,t=R.get(a.data.index)??a.data.index,r=M[e];r&&r.type===`provider-tool`&&a.data.output!=null&&(r.output=a.data.output),J(n,{type:`provider-tool:complete`,index:t,id:a.data.id,name:a.data.name,output:a.data.output});break}case`complete`:B(),ne=a.data.finishReason,re=a.data.usage;break;case`error`:return B(),a.data.usage&&K(S,ge(a.data.usage,{provider:r.name,model:N||i})),e?.end(`error`),E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:a.data.type,message:a.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,B)),ne===null)return B(),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});let se=ge(re,{provider:r.name,model:N||i});K(S,se);let ce={kind:`llm`,model:N,request:{messages:b},response:{content:M},usage:ve(re),finishReason:ne};Ce(e,M),e?.setResult(ce),e?.end();let V={role:`assistant`,id:te,model:N,content:M,finishReason:ne};if(T(V),J(n,{type:`turn:complete`,message:V,usage:se}),ne!==`function_call`)return E({ok:!0,response:V,messages:x,final:V,usage:S});let H=M.filter(e=>e.type===`tool-call`);if(H.length===0)return E({ok:!0,response:V,messages:x,final:V,usage:S});if(t.aborted)throw l?.end(`ok`),new k(`Stream aborted`,{reason:t.reason,messages:x,usage:S});let U=crypto.randomUUID();J(n,{type:`tool-results:start`,id:U});let W={onStart(e){J(n,{type:`tool:exec-start`,index:I.get(e.id)??-1,id:e.id,name:e.name,parameters:e.parameters})},onDelta(e,t){J(n,{type:`tool:exec-delta`,index:I.get(e.id)??-1,id:e.id,name:e.name,chunk:t})},onComplete(e,t){J(n,{type:`tool:exec-complete`,index:I.get(e.id)??-1,id:e.id,name:e.name,result:t.result,usage:t.usage})},onError(e,t){J(n,{type:`tool:exec-error`,index:I.get(e.id)??-1,id:e.id,name:e.name,error:{type:t instanceof j?`fatal`:`aborted`,message:t.message},usage:t.usage})}},le,ue;try{({results:le,usage:ue}=await ke(H,s,t,y,l,W))}catch(e){throw e instanceof j?(l?.end(`error`),new j(e.message,{toolName:e.toolName,messages:e.messages??x,partial:e.partial??V,usage:he(S,e.usage),cause:e.cause})):e instanceof k?(l?.end(`ok`),new k(`Stream aborted`,{reason:e.reason,messages:e.messages??x,partial:e.partial,usage:he(S,e.usage)})):e}if(K(S,ue),le.length>0){let e={role:`tool`,id:U,content:le};T(e),J(n,{type:`tool-results:complete`,message:e})}}}function Le(e=new Date){return{start:e.toISOString()}}function Y(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var Re=class{currentTurnId=null;currentTurnTiming;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage=G();createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=Y(Le(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=Le(),this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage=G(),{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:Le()};this.currentTextPart={id:e,timing:r.timing},n.push({type:`part:start`,turnId:t,part:r});break}case`text:delta`:this.currentTextPart&&n.push({type:`text:delta`,turnId:t,partId:this.currentTextPart.id,delta:e.delta});break;case`text:end`:if(this.currentTextPart){let e=Y(this.currentTextPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:e}),this.currentTextPart=null}break;case`citation`:{this.closeOpenParts(n);let r=Y(Le()),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:Le(),...e.redacted===void 0?{}:{redacted:e.redacted},...e.continuity?{continuity:e.continuity}:{},...e.providerMetadata?{providerMetadata:e.providerMetadata}:{}};this.currentThinkingPart={id:r,timing:i.timing},n.push({type:`part:start`,turnId:t,part:i});break}case`thinking:delta`:this.currentThinkingPart&&n.push({type:`thinking:delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`text:citation`:this.currentTextPart&&n.push({type:`text:citation`,turnId:t,partId:this.currentTextPart.id,citation:e.citation});break;case`thinking:summary-delta`:this.currentThinkingPart&&n.push({type:`thinking:summary-delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`thinking:update`:this.currentThinkingPart&&n.push({type:`thinking:update`,turnId:t,partId:this.currentThinkingPart.id,redacted:e.redacted,continuity:e.continuity,providerMetadata:e.providerMetadata});break;case`thinking:end`:if(this.currentThinkingPart){let e=Y(this.currentThinkingPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:e}),this.currentThinkingPart=null}break;case`tool:request`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=Le(),a=e.kind===`agent`?{id:r,type:`action`,kind:`agent`,status:`pending`,timing:i,detail:{name:e.name,children:[]}}:{id:r,type:`action`,kind:`tool`,status:`pending`,timing:i,detail:{name:e.name,parameters:{}}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i,name:e.name,kind:e.kind}),n.push({type:`part:start`,turnId:t,part:a});break}case`tool:args-delta`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:args-delta`,turnId:t,partId:r.partId,delta:e.delta,accumulated:e.accumulated});break}case`tool:exec-start`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:running`,turnId:t,partId:r.partId,parameters:e.parameters});break}case`tool:exec-delta`:{let r=this.toolIdMap.get(e.id);r&&(typeof e.chunk==`string`?n.push({type:`action:progress`,turnId:t,partId:r.partId,chunk:e.chunk}):e.chunk.type===`turn-event`&&n.push({type:`action:child-event`,turnId:t,partId:r.partId,event:e.chunk.event}));break}case`tool:exec-complete`:{let r=this.toolIdMap.get(e.id);if(r){K(this.accumulatedUsage,e.usage);let i=Y(r.timing);r.timing=i,e.result.type===`success`?n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.result.content},timing:i}):n.push({type:`action:error`,turnId:t,partId:r.partId,error:e.result.error,timing:i})}break}case`tool:exec-error`:{let r=this.toolIdMap.get(e.id);if(r){K(this.accumulatedUsage,e.usage);let i=Y(r.timing);r.timing=i,n.push({type:`action:error`,turnId:t,partId:r.partId,error:e.error,timing:i})}break}case`provider-tool:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=Le(),a={id:r,type:`action`,kind:`provider-tool`,status:`running`,timing:i,detail:{name:e.name}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i}),n.push({type:`part:start`,turnId:t,part:a}),n.push({type:`action:running`,turnId:t,partId:r});break}case`provider-tool:complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=Y(r.timing);r.timing=i,n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.output},timing:i})}break}case`turn:complete`:this.closeOpenParts(n),K(this.accumulatedUsage,e.usage);break;case`tool-results:start`:case`tool-results:complete`:break;case`error`:{let t=e.error,r=t.kind===`model`?t.error.error.message:t.kind===`tool`?`Tool error (${t.error.name}): ${t.error.message}`:`Parse error: ${t.message}`;n.push({type:`error`,error:{type:t.kind,message:r}});break}}return n}finalizeTurn(e=`complete`){let t=this.currentTurnId;if(!t)return[];let n=[];this.closeOpenParts(n);let r=Y(this.currentTurnTiming);return n.push({type:`turn:end`,turnId:t,status:e,usage:{...this.accumulatedUsage},timing:r}),this.currentTurnId=null,this.currentTurnTiming=void 0,n}closeOpenParts(e){let t=this.currentTurnId;t&&(this.currentTextPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:Y(this.currentTextPart.timing)}),null),this.currentThinkingPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:Y(this.currentThinkingPart.timing)}),null))}};function ze(e){return Array.isArray(e)?e:[e]}function Be(e){return e.then(()=>{},()=>{})}function Ve(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:Be(a)}}var He=class{_turns=[];_log=[];_sessionAnnotations=[];constructor(e){e?.turns&&(this._turns=[...e.turns]),e?.log&&(this._log=[...e.log]),e?.sessionAnnotations&&(this._sessionAnnotations=[...e.sessionAnnotations])}get turns(){return[...this._turns]}get log(){return[...this._log]}get sessionAnnotations(){return[...this._sessionAnnotations]}addTurn(e){this._turns.push(e)}replaceTurns(e){this._turns=[...e]}replaceLog(e){this._log=[...e]}replaceSessionAnnotations(e=[]){this._sessionAnnotations=[...e]}appendToLog(e){Array.isArray(e)?this._log.push(...e):this._log.push(e)}latestTurn(){return this._turns[this._turns.length-1]}toString(){return JSON.stringify({turns:this._turns,sessionAnnotations:this._sessionAnnotations})}};const Ue={trace:0,debug:1,info:2,warn:3,error:4},We=()=>performance.timeOrigin+performance.now();var Ge=class{writers=[];minLevel=`info`;addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}shouldLog(e){return Ue[e]>=Ue[this.minLevel]}spanStart(e){for(let t of this.writers)t.onSpanStart(e)}spanEnd(e){for(let t of this.writers)t.onSpanEnd(e)}spanUpdate(e){for(let t of this.writers)t.onSpanUpdate?.(e)}event(e,t){for(let n of this.writers)n.onEvent?.(e,t)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}},Ke=class{rec=new Ge;constructor(e){e?.minLevel&&(this.rec.minLevel=e.minLevel);for(let t of e?.writers??[])this.rec.addWriter(t)}get minLevel(){return this.rec.minLevel}set minLevel(e){this.rec.minLevel=e}addWriter(e){this.rec.addWriter(e)}removeWriter(e){this.rec.removeWriter(e)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:We(),status:`ok`,attributes:{...t?.attributes??{}},events:[]};return this.rec.spanStart(n),new qe(n,this.rec)}flush(){return this.rec.flush()}},qe=class e{data;rec;ended=!1;constructor(e,t){this.data=e,this.rec=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:We(),status:`ok`,attributes:{...n?.attributes??{}},events:[]};return this.rec.spanStart(r),new e(r,this.rec)}end(e=`ok`){this.ended||(this.ended=!0,this.data.endTime=We(),this.data.status=e,this.rec.spanEnd(this.data))}addEvent(e,t,n){if(this.ended||!this.rec.shouldLog(t))return;let r={name:e,timestamp:We(),level:t,attributes:n};this.data.events.push(r),this.rec.event(this.data,r)}trace(e,t){this.addEvent(e,`trace`,t)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,this.rec.spanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.rec.spanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.rec.spanUpdate(this.data))}};function Je(e){if(!e)return{};let{trace:t,log:n,level:r}=e;if(t)return n&&console.warn(`[axle] observability.log is ignored when observability.trace is set; add a LogWriter to your tracer's writers instead`),{parent:t};if(n){let e=new Ke({minLevel:r,writers:[new F(n)]});return{parent:e,owned:e}}return{}}function Ye(e){return Xe(e)?`cancelled`:`error`}function Xe(e){return e instanceof k||e instanceof A||e instanceof Error&&e.name===`AbortError`}function Ze(e,t){return{...e,...t,providerOptions:e?.providerOptions||t?.providerOptions?{...e?.providerOptions,...t?.providerOptions}:void 0}}var Qe=class{provider;model;history;name;fileResolver;requestOptions;registry;sessionId;system;mcps=[];resolvedMcps=new WeakSet;memory;spanParent;ownedTracer;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e,t){this.provider=e.provider,this.model=e.model,this.sessionId=e.sessionId??crypto.randomUUID(),this.history=new He;let n=Je(e.observability);if(this.spanParent=n.parent,this.ownedTracer=n.owned,this.system=e.system,this.name=e.name,this.fileResolver=e.fileResolver,this.requestOptions={reasoning:e.reasoning,maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,stop:e.stop,toolChoice:e.toolChoice,parallelToolCalls:e.parallelToolCalls,providerOptions:e.providerOptions},this.registry=new xe({tools:e.tools,providerTools:e.providerTools}),e.mcps&&(this.mcps=[...e.mcps]),e.memory){this.memory=e.memory;let t=e.memory.tools?.();t&&this.registry.add(t)}t&&this.restore(t)}addMcp(e){this.mcps.push(e)}addMcps(e){this.mcps.push(...e)}hasTools(){return this.registry.size>0||this.mcps.length>0}on(e){return this.eventCallbacks.push(e),()=>{let t=this.eventCallbacks.indexOf(e);t>=0&&this.eventCallbacks.splice(t,1)}}context(){return L({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 D(`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=pe(e,{metadata:r}),o=Ze(this.requestOptions,i),{handle:s,settled:c}=Ve(this.sendQueue,async e=>{let t=this.spanParent?.startSpan(`agent.send`,{type:`workflow`,attributes:{sessionId:this.sessionId,...this.name?{agentName:this.name}:{}}});I(t,`message`,M(a.message.content));let r=`ok`;try{let i=await this.run(a,{signal:e,fileResolver:n,requestOptions:o,span:t});return i.ok||(r=`error`),t?.setAttributes({inputTokens:i.usage.in,outputTokens:i.usage.out}),i}catch(e){throw r=Ye(e),t?.error(e instanceof Error?e.message:String(e)),e}finally{t?.end(r),await this.ownedTracer?.flush()}},i.signal);return this.sendQueue=c,s}async resolveMcpTools(e,t){for(let n of this.mcps){if(this.resolvedMcps.has(n))continue;let r=await n.listTools({prefix:n.name,span:t,signal:e});this.registry.addMcp(r),this.resolvedMcps.add(n)}}emitEvent(e){for(let t of this.eventCallbacks)t(e)}toToolDefinitions(e){return e.map(e=>({name:e.name,description:e.description,schema:e.schema}))}async run(t,n){let{signal:r,fileResolver:i,requestOptions:a}=n,o=n.span,s=new Re,c=new e({turns:this.history.turns,sessionAnnotations:this.history.sessionAnnotations}),l,u=e=>{let t=c.apply(e);t.handled&&(this.history.replaceTurns(t.state.turns),this.history.replaceSessionAnnotations(t.state.sessionAnnotations??[])),this.emitEvent(e)},d=()=>l?c.state.turns.find(e=>e.id===l):void 0,f=G();if(r.aborted)throw new A(`Agent send aborted`,{reason:r.reason,usage:f});try{await this.resolveMcpTools(r,o)}catch(e){throw r.aborted||e instanceof k||e instanceof Error&&e.name===`AbortError`?new A(`Agent send aborted`,{reason:e instanceof k?e.reason:r.reason,usage:f}):e}let p=this.system,m=[...this.history.log,t.message];if(this.memory){let e=await this.memory.recall({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:m,span:o});e.systemSuffix&&(p=(p??``)+`
|
|
6
6
|
|
|
7
|
-
`+e.systemSuffix)}if(r.aborted)throw new
|
|
8
|
-
`)}function
|
|
9
|
-
`)||`MCP tool execution error`}var
|
|
7
|
+
`+e.systemSuffix)}if(r.aborted)throw new A(`Agent send aborted`,{reason:r.reason,usage:f});this.history.appendToLog(t.message);for(let e of s.createUserTurn(t.message))u(e);let h=s.startAgentTurn();l=h.turnId,u(h);let g=o?.startSpan(`stream`,{type:`internal`})??void 0,{signal:_,...v}=a??{},y=Fe({provider:this.provider,model:this.model,messages:m,system:p,registry:this.registry,span:g,fileResolver:i??this.fileResolver,...v,signal:r});y.on(e=>{let t=s.handleStreamEvent(e);for(let e of t)u(e)});let b,x=`ok`;try{b=await y.final,b.ok||(x=`error`)}catch(e){if(x=Ye(e),e instanceof j){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=s.finalizeTurn(`error`);for(let e of t)u(e);throw new j(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:e.usage??f,cause:e.cause})}if(e instanceof k){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=s.finalizeTurn(`cancelled`);for(let e of t)u(e);throw new A(`Agent send aborted`,{reason:e.reason,messages:e.messages,partial:e.partial,turn:d(),usage:e.usage??f})}throw e}finally{g?.end(x)}let S=b.ok?`complete`:`error`;b.ok&&b.final?.finishReason&&o?.setAttribute(`finishReason`,b.final.finishReason),b.messages.length>0&&this.history.appendToLog(b.messages);let C=s.finalizeTurn(S);for(let e of C)u(e);let w=b.usage??f,T=d();if(!b.ok)return{ok:!1,error:b.error,turn:T,usage:w};let E;try{E=t.parse(b.final)}catch(e){return{ok:!1,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)},turn:T,usage:w}}if(!T)throw new D(`Agent turn missing after send`);if(this.memory)try{await this.memory.record({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:this.history.log,newMessages:b.messages,span:o})}catch(e){o?.warn(`memory record failed`,{error:e instanceof Error?e.message:String(e)})}return{ok:!0,response:E,turn:T,usage:w}}};function $e(e){try{let t=l.fromJSONSchema(e);return t instanceof l.ZodObject?t.strict():l.object({}).passthrough()}catch{return l.object({}).passthrough()}}function et(e,t,n){return e.map(e=>nt(e,t,n))}function tt(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=$e(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function nt(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=$e(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 j(`MCP tool call failed: ${e.name}`,{toolName:r,cause:t})}if(`isError`in a&&a.isError)throw Error(it(a.content));return rt(a.content)}}}function rt(e){return e.some(e=>e.type===`image`)?e.filter(e=>e.type===`text`||e.type===`image`).map(e=>{if(e.type===`text`)return{type:`text`,text:e.text};let t=e;return{type:`file`,file:{kind:`image`,mimeType:t.mimeType,name:`mcp-image`,source:{type:`base64`,data:t.data}}}}):e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
8
|
+
`)}function it(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
9
|
+
`)||`MCP tool execution error`}var at=class{config;client;transport;cachedMcpTools;_connected=!1;constructor(e){this.config=e}get name(){return this.config.name??this.client?.getServerVersion()?.name}get connected(){return this._connected}async connect(e){if(this._connected)return;let t=e?.span?.startSpan(`mcp:connect`,{type:`internal`});this.client=new d({name:`axle`,version:`1.0.0`}),this.config.transport===`stdio`?this.transport=new f({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new p(new URL(this.config.url),{requestInit:this.config.headers?{headers:this.config.headers}:void 0});try{await this.client.connect(this.transport,{signal:e?.signal}),this._connected=!0,t?.end(`ok`)}catch(e){throw t?.end(`error`),e}}async listTools(e){let t=this.assertConnected();return et(await this.fetchTools(t,e?.span,e?.signal),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return tt(await this.fetchTools(t,e?.span,e?.signal),e?.prefix)}async refreshTools(){return this.assertConnected(),this.cachedMcpTools=void 0,this.listTools()}async close(e){this._connected&&(e?.span?.debug(`mcp:close`),await this.client?.close(),this._connected=!1,this.client=void 0,this.transport=void 0,this.cachedMcpTools=void 0)}async fetchTools(e,t,n){if(this.cachedMcpTools)return this.cachedMcpTools;t?.debug(`mcp:listTools`);let r=await e.listTools(void 0,{signal:n});return this.cachedMcpTools=r.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})),this.cachedMcpTools}assertConnected(){if(!this._connected||!this.client)throw Error(`MCP not connected. Call connect() first.`);return this.client}};function ot(e){return e?.map(e=>({type:`provider`,name:e.name,config:e.config}))}async function st(e,t){if(e.version!==1)throw new D(`Unsupported agent definition version: ${e.version}`);let n=await t(e),r=e.model??n.model;if(!r)throw new D(`AgentDefinition requires a model or model resolver`);if(e.tools?.length&&!n.tools)throw new D(`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??ot(e.providerTools),mcps:n.mcps??e.mcps?.map(e=>new at(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 ct=class e extends D{missingVariables;constructor(t){super(lt(t),{code:`INSTRUCT_VARIABLE_ERROR`,details:{missingVariables:t}}),this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),missingVariables:this.missingVariables}}};function lt(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var ut=class e extends Error{missingVariables;constructor(t){super(ft(t)),this.name=`MissingVariablesError`,this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}};function dt(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 ut(e)}return e}function ft(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var pt=class e{prompt;inputs={};files=[];textReferences=[];contextSections=[];vars;metadata;schema;constructor(e){this.prompt=e.prompt,this.schema=e.schema,this.vars=e.vars??`required`,this.metadata=e.metadata}clone(){let t=new e({prompt:this.prompt,schema:this.schema,vars:this.vars,metadata:this.metadata});return t.inputs={...this.inputs},t.files=[...this.files],t.textReferences=this.textReferences.map(e=>({...e})),t.contextSections=this.contextSections.map(e=>({...e})),t}withInputs(e){let t=this.clone();return t.inputs={...t.inputs,...e},t}withInput(e,t){return this.withInputs({[e]:t})}setInputs(e){this.inputs={...e}}addInput(e,t){this.inputs[e]=t}addFile(e,t){if(typeof e==`string`){this.textReferences.push({content:e,name:t?.name});return}if(e.kind===`text`&&e.source.type===`text`){this.textReferences.push({content:e.source.content,name:t?.name??e.name});return}this.files.push(t?.name?{...e,name:t.name}:e)}addContext(e,t){return this.contextSections.push({content:e,...t?.title?{title:t.title}:{}}),this}hasFiles(){return this.files.length>0}render(e={}){let t;try{t=dt(this.prompt,this.inputs,{strict:(e.vars??this.vars)===`required`})}catch(e){throw e instanceof ut?new ct(e.missingVariables):e}if(this.textReferences.length>0)for(let[e,n]of this.textReferences.entries()){let r=n.name?`: ${n.name}`:``,i=mt(n.content);t+=`\n\n## Reference ${e+1}${r}\n\n${i}\n${n.content}\n${i}`}for(let[e,n]of this.contextSections.entries()){let r=n.title?`: ${n.title}`:``,i=mt(n.content);t+=`\n\n## Context ${e+1}${r}\n\n${i}\n${n.content}\n${i}`}if(!this.schema)return t;let n=`# Output Format Instructions
|
|
10
10
|
|
|
11
11
|
Return only valid JSON matching this schema. Do not wrap it in markdown. Do not include prose before or after the JSON.
|
|
12
|
-
`,[,r]=W(this.schema);for(let[e,t]of ce(this.schema))n+=`\n- ${e}: ${t}`;return n+=`\n\nExample:\n${JSON.stringify(r,null,2)}\n\n`,n+t}},lt=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 ut(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 dt(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 ft(e,t,n=`[redacted]`){return pt(e,null,t,n)}function pt(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=>pt(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=pt(a,t,n,r);return i}const mt=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function Z(e){return ft(e,mt,`[redacted-file-value]`)}const ht=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 gt({type:`base64`,data:n.data},e,t);if(n.type===`text`)return gt({type:`text`,content:n.content},e,t);if(n.type===`url`)return gt({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return gt(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function gt(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 _t=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function vt(e){return e.startsWith(`text/`)||_t.has(e)}function yt(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(vt(t))return{kind:`text`,mimeType:t};{let n=v(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function bt(e,t){let n=y(e);try{await h(n)}catch{throw Error(`File not found: ${e}`)}let r=await _(n);if(r.size>ht)throw Error(`File too large: ${r.size} bytes. Maximum allowed: ${ht} bytes`);let i=n.split(`/`).pop()||``,a=yt(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 xt(e,t={model:``}){return Promise.all(e.map(e=>St(e,t)))}async function St(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 It(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 Ct(r.file,t,`user-message`));return{role:`user`,content:n}}}async function Ct(e,t,n){if(e.kind===`image`)return{type:`image`,source:Tt(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:Et(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 wt(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 Tt(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:wt(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function Et(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 Dt(e){return e===!0?{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function Ot(e){return e.map(e=>{let t=l.toJSONSchema(e.schema);if(!Ft(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}const kt={web_search:`web_search_20250305`};function At(e){return(e??[]).map(e=>({type:kt[e.name]??e.name,name:e.name,...e.config}))}function jt(e,t,n,r){if(e===void 0&&t!==!1)return{};let i=t===!1?{disable_parallel_tool_use:!0}:{};if(e===void 0||e===`auto`)return{tool_choice:{type:`auto`,...i}};if(e===`required`)return{tool_choice:{type:`any`,...i}};if(e===`none`)return{tool_choice:{type:`none`}};if(!(n?.some(t=>t.name===e.name)||r?.some(t=>t.name===e.name)))throw Error(`Tool choice references an unavailable tool: ${e.name}`);return{tool_choice:{type:`tool`,name:e.name,...i}}}function Mt(e){let t=[];for(let n of e)if(n.type===`text`){let e=n.citations?.map(Nt);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 Nt(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 Pt(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 Ft(e){return e&&typeof e==`object`&&e.type===`object`}async function It(e,t){return Promise.all(e.map(async e=>e.type===`text`?{type:`text`,text:e.text}:Ct(e.file,t,`tool-result`)))}async function Lt(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v;try{X(g,`Generate aborted`);let e=await xt(r,{model:n,fileResolver:s?.fileResolver,signal:g}),y={model:n,max_tokens:l??16e3,messages:e,...i&&{system:i},...f&&{stop_sequences:Pe(f)},...(a||o)&&{tools:[...a?Ot(a):[],...At(o)]},...Dt(c),...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...jt(p,m,a,o),...h};_?.debug(`Anthropic request`,{request:Z(y)});let b=await dt(t.messages.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=Rt(b)}catch(e){X(g,`Generate aborted`),v=ut(e)}return _?.debug(`Anthropic response`,{result:v}),v}function Rt(e){let t=Pt(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:Bt(e.usage),raw:e};if(t===`function_call`){let t=Mt(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:M(t),usage:Bt(e.usage),raw:e}}if(e.type==`message`){let n=Mt(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:M(n),usage:Bt(e.usage),raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:Bt(e.usage),raw:e}}function zt(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)}function Bt(e){return K({in:zt(e),out:e.output_tokens},{cachedIn:e.cache_read_input_tokens??void 0,cacheWriteIn:e.cache_creation_input_tokens??void 0})}function Vt(){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:Pt(s.delta.stop_reason),usage:K({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:Nt(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: ${P(e.argumentsBuffer)}`)}o.delete(s.index)}}e.delete(s.index);break}}return c}return{handleEvent:s}}async function*Ht(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span,v=[...a?Ot(a):[],...At(o)],y=Vt();try{let e=await xt(r,{model:n,fileResolver:s?.fileResolver,signal:c}),b={model:n,max_tokens:u??Ut(n),messages:e,...i&&{system:i},...p&&{stop_sequences:Pe(p)},...v.length>0&&{tools:v},...Dt(l),...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...jt(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 Ut(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 Wt(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 Lt({client:n,model:e,...t})},createStreamingRequest(e,t){return Ht({client:n,model:e,...t})}}}const Gt={Models:i,DefaultModel:s};async function Kt(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=qt(t.signal,r);try{let r=await dt(e({signal:a.signal}),a.signal,`Request aborted`);if(!Jt(r.status)||i>=n)return r;let o=Yt(r,i);t.onRetry?.({attempt:i+1,delayMs:o,status:r.status}),await Zt(o,t.signal),i+=1}catch(e){if(X(t.signal,`Request aborted`),i>=n)throw e;let r=Yt(void 0,i);t.onRetry?.({attempt:i+1,delayMs:r,error:e}),await Zt(r,t.signal),i+=1}finally{a.cleanup()}}}function qt(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 Jt(e){return e===408||e===409||e===429||e>=500}function Yt(e,t){let n=Xt(e);if(n!==void 0)return n;let r=Math.min(500*2**t,8e3);return r+Math.floor(Math.random()*r*.25)}function Xt(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 Zt(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 Qt={web_search:`openrouter:web_search`};function $t(e,t){let n=[];for(let r of e){let e=Qt[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 en(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 tn(e){let t=e.outputSpan;return!t||t.start===void 0&&t.end===void 0?!1:t.start!==0||t.end!==0}async function nn(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>un(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function rn(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`none`}:{}}function an(e){return K({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 on(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 sn(e,t,n){if(!(!e||e.length===0)){if(!t){n?.(`providerTools not supported by ChatCompletions provider`);return}switch(t){case`openrouter`:return $t(e,n)}}}function cn(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 ln(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 un(e,t){switch(e.role){case`tool`:return dn(e,t);case`assistant`:return fn(e);default:return pn(e,t)}}async function dn(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await hn(e.content,t),tool_call_id:e.id})))}function fn(e){let t=e.content.filter(e=>e.type===`tool-call`),n=e.content.filter(e=>e.type===`text`),r=t.length>0?t.map(e=>({type:`function`,id:e.id,function:{name:e.name,arguments:JSON.stringify(e.parameters)}})):void 0;return{role:`assistant`,content:n.map(e=>e.text).join(``),...r&&{tool_calls:r}}}async function pn(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>mn(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 mn(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?gn(e.file,t,`user-message`):null}async function hn(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(yn(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(`
|
|
13
|
-
`)}async function
|
|
14
|
-
`);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=
|
|
15
|
-
`),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=>Ln(e.file,t,`tool-result`)))]}))).flat(1)}}function Pn(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 Fn(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>In(e,t)))).filter(e=>e!==null)}}async function In(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?Ln(e.file,t,`user-message`):null}async function Ln(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:zn(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 Rn(await Q(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function Rn(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 zn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function Bn(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 Vn(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v={...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]},...kn(p,m,a,o),...h},y;try{X(g,`Generate aborted`);let e=await jn(r,{model:n,fileResolver:s?.fileResolver,signal:g}),c=En(a,i,v);p!==`none`&&On(c,o);let l={contents:e,config:c};_?.debug(`Gemini request`,{request:Z(l)});let u=await dt(t.models.generateContent({model:n,...l}),g,`Generate aborted`);X(g,`Generate aborted`),y=Hn(u,{span:_})}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),y=ut(e)}return _?.debug(`Gemini response`,{result:y}),y}function Hn(e,t){let{span:n}=t,r=e.usageMetadata?.promptTokenCount??0,i=K({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]=Bn(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=Wn(a,e);Un(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:M(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function Un(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 Wn(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(Gn(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 Gn(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 Kn(){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 qn(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]=Bn(m.finishReason),r=n?`function_call`:t;!e&&!n?p.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${m.finishReason}`,usage:K({in:a,out:o},{cachedIn:s,reasoningOut:c}),raw:f}}):p.push({type:`complete`,data:{finishReason:r,usage:K({in:a,out:o},{cachedIn:s,reasoningOut:c})}})}return p}return{handleChunk:f}}function qn(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:Jn(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 Jn(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*Yn(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span,v=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]},...kn(m,h,a,o),...g});m!==`none`&&On(v,o);let y=Kn();try{let e={contents:await jn(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 Xn(e,t={}){let n=new S({apiKey:e,httpOptions:{retryOptions:{attempts:Zn(t.maxRetries)},...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}}});return{name:`Gemini`,async createGenerationRequest(e,t){return await Vn({client:n,model:e,...t})},createStreamingRequest(e,t){return Yn({client:n,model:e,...t})}}}function Zn(e=2){return Y(e,`maxRetries`,{min:0})+1}const Qn={Models:r,DefaultModel:n};async function $n(e){let{provider:t,model:n,messages:r,system:i,tools:a,providerTools:o,span:s,fileResolver:c,...l}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,providerTools:o,runtime:{span:s,fileResolver:c},...l})}async function er(e){if(`instruct`in e){let{instruct:t,messages:n,...r}=e,i=fe(t),a=await tr({...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 tr(e)}async function tr(e){let{provider:t,model:n,messages:r,system:i,onToolCall:a,maxIterations:o,span: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=Te(e),y=[...r],b=[],x=G(),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:he(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:he(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 $n({provider:t,model:n,messages:y,system:i,tools:D,providerTools:O.length>0?O:void 0,span: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(ye(x,k),k.type!==`error`&&be(e,k.content),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=ee(k.content);if(j.length===0)return T({ok:!0,response:C,messages:b,final:C,usage:x});let{results:M}=await Ee(j,a,_,v,s);X(_,`Generate aborted`),M.length>0&&w({role:`tool`,id:crypto.randomUUID(),content:M})}}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 nr(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 rr={web_search:`web_search_preview`,code_execution:`code_interpreter`};function ir(e){return e?.map(e=>({type:rr[e.name]??e.name,...e.config}))}function ar(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:rr[r.name]??r.name}};throw Error(`Tool choice references an unavailable tool: ${e.name}`)}function or(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`none`}}:{}}async function sr(e,t={model:``}){return(await Promise.all(e.map(e=>cr(e,t)))).flat(1)}async function cr(e,t){switch(e.role){case`tool`:return lr(e,t);case`assistant`:return ur(e);default:return dr(e,t)}}async function lr(e,t){return Promise.all(e.content.map(async e=>({type:`function_call_output`,call_id:e.id,output:typeof e.content==`string`?e.content:await Promise.all(e.content.map(e=>e.type===`text`?Promise.resolve({type:`input_text`,text:e.text}):pr(e.file,t,`tool-result`)))})))}function ur(e){let t=[],n=M(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 dr(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>fr(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function fr(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?pr(e.file,t,`user-message`):(e.type,null)}async function pr(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:mr(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 hr(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}:hr(r,e)}function mr(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 hr(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 gr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v;try{if(X(g,`Generate aborted`),f!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let e=[...nr(a)??[],...ir(o)??[]],y={model:n,input:await sr(r,{model:n,fileResolver:s?.fileResolver,signal:g}),...i&&{instructions:i},...e.length>0?{tools:e}:{},...or(c),...l===void 0?{}:{max_output_tokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...ar(p,a,o),...m===void 0?{}:{parallel_tool_calls:m},...h};_?.debug(`OpenAI ResponsesAPI request`,{request:Z(y)});let b=await dt(t.responses.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=_r(b)}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),v=ut(e)}return _?.debug(`OpenAI ResponsesAPI response`,{result:v}),v}function _r(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:br(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=vr(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:M(n),usage:br(e.usage),raw:e}}function vr(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(yr).filter(e=>e!==null);t.push({type:`text`,text:e.text,...n.length>0?{citations:n}:{}})}return t}function yr(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 br(e){return K({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 xr(){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=Sr(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=Sr(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=Cr(u.annotation);if(!e)break;let t=a.get(Sr(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:K({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 Sr(e,t){return`${e}:${t}`}function Cr(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*wr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span;if(p!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let v=[...nr(a)??[],...ir(o)??[]],y=xr();try{let e={model:n,input:await sr(r,{model:n,fileResolver:s?.fileResolver,signal:c}),...i&&{instructions:i},stream:!0,...v.length>0?{tools:v}:{},...or(l),...u===void 0?{}:{max_output_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...ar(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 Tr(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 gr({client:n,model:e,...t})},createStreamingRequest(e,t){return wr({client:n,model:e,...t})}}}const Er={Models:a,DefaultModel:o},Dr={trace:0,debug:1,info:2,warn:3,error:4};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 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 kr(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(`
|
|
16
|
-
`);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
|
|
17
|
-
`)}function
|
|
18
|
-
`;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function
|
|
19
|
-
`)}function
|
|
20
|
-
`)}function
|
|
12
|
+
`,[,r]=W(this.schema);for(let[e,t]of le(this.schema))n+=`\n- ${e}: ${t}`;return n+=`\n\nExample:\n${JSON.stringify(r,null,2)}\n\n`,n+t}};function mt(e){let t=Math.max(0,...Array.from(e.matchAll(/`+/g),e=>e[0].length));return"`".repeat(Math.max(3,t+1))}var ht=class e extends D{constructor(t,n){super(t,{code:`TASK_ERROR`,id:n?.id,details:{taskType:n?.taskType,taskIndex:n?.taskIndex,...n?.details},cause:n?.cause}),Object.setPrototypeOf(this,e.prototype)}};function X(e,t,n={}){if(!Number.isInteger(e))throw Error(`${t} must be an integer`);if(n.min!==void 0&&e<n.min)throw Error(`${t} must be an integer greater than or equal to ${n.min}`);return e}function gt(e){if(e==null)return{type:`error`,error:{type:`Undetermined`,message:`Unknown error occurred`},usage:{in:0,out:0},raw:e};if(e instanceof Error)return{type:`error`,error:{type:e.name||`Error`,message:e.message||`Unexpected error`},usage:{in:0,out:0},raw:e};if(typeof e==`object`){let t=e,n=t?.error?.error?.type||t?.error?.type||t?.type||t?.code||t?.status||`Undetermined`,r=t?.error?.error?.message||t?.error?.message||t?.message||t?.error||`Unexpected error`;return{type:`error`,error:{type:String(n),message:String(r)},usage:{in:0,out:0},raw:e}}return{type:`error`,error:{type:`Undetermined`,message:String(e)},usage:{in:0,out:0},raw:e}}function Z(e,t=`Operation aborted`){if(e?.aborted)throw new k(t,{reason:e.reason})}function _t(e,t,n=`Operation aborted`){return t?t.aborted?Promise.reject(new k(n,{reason:t.reason})):new Promise((r,i)=>{let a=()=>{t.removeEventListener(`abort`,a),i(new k(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 vt(e,t,n=`[redacted]`){return yt(e,null,t,n)}function yt(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=>yt(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=yt(a,t,n,r);return i}const bt=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function xt(e){return vt(e,bt,`[redacted-file-value]`)}const St=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 Ct({type:`base64`,data:n.data},e,t);if(n.type===`text`)return Ct({type:`text`,content:n.content},e,t);if(n.type===`url`)return Ct({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return Ct(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function Ct(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 wt=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function Tt(e){return e.startsWith(`text/`)||wt.has(e)}function Et(e){let t=h.getType(e);if(!t){let t=y(e).toLowerCase();throw Error(`Unsupported file type: ${t||`(no extension)`}`)}if(t.startsWith(`image/`))return{kind:`image`,mimeType:t};if(t===`application/pdf`)return{kind:`document`,mimeType:t};if(Tt(t))return{kind:`text`,mimeType:t};{let n=y(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function Dt(e,t){let n=b(e);try{await g(n)}catch{throw Error(`File not found: ${e}`)}let r=await v(n);if(r.size>St)throw Error(`File too large: ${r.size} bytes. Maximum allowed: ${St} 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 _(n,`utf-8`);return{kind:`text`,mimeType:a.mimeType,size:r.size,name:i,source:{type:`text`,content:t}}}else{if(a.kind===`text`)throw Error(`Cannot read text file as binary: ${e}`);let t=(await _(n)).toString(`base64`);return{kind:a.kind,mimeType:a.mimeType,size:r.size,name:i,source:{type:`base64`,data:t}}}}async function Ot(e,t={model:``}){return Promise.all(e.map(e=>kt(e,t)))}async function kt(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 Wt(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 At(r.file,t,`user-message`));return{role:`user`,content:n}}}async function At(e,t,n){if(e.kind===`image`)return{type:`image`,source:Mt(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:Nt(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 jt(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 Mt(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:jt(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function Nt(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 Pt(e,t=``){return e===!0?Ft(t)?{thinking:{type:`adaptive`},output_config:{effort:`high`}}:{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function Ft(e){let t=e.toLowerCase().match(/claude-(opus|sonnet)-(\d+)-(\d+)/);if(!t)return!1;let[,n,r,i]=t,a=Number(r),o=Number(i);return!Number.isFinite(a)||!Number.isFinite(o)?!1:n===`opus`||n===`sonnet`?a>4||a===4&&o>=6:!1}function It(e){return e.map(e=>{let t=l.toJSONSchema(e.schema);if(!Ut(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}const Lt={web_search:`web_search_20250305`};function Rt(e){return(e??[]).map(e=>({type:Lt[e.name]??e.name,name:e.name,...e.config}))}function zt(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 Bt(e){let t=[];for(let n of e)if(n.type===`text`){let e=n.citations?.map(Vt);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 Vt(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 Ut(e){return e&&typeof e==`object`&&e.type===`object`}async function Wt(e,t){return Promise.all(e.map(async e=>e.type===`text`?{type:`text`,text:e.text}:At(e.file,t,`tool-result`)))}async function Gt(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v;try{Z(g,`Generate aborted`);let e=await Ot(r,{model:n,fileResolver:s?.fileResolver,signal:g}),y={model:n,max_tokens:l??16e3,messages:e,...i&&{system:i},...f&&{stop_sequences:ze(f)},...(a||o)&&{tools:[...a?It(a):[],...Rt(o)]},...Pt(c,n),...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...zt(p,m,a,o),...h};_?.debug(`Anthropic request`,{request:xt(y)});let b=await _t(t.messages.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);Z(g,`Generate aborted`),v=Kt(b)}catch(e){Z(g,`Generate aborted`),v=gt(e)}return _?.debug(`Anthropic response`,{result:v}),v}function Kt(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:Jt(e.usage),raw:e};if(t===`function_call`){let t=Bt(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:M(t),usage:Jt(e.usage),raw:e}}if(e.type==`message`){let n=Bt(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:M(n),usage:Jt(e.usage),raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:Jt(e.usage),raw:e}}function qt(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)}function Jt(e){return q({in:qt(e),out:e.output_tokens},{cachedIn:e.cache_read_input_tokens??void 0,cacheWriteIn:e.cache_creation_input_tokens??void 0})}function Yt(){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:q({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:Vt(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: ${ie(e.argumentsBuffer)}`)}o.delete(s.index)}}e.delete(s.index);break}}return c}return{handleEvent:s}}async function*Xt(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span,v=[...a?It(a):[],...Rt(o)],y=Yt();try{let e=await Ot(r,{model:n,fileResolver:s?.fileResolver,signal:c}),b={model:n,max_tokens:u??Zt(n),messages:e,...i&&{system:i},...p&&{stop_sequences:ze(p)},...v.length>0&&{tools:v},...Pt(l,n),...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...zt(m,h,a,o),...g};_?.debug(`Anthropic streaming request`,{request:xt(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 Zt(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 Qt(e,t={}){let n=new m({apiKey:e,maxRetries:X(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`anthropic`,async createGenerationRequest(e,t){return await Gt({client:n,model:e,...t})},createStreamingRequest(e,t){return Xt({client:n,model:e,...t})}}}const $t={Models:i,DefaultModel:s};async function en(e,t={}){let n=X(t.maxRetries??2,`maxRetries`,{min:0}),r=t.timeoutMs===void 0?void 0:X(t.timeoutMs,`timeoutMs`,{min:1}),i=0;for(;;){Z(t.signal,`Request aborted`);let a=tn(t.signal,r);try{let r=await _t(e({signal:a.signal}),a.signal,`Request aborted`);if(!nn(r.status)||i>=n)return r;let o=rn(r,i);t.onRetry?.({attempt:i+1,delayMs:o,status:r.status}),await on(o,t.signal),i+=1}catch(e){if(Z(t.signal,`Request aborted`),i>=n)throw e;let r=rn(void 0,i);t.onRetry?.({attempt:i+1,delayMs:r,error:e}),await on(r,t.signal),i+=1}finally{a.cleanup()}}}function tn(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 nn(e){return e===408||e===409||e===429||e>=500}function rn(e,t){let n=an(e);if(n!==void 0)return n;let r=Math.min(500*2**t,8e3);return r+Math.floor(Math.random()*r*.25)}function an(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 on(e,t){if(e<=0){Z(t,`Request aborted`);return}await new Promise((n,r)=>{let i,a=()=>{clearTimeout(i),t?.removeEventListener(`abort`,o)},o=()=>{a(),r(new DOMException(`Request aborted`,`AbortError`))},s=()=>{a(),n()};if(t?.aborted){o();return}i=setTimeout(s,e),t?.addEventListener(`abort`,o,{once:!0})}),Z(t,`Request aborted`)}const sn={web_search:`openrouter:web_search`};function cn(e,t){let n=[];for(let r of e){let e=sn[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 ln(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 un(e){let t=e.outputSpan;return!t||t.start===void 0&&t.end===void 0?!1:t.start!==0||t.end!==0}async function dn(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>vn(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function fn(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`none`}:{}}function pn(e){return q({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 mn(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 hn(e,t,n){if(!(!e||e.length===0)){if(!t){n?.(`providerTools not supported by ChatCompletions provider`);return}switch(t){case`openrouter`:return cn(e,n)}}}function gn(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 _n(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 vn(e,t){switch(e.role){case`tool`:return yn(e,t);case`assistant`:return bn(e);default:return xn(e,t)}}async function yn(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await Cn(e.content,t),tool_call_id:e.id})))}function bn(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 xn(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>Sn(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 Sn(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?wn(e.file,t,`user-message`):null}async function Cn(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(Dn(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(`
|
|
13
|
+
`)}async function wn(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:Dn(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:En(r,e)}}}return{type:`image_url`,image_url:{url:Tn(await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}}}function Tn(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 En(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 Dn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}async function On(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?.span,S;try{Z(b,`Generate aborted`);let e=await dn(r,i,{model:n,fileResolver:s?.fileResolver,signal:b}),C=mn(a),w=hn(o,l,x?.warn.bind(x)),T=[...C??[],...w??[]],E={model:n,messages:e,...T.length>0?{tools:T}:{},...fn(f),...p===void 0?{}:{max_tokens:p},...m===void 0?{}:{temperature:m},...h===void 0?{}:{top_p:h},...g===void 0?{}:{stop:g},...gn(_,a,o),...v===void 0?{}:{parallel_tool_calls:v},...y};x?.debug(`ChatCompletions request`,{model:E.model,messages:E.messages.length,tools:E.tools?.length??0}),x?.trace(`ChatCompletions request body`,{request:xt(E)});let D={"Content-Type":`application/json`};c&&(D.Authorization=`Bearer ${c}`);let O=await en(({signal:e})=>fetch(`${t}/chat/completions`,{method:`POST`,headers:D,body:JSON.stringify(E),signal:e}),{maxRetries:u,timeoutMs:d,signal:b,onRetry:e=>x?.warn(`ChatCompletions request retry`,{attempt:e.attempt,maxRetries:u,timeoutMs:d,delayMs:e.delayMs,status:e.status,error:e.error instanceof Error?e.error.message:void 0})});if(!O.ok){let e=await O.text().catch(()=>``);throw Error(`HTTP error! status: ${O.status}${e?` - ${e}`:``}`)}let k=await _t(O.json(),b,`Generate aborted`);Z(b,`Generate aborted`),S=kn(k)}catch(e){Z(b,`Generate aborted`),x?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),S=gt(e)}return x?.trace(`ChatCompletions response`,{result:S}),S}function kn(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(ln).filter(e=>e!==null),a=i.filter(un),o=i.filter(e=>!un(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`)?_n(`tool_calls`):_n(t.finish_reason);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:s,content:n,text:M(n),usage:pn(e.usage),raw:e}}function An(){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=pn(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(ln).filter(e=>e!==null),r=a===`text`?e.filter(un):[];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: ${ie(t.argumentsBuffer)}`)}e.clear(),o=_n(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*jn(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?.span,S=An();try{let e=await dn(r,i,{model:n,fileResolver:s?.fileResolver,signal:c}),C=mn(a),w=hn(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}:{},...fn(p),...m===void 0?{}:{max_tokens:m},...h===void 0?{}:{temperature:h},...g===void 0?{}:{top_p:g},..._===void 0?{}:{stop:_},...gn(v,a,o),...y===void 0?{}:{parallel_tool_calls:y},...b};x?.debug(`ChatCompletions request`,{model:E.model,messages:E.messages.length,tools:E.tools?.length??0,stream:!0}),x?.trace(`ChatCompletions request body`,{request:xt(E)});let D={"Content-Type":`application/json`};l&&(D.Authorization=`Bearer ${l}`);let O=await en(({signal:e})=>fetch(`${t}/chat/completions`,{method:`POST`,headers:D,body:JSON.stringify(E),signal:e}),{maxRetries:d,timeoutMs:f,signal:c,onRetry:e=>x?.warn(`ChatCompletions streaming request retry`,{attempt:e.attempt,maxRetries:d,timeoutMs:f,delayMs:e.delayMs,status:e.status,error:e.error instanceof Error?e.error.message:void 0})});if(!O.ok){let e=await O.text().catch(()=>``);throw Error(`HTTP error! status: ${O.status}${e?` - ${e}`:``}`)}if(!O.body)throw Error(`Response body is null`);let k=O.body.getReader(),A=new TextDecoder,j=``;for(;;){let{done:e,value:t}=await k.read();if(e)break;j+=A.decode(t,{stream:!0});let n=j.split(`
|
|
14
|
+
`);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=Mn(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 Mn(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 Nn(e,t,n){let r=typeof t==`string`?t:t?.apiKey,i=typeof t==`string`?n:t,a=X(i?.maxRetries??2,`maxRetries`,{min:0}),o=i?.timeoutMs===void 0?void 0:X(i.timeoutMs,`timeoutMs`,{min:1}),s=i?.providerToolVendor;return{name:`ChatCompletions`,async createGenerationRequest(t,n){return await On({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,providerToolVendor:s,...n})},createStreamingRequest(t,n){return jn({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,providerToolVendor:s,...n})}}}function Pn(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 Fn={web_search:`googleSearch`,code_execution:`codeExecution`};function In(e,t){if(!(!t||t.length===0)){e.tools||=[];for(let n of t){let t=Fn[n.name]??n.name;e.tools.push({[t]:n.config??{}})}}}function Ln(e,t,n,r){if(t===!1)throw Error(`Gemini does not support disabling parallel tool calls`);if(e===void 0)return{};if(e===`auto`)return{toolConfig:{functionCallingConfig:{mode:S.AUTO}}};if(e===`none`)return{toolConfig:{functionCallingConfig:{mode:S.NONE}}};if(e===`required`){if(!n||n.length===0)throw Error(`Gemini requires function tools for required tool choice`);return{toolConfig:{functionCallingConfig:{mode:S.ANY}}}}if(n?.some(t=>t.name===e.name))return{toolConfig:{functionCallingConfig:{mode:S.ANY,allowedFunctionNames:[e.name]}}};throw r?.some(t=>t.name===e.name)?Error(`Gemini does not support provider tool choice: ${e.name}`):Error(`Tool choice references an unavailable tool: ${e.name}`)}function Rn(e){return e===!0?{thinkingConfig:{thinkingBudget:8192,includeThoughts:!0}}:e===!1?{thinkingConfig:{thinkingBudget:0}}:{}}async function zn(e,t={model:``}){return(await Promise.all(e.map(e=>Bn(e,t)))).filter(e=>e!==void 0)}async function Bn(e,t){switch(e.role){case`tool`:return Vn(e,t);case`assistant`:return Hn(e);case`user`:return Un(e,t)}}async function Vn(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(`
|
|
15
|
+
`),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=>Gn(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 Un(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>Wn(e,t)))).filter(e=>e!==null)}}async function Wn(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?Gn(e.file,t,`user-message`):null}async function Gn(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:qn(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 Kn(await Q(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function Kn(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 qn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function Jn(e){switch(e){case x.STOP:return[!0,`stop`];case x.MAX_TOKENS:return[!0,`length`];case x.FINISH_REASON_UNSPECIFIED:case x.SAFETY:case x.RECITATION:case x.LANGUAGE:case x.OTHER:case x.BLOCKLIST:case x.PROHIBITED_CONTENT:case x.SPII:case x.MALFORMED_FUNCTION_CALL:case x.IMAGE_SAFETY:return[!1,`error`]}return[!1,`error`]}async function Yn(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v={...Rn(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]},...Ln(p,m,a,o),...h},y;try{Z(g,`Generate aborted`);let e=await zn(r,{model:n,fileResolver:s?.fileResolver,signal:g}),c=Pn(a,i,v);p!==`none`&&In(c,o);let l={contents:e,config:c};_?.debug(`Gemini request`,{request:xt(l)});let u=await _t(t.models.generateContent({model:n,...l}),g,`Generate aborted`);Z(g,`Generate aborted`),y=Xn(u,{span:_})}catch(e){Z(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),y=gt(e)}return _?.debug(`Gemini response`,{result:y}),y}function Xn(e,t){let{span:n}=t,r=e.usageMetadata?.promptTokenCount??0,i=q({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]=Jn(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=Qn(a,e);Zn(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:M(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function Zn(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 Qn(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($n(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 $n(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 er(){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 tr(m)){let r=e===void 0?t:u.get(e);if(r===void 0||r<0){console.warn(`[Gemini] received citation without a resolvable text part`,{citation:n});continue}p.push({type:`text-citation`,data:{index:r,citation:n}})}if(m.finishReason&&m.finishReason!==x.FINISH_REASON_UNSPECIFIED){d(p);let[e,t]=Jn(m.finishReason),r=n?`function_call`:t;!e&&!n?p.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${m.finishReason}`,usage:q({in:a,out:o},{cachedIn:s,reasoningOut:c}),raw:f}}):p.push({type:`complete`,data:{finishReason:r,usage:q({in:a,out:o},{cachedIn:s,reasoningOut:c})}})}return p}return{handleChunk:f}}function tr(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:nr(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 nr(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*rr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span,v=Pn(a,i,{...Rn(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]},...Ln(m,h,a,o),...g});m!==`none`&&In(v,o);let y=er();try{let e={contents:await zn(r,{model:n,fileResolver:s?.fileResolver,signal:c}),config:v};_?.debug(`Gemini streaming request`,{request:xt(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 ir(e,t={}){let n=new C({apiKey:e,httpOptions:{retryOptions:{attempts:ar(t.maxRetries)},...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}}});return{name:`Gemini`,async createGenerationRequest(e,t){return await Yn({client:n,model:e,...t})},createStreamingRequest(e,t){return rr({client:n,model:e,...t})}}}function ar(e=2){return X(e,`maxRetries`,{min:0})+1}const or={Models:r,DefaultModel:n};async function sr(e){let{provider:t,model:n,messages:r,system:i,tools:a,providerTools:o,span:s,fileResolver:c,...l}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,providerTools:o,runtime:{span:s,fileResolver:c},...l})}async function cr(e){if(`instruct`in e){let{instruct:t,messages:n,...r}=e,i=pe(t),a=await lr({...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 lr(e)}async function lr(e){let{provider:t,model:n,messages:r,system:i,onToolCall:a,maxIterations:o,span: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=Oe(e),y=[...r],b=[],x=G(),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:ve(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:ve(t.usage),finishReason:t.finishReason}),e.end()};try{for(;;){if(Z(_,`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 sr({provider:t,model:n,messages:y,system:i,tools:D,providerTools:O.length>0?O:void 0,span:e,fileResolver:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_}),Z(_,`Generate aborted`)}catch(t){throw t instanceof Error&&t.name===`AbortError`&&e?.end(`ok`),t}if(Se(x,k,{provider:t.name,model:k.type===`error`?n:k.model??n}),k.type!==`error`&&Ce(e,k.content),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=N(k.content);if(j.length===0)return T({ok:!0,response:C,messages:b,final:C,usage:x});let{results:ee,usage:M}=await ke(j,a,_,v,s);K(x,M),Z(_,`Generate aborted`),ee.length>0&&w({role:`tool`,id:crypto.randomUUID(),content:ee})}}catch(e){throw e instanceof j?(s?.end(`error`),new j(e.message,{toolName:e.toolName,messages:e.messages??b,partial:e.partial??C,usage:he(x,e.usage),cause:e.cause})):e instanceof k?(s?.end(`ok`),new k(`Generate aborted`,{reason:e.reason,messages:e.messages??b,partial:e.partial,usage:he(x,e.usage)})):e instanceof Error&&e.name===`AbortError`?(s?.end(`ok`),new k(`Generate aborted`,{reason:_.reason,messages:b,usage:x})):e}}function ur(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 dr={web_search:`web_search_preview`,code_execution:`code_interpreter`};function fr(e){return e?.map(e=>({type:dr[e.name]??e.name,...e.config}))}function pr(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:dr[r.name]??r.name}};throw Error(`Tool choice references an unavailable tool: ${e.name}`)}function mr(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`none`}}:{}}async function hr(e,t={model:``}){return(await Promise.all(e.map(e=>gr(e,t)))).flat(1)}async function gr(e,t){switch(e.role){case`tool`:return _r(e,t);case`assistant`:return vr(e);default:return yr(e,t)}}async function _r(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}):xr(e.file,t,`tool-result`)))})))}function vr(e){let t=[],n=M(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 yr(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>br(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function br(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?xr(e.file,t,`user-message`):(e.type,null)}async function xr(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:Sr(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 Cr(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}:Cr(r,e)}function Sr(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 Cr(e,t){if(e.type===`url`)return{type:`input_file`,filename:e.name??t.name,file_url:e.url};if(e.type===`base64`)return{type:`input_file`,filename:e.name??t.name,file_data:`data:${e.mimeType??t.mimeType};base64,${e.data}`};throw Error(`Unsupported OpenAI file source: ${e.type}`)}async function wr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v;try{if(Z(g,`Generate aborted`),f!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let e=[...ur(a)??[],...fr(o)??[]],y={model:n,input:await hr(r,{model:n,fileResolver:s?.fileResolver,signal:g}),...i&&{instructions:i},...e.length>0?{tools:e}:{},...mr(c),...l===void 0?{}:{max_output_tokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...pr(p,a,o),...m===void 0?{}:{parallel_tool_calls:m},...h};_?.debug(`OpenAI ResponsesAPI request`,{request:xt(y)});let b=await _t(t.responses.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);Z(g,`Generate aborted`),v=Tr(b)}catch(e){Z(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),v=gt(e)}return _?.debug(`OpenAI ResponsesAPI response`,{result:v}),v}function Tr(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:Or(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=Er(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:M(n),usage:Or(e.usage),raw:e}}function Er(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(Dr).filter(e=>e!==null);t.push({type:`text`,text:e.text,...n.length>0?{citations:n}:{}})}return t}function Dr(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 Or(e){return q({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 kr(){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=Ar(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=Ar(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=jr(u.annotation);if(!e)break;let t=a.get(Ar(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:q({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 Ar(e,t){return`${e}:${t}`}function jr(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*Mr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span;if(p!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let v=[...ur(a)??[],...fr(o)??[]],y=kr();try{let e={model:n,input:await hr(r,{model:n,fileResolver:s?.fileResolver,signal:c}),...i&&{instructions:i},stream:!0,...v.length>0?{tools:v}:{},...mr(l),...u===void 0?{}:{max_output_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...pr(m,a,o),...h===void 0?{}:{parallel_tool_calls:h},...g};_?.debug(`OpenAI ResponsesAPI streaming request`,{request:xt(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 Nr(e,t={}){let n=new w({apiKey:e,maxRetries:X(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`OpenAI`,async createGenerationRequest(e,t){return await wr({client:n,model:e,...t})},createStreamingRequest(e,t){return Mr({client:n,model:e,...t})}}}const Pr={Models:a,DefaultModel:o};function Fr(e){return{kind:`agent`,name:e.name,description:e.description,schema:e.schema,async execute(t,n){let r=await e.createAgent(t,n),i=Ir(e.prompt,t),a=r.on(e=>n.emit({type:`turn-event`,event:e})),o;try{o=await r.send(i,{...e.request,signal:n.signal}).final}catch(t){throw Lr(t,e.name)}finally{a()}if(o.usage&&n.reportUsage?.(o.usage),!o.ok)throw Error(`Subagent failed: ${JSON.stringify(o.error)}`);let s=o.response;return typeof s==`string`?s:JSON.stringify(s)}}}function Ir(e,t){return typeof e==`function`?e(t):typeof e==`string`?e:`Complete this delegated task. Input: ${JSON.stringify(t)}`}function Lr(e,t){return e instanceof j?new j(e.message,{toolName:t,usage:e.usage,cause:e}):e instanceof k?new k(e.message,{reason:e.reason,usage:e.usage}):e}function Rr(e,t={}){let n=t.maxItems??50,r=Math.max(1,t.maxConcurrency??8),i=u.object({items:u.array(e.schema).min(1).max(n).describe(`Inputs to run through ${e.name}. Results are returned in the same order.`)});return{...e.kind?{kind:e.kind}:{},name:t.name??`${e.name}_batch`,description:t.description??`Run ${e.name} for multiple inputs concurrently and return ordered per-item results.`,schema:i,async execute(t,n){let i=await zr(t.items,r,n.signal,async(t,r)=>{try{return{index:r,input:t,ok:!0,output:await e.execute(t,n)}}catch(e){if(e instanceof j||e instanceof k)throw e;return{index:r,input:t,ok:!1,error:{type:`execution`,message:e instanceof Error?e.message:String(e)}}}});return JSON.stringify({results:i})}}}async function zr(e,t,n,r){let i=Array(e.length),a=0,o=!1,s=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:s},async()=>{for(;!o&&a<e.length;){if(n.aborted)throw o=!0,new k(`Operation aborted`,{reason:n.reason});let t=a++;try{i[t]=await r(e[t],t)}catch(e){throw o=!0,e}}})),i}const Br={trace:0,debug:1,info:2,warn:3,error:4};var Vr=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 Br[e]>=Br[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 Hr(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(`
|
|
16
|
+
`);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 Hr(e){return Ur(E.lexer(e))}function Ur(e=[]){return e.map(e=>Wr(e)).filter(e=>e.length>0).join(`
|
|
17
|
+
`)}function Wr(e){switch(e.type){case`space`:return``;case`heading`:return T.bold($(e.tokens));case`paragraph`:return $(e.tokens);case`blockquote`:return Xr(Ur(e.tokens),`> `);case`code`:return(e.lang?T.dim(`${e.lang}\n`):``)+T.yellow(e.text);case`list`:return Kr(e)?Jr(e):e.raw;case`hr`:return T.dim(`-`.repeat(40));case`table`:return qr(e)?Yr(e):e.raw;case`html`:return e.text;case`text`:return e.tokens?$(e.tokens):Qr(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 Qr(e.text);case`strong`:return T.bold($(e.tokens));case`em`:return T.italic($(e.tokens));case`codespan`:return T.yellow(e.text);case`del`:return T.strikethrough($(e.tokens));case`link`:{let t=$(e.tokens);return e.href&&e.href!==e.text?`${T.blue.underline(t)} ${T.dim(`(${e.href})`)}`:T.blue.underline(t)}case`image`:return e.text?`${e.text} (${e.href})`:e.href;case`br`:return`
|
|
18
|
+
`;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function Kr(e){return e.type===`list`&&`items`in e&&Array.isArray(e.items)}function qr(e){return e.type===`table`&&`header`in e&&`rows`in e}function Jr(e){return e.items.map((t,n)=>{let r=e.ordered?`${Number(e.start||1)+n}. `:`- `,i=t.task?`[${t.checked?`x`:` `}] `:``,a=Ur(t.tokens).trimEnd();return r+i+Zr(a,r.length+i.length)}).join(`
|
|
19
|
+
`)}function Yr(e){let t=e.header.map(e=>$(e.tokens)).join(` | `),n=e.rows.map(e=>e.map(e=>$(e.tokens)).join(` | `));return[T.bold(t),...n].join(`
|
|
20
|
+
`)}function Xr(e,t){return e.split(`
|
|
21
21
|
`).map(e=>t+e).join(`
|
|
22
|
-
`)}function
|
|
22
|
+
`)}function Zr(e,t){let[n=``,...r]=e.split(`
|
|
23
23
|
`);if(r.length===0)return n;let i=` `.repeat(t);return[n,...r.map(e=>i+e)].join(`
|
|
24
|
-
`)}function
|
|
24
|
+
`)}function Qr(e){return e.replace(/"/g,`"`).replace(/'/g,`'`).replace(/</g,`<`).replace(/>/g,`>`).replace(/&/g,`&`)}export{Qe as Agent,$t as Anthropic,k as AxleAbortError,A as AxleAgentAbortError,D as AxleError,Ne as AxleStopReason,j as AxleToolFatalError,or as Gemini,He as History,pt as Instruct,ct as InstructVariableError,F as LogWriter,at as MCP,Pr as OpenAI,Vr as SimpleWriter,ht as TaskError,xe as ToolRegistry,Ke as Tracer,e as TurnAccumulator,Re as TurnEventBuilder,K as addStats,Qt as anthropic,Nn as chatCompletions,st as createAgentConfig,Fr as createAgentTool,Ve as createHandle,G as createStats,L as estimateContextUsage,ir as gemini,cr as generate,sr as generateTurn,Dt as loadFileContent,he as mergeStats,Nr as openai,Rr as parallelize,de as parseResponse,Fe as stream};
|
package/dist/ui.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
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 };
|
|
1
|
+
import { A as TurnPart, C as SubagentAction, D as ToolAction, E as TimingInfo, L as Citation, O as Turn, R as CitationOutputSpan, S as ProviderToolAction, T as ThinkingPart, Y as ThinkingContinuity, _ as Annotation, _t as UsageEntry, a as UnknownEvent, b as CitationPart, f as AnnotationEvent, g as ActionResult, gt as TokenStats, h as ActionPart, ht as Stats, i as TurnAccumulatorState, j as TurnStatus, k as TurnMetadata, m as TurnEvent, n as TurnAccumulator, p as AnnotationTarget, q as DocumentLocator, r as TurnAccumulatorResult, st as FileInfo, t as AccumulatableEvent, v as AnnotationPlacement, w as TextPart, x as FilePart, y as AnnotationStatus, z as CitationSource } from "./accumulator-CblCRkql.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 TokenStats, type ToolAction, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, type TurnMetadata, type TurnPart, type TurnStatus, type UnknownEvent, type UsageEntry };
|
package/dist/ui.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./accumulator-
|
|
1
|
+
import{t as e}from"./accumulator-BnFn9yqM.js";export{e as TurnAccumulator};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e=class{_state;constructor(e){this._state={turns:e?.turns??[],sessionAnnotations:e?.sessionAnnotations}}get state(){return this._state}apply(e){let t=e;switch(e.type){case`session:restore`:return this.replaceState({turns:t.turns??[],sessionAnnotations:t.sessionAnnotations},e);case`turn:user`:return this.replaceTurns([...this._state.turns,t.turn],e);case`turn:start`:{let n={id:t.turnId,owner:`agent`,parts:[],status:`streaming`,...t.timing?{timing:t.timing}:{}};return this.replaceTurns([...this._state.turns,n],e)}case`part:start`:return this.updateTurn(t.turnId,e,e=>({...e,parts:[...e.parts,t.part]}));case`text:delta`:return this.updatePart(t.turnId,t.partId,e,e=>e.type===`text`?{...e,text:e.text+t.delta}:e);case`text:citation`:return this.updatePart(t.turnId,t.partId,e,e=>e.type===`text`?{...e,citations:[...e.citations??[],t.citation]}:e);case`thinking:delta`:return this.updatePart(t.turnId,t.partId,e,e=>e.type===`thinking`?{...e,text:(e.text??``)+t.delta}:e);case`thinking:summary-delta`:return this.updatePart(t.turnId,t.partId,e,e=>e.type===`thinking`?{...e,summary:(e.summary??``)+t.delta}:e);case`thinking:update`:return this.updatePart(t.turnId,t.partId,e,e=>e.type===`thinking`?{...e,...t.redacted===void 0?{}:{redacted:t.redacted},...t.continuity?{continuity:t.continuity}:{},...t.providerMetadata?{providerMetadata:t.providerMetadata}:{}}:e);case`part:end`:return this.updatePart(t.turnId,t.partId,e,e=>({...e,timing:t.timing??e.timing}));case`action:args-delta`:return this.updatePart(t.turnId,t.partId,e,e=>e.type!==`action`||e.kind!==`tool`?e:{...e,detail:{...e.detail,pendingArgs:t.accumulated}});case`action:running`:return this.updatePart(t.turnId,t.partId,e,e=>{if(e.type!==`action`)return e;if(e.kind===`tool`){let{pendingArgs:n,...r}=e.detail;return{...e,status:`running`,detail:t.parameters?{...r,parameters:t.parameters}:r}}return{...e,status:`running`}});case`action:progress`:return this.updatePart(t.turnId,t.partId,e,e=>{if(e.type!==`action`)return e;let n=e.detail.result,r=n?.type===`in-progress`?n.content:``;return{...e,detail:{...e.detail,result:{type:`in-progress`,content:r+t.chunk}}}});case`action:complete`:return this.updatePart(t.turnId,t.partId,e,e=>e.type===`action`?{...e,status:`complete`,detail:{...e.detail,result:t.result},timing:t.timing??e.timing}:e);case`action:error`:return this.updatePart(t.turnId,t.partId,e,e=>e.type===`action`?{...e,status:`error`,detail:{...e.detail,result:{type:`error`,error:t.error}},timing:t.timing??e.timing}:e);case`turn:end`:return this.updateTurn(t.turnId,e,e=>({...e,status:t.status,usage:t.usage,timing:t.timing??e.timing}));case`annotation:start`:return this.addAnnotation(e);case`annotation:update`:return this.replaceAnnotation(e,!1);case`annotation:end`:return this.replaceAnnotation(e,!0);case`error`:case`action:child-event`:return this.handled(e);default:return{handled:!1,state:this._state,event:e}}}replaceState(e,t){return this._state=e,this.handled(t)}replaceTurns(e,t){return this.replaceState({...this._state,turns:e},t)}updateTurn(e,t,n){let r=!1,i=this._state.turns.map(t=>{if(t.id!==e)return t;let i=n(t);return i===t?t:(r=!0,i)});return r?this.replaceTurns(i,t):this.handled(t)}updatePart(e,t,n,r){return this.updateTurn(e,n,e=>{let n=!1,i=e.parts.map(e=>{if(e.id!==t)return e;let i=r(e);return i===e?e:(n=!0,i)});return n?{...e,parts:i}:e})}addAnnotation(e){let n=e,r=n.target,i=t(n.annotation);return!r||!i?this.handled(e):r.type===`session`?this.replaceState({...this._state,sessionAnnotations:[...this._state.sessionAnnotations??[],i]},e):r.type===`turn`?this.updateTurn(r.turnId,e,e=>({...e,annotations:[...e.annotations??[],i]})):r.type===`part`?this.updatePart(r.turnId,r.partId,e,e=>({...e,annotations:[...e.annotations??[],i]})):this.handled(e)}replaceAnnotation(e,r){let i=e,a=i.target,o=t(i.annotation,r);if(!a||!o)return this.handled(e);if(a.type===`session`){let t=n(this._state.sessionAnnotations,o);return t?this.replaceState({...this._state,sessionAnnotations:t},e):this.handled(e)}return a.type===`turn`?this.updateTurn(a.turnId,e,e=>{let t=n(e.annotations,o);return t?{...e,annotations:t}:e}):a.type===`part`?this.updatePart(a.turnId,a.partId,e,e=>{let t=n(e.annotations,o);return t?{...e,annotations:t}:e}):this.handled(e)}handled(e){return{handled:!0,state:this._state,event:e}}};function t(e,t=!1){if(!e)return;let n=t?e.status??`complete`:e.status,r={...e,placement:e.placement??`after`};return n?{...r,status:n}:r}function n(e,t){if(!e)return;let n=!1,r=e.map(e=>e.id===t.id?(n=!0,t):e);return n?r:void 0}export{e as t};
|