@fifthrevision/axle 0.25.5 → 0.26.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.
@@ -773,6 +773,33 @@ interface ContentPartCitation {
773
773
  providerMetadata?: Record<string, unknown>;
774
774
  }
775
775
  //#endregion
776
+ //#region src/messages/compaction.d.ts
777
+ /**
778
+ * Record of one applied compaction: when it happened. Inspection only —
779
+ * records carry no message content and cannot reconstruct the pre-compaction
780
+ * conversation.
781
+ *
782
+ * @experimental Compaction is under active design and may change in any release.
783
+ */
784
+ interface CompactionRecord {
785
+ /** Stable record id. Shared with the compaction turn. */
786
+ id: string;
787
+ /** ISO timestamp for when the compaction ran. */
788
+ at: string;
789
+ }
790
+ /**
791
+ * Validate that a compacted conversation is structurally well-formed.
792
+ *
793
+ * The messages must stand alone: every tool call must be answered by the
794
+ * tool message(s) immediately following it — providers reject conversations
795
+ * that interleave other messages between a call and its result — and every
796
+ * tool result must answer a preceding call.
797
+ *
798
+ * @experimental Compaction is under active design and may change in any release.
799
+ * @throws AxleError with code `COMPACTION_INVALID_MESSAGES`
800
+ */
801
+ declare function validateCompactedMessages(messages: AxleMessage[]): void;
802
+ //#endregion
776
803
  //#region src/turns/types.d.ts
777
804
  /**
778
805
  * Lifecycle state for a renderable turn.
@@ -863,7 +890,7 @@ interface Turn<TAnnotation extends Annotation = Annotation> {
863
890
  /**
864
891
  * Any renderable part within a turn.
865
892
  */
866
- type TurnPart<TAnnotation extends Annotation = Annotation> = TextPart<TAnnotation> | CitationPart<TAnnotation> | FilePart<TAnnotation> | ThinkingPart<TAnnotation> | ActionPart<TAnnotation>;
893
+ type TurnPart<TAnnotation extends Annotation = Annotation> = TextPart<TAnnotation> | CitationPart<TAnnotation> | FilePart<TAnnotation> | ThinkingPart<TAnnotation> | ActionPart<TAnnotation> | CompactionPart<TAnnotation>;
867
894
  /**
868
895
  * Assistant or user text content.
869
896
  */
@@ -938,6 +965,28 @@ interface ThinkingPart<TAnnotation extends Annotation = Annotation> {
938
965
  /** Optional timing metadata. */
939
966
  timing?: TimingInfo;
940
967
  }
968
+ /**
969
+ * Part marking a compaction of the model-facing conversation.
970
+ *
971
+ * Compaction renders as an agent turn containing this single part. The turn's
972
+ * `status` carries the lifecycle: `"streaming"` while the compaction callback
973
+ * runs, `"complete"` once applied, `"error"` on failure. Skipped compactions
974
+ * are removed from the turns, not settled.
975
+ *
976
+ * @experimental Compaction is under active design and may change in any release.
977
+ */
978
+ interface CompactionPart<TAnnotation extends Annotation = Annotation> {
979
+ /** Stable part id. Shared with the compaction record. */
980
+ id: string;
981
+ /** Part discriminator. */
982
+ type: "compaction";
983
+ /** The applied record, present once the compaction completes. */
984
+ record?: CompactionRecord;
985
+ /** Annotations attached to this part. */
986
+ annotations?: TAnnotation[];
987
+ /** Optional timing metadata. */
988
+ timing?: TimingInfo;
989
+ }
941
990
  /**
942
991
  * Shared fields for tool, subagent, and provider-managed actions.
943
992
  *
@@ -1056,6 +1105,16 @@ type TurnEvent<TAnnotation extends Annotation = Annotation> = {
1056
1105
  status: TurnStatus;
1057
1106
  usage: Stats;
1058
1107
  timing?: TimingInfo;
1108
+ } | {
1109
+ type: "compaction:start";
1110
+ id: string;
1111
+ timing?: TimingInfo;
1112
+ } | {
1113
+ type: "compaction:end";
1114
+ id: string;
1115
+ outcome: "complete" | "skipped" | "error";
1116
+ record?: CompactionRecord;
1117
+ timing?: TimingInfo;
1059
1118
  } | {
1060
1119
  type: "part:start";
1061
1120
  turnId: string;
@@ -1222,6 +1281,7 @@ declare class TurnAccumulator<TAnnotation extends Annotation = Annotation, THost
1222
1281
  constructor(init?: TurnAccumulatorState<TAnnotation>);
1223
1282
  get state(): TurnAccumulatorState<TAnnotation>;
1224
1283
  apply(event: AccumulatableEvent<TAnnotation, THostEvent>): TurnAccumulatorResult<TAnnotation, THostEvent>;
1284
+ private applyTurnEvent;
1225
1285
  private replaceState;
1226
1286
  private replaceTurns;
1227
1287
  private updateTurn;
@@ -1231,4 +1291,4 @@ declare class TurnAccumulator<TAnnotation extends Annotation = Annotation, THost
1231
1291
  private handled;
1232
1292
  }
1233
1293
  //#endregion
1234
- export { AxleStopReason as $, TurnPart as A, TokenUsage as At, ContentPart as B, SubagentAction as C, Span as Ct, ToolAction as D, SpanResult as Dt, TimingInfo as E, SpanOptions 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, TraceWriter as Mt, AxleMessage as N, Turn as O, SpanStatus as Ot, AxleToolCallMessage as P, AxleModelRequestOptions as Q, CitationOutputSpan as R, ProviderToolAction as S, LLMResult as St, ThinkingPart as T, SpanEvent as Tt, ContentPartProviderTool as U, ContentPartCitation as V, ContentPartText as W, ToolResultPart as X, ThinkingContinuity as Y, AIProvider as Z, Annotation as _, TokenStats as _t, UnknownEvent as a, ResolvedProviderTool as at, CitationPart as b, LLMRequest as bt, ToolContext as c, FileInfo as ct, ToolRegistry as d, FileResolveFormat as dt, ContextUsage as et, AnnotationEvent as f, FileResolveRequest as ft, ActionResult as g, Stats as gt, ActionPart as h, loadFileContent as ht, TurnAccumulatorState as i, ProviderOptions as it, TurnStatus as j, ToolResult as jt, TurnMetadata as k, SpanType as kt, ToolDefinition as l, FileKind as lt, TurnEvent as m, ResolvedFileSource as mt, TurnAccumulator as n, ModelResult as nt, ExecutableTool as o, ToolChoice as ot, AnnotationTarget as p, FileResolver as pt, DocumentLocator as q, TurnAccumulatorResult as r, ProviderClientOptions as rt, ProviderTool as s, DeferredFileInfo as st, AccumulatableEvent as t, ModelError as tt, ToolProgressChunk as u, FileProviderId as ut, AnnotationPlacement as v, UsageEntry as vt, TextPart as w, SpanData as wt, FilePart as x, LLMResponse as xt, AnnotationStatus as y, EventLevel as yt, CitationSource as z };
1294
+ export { ToolResultPart as $, TurnMetadata as A, SpanResult as At, Citation as B, ProviderToolAction as C, LLMRequest as Ct, TimingInfo as D, SpanData as Dt, ThinkingPart as E, Span as Et, AxleAssistantMessage as F, TraceWriter as Ft, ContentPartFile as G, CitationSource as H, AxleMessage as I, ContentPartThinking as J, ContentPartProviderTool as K, AxleToolCallMessage as L, TurnStatus as M, SpanType as Mt, CompactionRecord as N, TokenUsage as Nt, ToolAction as O, SpanEvent as Ot, validateCompactedMessages as P, ToolResult as Pt, ThinkingContinuity as Q, AxleToolCallResult as R, FilePart as S, EventLevel as St, TextPart as T, LLMResult as Tt, ContentPart as U, CitationOutputSpan as V, ContentPartCitation as W, DocumentLocator as X, ContentPartToolCall as Y, MessageMetadata as Z, Annotation as _, ResolvedFileSource as _t, UnknownEvent as a, ModelResult as at, CitationPart as b, TokenStats as bt, ToolContext as c, ResolvedProviderTool as ct, ToolRegistry as d, FileInfo as dt, AIProvider as et, AnnotationEvent as f, FileKind as ft, ActionResult as g, FileResolver as gt, ActionPart as h, FileResolveRequest as ht, TurnAccumulatorState as i, ModelError as it, TurnPart as j, SpanStatus as jt, Turn as k, SpanOptions as kt, ToolDefinition as l, ToolChoice as lt, TurnEvent as m, FileResolveFormat as mt, TurnAccumulator as n, AxleStopReason as nt, ExecutableTool as o, ProviderClientOptions as ot, AnnotationTarget as p, FileProviderId as pt, ContentPartText as q, TurnAccumulatorResult as r, ContextUsage as rt, ProviderTool as s, ProviderOptions as st, AccumulatableEvent as t, AxleModelRequestOptions as tt, ToolProgressChunk as u, DeferredFileInfo as ut, AnnotationPlacement as v, loadFileContent as vt, SubagentAction as w, LLMResponse as wt, CompactionPart as x, UsageEntry as xt, AnnotationStatus as y, Stats as yt, AxleUserMessage as z };
@@ -0,0 +1 @@
1
+ const e=new Set(Object.keys({"session:restore":!0,"turn:user":!0,"turn:start":!0,"turn:end":!0,"compaction:start":!0,"compaction:end":!0,"part:start":!0,"text:delta":!0,"text:citation":!0,"thinking:delta":!0,"thinking:summary-delta":!0,"thinking:update":!0,"part:end":!0,"action:args-delta":!0,"action:running":!0,"action:progress":!0,"action:complete":!0,"action:error":!0,"action:child-event":!0,"annotation:start":!0,"annotation:update":!0,"annotation:end":!0,error:!0}));function t(t){return e.has(t.type)}var n=class e{_state;constructor(e){this._state={turns:e?.turns??[],sessionAnnotations:e?.sessionAnnotations}}get state(){return this._state}apply(e){return t(e)?this.applyTurnEvent(e):{handled:!1,state:this._state,event:e}}applyTurnEvent(t){switch(t.type){case`session:restore`:return this.replaceState({turns:t.turns??[],sessionAnnotations:t.sessionAnnotations},t);case`turn:user`:return this.replaceTurns([...this._state.turns,t.turn],t);case`turn:start`:{let e={id:t.turnId,owner:`agent`,parts:[],status:`streaming`,...t.timing?{timing:t.timing}:{}};return this.replaceTurns([...this._state.turns,e],t)}case`compaction:start`:{let e={id:t.id,owner:`agent`,parts:[{id:t.id,type:`compaction`}],status:`streaming`,...t.timing?{timing:t.timing}:{}};return this.replaceTurns([...this._state.turns,e],t)}case`compaction:end`:{if(t.outcome===`skipped`){let e=this._state.turns.filter(e=>e.id!==t.id);return e.length===this._state.turns.length?this.handled(t):this.replaceTurns(e,t)}let e=t.outcome===`complete`?`complete`:`error`,n=!1,r=this._state.turns.map(r=>r.id===t.id?(n=!0,{...r,status:e,parts:r.parts.map(e=>e.type===`compaction`&&t.record?{...e,record:t.record}:e),timing:t.timing??r.timing}):r);return n?this.replaceTurns(r,t):this.handled(t)}case`part:start`:return this.updateTurn(t.turnId,t,e=>({...e,parts:[...e.parts,t.part]}));case`text:delta`:return this.updatePart(t.turnId,t.partId,t,e=>e.type===`text`?{...e,text:e.text+t.delta}:e);case`text:citation`:return this.updatePart(t.turnId,t.partId,t,e=>e.type===`text`?{...e,citations:[...e.citations??[],t.citation]}:e);case`thinking:delta`:return this.updatePart(t.turnId,t.partId,t,e=>e.type===`thinking`?{...e,text:(e.text??``)+t.delta}:e);case`thinking:summary-delta`:return this.updatePart(t.turnId,t.partId,t,e=>e.type===`thinking`?{...e,summary:(e.summary??``)+t.delta}:e);case`thinking:update`:return this.updatePart(t.turnId,t.partId,t,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,t,e=>({...e,timing:t.timing??e.timing}));case`action:args-delta`:return this.updatePart(t.turnId,t.partId,t,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,t,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,t,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,t,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,t,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,t,e=>({...e,status:t.status,usage:t.usage,timing:t.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(t.turnId,t.partId,t,n=>{if(n.type!==`action`||n.kind!==`agent`)return n;let r=new e({turns:n.detail.children}).apply(t.event);return{...n,detail:{...n.detail,children:r.state.turns}}});default:return this.handled(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 t=e.target,n=r(e.annotation);return n?t.type===`session`?this.replaceState({...this._state,sessionAnnotations:[...this._state.sessionAnnotations??[],n]},e):t.type===`turn`?this.updateTurn(t.turnId,e,e=>({...e,annotations:[...e.annotations??[],n]})):this.updatePart(t.turnId,t.partId,e,e=>({...e,annotations:[...e.annotations??[],n]})):this.handled(e)}replaceAnnotation(e,t){let n=e.target,a=r(e.annotation,t);if(!a)return this.handled(e);if(n.type===`session`){let t=i(this._state.sessionAnnotations,a);return t?this.replaceState({...this._state,sessionAnnotations:t},e):this.handled(e)}return n.type===`turn`?this.updateTurn(n.turnId,e,e=>{let t=i(e.annotations,a);return t?{...e,annotations:t}:e}):this.updatePart(n.turnId,n.partId,e,e=>{let t=i(e.annotations,a);return t?{...e,annotations:t}:e})}handled(e){return{handled:!0,state:this._state,event:e}}};function r(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 i(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{n as t};
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as AxleStopReason, A as TurnPart, At as TokenUsage, B as ContentPart, C as SubagentAction, Ct as Span, D as ToolAction, Dt as SpanResult, Et as SpanOptions, F as AxleToolCallResult, G as ContentPartThinking, H as ContentPartFile, I as AxleUserMessage, J as MessageMetadata, K as ContentPartToolCall, L as Citation, M as AxleAssistantMessage, Mt as TraceWriter, N as AxleMessage, O as Turn, Ot as SpanStatus, P as AxleToolCallMessage, Q as AxleModelRequestOptions, R as CitationOutputSpan, S as ProviderToolAction, St as LLMResult, T as ThinkingPart, Tt as SpanEvent, U as ContentPartProviderTool, V as ContentPartCitation, W as ContentPartText, X as ToolResultPart, Y as ThinkingContinuity, Z as AIProvider, _ as Annotation, _t as TokenStats, at as ResolvedProviderTool, b as CitationPart, bt as LLMRequest, c as ToolContext, ct as FileInfo, d as ToolRegistry, dt as FileResolveFormat, et as ContextUsage, f as AnnotationEvent, ft as FileResolveRequest, g as ActionResult, gt as Stats, h as ActionPart, ht as loadFileContent, i as TurnAccumulatorState, it as ProviderOptions, j as TurnStatus, jt as ToolResult, k as TurnMetadata, kt as SpanType, l as ToolDefinition, lt as FileKind, m as TurnEvent, mt as ResolvedFileSource, n as TurnAccumulator, nt as ModelResult, o as ExecutableTool, ot as ToolChoice, p as AnnotationTarget, pt as FileResolver, q as DocumentLocator, r as TurnAccumulatorResult, rt as ProviderClientOptions, s as ProviderTool, st as DeferredFileInfo, t as AccumulatableEvent, tt as ModelError, u as ToolProgressChunk, ut as FileProviderId, v as AnnotationPlacement, vt as UsageEntry, w as TextPart, wt as SpanData, x as FilePart, xt as LLMResponse, y as AnnotationStatus, yt as EventLevel, z as CitationSource } from "./accumulator-yYlD8Bfm.js";
1
+ import { $ as ToolResultPart, A as TurnMetadata, At as SpanResult, B as Citation, C as ProviderToolAction, Ct as LLMRequest, Dt as SpanData, E as ThinkingPart, Et as Span, F as AxleAssistantMessage, Ft as TraceWriter, G as ContentPartFile, H as CitationSource, I as AxleMessage, J as ContentPartThinking, K as ContentPartProviderTool, L as AxleToolCallMessage, M as TurnStatus, Mt as SpanType, N as CompactionRecord, Nt as TokenUsage, O as ToolAction, Ot as SpanEvent, P as validateCompactedMessages, Pt as ToolResult, Q as ThinkingContinuity, R as AxleToolCallResult, S as FilePart, St as EventLevel, T as TextPart, Tt as LLMResult, U as ContentPart, V as CitationOutputSpan, W as ContentPartCitation, X as DocumentLocator, Y as ContentPartToolCall, Z as MessageMetadata, _ as Annotation, _t as ResolvedFileSource, at as ModelResult, b as CitationPart, bt as TokenStats, c as ToolContext, ct as ResolvedProviderTool, d as ToolRegistry, dt as FileInfo, et as AIProvider, f as AnnotationEvent, ft as FileKind, g as ActionResult, gt as FileResolver, h as ActionPart, ht as FileResolveRequest, i as TurnAccumulatorState, it as ModelError, j as TurnPart, jt as SpanStatus, k as Turn, kt as SpanOptions, l as ToolDefinition, lt as ToolChoice, m as TurnEvent, mt as FileResolveFormat, n as TurnAccumulator, nt as AxleStopReason, o as ExecutableTool, ot as ProviderClientOptions, p as AnnotationTarget, pt as FileProviderId, q as ContentPartText, r as TurnAccumulatorResult, rt as ContextUsage, s as ProviderTool, st as ProviderOptions, t as AccumulatableEvent, tt as AxleModelRequestOptions, u as ToolProgressChunk, ut as DeferredFileInfo, v as AnnotationPlacement, vt as loadFileContent, w as SubagentAction, wt as LLMResponse, x as CompactionPart, xt as UsageEntry, y as AnnotationStatus, yt as Stats, z as AxleUserMessage } from "./accumulator-BQ_1i4qv.js";
2
2
  import * as z$2 from "zod";
3
3
  import { ZodObject, z } from "zod";
4
4
 
@@ -142,32 +142,72 @@ declare class Instruct<TSchema extends OutputSchema | undefined = undefined> {
142
142
  //#endregion
143
143
  //#region src/core/agent/history.d.ts
144
144
  /**
145
- * In-memory conversation and presentation history for an agent.
145
+ * Complete state for constructing a `History`. Reconstructing from a saved
146
+ * session goes through the constructor — there is no field-by-field mutation.
147
+ */
148
+ interface HistoryInit<TAnnotation extends Annotation = Annotation> {
149
+ turns?: Turn<TAnnotation>[];
150
+ messages?: AxleMessage[];
151
+ archive?: AxleMessage[];
152
+ compactions?: CompactionRecord[];
153
+ sessionAnnotations?: TAnnotation[];
154
+ }
155
+ /**
156
+ * In-memory conversation and presentation state for an agent.
157
+ *
158
+ * All state is private; reads return copies and writes go through
159
+ * use-case-specific methods:
146
160
  *
147
- * `log` is the canonical model-facing message history. `turns` and
148
- * `sessionAnnotations` are renderable presentation state for consumers.
161
+ * - `messages` the active, model-facing conversation. Requests are built
162
+ * from it; compaction replaces it.
163
+ * - `archive` — every message ever appended, in order, untouched by
164
+ * compaction. The chronological record, for inspection only.
165
+ * - `turns` — the renderable session turns: user/agent entries and compaction entries.
166
+ * Forever-accumulating; consumers decide how to render or prune it.
167
+ * - `compactions` — receipts for each applied compaction.
168
+ * - `sessionAnnotations` — session-level render annotations.
149
169
  *
150
170
  * @typeParam TAnnotation - Annotation union supported by the host renderer.
151
171
  */
152
172
  declare class History<TAnnotation extends Annotation = Annotation> {
153
173
  private _turns;
154
- private _log;
174
+ private _messages;
175
+ private _archive;
176
+ private _compactions;
155
177
  private _sessionAnnotations;
156
- constructor(init?: {
157
- turns?: Turn<TAnnotation>[];
158
- log?: AxleMessage[];
159
- sessionAnnotations?: TAnnotation[];
160
- });
178
+ constructor(init?: HistoryInit<TAnnotation>);
161
179
  get turns(): Turn<TAnnotation>[];
162
- get log(): AxleMessage[];
180
+ get messages(): AxleMessage[];
181
+ get archive(): AxleMessage[];
182
+ get compactions(): CompactionRecord[];
163
183
  get sessionAnnotations(): TAnnotation[];
164
- addTurn(turn: Turn<TAnnotation>): void;
165
- replaceTurns(turns: Turn<TAnnotation>[]): void;
166
- replaceLog(messages: AxleMessage[]): void;
167
- replaceSessionAnnotations(annotations?: TAnnotation[]): void;
168
- appendToLog(messages: AxleMessage | AxleMessage[]): void;
169
- latestTurn(): Turn<TAnnotation> | undefined;
170
- toString(): string;
184
+ /**
185
+ * Append conversation messages. Every appended message goes to both the
186
+ * active conversation and the archive, so the archive is always the
187
+ * complete chronological record regardless of compaction.
188
+ *
189
+ * @internal The Agent is History's only writer. Direct writes bypass the
190
+ * work queue and the event fold, desynchronizing engine state.
191
+ */
192
+ append(messages: AxleMessage | AxleMessage[]): void;
193
+ /**
194
+ * Replace the renderable turn state wholesale. Used to sync the
195
+ * accumulated state after applying a turn event.
196
+ *
197
+ * @internal The Agent is History's only writer. External writes are
198
+ * overwritten by the agent's accumulator on the next event.
199
+ */
200
+ replaceTurns(turns: Turn<TAnnotation>[], sessionAnnotations: TAnnotation[]): void;
201
+ /**
202
+ * Apply a compaction: the new state replaces the active conversation and
203
+ * the record is kept. The archive is untouched — it already holds
204
+ * everything ever appended. The corresponding compaction turn arrives
205
+ * through the event fold, not here.
206
+ *
207
+ * @internal The Agent is History's only writer; use `agent.compact()`.
208
+ * @experimental Compaction is under active design and may change in any release.
209
+ */
210
+ compact(messages: AxleMessage[], record: CompactionRecord): void;
171
211
  }
172
212
  //#endregion
173
213
  //#region src/memory/types.d.ts
@@ -340,6 +380,13 @@ type GenerateResult<TResponse = AxleAssistantMessage> = {
340
380
  messages: AxleMessage[];
341
381
  final: AxleAssistantMessage;
342
382
  usage?: Stats;
383
+ /**
384
+ * Present when a configured limit ended the tool loop at a request
385
+ * boundary. The conversation is well-formed and continuable;
386
+ * `final.finishReason` keeps the provider's own reason for the last
387
+ * message (typically `FunctionCall` — the model wanted to continue).
388
+ */
389
+ stopped?: "max-iterations" | "token-limit";
343
390
  } | {
344
391
  ok: false;
345
392
  response?: undefined;
@@ -347,6 +394,12 @@ type GenerateResult<TResponse = AxleAssistantMessage> = {
347
394
  messages: AxleMessage[];
348
395
  error: GenerateError;
349
396
  usage?: Stats;
397
+ /**
398
+ * Present on a `parse` error when a loop limit ended an Instruct call
399
+ * before the model produced parseable output. The conversation is still
400
+ * well-formed and continuable.
401
+ */
402
+ stopped?: "max-iterations" | "token-limit";
350
403
  };
351
404
  type StreamResult<TResponse = AxleAssistantMessage> = GenerateResult<TResponse>;
352
405
  //#endregion
@@ -355,16 +408,6 @@ interface Handle<T> {
355
408
  cancel(reason?: unknown): void;
356
409
  readonly final: Promise<T>;
357
410
  }
358
- /**
359
- * Creates a cancellable, queued async handle.
360
- * Waits for `queue` before running `work`, merges an optional external signal
361
- * with an internal abort controller, and returns the handle + settled promise
362
- * for queue chaining.
363
- */
364
- declare function createHandle<T>(queue: Promise<void>, work: (signal: AbortSignal) => Promise<T>, externalSignal?: AbortSignal): {
365
- handle: Handle<T>;
366
- settled: Promise<void>;
367
- };
368
411
  //#endregion
369
412
  //#region src/core/agent/types.d.ts
370
413
  /**
@@ -505,7 +548,7 @@ type AgentDefinitionResolver = (definition: AgentDefinition) => MaybePromise<Res
505
548
  * renderable turn state. It intentionally does not include executable runtime
506
549
  * objects such as providers, tools, MCP clients, memory implementations, file
507
550
  * resolvers, or tracers. Recreate those from host-owned configuration, then
508
- * call `agent.restore(session)`.
551
+ * construct a new agent with the session: `new Agent(config, session)`.
509
552
  *
510
553
  * @typeParam TAnnotation - Annotation union supported by the host renderer.
511
554
  */
@@ -514,8 +557,12 @@ interface AgentSession<TAnnotation extends Annotation = Annotation> {
514
557
  version: 1;
515
558
  /** Stable conversation/session id. */
516
559
  sessionId: string;
517
- /** Canonical model-facing message history used for continuation. */
560
+ /** Active model-facing conversation used for continuation. */
518
561
  messages: AxleMessage[];
562
+ /** Complete chronological record of every appended message, untouched by compaction. May be empty; absent in pre-compaction snapshots. */
563
+ archive?: AxleMessage[];
564
+ /** Compaction records, in order. Empty when no compaction has run; absent in pre-compaction snapshots. */
565
+ compactions?: CompactionRecord[];
519
566
  /** Renderable turn state for exact UI restoration. */
520
567
  turns?: Turn<TAnnotation>[];
521
568
  /** Session-level annotations for generic renderer state. */
@@ -545,6 +592,22 @@ interface AgentErrorResult {
545
592
  }
546
593
  type AgentHandle<T = string> = Handle<AgentResult<T> | AgentErrorResult>;
547
594
  type TurnEventCallback = (event: TurnEvent) => void;
595
+ /**
596
+ * Caller-supplied compaction policy and strategy.
597
+ *
598
+ * The callback owns the decision: return `null` for "not now" (cheap — the
599
+ * usage estimate is local), or the complete new active conversation. The
600
+ * engine owns validation, record stamping, state processing, and event
601
+ * emission.
602
+ *
603
+ * @experimental Compaction is under active design and may change in any release.
604
+ */
605
+ type CompactionCallback = (state: {
606
+ messages: AxleMessage[];
607
+ }, context: {
608
+ usage: ContextUsage;
609
+ signal?: AbortSignal;
610
+ }) => MaybePromise<AxleMessage[] | null>;
548
611
  interface SendMessageOptions extends AxleModelRequestOptions {
549
612
  fileResolver?: FileResolver;
550
613
  /**
@@ -571,7 +634,9 @@ declare class Agent {
571
634
  private spanParent?;
572
635
  private ownedTracer?;
573
636
  private eventCallbacks;
574
- private sendQueue;
637
+ private compactionCallback?;
638
+ private workQueue;
639
+ private accumulator;
575
640
  /**
576
641
  * Create an agent from runtime config and, optionally, restore saved session state.
577
642
  *
@@ -584,25 +649,63 @@ declare class Agent {
584
649
  hasTools(): boolean;
585
650
  on(callback: TurnEventCallback): () => void;
586
651
  context(): ContextUsage;
652
+ private estimateContext;
587
653
  /**
588
- * Capture the serializable session state for later continuation.
654
+ * Register the compaction callback: the policy and strategy for shrinking
655
+ * the active conversation. One callback per agent; registering again
656
+ * replaces it.
657
+ */
658
+ onCompaction(callback: CompactionCallback): void;
659
+ /**
660
+ * Run the registered compaction callback against the active conversation.
589
661
  *
590
- * The returned object contains message history and renderable turn state, but
591
- * not executable configuration such as providers, tools, MCP clients, memory,
592
- * or tracers.
662
+ * Compaction is optional: with no callback registered this is a no-op that
663
+ * resolves `null`. Otherwise the call is enqueued behind in-flight sends so
664
+ * compaction never races a turn. The callback may return `null` to skip;
665
+ * cancellation also resolves `null`. Errors propagate — a manual compact
666
+ * was explicitly requested.
667
+ *
668
+ * Do not await this from inside a running send (a tool's `execute`,
669
+ * `onToolCall`, or a compaction callback): the send holds the queue, so the
670
+ * nested call deadlocks.
593
671
  */
594
- snapshot(): AgentSession;
672
+ compact(options?: {
673
+ signal?: AbortSignal;
674
+ }): Promise<CompactionRecord | null>;
595
675
  /**
596
- * Replace the agent's continuation and render state from a saved session.
676
+ * Capture the serializable session state for later continuation.
677
+ *
678
+ * Enqueued behind in-flight sends and compactions, so the capture is
679
+ * always at rest — a snapshot never contains a streaming or running turn.
680
+ * The returned object contains message history and renderable turn state,
681
+ * but not executable configuration such as providers, tools, MCP clients,
682
+ * memory, or tracers.
597
683
  *
598
- * Restore does not change runtime configuration. The current provider, model,
599
- * tools, MCP clients, memory, and other constructor-supplied objects remain in
600
- * effect.
684
+ * Do not await this from inside a running send (a tool's `execute`,
685
+ * `onToolCall`, or a compaction callback): the send holds the queue, so the
686
+ * nested call deadlocks.
601
687
  */
602
- restore(session: AgentSession): void;
688
+ snapshot(): Promise<AgentSession>;
603
689
  send(message: string | Instruct<undefined>, options?: SendMessageOptions): AgentHandle<string>;
604
690
  send<TSchema extends OutputSchema>(instruct: Instruct<TSchema>, options?: SendMessageOptions): AgentHandle<ParsedSchema<TSchema>>;
691
+ /**
692
+ * Enqueue work behind everything already queued on this agent. Sends and
693
+ * compactions share one queue, so they never overlap.
694
+ *
695
+ * The work is exposed as two promises: `final` carries the outcome to the
696
+ * caller; `workQueue` carries only sequencing, with the outcome stripped —
697
+ * a rejected `final` in the queue would poison the chain and block all
698
+ * later work. Cancelled work still runs in order, but with an
699
+ * already-aborted signal.
700
+ */
701
+ private queue;
605
702
  private resolveMcpTools;
703
+ /**
704
+ * The single write path for renderable turn state: every event folds
705
+ * through the agent-lifetime accumulator, History mirrors the result, and
706
+ * subscribers are notified. Engine-internal state and consumer-folded
707
+ * state agree by construction because they run the same fold.
708
+ */
606
709
  private emitEvent;
607
710
  private toToolDefinitions;
608
711
  private run;
@@ -766,6 +869,13 @@ interface GenerateParams extends AxleModelRequestOptions {
766
869
  registry?: ToolRegistry;
767
870
  onToolCall?: ToolCallCallback;
768
871
  maxIterations?: number;
872
+ /**
873
+ * Context budget for the tool loop, in tokens. Checked at each request
874
+ * boundary against the previous model call's reported usage (effective
875
+ * input + output); when crossed, the loop returns `stopped: "token-limit"`
876
+ * with everything accumulated so far.
877
+ */
878
+ maxContextTokens?: number;
769
879
  span?: Span;
770
880
  fileResolver?: FileResolver;
771
881
  }
@@ -807,87 +917,71 @@ type StreamEvent = {
807
917
  message: AxleToolCallMessage;
808
918
  } | {
809
919
  type: "text:start";
810
- index: number;
811
920
  } | {
812
921
  type: "text:delta";
813
- index: number;
814
922
  delta: string;
815
923
  accumulated: string;
816
924
  } | {
817
925
  type: "text:citation";
818
- index: number;
819
926
  citation: Citation;
820
927
  citations: Citation[];
821
928
  } | {
822
929
  type: "text:end";
823
- index: number;
824
930
  final: string;
825
931
  } | {
826
932
  type: "citation";
827
- index: number;
828
933
  citations: Citation[];
829
934
  providerMetadata?: Record<string, unknown>;
830
935
  } | {
831
936
  type: "thinking:start";
832
- index: number;
833
937
  redacted?: boolean;
834
938
  continuity?: ThinkingContinuity;
835
939
  providerMetadata?: Record<string, unknown>;
836
940
  } | {
837
941
  type: "thinking:delta";
838
- index: number;
839
942
  delta: string;
840
943
  accumulated: string;
841
944
  } | {
842
945
  type: "thinking:summary-delta";
843
- index: number;
844
946
  delta: string;
845
947
  accumulated: string;
846
948
  } | {
847
949
  type: "thinking:update";
848
- index: number;
849
950
  redacted?: boolean;
850
951
  continuity?: ThinkingContinuity;
851
952
  providerMetadata?: Record<string, unknown>;
852
953
  } | {
853
954
  type: "thinking:end";
854
- index: number;
855
955
  final: string;
856
956
  } | {
857
957
  type: "tool:request";
858
- index: number;
859
958
  id: string;
860
959
  name: string;
861
960
  kind?: "tool" | "agent";
862
961
  } | {
863
962
  type: "tool:args-delta";
864
- index: number;
865
963
  id: string;
866
964
  name: string;
867
965
  delta: string;
868
966
  accumulated: string;
869
967
  } | {
870
968
  type: "tool:exec-start";
871
- index: number;
872
969
  id: string;
873
970
  name: string;
874
971
  parameters: Record<string, unknown>;
875
972
  } | {
876
973
  type: "tool:exec-delta";
877
- index: number;
878
974
  id: string;
879
975
  name: string;
880
976
  chunk: ToolProgressChunk;
881
977
  } | {
882
978
  type: "tool:exec-complete";
883
- index: number;
884
979
  id: string;
885
980
  name: string;
886
981
  result: ToolCallResult;
887
982
  usage?: Stats;
888
983
  } | {
889
984
  type: "tool:exec-error";
890
- index: number;
891
985
  id: string;
892
986
  name: string;
893
987
  error: {
@@ -897,12 +991,10 @@ type StreamEvent = {
897
991
  usage?: Stats;
898
992
  } | {
899
993
  type: "provider-tool:start";
900
- index: number;
901
994
  id: string;
902
995
  name: string;
903
996
  } | {
904
997
  type: "provider-tool:complete";
905
- index: number;
906
998
  id: string;
907
999
  name: string;
908
1000
  output?: unknown;
@@ -921,6 +1013,14 @@ interface StreamParams extends AxleModelRequestOptions {
921
1013
  registry?: ToolRegistry;
922
1014
  onToolCall?: ToolCallCallback;
923
1015
  maxIterations?: number;
1016
+ /**
1017
+ * Context budget for the tool loop, in tokens. Checked after each turn's
1018
+ * tools are answered, against that turn's reported usage (effective input
1019
+ * + output); when crossed, the loop returns `stopped: "token-limit"` with
1020
+ * everything accumulated so far. The caller decides what to do — e.g.
1021
+ * compact the conversation and start a new stream.
1022
+ */
1023
+ maxContextTokens?: number;
924
1024
  span?: Span;
925
1025
  fileResolver?: FileResolver;
926
1026
  }
@@ -1140,4 +1240,4 @@ declare function createStats(): Stats;
1140
1240
  declare function addStats(total: Stats, usage?: Stats): void;
1141
1241
  declare function mergeStats(...usages: Array<Stats | undefined>): Stats;
1142
1242
  //#endregion
1143
- export { type AIProvider, type AccumulatableEvent, type ActionPart, type ActionResult, Agent, type AgentConfig, type AgentDefinition, type AgentDefinitionRequestOptions, type AgentDefinitionResolver, type AgentErrorResult, type AgentHandle, type AgentMemory, type AgentResult, type AgentSession, type Annotation, type AnnotationEvent, type AnnotationPlacement, type AnnotationStatus, type AnnotationTarget, Anthropic, AxleAbortError, AxleAgentAbortError, type AxleAssistantMessage, type AxleConfiguration, AxleError, type AxleMessage, type AxleModelRequestOptions, AxleStopReason, type AxleToolCallMessage, type AxleToolCallResult, AxleToolFatalError, type AxleUserMessage, type BraveWebSearchOptions, type ChatCompletionsOptions, type ChatCompletionsVendor, type Citation, type CitationOutputSpan, type CitationPart, type CitationSource, type ContentPart, type ContentPartCitation, type ContentPartFile, type ContentPartProviderTool, type ContentPartText, type ContentPartThinking, type ContentPartToolCall, type ContextUsage, type CreateAgentToolOptions, type DeferredFileInfo, type DocumentLocator, type EventLevel, type ExecutableTool, type FileInfo, type FileKind, type FilePart, type FileProviderId, type FileResolveFormat, type FileResolveRequest, type FileResolver, type FileStore, Gemini, type GenerateInstructParams, type GenerateInstructResult, type GenerateParams, type Handle, History, Instruct, type InstructContextSection, type InstructInputs, type InstructOptions, type InstructResponse, InstructVariableError, type InstructVarsMode, type LLMRequest, type LLMResponse, type LLMResult, type LogEntry, type LogFn, LogWriter, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MaybePromise, type MemoryContext, type MessageMetadata, type ObservabilityOptions, OpenAI, type OutputSchema, type ParallelToolResult, type ParallelizeOptions, type ParsedSchema, type ProviderClientOptions, type ProviderDefinition, type ProviderOptions, type ProviderTool, type ProviderToolAction, type ProviderToolDefinitionRef, type RecallResult, type ResolvedAgentDefinition, type ResolvedFileSource, type SavedAgent, type SendMessageOptions, SimpleWriter, type SimpleWriterOptions, type Span, type SpanData, type SpanEvent, type SpanOptions, type SpanResult, type SpanStatus, type SpanType, type Stats, type StreamEvent, type StreamEventCallback, type StreamHandle, type StreamInstructHandle, type StreamInstructParams, type StreamInstructResult, type StreamParams, type StreamResult, type SubagentAction, TaskError, type TextPart, type ThinkingContinuity, type ThinkingPart, type TokenStats, type TokenUsage, type ToolAction, type ToolChoice, type ToolContext, type ToolDefinition, type ToolDefinitionRef, type ToolProgressChunk, ToolRegistry, type ToolResult, type ToolResultPart, type TraceWriter, Tracer, type TracerOptions, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, TurnEventBuilder, type TurnEventCallback, type TurnMetadata, type TurnPart, type TurnStatus, type UsageEntry, type WebSearchBackend, type WebSearchBackendContext, type WebSearchRequest, type WebSearchResponse, type WebSearchResult, addStats, anthropic, braveWebSearch, chatCompletions, configureAxle, createAgentConfig, createAgentTool, createHandle, createStats, estimateContextUsage, gemini, generate, generateTurn, loadFileContent, mergeStats, openai, parallelize, parseResponse, stream };
1243
+ export { type AIProvider, type AccumulatableEvent, type ActionPart, type ActionResult, Agent, type AgentConfig, type AgentDefinition, type AgentDefinitionRequestOptions, type AgentDefinitionResolver, type AgentErrorResult, type AgentHandle, type AgentMemory, type AgentResult, type AgentSession, type Annotation, type AnnotationEvent, type AnnotationPlacement, type AnnotationStatus, type AnnotationTarget, Anthropic, AxleAbortError, AxleAgentAbortError, type AxleAssistantMessage, type AxleConfiguration, AxleError, type AxleMessage, type AxleModelRequestOptions, AxleStopReason, type AxleToolCallMessage, type AxleToolCallResult, AxleToolFatalError, type AxleUserMessage, type BraveWebSearchOptions, type ChatCompletionsOptions, type ChatCompletionsVendor, type Citation, type CitationOutputSpan, type CitationPart, type CitationSource, type CompactionCallback, type CompactionPart, type CompactionRecord, type ContentPart, type ContentPartCitation, type ContentPartFile, type ContentPartProviderTool, type ContentPartText, type ContentPartThinking, type ContentPartToolCall, type ContextUsage, type CreateAgentToolOptions, type DeferredFileInfo, type DocumentLocator, type EventLevel, type ExecutableTool, type FileInfo, type FileKind, type FilePart, type FileProviderId, type FileResolveFormat, type FileResolveRequest, type FileResolver, type FileStore, Gemini, type GenerateInstructParams, type GenerateInstructResult, type GenerateParams, type Handle, History, Instruct, type InstructContextSection, type InstructInputs, type InstructOptions, type InstructResponse, InstructVariableError, type InstructVarsMode, type LLMRequest, type LLMResponse, type LLMResult, type LogEntry, type LogFn, LogWriter, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MaybePromise, type MemoryContext, type MessageMetadata, type ObservabilityOptions, OpenAI, type OutputSchema, type ParallelToolResult, type ParallelizeOptions, type ParsedSchema, type ProviderClientOptions, type ProviderDefinition, type ProviderOptions, type ProviderTool, type ProviderToolAction, type ProviderToolDefinitionRef, type RecallResult, type ResolvedAgentDefinition, type ResolvedFileSource, type SavedAgent, type SendMessageOptions, SimpleWriter, type SimpleWriterOptions, type Span, type SpanData, type SpanEvent, type SpanOptions, type SpanResult, type SpanStatus, type SpanType, type Stats, type StreamEvent, type StreamEventCallback, type StreamHandle, type StreamInstructHandle, type StreamInstructParams, type StreamInstructResult, type StreamParams, type StreamResult, type SubagentAction, TaskError, type TextPart, type ThinkingContinuity, type ThinkingPart, type TokenStats, type TokenUsage, type ToolAction, type ToolChoice, type ToolContext, type ToolDefinition, type ToolDefinitionRef, type ToolProgressChunk, ToolRegistry, type ToolResult, type ToolResultPart, type TraceWriter, Tracer, type TracerOptions, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, TurnEventBuilder, type TurnEventCallback, type TurnMetadata, type TurnPart, type TurnStatus, type UsageEntry, type WebSearchBackend, type WebSearchBackendContext, type WebSearchRequest, type WebSearchResponse, type WebSearchResult, addStats, anthropic, braveWebSearch, chatCompletions, configureAxle, createAgentConfig, createAgentTool, createStats, estimateContextUsage, gemini, generate, generateTurn, loadFileContent, mergeStats, openai, parallelize, parseResponse, stream, validateCompactedMessages };
package/dist/index.js CHANGED
@@ -1,25 +1,25 @@
1
- import{t as e}from"./accumulator-BnFn9yqM.js";import{d as t,i as n,o as r,p as i,r as a,t as o,u as s}from"./models-CT626Bau.js";import*as c from"zod";import l,{z as u}from"zod";import{Client as d}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as f}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as p}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import m from"@anthropic-ai/sdk";import"glob";import h from"mime";import{access as g,readFile as _,stat as v}from"node:fs/promises";import{extname as y,resolve as b}from"node:path";import{FinishReason as x,FunctionCallingConfigMode as S,GoogleGenAI as C}from"@google/genai";import w from"openai";import T from"chalk";import{marked as E}from"marked";let D={};function O(e){D={...D,...e}}function k(){return{...D}}var A=class e extends Error{code;id;details;constructor(t,n){super(t,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||`AXLE_ERROR`,this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id?{id:this.id}:{},...this.details?{details:this.details}:{},...this.cause?{cause:j(this.cause)}:{}}}};function j(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:j(e.cause)}:{}}:e}var M=class e extends A{reason;messages;partial;usage;constructor(t=`Operation aborted`,n){super(t,{code:`ABORTED`,details:{reason:n?.reason,usage:n?.usage}}),this.name=`AbortError`,this.reason=n?.reason,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),reason:this.reason,...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}},N=class e extends M{turn;constructor(t=`Agent send aborted`,n){super(t,n),this.turn=n?.turn,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.turn?{turn:this.turn}:{}}}},P=class e extends A{toolName;messages;partial;usage;constructor(t=`Fatal tool error`,n){super(t,{code:`TOOL_FATAL_ERROR`,details:{toolName:n?.toolName,usage:n?.usage},cause:n?.cause}),this.toolName=n?.toolName,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.toolName?{toolName:this.toolName}:{},...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}};function ee(e){let{text:t,files:n}=e,r=[];if(t&&r.push({type:`text`,text:t}),n)for(let e of n)r.push({type:`file`,file:e});return r}function F(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(`
1
+ import{t as e}from"./accumulator-jZHrnyOF.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-CT626Bau.js";import*as c from"zod";import l,{z as u}from"zod";import{Client as d}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as f}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as p}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import m from"@anthropic-ai/sdk";import"glob";import h from"mime";import{access as g,readFile as _,stat as v}from"node:fs/promises";import{extname as y,resolve as b}from"node:path";import{FinishReason as x,FunctionCallingConfigMode as S,GoogleGenAI as C}from"@google/genai";import w from"openai";import T from"chalk";import{marked as E}from"marked";let D={};function O(e){D={...D,...e}}function k(){return{...D}}var A=class e extends Error{code;id;details;constructor(t,n){super(t,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||`AXLE_ERROR`,this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id?{id:this.id}:{},...this.details?{details:this.details}:{},...this.cause?{cause:j(this.cause)}:{}}}};function j(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:j(e.cause)}:{}}:e}var M=class e extends A{reason;messages;partial;usage;constructor(t=`Operation aborted`,n){super(t,{code:`ABORTED`,details:{reason:n?.reason,usage:n?.usage}}),this.name=`AbortError`,this.reason=n?.reason,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),reason:this.reason,...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}},N=class e extends M{turn;constructor(t=`Agent send aborted`,n){super(t,n),this.turn=n?.turn,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.turn?{turn:this.turn}:{}}}},P=class e extends A{toolName;messages;partial;usage;constructor(t=`Fatal tool error`,n){super(t,{code:`TOOL_FATAL_ERROR`,details:{toolName:n?.toolName,usage:n?.usage},cause:n?.cause}),this.toolName=n?.toolName,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.toolName?{toolName:this.toolName}:{},...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}};function F(e){let t=(e,t)=>{throw new A(e,{code:`COMPACTION_INVALID_MESSAGES`,details:t})},n=new Set;for(let r=0;r<e.length;r++){let i=e[r];switch(n.size>0&&i.role!==`tool`&&t(`Compacted messages interleave a "${i.role}" message before tool calls are answered: ${[...n].join(`, `)}`,{messageIndex:r,toolCallIds:[...n]}),i.role){case`user`:break;case`assistant`:for(let e of i.content)e.type===`tool-call`&&(n.has(e.id)&&t(`Compacted messages repeat unanswered tool call id "${e.id}"`,{messageIndex:r,toolCallId:e.id}),n.add(e.id));break;case`tool`:for(let e of i.content)n.has(e.id)||t(`Compacted messages have a tool result for id "${e.id}" with no preceding tool call`,{messageIndex:r,toolCallId:e.id}),n.delete(e.id);break;default:t(`Compacted messages include a message with unknown role "${i.role}"`,{messageIndex:r})}}n.size>0&&t(`Compacted messages end with unanswered tool calls: ${[...n].join(`, `)}`,{toolCallIds:[...n]})}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 I(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
2
 
3
- `)}function te(e){return e.filter(e=>e.type===`thinking`).map(e=>e.text??``).join(`
3
+ `)}function L(e){return e.filter(e=>e.type===`thinking`).map(e=>e.text??``).join(`
4
4
 
5
- `)}function I(e){return e.filter(e=>e.type===`tool-call`)}function ne(e){return e.filter(e=>e.type===`provider-tool`)}function L(e){let t=[];for(let n of e)(n.type===`text`&&n.citations||n.type===`citation`)&&t.push(...n.citations);return t}function R(e,t=500){return e.length>t?`${e.slice(0,t)}… (${e.length} chars)`:e}function re(e,t=600){if(e.length<=t)return e;let n=Math.floor(t/2);return`${e.slice(0,n)}…[${e.length} chars]…${e.slice(-n)}`}var z=class{log;constructor(e){this.log=e}onSpanStart(){}onSpanEnd(e){let t=e.status===`error`?`error`:e.type===`tool`||e.type===`workflow`?`info`:`debug`;this.log({level:t,message:e.name,fields:{...e.attributes,type:e.type,status:e.status,traceId:e.traceId,spanId:e.spanId,...e.parentSpanId?{parentSpanId:e.parentSpanId}:{},...e.endTime===void 0?{}:{durationMs:Math.round(e.endTime-e.startTime)}}})}onEvent(e,t){this.log({level:t.level,message:t.name,fields:{traceId:e.traceId,spanId:e.spanId,name:e.name,...t.attributes}})}};function B(e,t,n){if(!n)return;let r=R(n);e?.info(t,{text:r}),r!==n&&e?.debug(t,{text:n})}function ie(e){let t=G(e.system??``),n=U(e.tools),r=U(e.mcpTools),i=ce(e.providerTools),a=e.messages.reduce((e,t)=>e+ae(t),0),o=t+n+r+i+a;return{total:o,system:t,tools:n,mcpTools:r,providerTools:i,messages:a,...e.limit===void 0?{}:{limit:e.limit,free:Math.max(0,e.limit-o)}}}function ae(e){switch(e.role){case`user`:return V(e.content);case`assistant`:return V(e.content);case`tool`:return e.content.reduce((e,t)=>e+oe(t),0)}}function V(e){return typeof e==`string`?G(e):e.reduce((e,t)=>e+H(t),0)}function H(e){switch(e.type){case`text`:return G(e.text);case`thinking`:return G(e.summary??e.text??``);case`tool-call`:return G(e.name)+W(e.parameters);case`provider-tool`:return G(e.name)+W(e.input)+W(e.output);case`citation`:return W(e.citations);case`file`:return W(e.file)}}function oe(e){return G(e.name)+se(e.content)}function se(e){return typeof e==`string`?G(e):e.reduce((e,t)=>t.type===`text`?e+G(t.text):e+W(t.file),0)}function U(e){let t=e?.map(le)??[];return t.length===0?0:W({tools:t})}function ce(e){return!e||e.length===0?0:W({providerTools:e})}function le(e){try{return{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}catch{return{name:e.name,description:e.description}}}function W(e){return e==null?0:G(JSON.stringify(e))}function G(e){return e?Math.ceil(e.length/3):0}function ue(e){if(e instanceof c.ZodString)return[`string`,`Your answer`];if(e instanceof c.ZodNumber)return[`number`,42];if(e instanceof c.ZodBoolean)return[`boolean`,!0];if(e instanceof c.ZodEnum){let t=e.options;return[t.map(fe).join(` | `),t[0]]}if(e instanceof c.ZodLiteral){let t=e.value;return[fe(t),t]}if(e instanceof c.ZodArray){let t=e.element;if(t instanceof c.ZodString)return[`string array`,[`answer 1`,`answer 2`,`third answer`]];if(t instanceof c.ZodNumber)return[`number array`,[42,59,3.14]];if(t instanceof c.ZodBoolean)return[`boolean array`,[!0,!1,!1]];if(t instanceof c.ZodObject){let[,e]=ue(t);return[`object array`,[e,e]]}else if(t instanceof c.ZodEnum||t instanceof c.ZodLiteral){let[e,n]=ue(t);return[`${e} array`,[n]]}return[`array`,[]]}if(e instanceof c.ZodObject){let t=e.shape,n={};for(let[e,r]of Object.entries(t)){let[,t]=ue(r);n[e]=t}return[`JSON object`,n]}if(e instanceof c.ZodOptional){let[t,n]=ue(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function de(e){if(e instanceof c.ZodObject)return Object.entries(e.shape).map(([e,t])=>{let[n]=ue(t);return[e,n]});let[t]=ue(e);return[[`response`,t]]}function fe(e){return typeof e==`string`?JSON.stringify(e):String(e)}function pe(e,t){if(!t)return e;let n=me(e);try{return t.parse(n)}catch(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Validation failed: ${t}`)}throw e}}function me(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i),r=n?n[1].trim():t;try{return JSON.parse(r)}catch(e){throw Error(`Cannot parse response as JSON: ${e.message}`)}}function he(e,t={}){if(typeof e==`string`)return{message:{role:`user`,id:crypto.randomUUID(),content:[{type:`text`,text:e}],...t.metadata?{metadata:t.metadata}:{}},parse:e=>ge(e,void 0)};let n=e.render(),r=e.files,i=e.schema,a=t.metadata??e.metadata;return{message:{role:`user`,id:crypto.randomUUID(),content:ee({text:n,files:r}),...a?{metadata:a}:{}},parse:e=>ge(e,i)}}function ge(e,t){return e?pe(F(e.content),t):null}function K(){return{in:0,out:0}}function q(e,t){t&&(e.in+=t.in??0,e.out+=t.out??0,Se(e,`cachedIn`,t.cachedIn),Se(e,`cacheWriteIn`,t.cacheWriteIn),Se(e,`reasoningOut`,t.reasoningOut),t.breakdown?.length&&(e.breakdown=ye(e.breakdown,t.breakdown)))}function _e(...e){let t=K();for(let n of e)q(t,n);return t}function ve(e,t){return{...e,breakdown:[{provider:t.provider,model:t.model,in:e.in,out:e.out,...e.cachedIn===void 0?{}:{cachedIn:e.cachedIn},...e.cacheWriteIn===void 0?{}:{cacheWriteIn:e.cacheWriteIn},...e.reasoningOut===void 0?{}:{reasoningOut:e.reasoningOut}}]}}function ye(e,t){let n=e?[...e]:[];for(let e of t){let t=n.find(t=>t.provider===e.provider&&t.model===e.model);if(!t){n.push({...e});continue}t.in+=e.in,t.out+=e.out,Se(t,`cachedIn`,e.cachedIn),Se(t,`cacheWriteIn`,e.cacheWriteIn),Se(t,`reasoningOut`,e.reasoningOut)}return n}function be(e,t){return{...e,...Ce(`cachedIn`,t.cachedIn),...Ce(`cacheWriteIn`,t.cacheWriteIn),...Ce(`reasoningOut`,t.reasoningOut)}}function xe(e){if(e)return{inputTokens:e.in,outputTokens:e.out,...e.cachedIn===void 0?{}:{cachedInputTokens:e.cachedIn},...e.cacheWriteIn===void 0?{}:{cacheWriteInputTokens:e.cacheWriteIn},...e.reasoningOut===void 0?{}:{reasoningOutputTokens:e.reasoningOut}}}function Se(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function Ce(e,t){return typeof t==`number`?{[e]:t}:{}}var we=class{tools=new Map;mcpTools=new Map;providerTools=new Map;constructor(e){e?.tools&&this.add(e.tools),e?.providerTools&&this.addProvider(e.providerTools)}add(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.tools.set(e.name,e)}}addMcp(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.mcpTools.set(e.name,e)}}addProvider(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.providerTools.set(e.name,e)}}remove(e){let t=this.tools.delete(e),n=this.mcpTools.delete(e),r=this.providerTools.delete(e);return t||n||r}has(e){return this.tools.has(e)||this.mcpTools.has(e)||this.providerTools.has(e)}get(e){return this.tools.get(e)??this.mcpTools.get(e)}getProvider(e){return this.providerTools.get(e)}executable(){return[...this.tools.values(),...this.mcpTools.values()]}local(){return[...this.tools.values()]}mcp(){return[...this.mcpTools.values()]}provider(){return[...this.providerTools.values()]}get size(){return this.tools.size+this.mcpTools.size+this.providerTools.size}};const Te=c.object({query:c.string().trim().min(1).max(400)});function Ee(e){return{name:`web_search`,description:`Search the public web for current information. Returns source titles, URLs, and relevant extracted passages.`,schema:Te,async execute(t,n){n.span?.setAttribute(`webSearchBackend`,e.name);let r=await e.search({query:t.query},{signal:n.signal,span:n.span});return n.span?.setAttribute(`webSearchResultCount`,r.results.length),JSON.stringify({query:t.query,results:r.results})},summarize(e){return`Search the web for "${e.query}"`}}}function De(e){let t=e.apiKey.trim();if(!t)throw Error(`Brave Search apiKey is required`);let n=e.endpoint??`https://api.search.brave.com/res/v1/llm/context`,r=Oe(e.maxResults??5,`maxResults`,1,50),i=e.candidateCount===void 0?void 0:Oe(e.candidateCount,`candidateCount`,1,50),a=Oe(e.maxTokens??4096,`maxTokens`,1,32768),o=e.maxSnippets===void 0?void 0:Oe(e.maxSnippets,`maxSnippets`,1,256),s=e.maxTokensPerUrl===void 0?void 0:Oe(e.maxTokensPerUrl,`maxTokensPerUrl`,1,8192),c=e.maxSnippetsPerUrl===void 0?void 0:Oe(e.maxSnippetsPerUrl,`maxSnippetsPerUrl`,1,100),l=e.timeoutMs===void 0?void 0:Oe(e.timeoutMs,`timeoutMs`,1);return{name:`brave`,async search(u,d){let f=new URL(n);f.searchParams.set(`q`,u.query),f.searchParams.set(`maximum_number_of_urls`,String(r)),i!==void 0&&f.searchParams.set(`count`,String(i)),f.searchParams.set(`maximum_number_of_tokens`,String(a)),o!==void 0&&f.searchParams.set(`maximum_number_of_snippets`,String(o)),s!==void 0&&f.searchParams.set(`maximum_number_of_tokens_per_url`,String(s)),c!==void 0&&f.searchParams.set(`maximum_number_of_snippets_per_url`,String(c)),e.contextThresholdMode&&f.searchParams.set(`context_threshold_mode`,e.contextThresholdMode),e.country&&f.searchParams.set(`country`,e.country),e.searchLanguage&&f.searchParams.set(`search_lang`,e.searchLanguage),e.freshness&&f.searchParams.set(`freshness`,e.freshness);let p=l===void 0?void 0:AbortSignal.timeout(l),m=p?AbortSignal.any([d.signal,p]):d.signal,h=await fetch(f,{method:`GET`,headers:{Accept:`application/json`,"X-Subscription-Token":t},signal:m});if(!h.ok){let e=(await h.text().catch(()=>``)).replaceAll(t,`[REDACTED]`);throw Error(`Brave Search request failed with status ${h.status}${e?`: ${e}`:``}`)}let g=await h.json(),_=[],v=[...g.grounding?.generic??[],...g.grounding?.poi?[g.grounding.poi]:[],...g.grounding?.map??[]];for(let e of v){if(_.length>=r)break;!e.title||!e.url||!e.snippets?.length||_.push({title:e.title,url:e.url,snippets:e.snippets})}return{results:_}}}}function Oe(e,t,n,r){if(!Number.isInteger(e))throw Error(`${t} must be an integer`);if(e<n)throw Error(`${t} must be greater than or equal to ${n}`);if(r!==void 0&&e>r)throw Error(`${t} must be less than or equal to ${r}`);return e}function ke(e,t,n){t.usage&&q(e,n?ve(t.usage,n):t.usage)}function Ae(e,t){if(!e)return;B(e,`text`,F(t));let n=te(t);n&&e.debug(`thinking`,{thinking:n});for(let n of ne(t))e.info(n.name,{type:`provider-tool`,input:n.input}),n.output!==void 0&&e.trace(n.name,{type:`provider-tool`,output:n.output});je(e,L(t))}function je(e,t){if(t.length===0)return;let n=Me(t);e.info(`citations`,{count:t.length,sources:n.slice(0,8),...n.length>8?{more:n.length-8}:{}}),n.length>8&&e.debug(`citations`,{sources:n}),e.setAttribute(`citationCount`,t.length)}function Me(e){let t=new Set,n=[];for(let{source:r}of e){let e=Ne(r),i=`title`in r?r.title:void 0,a=e??i??r.type;t.has(a)||(t.add(a),n.push({type:r.type,...i?{title:i}:{},...e?{url:e}:{}}))}return n}function Ne(e){switch(e.type){case`web`:case`search-result`:return e.url;case`retrieved-context`:return e.uri;case`document`:return e.fileId;default:return}}function Pe(e){return JSON.stringify({error:e})}function Fe(e){let t=e.tools!==void 0||e.providerTools!==void 0;if(e.registry&&t)throw new A("Cannot specify both `registry` and `tools` / `providerTools`. Use one or the other.",{code:`TOOL_OPTIONS_CONFLICT`});return e.registry??new we({tools:e.tools,providerTools:e.providerTools})}function Ie(e,t){let n=e.getProvider(`web_search`),r=t.provider.resolveProviderToolName?.bind(t.provider);if(!r)return{registry:e,executable:()=>e.executable(),provider:()=>e.provider(),get:t=>e.get(t)};let i=()=>e.provider().map(e=>{let n=r(e.name,t.model);return n===void 0?e:{...e,nativeName:n}});if(!n||r(`web_search`,t.model)!==void 0)return{registry:e,executable:()=>e.executable(),provider:i,get:t=>e.get(t)};let a=t.configuration.webSearchFallback;if(!a)throw new A(`Provider ${t.provider.name} does not support native web_search and no Axle webSearchFallback is configured`,{code:`WEB_SEARCH_FALLBACK_NOT_CONFIGURED`,details:{provider:t.provider.name,model:t.model}});n.config&&t.span?.warn(`web_search provider config ignored by fallback backend`,{provider:t.provider.name,model:t.model,backend:a.name}),t.span?.info(`Using web search fallback backend`,{provider:t.provider.name,model:t.model,backend:a.name});let o=Ee(a);return{registry:e,executable:()=>[...e.executable().filter(e=>e.name!==`web_search`),o],provider:()=>i().filter(e=>e.name!==`web_search`),get:t=>t===`web_search`?o:e.get(t)}}async function Le(e,t=async()=>null,n,r,i,a){let o=[],s=K(),c=!1;for(let l of e){let e;try{e=await ze(l,t,n,r,i,a)}catch(e){throw c?Re(e,s):e}o.push(e.result),e.usage&&(q(s,e.usage),c=!0)}return{results:o,...c?{usage:s}:{}}}function Re(e,t){return e instanceof P?new P(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:_e(t,e.usage),cause:e.cause}):e instanceof M?new M(e.message,{reason:e.reason,messages:e.messages,partial:e.partial,usage:_e(t,e.usage)}):e}async function ze(e,t,n,r,i,a){if(n.aborted)throw new M(`Operation aborted`,{reason:n.reason});let o=r instanceof we?r:r.registry,s=r.get(e.name),c=i?.startSpan(e.name,{type:`tool`}),l,u={signal:n,span:c,registry:o,emit:t=>a?.onDelta?.(e,t),reportUsage:e=>{l??=K(),q(l,e)}};a?.onStart?.(e);let d,f=`exception`;try{if(d=await t(e.name,e.parameters,u),d==null&&s&&(f=`execution`,d={type:`success`,content:await s.execute(e.parameters,u)}),n.aborted)throw new M(`Operation aborted`,{reason:n.reason})}catch(t){let r=Be(t,n);if(r){c?.setResult({kind:`tool`,name:e.name,input:e.parameters,output:{type:r instanceof P?`fatal`:`aborted`,message:r.message}}),c?.end(r instanceof P?`error`:`ok`);let t=l?Re(r,l):r;throw a?.onError?.(e,t),t}d={type:`error`,error:{type:f,message:t instanceof Error?t.message:String(t)}}}d??={type:`error`,error:{type:`not-found`,message:`Tool not found: ${e.name}`}};let p={result:d,...l?{usage:l}:{}};a?.onComplete?.(e,p);let m=d.type===`success`?d.content:Pe(d.error);return c?.setResult({kind:`tool`,name:e.name,input:e.parameters,output:d.type===`success`?d.content:d.error}),c?.end(d.type===`success`?`ok`:`error`),{result:{id:e.id,name:e.name,content:m,...d.type===`error`?{isError:!0}:{}},...l?{usage:l}:{}}}function Be(e,t){if(e instanceof P||e instanceof M)return e;if(t.aborted)return new M(`Operation aborted`,{reason:t.reason})}let Ve=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function J(e,t){for(let n of e)n(t)}function He(e){let t=e.raw?`${e.message}\nRaw buffer: ${e.raw}`:e.message;return{type:`error`,error:{type:e.type,message:t}}}function Ue(e){return{name:e.name,description:e.description,schema:e.schema}}function We(e){let t=[],n,r;if(`instruct`in e){let{instruct:t,messages:i,...a}=e,o=he(t);r=o.parse,n={...a,messages:[...i??[],o.message]}}else n=e;let i=new AbortController,a=n.signal?AbortSignal.any([i.signal,n.signal]):i.signal,{promise:o,resolve:s,reject:c}=Promise.withResolvers(),l=k();return Promise.resolve().then(()=>Ge(n,a,t,l).then(e=>{if(r&&e.ok){try{s({...e,response:r(e.final)})}catch(t){s({ok:!1,messages:e.messages,final:e.final,usage:e.usage,error:{kind:`parse`,error:t,message:t instanceof Error?t.message:String(t)}})}return}s(e)},c)),{on(e){t.push(e)},cancel(e){i.abort(e)},get final(){return o}}}async function Ge(e,t,n,r){let{provider:i,model:a,messages:o,system:s,onToolCall:c,maxIterations:l,span:u,fileResolver:d,reasoning:f,maxOutputTokens:p,temperature:m,topP:h,stop:g,toolChoice:_,parallelToolCalls:v,providerOptions:y}=e,b=Ie(Fe(e),{provider:i,model:a,span:u,configuration:r}),x=[...o],S=[],C=K(),w=0,T=0,E=e=>{x.push(e),S.push(e)},D=e=>{e.ok||J(n,{type:`error`,error:e.error});let t=e.ok?e.final.content:null,r=e.ok?e.final.finishReason:void 0;return u?.setResult({kind:`llm`,model:a,request:{messages:o},response:{content:t??null},usage:xe(e.usage),finishReason:r}),u?.end(e.ok?`ok`:`error`),e},O=(e,n,r,i)=>{i();let a=e.length?{role:`assistant`,id:n,model:r,content:e,finishReason:`cancelled`}:void 0;throw a&&E(a),u?.end(`ok`),new M(`Stream aborted`,{reason:t.reason,messages:S,partial:a,usage:C})};for(;;){if(t.aborted&&O([],``,``,()=>{}),l!==void 0&&T>=l)return D({ok:!1,messages:S,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${l})`}}},usage:C});T+=1;let e=u?.startSpan(`turn-${T}`,{type:`llm`}),r=b.executable(),o=r.length>0?r.map(Ue):void 0,k=b.provider(),A=i.createStreamingRequest(a,{messages:x,system:s,tools:o,providerTools:k.length>0?k:void 0,runtime:{span:e,fileResolver:d},signal:t,reasoning:f,maxOutputTokens:p,temperature:m,topP:h,stop:g,toolChoice:_,parallelToolCalls:v,providerOptions:y}),j=[],N=``,ee=``,F=null,te=K(),I=-1,ne=null,L=``,R=new Map,re=new Map,z=new Map,B=new Map,ie=new Set,ae=(e,t)=>{J(n,{type:`tool:request`,index:R.get(e)??-1,id:e,name:t,kind:b.get(t)?.kind??`tool`})},V=-1,H=()=>{ne!==null&&I>=0&&(J(n,{type:ne===`text`?`text:end`:`thinking:end`,index:I,final:L}),ne=null,L=``,I=-1)};for await(let r of A){switch(r.type){case`start`:N=r.id,ee=r.data.model,J(n,{type:`turn:start`,id:N,model:ee});break;case`text-start`:H(),j.push({type:`text`,text:``}),V=j.length-1,I=w++,z.set(r.data.index,V),B.set(r.data.index,I),ne=`text`,L=``,J(n,{type:`text:start`,index:I});break;case`text-delta`:{let e=j[V];e.text+=r.data.text,L=e.text,J(n,{type:`text:delta`,index:I,delta:r.data.text,accumulated:L});break}case`text-citation`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??I,i=j[e];if(!i||i.type!==`text`)break;i.citations=[...i.citations??[],r.data.citation],J(n,{type:`text:citation`,index:t,citation:r.data.citation,citations:i.citations});break}case`citation`:{H();let e=w++;j.push({type:`citation`,citations:r.data.citations,...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),V=j.length-1,z.set(r.data.index,V),B.set(r.data.index,e),J(n,{type:`citation`,index:e,citations:r.data.citations,providerMetadata:r.data.providerMetadata});break}case`text-complete`:H();break;case`thinking-start`:H(),j.push({type:`thinking`,text:``,...r.data.id?{id:r.data.id}:{},...r.data.redacted===void 0?{}:{redacted:r.data.redacted},...r.data.continuity?{continuity:r.data.continuity}:{},...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),V=j.length-1,I=w++,z.set(r.data.index,V),B.set(r.data.index,I),ne=`thinking`,L=``,J(n,{type:`thinking:start`,index:I,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break;case`thinking-delta`:{let e=j[V];e.text=(e.text??``)+r.data.text,L=e.text,J(n,{type:`thinking:delta`,index:I,delta:r.data.text,accumulated:L});break}case`thinking-summary-delta`:{let e=j[V];e.summary=(e.summary??``)+r.data.text,L=e.summary,J(n,{type:`thinking:summary-delta`,index:I,delta:r.data.text,accumulated:L});break}case`thinking-metadata`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??I,i=j[e];if(!i||i.type!==`thinking`)break;r.data.redacted!==void 0&&(i.redacted=r.data.redacted),r.data.continuity&&(i.continuity=r.data.continuity),r.data.providerMetadata&&(i.providerMetadata=r.data.providerMetadata),J(n,{type:`thinking:update`,index:t,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break}case`thinking-complete`:H();break;case`tool-call-start`:{H();let e=w++;j.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),V=j.length-1,z.set(r.data.index,V),B.set(r.data.index,e),R.set(r.data.id,e),r.data.name?ae(r.data.id,r.data.name):ie.add(r.data.id);break}case`tool-call-args-delta`:ie.has(r.data.id)&&r.data.name&&(ie.delete(r.data.id),ae(r.data.id,r.data.name)),J(n,{type:`tool:args-delta`,index:R.get(r.data.id)??-1,id:r.data.id,name:r.data.name,delta:r.data.delta,accumulated:r.data.accumulated});break;case`tool-call-complete`:{let e=j[z.get(r.data.index)??V];if(!e||e.type!==`tool-call`)break;r.data.id&&(e.id=r.data.id),r.data.name&&(e.name=r.data.name),e.parameters=r.data.arguments,r.data.providerMetadata&&(e.providerMetadata=r.data.providerMetadata),r.data.error&&re.set(e.id,r.data.error),ie.has(e.id)&&e.name&&(ie.delete(e.id),ae(e.id,e.name));break}case`provider-tool-start`:{H();let e=w++;j.push({type:`provider-tool`,id:r.data.id,name:r.data.name}),V=j.length-1,z.set(r.data.index,V),B.set(r.data.index,e),J(n,{type:`provider-tool:start`,index:e,id:r.data.id,name:r.data.name});break}case`provider-tool-complete`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??r.data.index,i=j[e];i&&i.type===`provider-tool`&&r.data.output!=null&&(i.output=r.data.output),J(n,{type:`provider-tool:complete`,index:t,id:r.data.id,name:r.data.name,output:r.data.output});break}case`complete`:H(),F=r.data.finishReason,te=r.data.usage;break;case`error`:return H(),r.data.usage&&q(C,ve(r.data.usage,{provider:i.name,model:ee||a})),e?.end(`error`),D({ok:!1,messages:S,error:{kind:`model`,error:{type:`error`,error:{type:r.data.type,message:r.data.message}}},usage:C});default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.aborted)break}if(t.aborted&&(e?.end(`ok`),O(j,N,ee,H)),F===null)return H(),e?.end(`error`),D({ok:!1,messages:S,error:{kind:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:C});let oe=ve(te,{provider:i.name,model:ee||a});q(C,oe);let se={kind:`llm`,model:ee,request:{messages:x},response:{content:j},usage:xe(te),finishReason:F};Ae(e,j),e?.setResult(se),e?.end();let U={role:`assistant`,id:N,model:ee,content:j,finishReason:F};if(E(U),J(n,{type:`turn:complete`,message:U,usage:oe}),F!==`function_call`)return D({ok:!0,response:U,messages:S,final:U,usage:C});let ce=j.filter(e=>e.type===`tool-call`);if(ce.length===0)return D({ok:!0,response:U,messages:S,final:U,usage:C});if(t.aborted)throw u?.end(`ok`),new M(`Stream aborted`,{reason:t.reason,messages:S,usage:C});let le=crypto.randomUUID();J(n,{type:`tool-results:start`,id:le});let W=[],G=new Map;for(let e of ce){let t=re.get(e.id);if(!t){W.push(e);continue}let r=He(t);G.set(e.id,{id:e.id,name:e.name,content:Pe(r.error),isError:!0}),J(n,{type:`tool:exec-complete`,index:R.get(e.id)??-1,id:e.id,name:e.name,result:r})}let ue={onStart(e){J(n,{type:`tool:exec-start`,index:R.get(e.id)??-1,id:e.id,name:e.name,parameters:e.parameters})},onDelta(e,t){J(n,{type:`tool:exec-delta`,index:R.get(e.id)??-1,id:e.id,name:e.name,chunk:t})},onComplete(e,t){J(n,{type:`tool:exec-complete`,index:R.get(e.id)??-1,id:e.id,name:e.name,result:t.result,usage:t.usage})},onError(e,t){J(n,{type:`tool:exec-error`,index:R.get(e.id)??-1,id:e.id,name:e.name,error:{type:t instanceof P?`fatal`:`aborted`,message:t.message},usage:t.usage})}},de=[],fe;try{W.length>0&&({results:de,usage:fe}=await Le(W,c,t,b,u,ue))}catch(e){throw e instanceof P?(u?.end(`error`),new P(e.message,{toolName:e.toolName,messages:e.messages??S,partial:e.partial??U,usage:_e(C,e.usage),cause:e.cause})):e instanceof M?(u?.end(`ok`),new M(`Stream aborted`,{reason:e.reason,messages:e.messages??S,partial:e.partial,usage:_e(C,e.usage)})):e}q(C,fe);let pe=new Map(de.map(e=>[e.id,e])),me=ce.flatMap(e=>{let t=G.get(e.id);if(t)return[t];let n=pe.get(e.id);return n?[n]:[]});if(me.length>0){let e={role:`tool`,id:le,content:me};E(e),J(n,{type:`tool-results:complete`,message:e})}}}function Ke(e=new Date){return{start:e.toISOString()}}function Y(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var qe=class{currentTurnId=null;currentTurnTiming;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage=K();createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=Y(Ke(r),r),a=()=>({...i});if(typeof e.content==`string`)n.push({id:crypto.randomUUID(),type:`text`,text:e.content,timing:a()});else for(let t of e.content)t.type===`text`?n.push({id:crypto.randomUUID(),type:`text`,text:t.text,...t.citations?{citations:t.citations}:{},...t.providerMetadata?{providerMetadata:t.providerMetadata}:{},timing:a()}):t.type===`file`&&n.push({id:crypto.randomUUID(),type:`file`,file:t.file,timing:a()});return[{type:`turn:user`,turn:{id:t,owner:`user`,parts:n,status:`complete`,timing:i,...e.metadata?{metadata:e.metadata}:{}}}]}startAgentTurn(){let e=crypto.randomUUID();return this.currentTurnId=e,this.currentTurnTiming=Ke(),this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage=K(),{type:`turn:start`,turnId:e,timing:this.currentTurnTiming}}handleStreamEvent(e){let t=this.currentTurnId;if(!t)return[];let n=[];switch(e.type){case`turn:start`:break;case`text:start`:{this.closeOpenParts(n);let e=crypto.randomUUID(),r={id:e,type:`text`,text:``,timing:Ke()};this.currentTextPart={id:e,timing:r.timing},n.push({type:`part:start`,turnId:t,part:r});break}case`text:delta`:this.currentTextPart&&n.push({type:`text:delta`,turnId:t,partId:this.currentTextPart.id,delta:e.delta});break;case`text:end`:if(this.currentTextPart){let e=Y(this.currentTextPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:e}),this.currentTextPart=null}break;case`citation`:{this.closeOpenParts(n);let r=Y(Ke()),i={id:crypto.randomUUID(),type:`citation`,citations:e.citations,...e.providerMetadata?{providerMetadata:e.providerMetadata}:{},timing:r};n.push({type:`part:start`,turnId:t,part:i}),n.push({type:`part:end`,turnId:t,partId:i.id,timing:r});break}case`thinking:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i={id:r,type:`thinking`,text:``,timing:Ke(),...e.redacted===void 0?{}:{redacted:e.redacted},...e.continuity?{continuity:e.continuity}:{},...e.providerMetadata?{providerMetadata:e.providerMetadata}:{}};this.currentThinkingPart={id:r,timing:i.timing},n.push({type:`part:start`,turnId:t,part:i});break}case`thinking:delta`:this.currentThinkingPart&&n.push({type:`thinking:delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`text:citation`:this.currentTextPart&&n.push({type:`text:citation`,turnId:t,partId:this.currentTextPart.id,citation:e.citation});break;case`thinking:summary-delta`:this.currentThinkingPart&&n.push({type:`thinking:summary-delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`thinking:update`:this.currentThinkingPart&&n.push({type:`thinking:update`,turnId:t,partId:this.currentThinkingPart.id,redacted:e.redacted,continuity:e.continuity,providerMetadata:e.providerMetadata});break;case`thinking:end`:if(this.currentThinkingPart){let e=Y(this.currentThinkingPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:e}),this.currentThinkingPart=null}break;case`tool:request`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=Ke(),a=e.kind===`agent`?{id:r,type:`action`,kind:`agent`,status:`pending`,timing:i,detail:{name:e.name,children:[]}}:{id:r,type:`action`,kind:`tool`,status:`pending`,timing:i,detail:{name:e.name,parameters:{}}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i,name:e.name,kind:e.kind}),n.push({type:`part:start`,turnId:t,part:a});break}case`tool:args-delta`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:args-delta`,turnId:t,partId:r.partId,delta:e.delta,accumulated:e.accumulated});break}case`tool:exec-start`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:running`,turnId:t,partId:r.partId,parameters:e.parameters});break}case`tool:exec-delta`:{let r=this.toolIdMap.get(e.id);r&&(typeof e.chunk==`string`?n.push({type:`action:progress`,turnId:t,partId:r.partId,chunk:e.chunk}):e.chunk.type===`turn-event`&&n.push({type:`action:child-event`,turnId:t,partId:r.partId,event:e.chunk.event}));break}case`tool:exec-complete`:{let r=this.toolIdMap.get(e.id);if(r){q(this.accumulatedUsage,e.usage);let i=Y(r.timing);r.timing=i,e.result.type===`success`?n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.result.content},timing:i}):n.push({type:`action:error`,turnId:t,partId:r.partId,error:e.result.error,timing:i})}break}case`tool:exec-error`:{let r=this.toolIdMap.get(e.id);if(r){q(this.accumulatedUsage,e.usage);let i=Y(r.timing);r.timing=i,n.push({type:`action:error`,turnId:t,partId:r.partId,error:e.error,timing:i})}break}case`provider-tool:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=Ke(),a={id:r,type:`action`,kind:`provider-tool`,status:`running`,timing:i,detail:{name:e.name}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i}),n.push({type:`part:start`,turnId:t,part:a}),n.push({type:`action:running`,turnId:t,partId:r});break}case`provider-tool:complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=Y(r.timing);r.timing=i,n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.output},timing:i})}break}case`turn:complete`:this.closeOpenParts(n),q(this.accumulatedUsage,e.usage);break;case`tool-results:start`:case`tool-results:complete`:break;case`error`:{let t=e.error,r=t.kind===`model`?t.error.error.message:t.kind===`tool`?`Tool error (${t.error.name}): ${t.error.message}`:`Parse error: ${t.message}`;n.push({type:`error`,error:{type:t.kind,message:r}});break}}return n}finalizeTurn(e=`complete`){let t=this.currentTurnId;if(!t)return[];let n=[];this.closeOpenParts(n);let r=Y(this.currentTurnTiming);return n.push({type:`turn:end`,turnId:t,status:e,usage:{...this.accumulatedUsage},timing:r}),this.currentTurnId=null,this.currentTurnTiming=void 0,n}closeOpenParts(e){let t=this.currentTurnId;t&&(this.currentTextPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:Y(this.currentTextPart.timing)}),null),this.currentThinkingPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:Y(this.currentThinkingPart.timing)}),null))}};function Je(e){return Array.isArray(e)?e:[e]}function Ye(e){return e.then(()=>{},()=>{})}function Xe(e,t,n){let r=new AbortController,i=n?AbortSignal.any([n,r.signal]):r.signal,a=e.then(()=>t(i));return{handle:{cancel:e=>r.abort(e),get final(){return a}},settled:Ye(a)}}var Ze=class{_turns=[];_log=[];_sessionAnnotations=[];constructor(e){e?.turns&&(this._turns=[...e.turns]),e?.log&&(this._log=[...e.log]),e?.sessionAnnotations&&(this._sessionAnnotations=[...e.sessionAnnotations])}get turns(){return[...this._turns]}get log(){return[...this._log]}get sessionAnnotations(){return[...this._sessionAnnotations]}addTurn(e){this._turns.push(e)}replaceTurns(e){this._turns=[...e]}replaceLog(e){this._log=[...e]}replaceSessionAnnotations(e=[]){this._sessionAnnotations=[...e]}appendToLog(e){Array.isArray(e)?this._log.push(...e):this._log.push(e)}latestTurn(){return this._turns[this._turns.length-1]}toString(){return JSON.stringify({turns:this._turns,sessionAnnotations:this._sessionAnnotations})}};const Qe={trace:0,debug:1,info:2,warn:3,error:4},$e=()=>performance.timeOrigin+performance.now();var et=class{writers=[];minLevel=`info`;addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}shouldLog(e){return Qe[e]>=Qe[this.minLevel]}spanStart(e){for(let t of this.writers)t.onSpanStart(e)}spanEnd(e){for(let t of this.writers)t.onSpanEnd(e)}spanUpdate(e){for(let t of this.writers)t.onSpanUpdate?.(e)}event(e,t){for(let n of this.writers)n.onEvent?.(e,t)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}},tt=class{rec=new et;constructor(e){e?.minLevel&&(this.rec.minLevel=e.minLevel);for(let t of e?.writers??[])this.rec.addWriter(t)}get minLevel(){return this.rec.minLevel}set minLevel(e){this.rec.minLevel=e}addWriter(e){this.rec.addWriter(e)}removeWriter(e){this.rec.removeWriter(e)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:$e(),status:`ok`,attributes:{...t?.attributes??{}},events:[]};return this.rec.spanStart(n),new nt(n,this.rec)}flush(){return this.rec.flush()}},nt=class e{data;rec;ended=!1;constructor(e,t){this.data=e,this.rec=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:$e(),status:`ok`,attributes:{...n?.attributes??{}},events:[]};return this.rec.spanStart(r),new e(r,this.rec)}end(e=`ok`){this.ended||(this.ended=!0,this.data.endTime=$e(),this.data.status=e,this.rec.spanEnd(this.data))}addEvent(e,t,n){if(this.ended||!this.rec.shouldLog(t))return;let r={name:e,timestamp:$e(),level:t,attributes:n};this.data.events.push(r),this.rec.event(this.data,r)}trace(e,t){this.addEvent(e,`trace`,t)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,this.rec.spanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.rec.spanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.rec.spanUpdate(this.data))}};function rt(e){if(!e)return{};let{trace:t,log:n,level:r}=e;if(t)return n&&console.warn(`[axle] observability.log is ignored when observability.trace is set; add a LogWriter to your tracer's writers instead`),{parent:t};if(n){let e=new tt({minLevel:r,writers:[new z(n)]});return{parent:e,owned:e}}return{}}function it(e){return at(e)?`cancelled`:`error`}function at(e){return e instanceof M||e instanceof N||e instanceof Error&&e.name===`AbortError`}function ot(e,t){return{...e,...t,providerOptions:e?.providerOptions||t?.providerOptions?{...e?.providerOptions,...t?.providerOptions}:void 0}}var st=class{provider;model;history;name;fileResolver;requestOptions;registry;sessionId;system;mcps=[];resolvedMcps=new WeakSet;memory;spanParent;ownedTracer;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e,t){this.provider=e.provider,this.model=e.model,this.sessionId=e.sessionId??crypto.randomUUID(),this.history=new Ze;let n=rt(e.observability);if(this.spanParent=n.parent,this.ownedTracer=n.owned,this.system=e.system,this.name=e.name,this.fileResolver=e.fileResolver,this.requestOptions={reasoning:e.reasoning,maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,stop:e.stop,toolChoice:e.toolChoice,parallelToolCalls:e.parallelToolCalls,providerOptions:e.providerOptions},this.registry=new we({tools:e.tools,providerTools:e.providerTools}),e.mcps&&(this.mcps=[...e.mcps]),e.memory){this.memory=e.memory;let t=e.memory.tools?.();t&&this.registry.add(t)}t&&this.restore(t)}addMcp(e){this.mcps.push(e)}addMcps(e){this.mcps.push(...e)}hasTools(){return this.registry.size>0||this.mcps.length>0}on(e){return this.eventCallbacks.push(e),()=>{let t=this.eventCallbacks.indexOf(e);t>=0&&this.eventCallbacks.splice(t,1)}}context(){return ie({system:this.system,messages:this.history.log,tools:this.toToolDefinitions(this.registry.local()),providerTools:this.registry.provider(),mcpTools:this.toToolDefinitions(this.registry.mcp())})}snapshot(){let e=this.history.sessionAnnotations;return{version:1,sessionId:this.sessionId,messages:this.history.log,turns:this.history.turns,sessionAnnotations:e.length>0?e:void 0}}restore(e){if(e.version!==1)throw new A(`Unsupported agent session version: ${e.version}`);this.sessionId=e.sessionId,this.history.replaceLog(e.messages),this.history.replaceTurns(e.turns??[]),this.history.replaceSessionAnnotations(e.sessionAnnotations??[])}send(e,t){let{fileResolver:n,metadata:r,...i}=t??{},a=he(e,{metadata:r}),o=ot(this.requestOptions,i),{handle:s,settled:c}=Xe(this.sendQueue,async e=>{let t=this.spanParent?.startSpan(`agent.send`,{type:`workflow`,attributes:{sessionId:this.sessionId,...this.name?{agentName:this.name}:{}}});B(t,`message`,F(a.message.content));let r=`ok`;try{let i=await this.run(a,{signal:e,fileResolver:n,requestOptions:o,span:t});return i.ok||(r=`error`),t?.setAttributes({inputTokens:i.usage.in,outputTokens:i.usage.out}),i}catch(e){throw r=it(e),t?.error(e instanceof Error?e.message:String(e)),e}finally{t?.end(r),await this.ownedTracer?.flush()}},i.signal);return this.sendQueue=c,s}async resolveMcpTools(e,t){for(let n of this.mcps){if(this.resolvedMcps.has(n))continue;let r=await n.listTools({prefix:n.name,span:t,signal:e});this.registry.addMcp(r),this.resolvedMcps.add(n)}}emitEvent(e){for(let t of this.eventCallbacks)t(e)}toToolDefinitions(e){return e.map(e=>({name:e.name,description:e.description,schema:e.schema}))}async run(t,n){let{signal:r,fileResolver:i,requestOptions:a}=n,o=n.span,s=new qe,c=new e({turns:this.history.turns,sessionAnnotations:this.history.sessionAnnotations}),l,u=e=>{let t=c.apply(e);t.handled&&(this.history.replaceTurns(t.state.turns),this.history.replaceSessionAnnotations(t.state.sessionAnnotations??[])),this.emitEvent(e)},d=()=>l?c.state.turns.find(e=>e.id===l):void 0,f=K();if(r.aborted)throw new N(`Agent send aborted`,{reason:r.reason,usage:f});try{await this.resolveMcpTools(r,o)}catch(e){throw r.aborted||e instanceof M||e instanceof Error&&e.name===`AbortError`?new N(`Agent send aborted`,{reason:e instanceof M?e.reason:r.reason,usage:f}):e}let p=this.system,m=[...this.history.log,t.message];if(this.memory){let e=await this.memory.recall({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:m,span:o});e.systemSuffix&&(p=(p??``)+`
5
+ `)}function te(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 ie(e,t=500){return e.length>t?`${e.slice(0,t)}… (${e.length} chars)`:e}function ae(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 oe=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 se(e,t,n){if(!n)return;let r=ie(n);e?.info(t,{text:r}),r!==n&&e?.debug(t,{text:n})}function ce(e){let t=z(e.system??``),n=me(e.tools),r=me(e.mcpTools),i=he(e.providerTools),a=e.messages.reduce((e,t)=>e+le(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 le(e){switch(e.role){case`user`:return ue(e.content);case`assistant`:return ue(e.content);case`tool`:return e.content.reduce((e,t)=>e+fe(t),0)}}function ue(e){return typeof e==`string`?z(e):e.reduce((e,t)=>e+de(t),0)}function de(e){switch(e.type){case`text`:return z(e.text);case`thinking`:return z(e.summary??e.text??``);case`tool-call`:return z(e.name)+R(e.parameters);case`provider-tool`:return z(e.name)+R(e.input)+R(e.output);case`citation`:return R(e.citations);case`file`:return R(e.file)}}function fe(e){return z(e.name)+pe(e.content)}function pe(e){return typeof e==`string`?z(e):e.reduce((e,t)=>t.type===`text`?e+z(t.text):e+R(t.file),0)}function me(e){let t=e?.map(ge)??[];return t.length===0?0:R({tools:t})}function he(e){return!e||e.length===0?0:R({providerTools:e})}function ge(e){try{return{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}catch{return{name:e.name,description:e.description}}}function R(e){return e==null?0:z(JSON.stringify(e))}function z(e){return e?Math.ceil(e.length/3):0}function B(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(ve).join(` | `),t[0]]}if(e instanceof c.ZodLiteral){let t=e.value;return[ve(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]=B(t);return[`object array`,[e,e]]}else if(t instanceof c.ZodEnum||t instanceof c.ZodLiteral){let[e,n]=B(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]=B(r);n[e]=t}return[`JSON object`,n]}if(e instanceof c.ZodOptional){let[t,n]=B(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function _e(e){if(e instanceof c.ZodObject)return Object.entries(e.shape).map(([e,t])=>{let[n]=B(t);return[e,n]});let[t]=B(e);return[[`response`,t]]}function ve(e){return typeof e==`string`?JSON.stringify(e):String(e)}function ye(e,t){if(!t)return e;let n=be(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 be(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 xe(e,t={}){if(typeof e==`string`)return{message:{role:`user`,id:crypto.randomUUID(),content:[{type:`text`,text:e}],...t.metadata?{metadata:t.metadata}:{}},parse:e=>Se(e,void 0)};let n=e.render(),r=e.files,i=e.schema,a=t.metadata??e.metadata;return{message:{role:`user`,id:crypto.randomUUID(),content:ee({text:n,files:r}),...a?{metadata:a}:{}},parse:e=>Se(e,i)}}function Se(e,t){return e?ye(I(e.content),t):null}function V(){return{in:0,out:0}}function H(e,t){t&&(e.in+=t.in??0,e.out+=t.out??0,G(e,`cachedIn`,t.cachedIn),G(e,`cacheWriteIn`,t.cacheWriteIn),G(e,`reasoningOut`,t.reasoningOut),t.breakdown?.length&&(e.breakdown=we(e.breakdown,t.breakdown)))}function U(...e){let t=V();for(let n of e)H(t,n);return t}function Ce(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 we(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,G(t,`cachedIn`,e.cachedIn),G(t,`cacheWriteIn`,e.cacheWriteIn),G(t,`reasoningOut`,e.reasoningOut)}return n}function W(e,t){return{...e,...Ee(`cachedIn`,t.cachedIn),...Ee(`cacheWriteIn`,t.cacheWriteIn),...Ee(`reasoningOut`,t.reasoningOut)}}function Te(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 G(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function Ee(e,t){return typeof t==`number`?{[e]:t}:{}}var De=class{tools=new Map;mcpTools=new Map;providerTools=new Map;constructor(e){e?.tools&&this.add(e.tools),e?.providerTools&&this.addProvider(e.providerTools)}add(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.tools.set(e.name,e)}}addMcp(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.mcpTools.set(e.name,e)}}addProvider(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new A(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.providerTools.set(e.name,e)}}remove(e){let t=this.tools.delete(e),n=this.mcpTools.delete(e),r=this.providerTools.delete(e);return t||n||r}has(e){return this.tools.has(e)||this.mcpTools.has(e)||this.providerTools.has(e)}get(e){return this.tools.get(e)??this.mcpTools.get(e)}getProvider(e){return this.providerTools.get(e)}executable(){return[...this.tools.values(),...this.mcpTools.values()]}local(){return[...this.tools.values()]}mcp(){return[...this.mcpTools.values()]}provider(){return[...this.providerTools.values()]}get size(){return this.tools.size+this.mcpTools.size+this.providerTools.size}};const Oe=c.object({query:c.string().trim().min(1).max(400)});function ke(e){return{name:`web_search`,description:`Search the public web for current information. Returns source titles, URLs, and relevant extracted passages.`,schema:Oe,async execute(t,n){n.span?.setAttribute(`webSearchBackend`,e.name);let r=await e.search({query:t.query},{signal:n.signal,span:n.span});return n.span?.setAttribute(`webSearchResultCount`,r.results.length),JSON.stringify({query:t.query,results:r.results})},summarize(e){return`Search the web for "${e.query}"`}}}function Ae(e){let t=e.apiKey.trim();if(!t)throw Error(`Brave Search apiKey is required`);let n=e.endpoint??`https://api.search.brave.com/res/v1/llm/context`,r=K(e.maxResults??5,`maxResults`,1,50),i=e.candidateCount===void 0?void 0:K(e.candidateCount,`candidateCount`,1,50),a=K(e.maxTokens??4096,`maxTokens`,1,32768),o=e.maxSnippets===void 0?void 0:K(e.maxSnippets,`maxSnippets`,1,256),s=e.maxTokensPerUrl===void 0?void 0:K(e.maxTokensPerUrl,`maxTokensPerUrl`,1,8192),c=e.maxSnippetsPerUrl===void 0?void 0:K(e.maxSnippetsPerUrl,`maxSnippetsPerUrl`,1,100),l=e.timeoutMs===void 0?void 0:K(e.timeoutMs,`timeoutMs`,1);return{name:`brave`,async search(u,d){let f=new URL(n);f.searchParams.set(`q`,u.query),f.searchParams.set(`maximum_number_of_urls`,String(r)),i!==void 0&&f.searchParams.set(`count`,String(i)),f.searchParams.set(`maximum_number_of_tokens`,String(a)),o!==void 0&&f.searchParams.set(`maximum_number_of_snippets`,String(o)),s!==void 0&&f.searchParams.set(`maximum_number_of_tokens_per_url`,String(s)),c!==void 0&&f.searchParams.set(`maximum_number_of_snippets_per_url`,String(c)),e.contextThresholdMode&&f.searchParams.set(`context_threshold_mode`,e.contextThresholdMode),e.country&&f.searchParams.set(`country`,e.country),e.searchLanguage&&f.searchParams.set(`search_lang`,e.searchLanguage),e.freshness&&f.searchParams.set(`freshness`,e.freshness);let p=l===void 0?void 0:AbortSignal.timeout(l),m=p?AbortSignal.any([d.signal,p]):d.signal,h=await fetch(f,{method:`GET`,headers:{Accept:`application/json`,"X-Subscription-Token":t},signal:m});if(!h.ok){let e=(await h.text().catch(()=>``)).replaceAll(t,`[REDACTED]`);throw Error(`Brave Search request failed with status ${h.status}${e?`: ${e}`:``}`)}let g=await h.json(),_=[],v=[...g.grounding?.generic??[],...g.grounding?.poi?[g.grounding.poi]:[],...g.grounding?.map??[]];for(let e of v){if(_.length>=r)break;!e.title||!e.url||!e.snippets?.length||_.push({title:e.title,url:e.url,snippets:e.snippets})}return{results:_}}}}function K(e,t,n,r){if(!Number.isInteger(e))throw Error(`${t} must be an integer`);if(e<n)throw Error(`${t} must be greater than or equal to ${n}`);if(r!==void 0&&e>r)throw Error(`${t} must be less than or equal to ${r}`);return e}function je(e){if(e.maxIterations!==void 0&&e.maxIterations<1)throw new A(`maxIterations must be at least 1 (got ${e.maxIterations})`,{code:`INVALID_OPTIONS`});if(e.maxContextTokens!==void 0&&e.maxContextTokens<1)throw new A(`maxContextTokens must be at least 1 (got ${e.maxContextTokens})`,{code:`INVALID_OPTIONS`})}function Me(e,t,n){if(n.maxIterations!==void 0&&e>=n.maxIterations)return`max-iterations`;let r=t?t.in+t.out:0;if(n.maxContextTokens!==void 0&&r>=n.maxContextTokens)return`token-limit`}function Ne(e,t,n){t.usage&&H(e,n?Ce(t.usage,n):t.usage)}function Pe(e,t){if(!e)return;se(e,`text`,I(t));let n=L(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});Fe(e,re(t))}function Fe(e,t){if(t.length===0)return;let n=Ie(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 Ie(e){let t=new Set,n=[];for(let{source:r}of e){let e=Le(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 Le(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 Re(e){return JSON.stringify({error:e})}function ze(e){let t=e.tools!==void 0||e.providerTools!==void 0;if(e.registry&&t)throw new A("Cannot specify both `registry` and `tools` / `providerTools`. Use one or the other.",{code:`TOOL_OPTIONS_CONFLICT`});return e.registry??new De({tools:e.tools,providerTools:e.providerTools})}function Be(e,t){let n=e.getProvider(`web_search`),r=t.provider.resolveProviderToolName?.bind(t.provider);if(!r)return{registry:e,executable:()=>e.executable(),provider:()=>e.provider(),get:t=>e.get(t)};let i=()=>e.provider().map(e=>{let n=r(e.name,t.model);return n===void 0?e:{...e,nativeName:n}});if(!n||r(`web_search`,t.model)!==void 0)return{registry:e,executable:()=>e.executable(),provider:i,get:t=>e.get(t)};let a=t.configuration.webSearchFallback;if(!a)throw new A(`Provider ${t.provider.name} does not support native web_search and no Axle webSearchFallback is configured`,{code:`WEB_SEARCH_FALLBACK_NOT_CONFIGURED`,details:{provider:t.provider.name,model:t.model}});n.config&&t.span?.warn(`web_search provider config ignored by fallback backend`,{provider:t.provider.name,model:t.model,backend:a.name}),t.span?.info(`Using web search fallback backend`,{provider:t.provider.name,model:t.model,backend:a.name});let o=ke(a);return{registry:e,executable:()=>[...e.executable().filter(e=>e.name!==`web_search`),o],provider:()=>i().filter(e=>e.name!==`web_search`),get:t=>t===`web_search`?o:e.get(t)}}async function Ve(e,t=async()=>null,n,r,i,a){let o=[],s=V(),c=!1;for(let l of e){let e;try{e=await Ue(l,t,n,r,i,a)}catch(e){throw c?He(e,s):e}o.push(e.result),e.usage&&(H(s,e.usage),c=!0)}return{results:o,...c?{usage:s}:{}}}function He(e,t){return e instanceof P?new P(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:U(t,e.usage),cause:e.cause}):e instanceof M?new M(e.message,{reason:e.reason,messages:e.messages,partial:e.partial,usage:U(t,e.usage)}):e}async function Ue(e,t,n,r,i,a){if(n.aborted)throw new M(`Operation aborted`,{reason:n.reason});let o=r instanceof De?r:r.registry,s=r.get(e.name),c=i?.startSpan(e.name,{type:`tool`}),l,u={signal:n,span:c,registry:o,emit:t=>a?.onDelta?.(e,t),reportUsage:e=>{l??=V(),H(l,e)}};a?.onStart?.(e);let d,f=`exception`;try{if(d=await t(e.name,e.parameters,u),d==null&&s&&(f=`execution`,d={type:`success`,content:await s.execute(e.parameters,u)}),n.aborted)throw new M(`Operation aborted`,{reason:n.reason})}catch(t){let r=We(t,n);if(r){c?.setResult({kind:`tool`,name:e.name,input:e.parameters,output:{type:r instanceof P?`fatal`:`aborted`,message:r.message}}),c?.end(r instanceof P?`error`:`ok`);let t=l?He(r,l):r;throw a?.onError?.(e,t),t}d={type:`error`,error:{type:f,message:t instanceof Error?t.message:String(t)}}}d??={type:`error`,error:{type:`not-found`,message:`Tool not found: ${e.name}`}};let p={result:d,...l?{usage:l}:{}};a?.onComplete?.(e,p);let m=d.type===`success`?d.content:Re(d.error);return c?.setResult({kind:`tool`,name:e.name,input:e.parameters,output:d.type===`success`?d.content:d.error}),c?.end(d.type===`success`?`ok`:`error`),{result:{id:e.id,name:e.name,content:m,...d.type===`error`?{isError:!0}:{}},...l?{usage:l}:{}}}function We(e,t){if(e instanceof P||e instanceof M)return e;if(t.aborted)return new M(`Operation aborted`,{reason:t.reason})}let Ge=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});async function Ke(e,t){let n=[],r=``,i=``,a=null,o=V(),s=null,c=``,l=new Map,u=new Map,d=new Set,f=(e,n)=>{t.emit({type:`tool:request`,id:e,name:n,kind:t.tools.get(n)?.kind??`tool`})},p=-1,m=()=>{if(s!==null){let e=s===`text`?`text:end`:`thinking:end`;t.emit({type:e,final:c}),s=null,c=``}};for await(let h of e){switch(h.type){case`start`:r=h.id,i=h.data.model,t.emit({type:`turn:start`,id:r,model:i});break;case`text-start`:m(),n.push({type:`text`,text:``}),p=n.length-1,u.set(h.data.index,p),s=`text`,c=``,t.emit({type:`text:start`});break;case`text-delta`:{let e=n[p];e.text+=h.data.text,c=e.text,t.emit({type:`text:delta`,delta:h.data.text,accumulated:c});break}case`text-citation`:{let e=n[u.get(h.data.index)??p];if(!e||e.type!==`text`)break;e.citations=[...e.citations??[],h.data.citation],t.emit({type:`text:citation`,citation:h.data.citation,citations:e.citations});break}case`citation`:m(),n.push({type:`citation`,citations:h.data.citations,...h.data.providerMetadata?{providerMetadata:h.data.providerMetadata}:{}}),p=n.length-1,u.set(h.data.index,p),t.emit({type:`citation`,citations:h.data.citations,providerMetadata:h.data.providerMetadata});break;case`text-complete`:m();break;case`thinking-start`:m(),n.push({type:`thinking`,text:``,...h.data.id?{id:h.data.id}:{},...h.data.redacted===void 0?{}:{redacted:h.data.redacted},...h.data.continuity?{continuity:h.data.continuity}:{},...h.data.providerMetadata?{providerMetadata:h.data.providerMetadata}:{}}),p=n.length-1,u.set(h.data.index,p),s=`thinking`,c=``,t.emit({type:`thinking:start`,redacted:h.data.redacted,continuity:h.data.continuity,providerMetadata:h.data.providerMetadata});break;case`thinking-delta`:{let e=n[p];e.text=(e.text??``)+h.data.text,c=e.text,t.emit({type:`thinking:delta`,delta:h.data.text,accumulated:c});break}case`thinking-summary-delta`:{let e=n[p];e.summary=(e.summary??``)+h.data.text,c=e.summary,t.emit({type:`thinking:summary-delta`,delta:h.data.text,accumulated:c});break}case`thinking-metadata`:{let e=n[u.get(h.data.index)??p];if(!e||e.type!==`thinking`)break;h.data.redacted!==void 0&&(e.redacted=h.data.redacted),h.data.continuity&&(e.continuity=h.data.continuity),h.data.providerMetadata&&(e.providerMetadata=h.data.providerMetadata),t.emit({type:`thinking:update`,redacted:h.data.redacted,continuity:h.data.continuity,providerMetadata:h.data.providerMetadata});break}case`thinking-complete`:m();break;case`tool-call-start`:m(),n.push({type:`tool-call`,id:h.data.id,name:h.data.name,parameters:{}}),p=n.length-1,u.set(h.data.index,p),h.data.name?f(h.data.id,h.data.name):d.add(h.data.id);break;case`tool-call-args-delta`:d.has(h.data.id)&&h.data.name&&(d.delete(h.data.id),f(h.data.id,h.data.name)),t.emit({type:`tool:args-delta`,id:h.data.id,name:h.data.name,delta:h.data.delta,accumulated:h.data.accumulated});break;case`tool-call-complete`:{let e=n[u.get(h.data.index)??p];if(!e||e.type!==`tool-call`)break;h.data.id&&(e.id=h.data.id),h.data.name&&(e.name=h.data.name),e.parameters=h.data.arguments,h.data.providerMetadata&&(e.providerMetadata=h.data.providerMetadata),h.data.error&&l.set(e.id,h.data.error),d.has(e.id)&&e.name&&(d.delete(e.id),f(e.id,e.name));break}case`provider-tool-start`:m(),n.push({type:`provider-tool`,id:h.data.id,name:h.data.name}),p=n.length-1,u.set(h.data.index,p),t.emit({type:`provider-tool:start`,id:h.data.id,name:h.data.name});break;case`provider-tool-complete`:{let e=n[u.get(h.data.index)??p];e&&e.type===`provider-tool`&&h.data.output!=null&&(e.output=h.data.output),t.emit({type:`provider-tool:complete`,id:h.data.id,name:h.data.name,output:h.data.output});break}case`complete`:m(),a=h.data.finishReason,o=h.data.usage;break;case`error`:return m(),{kind:`provider-error`,errorType:h.data.type,message:h.data.message,usage:h.data.usage,model:i};default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.signal.aborted)break}return t.signal.aborted?(m(),{kind:`aborted`,partial:n.length?{role:`assistant`,id:r,model:i,content:n,finishReason:`cancelled`}:void 0}):a===null?(m(),{kind:`incomplete`}):{kind:`complete`,id:r,model:i,parts:n,finishReason:a,usage:o,toolCallArgumentErrors:l}}function qe(e){let t=e.raw?`${e.message}\nRaw buffer: ${e.raw}`:e.message;return{type:`error`,error:{type:e.type,message:t}}}async function Je(e,t,n,r){let{toolCallArgumentErrors:i}=t,{emit:a,signal:o,resolvedTools:s,span:c,onToolCall:l,newMessages:u,usage:d,addMessage:f}=r,p=crypto.randomUUID();a({type:`tool-results:start`,id:p});let m=[],h=new Map;for(let t of e){let e=i.get(t.id);if(!e){m.push(t);continue}let n=qe(e);h.set(t.id,{id:t.id,name:t.name,content:Re(n.error),isError:!0}),a({type:`tool:exec-complete`,id:t.id,name:t.name,result:n})}let g={onStart(e){a({type:`tool:exec-start`,id:e.id,name:e.name,parameters:e.parameters})},onDelta(e,t){a({type:`tool:exec-delta`,id:e.id,name:e.name,chunk:t})},onComplete(e,t){a({type:`tool:exec-complete`,id:e.id,name:e.name,result:t.result,usage:t.usage})},onError(e,t){a({type:`tool:exec-error`,id:e.id,name:e.name,error:{type:t instanceof P?`fatal`:`aborted`,message:t.message},usage:t.usage})}},_=[],v;try{m.length>0&&({results:_,usage:v}=await Ve(m,l,o,s,c,g))}catch(e){throw e instanceof P?(c?.end(`error`),new P(e.message,{toolName:e.toolName,messages:e.messages??u,partial:e.partial??n,usage:U(d,e.usage),cause:e.cause})):e instanceof M?(c?.end(`ok`),new M(`Stream aborted`,{reason:e.reason,messages:e.messages??u,partial:e.partial,usage:U(d,e.usage)})):e}H(d,v);let y=new Map(_.map(e=>[e.id,e])),b=e.flatMap(e=>{let t=h.get(e.id);if(t)return[t];let n=y.get(e.id);return n?[n]:[]});if(b.length>0){let e={role:`tool`,id:p,content:b};f(e),a({type:`tool-results:complete`,message:e})}}function Ye(e,t){for(let n of e)n(t)}function Xe(e){return{name:e.name,description:e.description,schema:e.schema}}function Ze(e){let t=[],n,r;if(`instruct`in e){let{instruct:t,messages:i,...a}=e,o=xe(t);r=o.parse,n={...a,messages:[...i??[],o.message]}}else n=e;je(n);let i=new AbortController,a=n.signal?AbortSignal.any([i.signal,n.signal]):i.signal,{promise:o,resolve:s,reject:c}=Promise.withResolvers(),l=k();return Promise.resolve().then(()=>Qe(n,a,t,l).then(e=>{if(r&&e.ok){try{s({...e,response:r(e.final)})}catch(t){s({ok:!1,messages:e.messages,final:e.final,usage:e.usage,...e.stopped?{stopped:e.stopped}:{},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 Qe(e,t,n,r){let{provider:i,model:a,messages:o,system:s,onToolCall:c,maxIterations:l,maxContextTokens:u,span:d,fileResolver:f,reasoning:p,maxOutputTokens:m,temperature:h,topP:g,stop:_,toolChoice:v,parallelToolCalls:y,providerOptions:b}=e,x=Be(ze(e),{provider:i,model:a,span:d,configuration:r}),S=[...o],C=[],w=V(),T=0,E=e=>{S.push(e),C.push(e)},D={emit:e=>Ye(n,e),signal:t,resolvedTools:x,span:d,onToolCall:c,newMessages:C,usage:w,addMessage:E},O=e=>{e.ok||Ye(n,{type:`error`,error:e.error});let t=e.ok?e.final.content:null,r=e.ok?e.final.finishReason:void 0;return d?.setResult({kind:`llm`,model:a,request:{messages:o},response:{content:t??null},usage:Te(e.usage),finishReason:r}),d?.end(e.ok?`ok`:`error`),e};for(;;){if(t.aborted)throw d?.end(`ok`),new M(`Stream aborted`,{reason:t.reason,messages:C,usage:w});T+=1;let e=d?.startSpan(`turn-${T}`,{type:`llm`}),r=x.executable(),o=r.length>0?r.map(Xe):void 0,c=x.provider(),k=await Ke(i.createStreamingRequest(a,{messages:S,system:s,tools:o,providerTools:c.length>0?c:void 0,runtime:{span:e,fileResolver:f},signal:t,reasoning:p,maxOutputTokens:m,temperature:h,topP:g,stop:_,toolChoice:v,parallelToolCalls:y,providerOptions:b}),{emit:e=>Ye(n,e),tools:x,signal:t});if(k.kind===`aborted`)throw e?.end(`ok`),k.partial&&E(k.partial),d?.end(`ok`),new M(`Stream aborted`,{reason:t.reason,messages:C,partial:k.partial,usage:w});if(k.kind===`provider-error`)return k.usage&&H(w,Ce(k.usage,{provider:i.name,model:k.model||a})),e?.end(`error`),O({ok:!1,messages:C,error:{kind:`model`,error:{type:`error`,error:{type:k.errorType,message:k.message}}},usage:w});if(k.kind===`incomplete`)return e?.end(`error`),O({ok:!1,messages:C,error:{kind:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:w});let{id:A,model:j,parts:N,finishReason:P,usage:F}=k,ee=Ce(F,{provider:i.name,model:j||a});H(w,ee);let I={kind:`llm`,model:j,request:{messages:S},response:{content:N},usage:Te(F),finishReason:P};Pe(e,N),e?.setResult(I),e?.end();let L={role:`assistant`,id:A,model:j,content:N,finishReason:P};if(E(L),Ye(n,{type:`turn:complete`,message:L,usage:ee}),P!==`function_call`)return O({ok:!0,response:L,messages:C,final:L,usage:w});let te=N.filter(e=>e.type===`tool-call`);if(te.length===0)return O({ok:!0,response:L,messages:C,final:L,usage:w});if(t.aborted)throw d?.end(`ok`),new M(`Stream aborted`,{reason:t.reason,messages:C,usage:w});await Je(te,k,L,D);let ne=Me(T,F,{maxIterations:l,maxContextTokens:u});if(ne)return O({ok:!0,response:L,messages:C,final:L,usage:w,stopped:ne})}}function q(e=new Date){return{start:e.toISOString()}}function J(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var $e=class{currentTurnId=null;currentTurnTiming;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage=V();createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=J(q(r),r),a=()=>({...i});if(typeof e.content==`string`)n.push({id:crypto.randomUUID(),type:`text`,text:e.content,timing:a()});else for(let t of e.content)t.type===`text`?n.push({id:crypto.randomUUID(),type:`text`,text:t.text,...t.citations?{citations:t.citations}:{},...t.providerMetadata?{providerMetadata:t.providerMetadata}:{},timing:a()}):t.type===`file`&&n.push({id:crypto.randomUUID(),type:`file`,file:t.file,timing:a()});return[{type:`turn:user`,turn:{id:t,owner:`user`,parts:n,status:`complete`,timing:i,...e.metadata?{metadata:e.metadata}:{}}}]}startAgentTurn(){let e=crypto.randomUUID();return this.currentTurnId=e,this.currentTurnTiming=q(),this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage=V(),{type:`turn:start`,turnId:e,timing:this.currentTurnTiming}}handleStreamEvent(e){let t=this.currentTurnId;if(!t)return[];let n=[];switch(e.type){case`turn:start`:break;case`text:start`:{this.closeOpenParts(n);let e=crypto.randomUUID(),r={id:e,type:`text`,text:``,timing:q()};this.currentTextPart={id:e,timing:r.timing},n.push({type:`part:start`,turnId:t,part:r});break}case`text:delta`:this.currentTextPart&&n.push({type:`text:delta`,turnId:t,partId:this.currentTextPart.id,delta:e.delta});break;case`text:end`:if(this.currentTextPart){let e=J(this.currentTextPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:e}),this.currentTextPart=null}break;case`citation`:{this.closeOpenParts(n);let r=J(q()),i={id:crypto.randomUUID(),type:`citation`,citations:e.citations,...e.providerMetadata?{providerMetadata:e.providerMetadata}:{},timing:r};n.push({type:`part:start`,turnId:t,part:i}),n.push({type:`part:end`,turnId:t,partId:i.id,timing:r});break}case`thinking:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i={id:r,type:`thinking`,text:``,timing:q(),...e.redacted===void 0?{}:{redacted:e.redacted},...e.continuity?{continuity:e.continuity}:{},...e.providerMetadata?{providerMetadata:e.providerMetadata}:{}};this.currentThinkingPart={id:r,timing:i.timing},n.push({type:`part:start`,turnId:t,part:i});break}case`thinking:delta`:this.currentThinkingPart&&n.push({type:`thinking:delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`text:citation`:this.currentTextPart&&n.push({type:`text:citation`,turnId:t,partId:this.currentTextPart.id,citation:e.citation});break;case`thinking:summary-delta`:this.currentThinkingPart&&n.push({type:`thinking:summary-delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`thinking:update`:this.currentThinkingPart&&n.push({type:`thinking:update`,turnId:t,partId:this.currentThinkingPart.id,redacted:e.redacted,continuity:e.continuity,providerMetadata:e.providerMetadata});break;case`thinking:end`:if(this.currentThinkingPart){let e=J(this.currentThinkingPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:e}),this.currentThinkingPart=null}break;case`tool:request`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=q(),a=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){H(this.accumulatedUsage,e.usage);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`tool:exec-error`:{let r=this.toolIdMap.get(e.id);if(r){H(this.accumulatedUsage,e.usage);let i=J(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=q(),a={id:r,type:`action`,kind:`provider-tool`,status:`running`,timing:i,detail:{name:e.name}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i}),n.push({type:`part:start`,turnId:t,part:a}),n.push({type:`action:running`,turnId:t,partId:r});break}case`provider-tool:complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=J(r.timing);r.timing=i,n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.output},timing:i})}break}case`turn:complete`:this.closeOpenParts(n),H(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))}},et=class{_turns;_messages;_archive;_compactions;_sessionAnnotations;constructor(e){this._turns=[...e?.turns??[]],this._messages=[...e?.messages??[]],this._archive=[...e?.archive??e?.messages??[]],this._compactions=[...e?.compactions??[]],this._sessionAnnotations=[...e?.sessionAnnotations??[]]}get turns(){return[...this._turns]}get messages(){return[...this._messages]}get archive(){return[...this._archive]}get compactions(){return[...this._compactions]}get sessionAnnotations(){return[...this._sessionAnnotations]}append(e){let t=Array.isArray(e)?e:[e];this._messages.push(...t),this._archive.push(...t)}replaceTurns(e,t){this._turns=e,this._sessionAnnotations=t}compact(e,t){this._messages=[...e],this._compactions.push(t)}};const tt={trace:0,debug:1,info:2,warn:3,error:4},nt=()=>performance.timeOrigin+performance.now();var rt=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 tt[e]>=tt[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()}},it=class{rec=new rt;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:nt(),status:`ok`,attributes:{...t?.attributes??{}},events:[]};return this.rec.spanStart(n),new at(n,this.rec)}flush(){return this.rec.flush()}},at=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:nt(),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=nt(),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:nt(),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 ot(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 it({minLevel:r,writers:[new oe(n)]});return{parent:e,owned:e}}return{}}function st(e){return ct(e)?`cancelled`:`error`}function ct(e){return e instanceof M||e instanceof N||e instanceof Error&&e.name===`AbortError`}function lt(e,t){return{...e,...t,providerOptions:e?.providerOptions||t?.providerOptions?{...e?.providerOptions,...t?.providerOptions}:void 0}}var ut=class{provider;model;history;name;fileResolver;requestOptions;registry;sessionId;system;mcps=[];resolvedMcps=new WeakSet;memory;spanParent;ownedTracer;eventCallbacks=[];compactionCallback;workQueue=Promise.resolve();accumulator;constructor(t,n){if(n&&n.version!==1)throw new A(`Unsupported agent session version: ${n.version}`);this.provider=t.provider,this.model=t.model,this.sessionId=n?.sessionId??t.sessionId??crypto.randomUUID(),this.history=new et(n?{turns:n.turns,messages:n.messages,archive:n.archive,compactions:n.compactions,sessionAnnotations:n.sessionAnnotations}:void 0),this.accumulator=new e({turns:this.history.turns,sessionAnnotations:this.history.sessionAnnotations});let r=ot(t.observability);if(this.spanParent=r.parent,this.ownedTracer=r.owned,this.system=t.system,this.name=t.name,this.fileResolver=t.fileResolver,this.requestOptions={reasoning:t.reasoning,maxOutputTokens:t.maxOutputTokens,temperature:t.temperature,topP:t.topP,stop:t.stop,toolChoice:t.toolChoice,parallelToolCalls:t.parallelToolCalls,providerOptions:t.providerOptions},this.registry=new De({tools:t.tools,providerTools:t.providerTools}),t.mcps&&(this.mcps=[...t.mcps]),t.memory){this.memory=t.memory;let e=t.memory.tools?.();e&&this.registry.add(e)}}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 this.estimateContext(this.history.messages)}estimateContext(e){return ce({system:this.system,messages:e,tools:this.toToolDefinitions(this.registry.local()),providerTools:this.registry.provider(),mcpTools:this.toToolDefinitions(this.registry.mcp())})}onCompaction(e){this.compactionCallback=e}compact(e){let t=this.compactionCallback;return t?this.queue(async e=>{if(e.aborted)return null;let n=this.spanParent?.startSpan(`agent.compact`,{type:`workflow`,attributes:{sessionId:this.sessionId,...this.name?{agentName:this.name}:{}}}),r=`ok`,i=crypto.randomUUID(),a=new Date().toISOString();this.emitEvent({type:`compaction:start`,id:i,timing:{start:a}});let o=(e,t)=>{n?.setAttribute(`outcome`,e),this.emitEvent({type:`compaction:end`,id:i,outcome:e,record:t,timing:{start:a,end:new Date().toISOString()}})};try{let r=this.context(),s=await t({messages:this.history.messages},{usage:r,signal:e});if(e.aborted||s==null)return o(`skipped`),null;F(s);let c={id:i,at:a};return this.history.compact(s,c),n&&n.setAttributes({beforeTokens:r.total,afterTokens:this.context().total}),o(`complete`,c),c}catch(t){if(e.aborted)return o(`skipped`),null;throw r=st(t),n?.error(t instanceof Error?t.message:String(t)),o(`error`),t}finally{n?.end(r),await this.ownedTracer?.flush()}},e?.signal).final:Promise.resolve(null)}snapshot(){return this.queue(async()=>{let{messages:e,archive:t,compactions:n,turns:r,sessionAnnotations:i}=this.history;return{version:1,sessionId:this.sessionId,messages:e,archive:t,compactions:n,turns:r,sessionAnnotations:i}}).final}send(e,t){let{fileResolver:n,metadata:r,...i}=t??{},a=xe(e,{metadata:r}),o=lt(this.requestOptions,i);return this.queue(async e=>{let t=this.spanParent?.startSpan(`agent.send`,{type:`workflow`,attributes:{sessionId:this.sessionId,...this.name?{agentName:this.name}:{}}});se(t,`message`,I(a.message.content));let r=`ok`;try{let i=await this.run(a,{signal:e,fileResolver:n,requestOptions:o,span:t});return i.ok||(r=`error`),t?.setAttributes({inputTokens:i.usage.in,outputTokens:i.usage.out}),i}catch(e){throw r=st(e),t?.error(e instanceof Error?e.message:String(e)),e}finally{t?.end(r),await this.ownedTracer?.flush()}},i.signal)}queue(e,t){let n=new AbortController,r=t?AbortSignal.any([t,n.signal]):n.signal,i=this.workQueue.then(()=>e(r));return this.workQueue=i.then(()=>{},()=>{}),{cancel:e=>n.abort(e),final:i}}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){let t=this.accumulator.apply(e);t.handled&&this.history.replaceTurns(t.state.turns,t.state.sessionAnnotations??[]);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(e,t){let{signal:n,fileResolver:r,requestOptions:i}=t,a=t.span,o=new $e,s,c=()=>s?this.accumulator.state.turns.find(e=>e.id===s):void 0,l=V();if(n.aborted)throw new N(`Agent send aborted`,{reason:n.reason,usage:l});try{await this.resolveMcpTools(n,a)}catch(e){throw n.aborted||e instanceof M||e instanceof Error&&e.name===`AbortError`?new N(`Agent send aborted`,{reason:e instanceof M?e.reason:n.reason,usage:l}):e}let u=this.system,d=[...this.history.messages,e.message];if(this.memory){let e=await this.memory.recall({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:d,span:a});e.systemSuffix&&(u=(u??``)+`
6
6
 
7
- `+e.systemSuffix)}if(r.aborted)throw new N(`Agent send aborted`,{reason:r.reason,usage:f});this.history.appendToLog(t.message);for(let e of s.createUserTurn(t.message))u(e);let h=s.startAgentTurn();l=h.turnId,u(h);let g=o?.startSpan(`stream`,{type:`internal`})??void 0,{signal:_,...v}=a??{},y=We({provider:this.provider,model:this.model,messages:m,system:p,registry:this.registry,span:g,fileResolver:i??this.fileResolver,...v,signal:r});y.on(e=>{let t=s.handleStreamEvent(e);for(let e of t)u(e)});let b,x=`ok`;try{b=await y.final,b.ok||(x=`error`)}catch(e){if(x=it(e),e instanceof P){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=s.finalizeTurn(`error`);for(let e of t)u(e);throw new P(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:e.usage??f,cause:e.cause})}if(e instanceof M){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=s.finalizeTurn(`cancelled`);for(let e of t)u(e);throw new N(`Agent send aborted`,{reason:e.reason,messages:e.messages,partial:e.partial,turn:d(),usage:e.usage??f})}throw e}finally{g?.end(x)}let S=b.ok?`complete`:`error`;b.ok&&b.final?.finishReason&&o?.setAttribute(`finishReason`,b.final.finishReason),b.messages.length>0&&this.history.appendToLog(b.messages);let C=s.finalizeTurn(S);for(let e of C)u(e);let w=b.usage??f,T=d();if(!b.ok)return{ok:!1,error:b.error,turn:T,usage:w};let E;try{E=t.parse(b.final)}catch(e){return{ok:!1,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)},turn:T,usage:w}}if(!T)throw new A(`Agent turn missing after send`);if(this.memory)try{await this.memory.record({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:this.history.log,newMessages:b.messages,span:o})}catch(e){o?.warn(`memory record failed`,{error:e instanceof Error?e.message:String(e)})}return{ok:!0,response:E,turn:T,usage:w}}};function ct(e){try{let t=l.fromJSONSchema(e);return t instanceof l.ZodObject?t.strict():l.object({}).passthrough()}catch{return l.object({}).passthrough()}}function lt(e,t,n){return e.map(e=>dt(e,t,n))}function ut(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=ct(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function dt(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=ct(e.inputSchema);return{name:r,description:e.description??``,schema:i,async execute(n,i){let a;try{a=await t.callTool({name:e.name,arguments:n},void 0,{signal:i.signal})}catch(t){throw i.signal.aborted||t instanceof Error&&t.name===`AbortError`?t:new P(`MCP tool call failed: ${e.name}`,{toolName:r,cause:t})}if(`isError`in a&&a.isError)throw Error(pt(a.content));return ft(a.content)}}}function ft(e){return e.some(e=>e.type===`image`)?e.filter(e=>e.type===`text`||e.type===`image`).map(e=>{if(e.type===`text`)return{type:`text`,text:e.text};let t=e;return{type:`file`,file:{kind:`image`,mimeType:t.mimeType,name:`mcp-image`,source:{type:`base64`,data:t.data}}}}):e.filter(e=>e.type===`text`).map(e=>e.text).join(`
8
- `)}function pt(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
9
- `)||`MCP tool execution error`}var mt=class{config;client;transport;cachedMcpTools;_connected=!1;constructor(e){this.config=e}get name(){return this.config.name??this.client?.getServerVersion()?.name}get connected(){return this._connected}async connect(e){if(this._connected)return;let t=e?.span?.startSpan(`mcp:connect`,{type:`internal`});this.client=new d({name:`axle`,version:`1.0.0`}),this.config.transport===`stdio`?this.transport=new f({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new p(new URL(this.config.url),{requestInit:this.config.headers?{headers:this.config.headers}:void 0});try{await this.client.connect(this.transport,{signal:e?.signal}),this._connected=!0,t?.end(`ok`)}catch(e){throw t?.end(`error`),e}}async listTools(e){let t=this.assertConnected();return lt(await this.fetchTools(t,e?.span,e?.signal),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return ut(await this.fetchTools(t,e?.span,e?.signal),e?.prefix)}async refreshTools(){return this.assertConnected(),this.cachedMcpTools=void 0,this.listTools()}async close(e){this._connected&&(e?.span?.debug(`mcp:close`),await this.client?.close(),this._connected=!1,this.client=void 0,this.transport=void 0,this.cachedMcpTools=void 0)}async fetchTools(e,t,n){if(this.cachedMcpTools)return this.cachedMcpTools;t?.debug(`mcp:listTools`);let r=await e.listTools(void 0,{signal:n});return this.cachedMcpTools=r.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})),this.cachedMcpTools}assertConnected(){if(!this._connected||!this.client)throw Error(`MCP not connected. Call connect() first.`);return this.client}};function ht(e){return e?.map(e=>({type:`provider`,name:e.name,config:e.config}))}async function gt(e,t){if(e.version!==1)throw new A(`Unsupported agent definition version: ${e.version}`);let n=await t(e),r=e.model??n.model;if(!r)throw new A(`AgentDefinition requires a model or model resolver`);if(e.tools?.length&&!n.tools)throw new A(`AgentDefinition includes tools but resolver did not return tools`);return{provider:n.provider,model:r,system:e.system,name:e.name,tools:n.tools,providerTools:n.providerTools??ht(e.providerTools),mcps:n.mcps??e.mcps?.map(e=>new mt(e)),reasoning:e.request?.reasoning,maxOutputTokens:e.request?.maxOutputTokens,temperature:e.request?.temperature,topP:e.request?.topP,stop:e.request?.stop,toolChoice:e.request?.toolChoice,parallelToolCalls:e.request?.parallelToolCalls,providerOptions:e.request?.providerOptions}}var _t=class e extends A{missingVariables;constructor(t){super(vt(t),{code:`INSTRUCT_VARIABLE_ERROR`,details:{missingVariables:t}}),this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),missingVariables:this.missingVariables}}};function vt(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var yt=class e extends Error{missingVariables;constructor(t){super(xt(t)),this.name=`MissingVariablesError`,this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}};function bt(e,t,n={}){let{placeholderStyle:r=`{{}}`,strict:i=!0}=n,a=r===`{{}}`?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g,o=[];if(e=e.replace(a,(e,n)=>{if(n=n.trim(),Object.prototype.hasOwnProperty.call(t,n)){let e=t[n];return e==null?``:String(e)}return o.push(n),e}),o.length>0){let e=[...new Set(o)];if(i)throw new yt(e)}return e}function xt(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var St=class e{prompt;inputs={};files=[];textReferences=[];contextSections=[];vars;metadata;schema;constructor(e){this.prompt=e.prompt,this.schema=e.schema,this.vars=e.vars??`required`,this.metadata=e.metadata}clone(){let t=new e({prompt:this.prompt,schema:this.schema,vars:this.vars,metadata:this.metadata});return t.inputs={...this.inputs},t.files=[...this.files],t.textReferences=this.textReferences.map(e=>({...e})),t.contextSections=this.contextSections.map(e=>({...e})),t}withInputs(e){let t=this.clone();return t.inputs={...t.inputs,...e},t}withInput(e,t){return this.withInputs({[e]:t})}setInputs(e){this.inputs={...e}}addInput(e,t){this.inputs[e]=t}addFile(e,t){if(typeof e==`string`){this.textReferences.push({content:e,name:t?.name});return}if(e.kind===`text`&&e.source.type===`text`){this.textReferences.push({content:e.source.content,name:t?.name??e.name});return}this.files.push(t?.name?{...e,name:t.name}:e)}addContext(e,t){return this.contextSections.push({content:e,...t?.title?{title:t.title}:{}}),this}hasFiles(){return this.files.length>0}render(e={}){let t;try{t=bt(this.prompt,this.inputs,{strict:(e.vars??this.vars)===`required`})}catch(e){throw e instanceof yt?new _t(e.missingVariables):e}if(this.textReferences.length>0)for(let[e,n]of this.textReferences.entries()){let r=n.name?`: ${n.name}`:``,i=Ct(n.content);t+=`\n\n## Reference ${e+1}${r}\n\n${i}\n${n.content}\n${i}`}for(let[e,n]of this.contextSections.entries()){let r=n.title?`: ${n.title}`:``,i=Ct(n.content);t+=`\n\n## Context ${e+1}${r}\n\n${i}\n${n.content}\n${i}`}if(!this.schema)return t;let n=`# Output Format Instructions
7
+ `+e.systemSuffix)}if(n.aborted)throw new N(`Agent send aborted`,{reason:n.reason,usage:l});this.history.append(e.message);for(let t of o.createUserTurn(e.message))this.emitEvent(t);let f=o.startAgentTurn();s=f.turnId,this.emitEvent(f);let p=a?.startSpan(`stream`,{type:`internal`})??void 0,{signal:m,...h}=i??{},g=Ze({provider:this.provider,model:this.model,messages:d,system:u,registry:this.registry,span:p,fileResolver:r??this.fileResolver,...h,signal:n});g.on(e=>{let t=o.handleStreamEvent(e);for(let e of t)this.emitEvent(e)});let _,v=`ok`;try{_=await g.final,_.ok||(v=`error`)}catch(e){if(v=st(e),e instanceof P){e.messages&&e.messages.length>0&&this.history.append(e.messages);let t=o.finalizeTurn(`error`);for(let e of t)this.emitEvent(e);throw new P(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:e.usage??l,cause:e.cause})}if(e instanceof M){e.messages&&e.messages.length>0&&this.history.append(e.messages);let t=o.finalizeTurn(`cancelled`);for(let e of t)this.emitEvent(e);throw new N(`Agent send aborted`,{reason:e.reason,messages:e.messages,partial:e.partial,turn:c(),usage:e.usage??l})}throw e}finally{p?.end(v)}let y=_.ok?`complete`:`error`;_.ok&&_.final?.finishReason&&a?.setAttribute(`finishReason`,_.final.finishReason),_.messages.length>0&&this.history.append(_.messages);let b=o.finalizeTurn(y);for(let e of b)this.emitEvent(e);let x=_.usage??l,S=c();if(!_.ok)return{ok:!1,error:_.error,turn:S,usage:x};let C;try{C=e.parse(_.final)}catch(e){return{ok:!1,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)},turn:S,usage:x}}if(!S)throw new A(`Agent turn missing after send`);if(this.memory)try{await this.memory.record({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:this.history.messages,newMessages:_.messages,span:a})}catch(e){a?.warn(`memory record failed`,{error:e instanceof Error?e.message:String(e)})}return{ok:!0,response:C,turn:S,usage:x}}};function dt(e){try{let t=l.fromJSONSchema(e);return t instanceof l.ZodObject?t.strict():l.object({}).passthrough()}catch{return l.object({}).passthrough()}}function ft(e,t,n){return e.map(e=>mt(e,t,n))}function pt(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=dt(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function mt(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=dt(e.inputSchema);return{name:r,description:e.description??``,schema:i,async execute(n,i){let a;try{a=await t.callTool({name:e.name,arguments:n},void 0,{signal:i.signal})}catch(t){throw i.signal.aborted||t instanceof Error&&t.name===`AbortError`?t:new P(`MCP tool call failed: ${e.name}`,{toolName:r,cause:t})}if(`isError`in a&&a.isError)throw Error(gt(a.content));return ht(a.content)}}}function ht(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 gt(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
9
+ `)||`MCP tool execution error`}var _t=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 ft(await this.fetchTools(t,e?.span,e?.signal),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return pt(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 vt(e){return e?.map(e=>({type:`provider`,name:e.name,config:e.config}))}async function yt(e,t){if(e.version!==1)throw new A(`Unsupported agent definition version: ${e.version}`);let n=await t(e),r=e.model??n.model;if(!r)throw new A(`AgentDefinition requires a model or model resolver`);if(e.tools?.length&&!n.tools)throw new A(`AgentDefinition includes tools but resolver did not return tools`);return{provider:n.provider,model:r,system:e.system,name:e.name,tools:n.tools,providerTools:n.providerTools??vt(e.providerTools),mcps:n.mcps??e.mcps?.map(e=>new _t(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 bt=class e extends A{missingVariables;constructor(t){super(xt(t),{code:`INSTRUCT_VARIABLE_ERROR`,details:{missingVariables:t}}),this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),missingVariables:this.missingVariables}}};function xt(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var St=class e extends Error{missingVariables;constructor(t){super(wt(t)),this.name=`MissingVariablesError`,this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}};function Ct(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 St(e)}return e}function wt(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var Tt=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=Ct(this.prompt,this.inputs,{strict:(e.vars??this.vars)===`required`})}catch(e){throw e instanceof St?new bt(e.missingVariables):e}if(this.textReferences.length>0)for(let[e,n]of this.textReferences.entries()){let r=n.name?`: ${n.name}`:``,i=Et(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=Et(n.content);t+=`\n\n## Context ${e+1}${r}\n\n${i}\n${n.content}\n${i}`}if(!this.schema)return t;let n=`# Output Format Instructions
10
10
 
11
11
  Return only valid JSON matching this schema. Do not wrap it in markdown. Do not include prose before or after the JSON.
12
- `,[,r]=ue(this.schema);for(let[e,t]of de(this.schema))n+=`\n- ${e}: ${t}`;return n+=`\n\nExample:\n${JSON.stringify(r,null,2)}\n\n`,n+t}};function Ct(e){let t=Math.max(0,...Array.from(e.matchAll(/`+/g),e=>e[0].length));return"`".repeat(Math.max(3,t+1))}var wt=class e extends A{constructor(t,n){super(t,{code:`TASK_ERROR`,id:n?.id,details:{taskType:n?.taskType,taskIndex:n?.taskIndex,...n?.details},cause:n?.cause}),Object.setPrototypeOf(this,e.prototype)}};function X(e,t,n={}){if(!Number.isInteger(e))throw Error(`${t} must be an integer`);if(n.min!==void 0&&e<n.min)throw Error(`${t} must be an integer greater than or equal to ${n.min}`);return e}function Tt(e){if(e==null)return{type:`error`,error:{type:`Undetermined`,message:`Unknown error occurred`},usage:{in:0,out:0},raw:e};if(e instanceof Error)return{type:`error`,error:{type:e.name||`Error`,message:e.message||`Unexpected error`},usage:{in:0,out:0},raw:e};if(typeof e==`object`){let t=e,n=t?.error?.error?.type||t?.error?.type||t?.type||t?.code||t?.status||`Undetermined`,r=t?.error?.error?.message||t?.error?.message||t?.message||t?.error||`Unexpected error`;return{type:`error`,error:{type:String(n),message:String(r)},usage:{in:0,out:0},raw:e}}return{type:`error`,error:{type:`Undetermined`,message:String(e)},usage:{in:0,out:0},raw:e}}function Z(e,t=`Operation aborted`){if(e?.aborted)throw new M(t,{reason:e.reason})}function Et(e,t,n=`Operation aborted`){return t?t.aborted?Promise.reject(new M(n,{reason:t.reason})):new Promise((r,i)=>{let a=()=>{t.removeEventListener(`abort`,a),i(new M(n,{reason:t.reason}))};t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,a),r(e)},e=>{t.removeEventListener(`abort`,a),i(e)})}):e}function Dt(e,t,n=`[redacted]`){return Ot(e,null,t,n)}function Ot(e,t,n,r){if(typeof e!=`object`||!e)return typeof e==`string`&&t&&n.has(t)?r:e;if(Array.isArray(e))return e.map(e=>Ot(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=Ot(a,t,n,r);return i}const kt=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function At(e){return Dt(e,kt,`[redacted-file-value]`)}const jt=20*1024*1024;async function Q(e,t){if(t.signal?.aborted)throw new DOMException(`File resolution aborted`,`AbortError`);let{source:n}=e;if(n.type===`base64`)return Mt({type:`base64`,data:n.data},e,t);if(n.type===`text`)return Mt({type:`text`,content:n.content},e,t);if(n.type===`url`)return Mt({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return Mt(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function Mt(e,t,n){if(n.accepted.includes(e.type))return{...e,mimeType:e.mimeType??t.mimeType,name:e.name??t.name};throw Error(`File source '${e.type}' is not supported for ${n.provider} ${t.kind} file '${t.name}'. Accepted: ${n.accepted.join(`, `)}`)}const Nt=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function Pt(e){return e.startsWith(`text/`)||Nt.has(e)}function Ft(e){let t=h.getType(e);if(!t){let t=y(e).toLowerCase();throw Error(`Unsupported file type: ${t||`(no extension)`}`)}if(t.startsWith(`image/`))return{kind:`image`,mimeType:t};if(t===`application/pdf`)return{kind:`document`,mimeType:t};if(Pt(t))return{kind:`text`,mimeType:t};{let n=y(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function It(e,t){let n=b(e);try{await g(n)}catch{throw Error(`File not found: ${e}`)}let r=await v(n);if(r.size>jt)throw Error(`File too large: ${r.size} bytes. Maximum allowed: ${jt} bytes`);let i=n.split(`/`).pop()||``,a=Ft(n);if((t||(a.kind===`text`?`utf-8`:`base64`))===`utf-8`){if(a.kind!==`text`)throw Error(`Cannot read ${a.kind} file as text: ${e}`);let t=await _(n,`utf-8`);return{kind:`text`,mimeType:a.mimeType,size:r.size,name:i,source:{type:`text`,content:t}}}else{if(a.kind===`text`)throw Error(`Cannot read text file as binary: ${e}`);let t=(await _(n)).toString(`base64`);return{kind:a.kind,mimeType:a.mimeType,size:r.size,name:i,source:{type:`base64`,data:t}}}}async function Lt(e,t={model:``}){return Promise.all(e.map(e=>Rt(e,t)))}async function Rt(e,t){if(e.role===`assistant`){let t=[];for(let n of e.content)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`thinking`){let e=n.continuity?.provider===`anthropic`?n.continuity:void 0;n.redacted?t.push({type:`redacted_thinking`,data:e?.redactedData??n.text??``}):e?.signature&&t.push({type:`thinking`,thinking:n.text??``,signature:e.signature})}else n.type===`tool-call`?t.push({type:`tool_use`,id:n.id,name:n.name,input:n.parameters}):n.type===`provider-tool`&&(t.push({type:`server_tool_use`,id:n.id,name:n.name,input:n.input??{}}),n.output!=null&&t.push({type:`web_search_tool_result`,tool_use_id:n.id,content:n.output}));return{role:`assistant`,content:t}}if(e.role===`tool`)return{role:`user`,content:await Promise.all(e.content.map(async e=>({type:`tool_result`,tool_use_id:e.id,content:typeof e.content==`string`?e.content:await en(e.content,t),...e.isError?{is_error:!0}:{}})))};if(typeof e.content==`string`)return{role:`user`,content:e.content};{let n=[];for(let r of e.content)r.type===`text`?n.push({type:`text`,text:r.text}):r.type===`file`&&n.push(await zt(r.file,t,`user-message`));return{role:`user`,content:n}}}async function zt(e,t,n){if(e.kind===`image`)return{type:`image`,source:Vt(await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`Anthropic only supports PDF document files. Received ${e.mimeType}`);let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`document`,source:Ht(r),title:r.name??e.name,citations:{enabled:!0}}}let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Anthropic text source: ${r.type}`);return n===`tool-result`?{type:`text`,text:r.content}:{type:`document`,source:{type:`text`,media_type:`text/plain`,data:r.content},title:r.name??e.name,citations:{enabled:!0}}}function Bt(e){if(e===`image/jpeg`||e===`image/png`||e===`image/gif`||e===`image/webp`)return e;throw Error(`Anthropic does not support image MIME type: ${e}. Supported types: image/jpeg, image/png, image/gif, image/webp.`)}function Vt(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:Bt(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function Ht(e){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:`application/pdf`,data:e.data};throw Error(`Unsupported Anthropic PDF source: ${e.type}`)}function Ut(e,t=``){return e===!0?Wt(t)?{thinking:{type:`adaptive`},output_config:{effort:`high`}}:{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function Wt(e){let t=e.toLowerCase().match(/claude-(opus|sonnet)-(\d+)-(\d+)/);if(!t)return!1;let[,n,r,i]=t,a=Number(r),o=Number(i);return!Number.isFinite(a)||!Number.isFinite(o)?!1:n===`opus`||n===`sonnet`?a>4||a===4&&o>=6:!1}function Gt(e){return e.map(e=>{let t=l.toJSONSchema(e.schema);if(!$t(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}const Kt={web_search:`web_search_20250305`};function qt(e){return Kt[e]??e}function Jt(e){return(e??[]).map(e=>({type:e.nativeName??qt(e.name),name:e.name,...e.config}))}function Yt(e,t,n,r){if(e===void 0&&t!==!1)return{};let i=t===!1?{disable_parallel_tool_use:!0}:{};if(e===void 0||e===`auto`)return{tool_choice:{type:`auto`,...i}};if(e===`required`)return{tool_choice:{type:`any`,...i}};if(e===`none`)return{tool_choice:{type:`none`}};if(!(n?.some(t=>t.name===e.name)||r?.some(t=>t.name===e.name)))throw Error(`Tool choice references an unavailable tool: ${e.name}`);return{tool_choice:{type:`tool`,name:e.name,...i}}}function Xt(e){let t=[];for(let n of e)if(n.type===`text`){let e=n.citations?.map(Zt);t.push({type:`text`,text:n.text,...e&&e.length>0?{citations:e}:{}})}else if(n.type===`thinking`){let e=n.thinking.length===0&&!!n.signature;t.push({type:`thinking`,...n.thinking?{text:n.thinking}:{},redacted:e,continuity:{provider:`anthropic`,signature:n.signature}})}else if(n.type===`redacted_thinking`)t.push({type:`thinking`,redacted:!0,continuity:{provider:`anthropic`,redactedData:n.data}});else if(n.type===`tool_use`){if(typeof n.input!=`object`||n.input===null||Array.isArray(n.input))throw Error(`Invalid tool call input for ${n.name}: expected object, got ${typeof n.input}`);t.push({type:`tool-call`,id:n.id,name:n.name,parameters:n.input})}return t}function Zt(e){switch(e.type){case`char_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`char`,start:e.start_char_index,end:e.end_char_index}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`page_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`page`,start:e.start_page_number,end:e.end_page_number}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`content_block_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`block`,start:e.start_block_index,end:e.end_block_index}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`web_search_result_location`:return{source:{type:`web`,title:e.title??void 0,url:e.url,citedText:e.cited_text},providerMetadata:{type:e.type,encryptedIndex:e.encrypted_index}};case`search_result_location`:return{source:{type:`search-result`,title:e.title??void 0,url:e.source,citedText:e.cited_text,locator:{type:`block`,start:e.start_block_index,end:e.end_block_index}},providerMetadata:{type:e.type,searchResultIndex:e.search_result_index}}}}function Qt(e){switch(e){case`max_tokens`:return`length`;case`end_turn`:return`stop`;case`stop_sequence`:return`stop`;case`tool_use`:return`function_call`;default:return`error`}}function $t(e){return e&&typeof e==`object`&&e.type===`object`}async function en(e,t){return Promise.all(e.map(async e=>e.type===`text`?{type:`text`,text:e.text}:zt(e.file,t,`tool-result`)))}async function tn(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v;try{Z(g,`Generate aborted`);let e=await Lt(r,{model:n,fileResolver:s?.fileResolver,signal:g}),y={model:n,max_tokens:l??16e3,messages:e,...i&&{system:i},...f&&{stop_sequences:Je(f)},...(a||o)&&{tools:[...a?Gt(a):[],...Jt(o)]},...Ut(c,n),...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Yt(p,m,a,o),...h};_?.debug(`Anthropic request`,{request:At(y)});let b=await Et(t.messages.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);Z(g,`Generate aborted`),v=nn(b)}catch(e){Z(g,`Generate aborted`),v=Tt(e)}return _?.debug(`Anthropic response`,{result:v}),v}function nn(e){let t=Qt(e.stop_reason);if(t===`error`)return{type:`error`,error:{type:`Uncaught error`,message:`Stop reason is not recognized or unhandled: ${e.stop_reason}`},usage:an(e.usage),raw:e};if(t===`function_call`){let t=Xt(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:F(t),usage:an(e.usage),raw:e}}if(e.type==`message`){let n=Xt(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:F(n),usage:an(e.usage),raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:an(e.usage),raw:e}}function rn(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)}function an(e){return be({in:rn(e),out:e.output_tokens},{cachedIn:e.cache_read_input_tokens??void 0,cacheWriteIn:e.cache_creation_input_tokens??void 0})}function on(){let e=new Map,t=new Map,n=0,r=0,i=0,a=0,o=new Map;function s(s){let c=[];switch(s.type){case`message_start`:n=(s.message.usage?.input_tokens??0)+(s.message.usage?.cache_creation_input_tokens??0)+(s.message.usage?.cache_read_input_tokens??0),a=s.message.usage?.cache_creation_input_tokens??0,i=s.message.usage?.cache_read_input_tokens??0,c.push({type:`start`,id:s.message.id,data:{model:s.message.model,timestamp:Date.now()}});break;case`message_delta`:s.usage&&(r=s.usage.output_tokens??r,s.usage.input_tokens!=null&&(n=s.usage.input_tokens+(s.usage.cache_creation_input_tokens??a)+(s.usage.cache_read_input_tokens??i)),a=s.usage.cache_creation_input_tokens??a,i=s.usage.cache_read_input_tokens??i),s.delta.stop_reason&&c.push({type:`complete`,data:{finishReason:Qt(s.delta.stop_reason),usage:be({in:n,out:r},{cachedIn:i,cacheWriteIn:a})}});case`message_stop`:break;case`content_block_start`:if(s.content_block.type===`text`)e.set(s.index,`text`),c.push({type:`text-start`,data:{index:s.index}});else if(s.content_block.type===`tool_use`){e.set(s.index,`tool`);let t=s.content_block;o.set(s.index,{id:t.id,name:t.name,argumentsBuffer:``}),c.push({type:`tool-call-start`,data:{index:s.index,id:t.id,name:t.name}})}else if(s.content_block.type===`thinking`){e.set(s.index,`thinking`);let t=s.content_block.thinking.length===0&&!!s.content_block.signature;c.push({type:`thinking-start`,data:{index:s.index,redacted:t,continuity:{provider:`anthropic`,signature:s.content_block.signature}}})}else if(s.content_block.type===`redacted_thinking`)e.set(s.index,`thinking`),c.push({type:`thinking-start`,data:{index:s.index,redacted:!0,continuity:{provider:`anthropic`,redactedData:s.content_block.data}}});else if(s.content_block.type===`server_tool_use`){e.set(s.index,`provider-tool`);let n=s.content_block;t.set(n.id,{index:s.index,name:n.name}),c.push({type:`provider-tool-start`,data:{index:s.index,id:n.id,name:n.name}})}else if(s.content_block.type===`web_search_tool_result`){let e=s.content_block,n=t.get(e.tool_use_id);n&&(c.push({type:`provider-tool-complete`,data:{index:n.index,id:e.tool_use_id,name:n.name,output:e.content}}),t.delete(e.tool_use_id))}break;case`content_block_delta`:if(s.delta.type===`text_delta`)c.push({type:`text-delta`,data:{text:s.delta.text,index:s.index}});else if(s.delta.type===`input_json_delta`){let e=o.get(s.index);e&&(e.argumentsBuffer+=s.delta.partial_json,c.push({type:`tool-call-args-delta`,data:{index:s.index,id:e.id,name:e.name,delta:s.delta.partial_json,accumulated:e.argumentsBuffer}}))}else s.delta.type===`thinking_delta`?c.push({type:`thinking-delta`,data:{text:s.delta.thinking,index:s.index}}):s.delta.type===`signature_delta`?c.push({type:`thinking-metadata`,data:{index:s.index,continuity:{provider:`anthropic`,signature:s.delta.signature}}}):s.delta.type===`citations_delta`&&(e.get(s.index)!==`text`&&console.warn(`[Anthropic] received citation delta outside a text block`,{index:s.index,blockType:e.get(s.index)}),c.push({type:`text-citation`,data:{index:s.index,citation:Zt(s.delta.citation)}}));break;case`content_block_stop`:{let t=e.get(s.index);if(t===`text`)c.push({type:`text-complete`,data:{index:s.index}});else if(t===`thinking`)c.push({type:`thinking-complete`,data:{index:s.index}});else if(t!==`provider-tool`&&t===`tool`){let e=o.get(s.index);if(e){try{let t=e.argumentsBuffer?JSON.parse(e.argumentsBuffer):{};c.push({type:`tool-call-complete`,data:{index:s.index,id:e.id,name:e.name,arguments:t}})}catch(t){throw Error(`Failed to parse tool call arguments for ${e.name}: ${t instanceof Error?t.message:String(t)}\nRaw buffer: ${re(e.argumentsBuffer)}`)}o.delete(s.index)}}e.delete(s.index);break}}return c}return{handleEvent:s}}async function*sn(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span,v=[...a?Gt(a):[],...Jt(o)],y=on();try{let e=await Lt(r,{model:n,fileResolver:s?.fileResolver,signal:c}),b={model:n,max_tokens:u??cn(n),messages:e,...i&&{system:i},...p&&{stop_sequences:Je(p)},...v.length>0&&{tools:v},...Ut(l,n),...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Yt(m,h,a,o),...g};_?.debug(`Anthropic streaming request`,{request:At(b)});let x=await t.messages.create({...b,stream:!0},{signal:c});for await(let e of x){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function cn(e){return e in t?t[e]:e.includes(`opus`)?e.match(/opus-4-[6-9]|opus-[5-9]/)?128e3:64e3:e.includes(`sonnet`)||e.includes(`haiku`)?e.match(/claude-3-[0-5]-/)?8192:64e3:16384}function ln(e,t={}){let n=new m({apiKey:e,maxRetries:X(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`anthropic`,resolveProviderToolName(e){return qt(e)},async createGenerationRequest(e,t){return await tn({client:n,model:e,...t})},createStreamingRequest(e,t){return sn({client:n,model:e,...t})}}}const un={Models:i,DefaultModel:s};async function dn(e,t={}){let n=X(t.maxRetries??2,`maxRetries`,{min:0}),r=t.timeoutMs===void 0?void 0:X(t.timeoutMs,`timeoutMs`,{min:1}),i=0;for(;;){Z(t.signal,`Request aborted`);let a=fn(t.signal,r);try{let r=await Et(e({signal:a.signal}),a.signal,`Request aborted`);if(!pn(r.status)||i>=n)return r;let o=mn(r,i);t.onRetry?.({attempt:i+1,delayMs:o,status:r.status}),await gn(o,t.signal),i+=1}catch(e){if(Z(t.signal,`Request aborted`),i>=n)throw e;let r=mn(void 0,i);t.onRetry?.({attempt:i+1,delayMs:r,error:e}),await gn(r,t.signal),i+=1}finally{a.cleanup()}}}function fn(e,t){if(t===void 0)return{signal:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>{n.abort(new DOMException(`Request timed out after ${t}ms`,`TimeoutError`))},t),i=()=>{n.abort(e?.reason)};return e?.aborted?i():e?.addEventListener(`abort`,i,{once:!0}),{signal:n.signal,cleanup:()=>{clearTimeout(r),e?.removeEventListener(`abort`,i)}}}function pn(e){return e===408||e===409||e===429||e>=500}function mn(e,t){let n=hn(e);if(n!==void 0)return n;let r=Math.min(500*2**t,8e3);return r+Math.floor(Math.random()*r*.25)}function hn(e){let t=e?.headers.get(`retry-after-ms`);if(t){let e=Number.parseFloat(t);if(Number.isFinite(e)&&e>=0)return e}let n=e?.headers.get(`retry-after`);if(!n)return;let r=Number.parseFloat(n);if(Number.isFinite(r)&&r>=0)return r*1e3;let i=Date.parse(n);if(Number.isFinite(i))return Math.max(i-Date.now(),0)}async function gn(e,t){if(e<=0){Z(t,`Request aborted`);return}await new Promise((n,r)=>{let i,a=()=>{clearTimeout(i),t?.removeEventListener(`abort`,o)},o=()=>{a(),r(new DOMException(`Request aborted`,`AbortError`))},s=()=>{a(),n()};if(t?.aborted){o();return}i=setTimeout(s,e),t?.addEventListener(`abort`,o,{once:!0})}),Z(t,`Request aborted`)}const _n={web_search:`openrouter:web_search`};function vn(e){return _n[e]}function yn(e,t){let n=[];for(let r of e){let e=r.nativeName??vn(r.name);if(!e){t?.(`providerTool not supported by ChatCompletions provider vendor`,{vendor:`openrouter`,name:r.name});continue}n.push({type:e,...r.config?{parameters:r.config}:{}})}return n.length>0?n:void 0}function bn(e){switch(e.type){case`url_citation`:{let t=e.url_citation;return t?.url?{source:{type:`web`,title:t.title,url:t.url,citedText:t.content},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:e.type}}:null}default:return null}}function xn(e){let t=e.outputSpan;return!t||t.start===void 0&&t.end===void 0?!1:t.start!==0||t.end!==0}function Sn(e){return e===!0?{reasoning:{enabled:!0}}:e===!1?{reasoning:{enabled:!1}}:{}}function Cn(e){if(e.kind===`document`)throw Error(`Together Chat Completions does not support PDF file parts`)}function wn(e,t){switch(t){case`openrouter`:return vn(e);default:return}}async function Tn(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>Nn(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function En(e,t){return t===`together`?Sn(e):Dn(e)}function Dn(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`none`}:{}}function On(e){return be({in:e?.prompt_tokens||0,out:e?.completion_tokens||0},{cachedIn:e?.prompt_tokens_details?.cached_tokens??e?.input_tokens_details?.cached_tokens,cacheWriteIn:e?.prompt_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.input_tokens_details?.cache_creation_tokens,reasoningOut:e?.completion_tokens_details?.reasoning_tokens??e?.output_tokens_details?.reasoning_tokens})}function kn(e){if(e&&e.length>0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}))}function An(e,t,n){if(!(!e||e.length===0)){if(!t){n?.(`providerTools not supported by ChatCompletions provider`);return}switch(t){case`openrouter`:return yn(e,n)}}}function jn(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,function:{name:e.name}}};throw n?.some(t=>t.name===e.name)?Error(`ChatCompletions does not support provider tool choice: ${e.name}`):Error(`Tool choice references an unavailable tool: ${e.name}`)}function Mn(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`function_call`;case`content_filter`:case`error`:return`error`;default:return`stop`}}async function Nn(e,t){switch(e.role){case`tool`:return Pn(e,t);case`assistant`:return Fn(e);default:return In(e,t)}}async function Pn(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await Rn(e.content,t),tool_call_id:e.id})))}function Fn(e){let t=e.content.filter(e=>e.type===`tool-call`),n=e.content.filter(e=>e.type===`text`),r=t.length>0?t.map(e=>({type:`function`,id:e.id,function:{name:e.name,arguments:JSON.stringify(e.parameters)}})):void 0;return{role:`assistant`,content:n.map(e=>e.text).join(``),...r&&{tool_calls:r}}}async function In(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>Ln(e,t)))).filter(e=>e!==null);return n.every(e=>e.type===`text`)?{role:`user`,content:n.map(e=>e.text).join(``)}:{role:`user`,content:n}}async function Ln(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?zn(e.file,t,`user-message`):null}async function Rn(e,t){let n=[];for(let r of e){if(r.type===`text`){n.push(r.text);continue}if(r.file.kind===`text`){let e=await Q(r.file,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:`tool-result`,resolver:t.fileResolver,signal:t.signal});if(e.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${e.type}`);n.push(Hn(r.file,e.content,e.name,e.mimeType));continue}t.warn?.(`ChatCompletions omitted unsupported tool-result file`,{model:t.model,kind:r.file.kind,name:r.file.name,mimeType:r.file.mimeType}),n.push(Un(r.file))}return n.join(`
13
- `)}async function zn(e,t,n){if(t.vendor===`together`&&Cn(e),e.kind===`text`){let r=await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${r.type}`);return{type:`text`,text:Hn(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`ChatCompletions document file inputs currently support PDF only. Received ${e.mimeType}`);let r=await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`file`,file:{filename:r.name??e.name,file_data:Vn(r,e)}}}return{type:`image_url`,image_url:{url:Bn(await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}}}function Bn(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions image source: ${e.type}`)}function Vn(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions file source: ${e.type}`)}function Hn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function Un(e){return[`Tool result attachment unavailable.`,`File: ${e.name}`,`MIME type: ${e.mimeType}`,``,`This tool returned a file of kind "${e.kind}", but Chat Completions tool-result messages support text only. The file content was not included. Continue without the file or ask for it to be attached in a user message.`].join(`
14
- `)}async function Wn(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,apiKey:c,vendor:l,maxRetries:u,timeoutMs:d,reasoning:f,maxOutputTokens:p,temperature:m,topP:h,stop:g,toolChoice:_,parallelToolCalls:v,providerOptions:y,signal:b}=e,x=s?.span,S;try{Z(b,`Generate aborted`);let e=await Tn(r,i,{model:n,vendor:l,fileResolver:s?.fileResolver,signal:b,warn:x?.warn.bind(x)}),C=kn(a),w=An(o,l,x?.warn.bind(x)),T=[...C??[],...w??[]],E={model:n,messages:e,...T.length>0?{tools:T}:{},...En(f,l),...p===void 0?{}:{max_tokens:p},...m===void 0?{}:{temperature:m},...h===void 0?{}:{top_p:h},...g===void 0?{}:{stop:g},...jn(_,a,o),...v===void 0?{}:{parallel_tool_calls:v},...y};x?.debug(`ChatCompletions request`,{model:E.model,messages:E.messages.length,tools:E.tools?.length??0}),x?.trace(`ChatCompletions request body`,{request:At(E)});let D={"Content-Type":`application/json`};c&&(D.Authorization=`Bearer ${c}`);let O=await dn(({signal:e})=>fetch(`${t}/chat/completions`,{method:`POST`,headers:D,body:JSON.stringify(E),signal:e}),{maxRetries:u,timeoutMs:d,signal:b,onRetry:e=>x?.warn(`ChatCompletions request retry`,{attempt:e.attempt,maxRetries:u,timeoutMs:d,delayMs:e.delayMs,status:e.status,error:e.error instanceof Error?e.error.message:void 0})});if(!O.ok){let e=await O.text().catch(()=>``);throw Error(`HTTP error! status: ${O.status}${e?` - ${e}`:``}`)}let k=await Et(O.json(),b,`Generate aborted`);Z(b,`Generate aborted`),S=Gn(k)}catch(e){Z(b,`Generate aborted`),x?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),S=Tt(e)}return x?.trace(`ChatCompletions response`,{result:S}),S}function Gn(e){let t=e.choices?.[0];if(!t)return{type:`error`,error:{type:`ChatCompletionsError`,message:`No choices in response`},usage:{in:0,out:0},raw:e};let n=[],r=t.message.reasoning_content??t.message.reasoning;r&&n.push({type:`thinking`,text:r});let i=(t.message.annotations??[]).map(bn).filter(e=>e!==null),a=i.filter(xn),o=i.filter(e=>!xn(e));if(t.message.content&&n.push({type:`text`,text:t.message.content,...a.length>0?{citations:a}:{}}),o.length>0&&n.push({type:`citation`,citations:o}),t.message.tool_calls)for(let e of t.message.tool_calls){let t;try{t=JSON.parse(e.function.arguments)}catch(t){throw Error(`Invalid tool call arguments for ${e.function.name}: ${t instanceof Error?t.message:String(t)}`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Invalid tool call arguments for ${e.function.name}: expected object, got ${typeof t}`);n.push({type:`tool-call`,id:e.id,name:e.function.name,parameters:t})}let s=n.some(e=>e.type===`tool-call`)?Mn(`tool_calls`):Mn(t.finish_reason);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:s,content:n,text:F(n),usage:On(e.usage),raw:e}}function Kn(){let e=new Map,t=0,n=-1,r=``,i=``,a=null,o,s;function c(e){n<0||(a===`text`?e.push({type:`text-complete`,data:{index:n}}):a===`thinking`&&e.push({type:`thinking-complete`,data:{index:n}}),a=null,n=-1)}function l(l){let u=[];l.usage&&(s=On(l.usage));let d=l.choices?.[0];if(!d)return u;r||(r=l.id,i=l.model,u.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}}));let f=d.delta,p=f.reasoning_content??f.reasoning;if(p&&(a!==`thinking`&&(c(u),n=t++,a=`thinking`,u.push({type:`thinking-start`,data:{index:n}})),u.push({type:`thinking-delta`,data:{index:n,text:p}})),f.content&&(a!==`text`&&(c(u),n=t++,a=`text`,u.push({type:`text-start`,data:{index:n}})),u.push({type:`text-delta`,data:{text:f.content,index:n}})),f.annotations){let e=f.annotations.map(bn).filter(e=>e!==null),r=a===`text`?e.filter(xn):[];for(let e of r)u.push({type:`text-citation`,data:{index:n,citation:e}});let i=e.filter(e=>!r.includes(e));i.length>0&&(c(u),u.push({type:`citation`,data:{index:t++,citations:i}}))}if(f.tool_calls){c(u);for(let n of f.tool_calls){let r=n.index;if(!e.has(r)){let i=t++,a=n.id||`tool-${i}`;e.set(r,{id:a,name:n.function?.name||``,argumentsBuffer:``,partIdx:i}),u.push({type:`tool-call-start`,data:{index:i,id:a,name:n.function?.name||``}})}let i=e.get(r);n.id&&(i.id=n.id),n.function?.name&&(i.name=n.function.name),n.function?.arguments&&(i.argumentsBuffer+=n.function.arguments,u.push({type:`tool-call-args-delta`,data:{index:i.partIdx,id:i.id,name:i.name,delta:n.function.arguments,accumulated:i.argumentsBuffer}}))}}if(d.finish_reason&&o===void 0){c(u);for(let[,t]of e)try{let e=t.argumentsBuffer?JSON.parse(t.argumentsBuffer):{};u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.id,name:t.name,arguments:e}})}catch(e){let n=e instanceof Error?e.message:String(e);u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.id,name:t.name,arguments:{},error:{type:`invalid-arguments`,message:`Failed to parse tool call arguments for ${t.name}: ${n}`,raw:re(t.argumentsBuffer)}}})}e.clear(),o=Mn(d.finish_reason)}return u}function u(){return o===void 0?e.size===0?[]:[{type:`error`,data:{type:`IncompleteStream`,message:`Stream ended without a completion signal while tool call arguments were still buffering for ${[...e.values()].map(e=>`${e.name||`unknown tool`} (${e.id})`).join(`, `)}; arguments were likely truncated or incomplete.`}}]:[{type:`complete`,data:{finishReason:o,usage:s??{in:0,out:0}}}]}return{handleChunk:l,finalize:u}}async function*qn(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,apiKey:l,vendor:u,maxRetries:d,timeoutMs:f,reasoning:p,maxOutputTokens:m,temperature:h,topP:g,stop:_,toolChoice:v,parallelToolCalls:y,providerOptions:b}=e,x=s?.span,S=Kn();try{let e=await Tn(r,i,{model:n,vendor:u,fileResolver:s?.fileResolver,signal:c,warn:x?.warn.bind(x)}),C=kn(a),w=An(o,u,x?.warn.bind(x)),T=[...C??[],...w??[]],E={model:n,messages:e,stream:!0,stream_options:{include_usage:!0},...T.length>0?{tools:T}:{},...En(p,u),...m===void 0?{}:{max_tokens:m},...h===void 0?{}:{temperature:h},...g===void 0?{}:{top_p:g},..._===void 0?{}:{stop:_},...jn(v,a,o),...y===void 0?{}:{parallel_tool_calls:y},...b};x?.debug(`ChatCompletions request`,{model:E.model,messages:E.messages.length,tools:E.tools?.length??0,stream:!0}),x?.trace(`ChatCompletions request body`,{request:At(E)});let D={"Content-Type":`application/json`};l&&(D.Authorization=`Bearer ${l}`);let O=await dn(({signal:e})=>fetch(`${t}/chat/completions`,{method:`POST`,headers:D,body:JSON.stringify(E),signal:e}),{maxRetries:d,timeoutMs:f,signal:c,onRetry:e=>x?.warn(`ChatCompletions streaming request retry`,{attempt:e.attempt,maxRetries:d,timeoutMs:f,delayMs:e.delayMs,status:e.status,error:e.error instanceof Error?e.error.message:void 0})});if(!O.ok){let e=await O.text().catch(()=>``);throw Error(`HTTP error! status: ${O.status}${e?` - ${e}`:``}`)}if(!O.body)throw Error(`Response body is null`);let k=O.body.getReader(),A=new TextDecoder,j=``;for(;;){let{done:e,value:t}=await k.read();if(e)break;j+=A.decode(t,{stream:!0});let n=j.split(`
15
- `);j=n.pop()||``;for(let e of n){let t=e.trim();if(!t||t.startsWith(`:`)||!t.startsWith(`data: `))continue;let n=t.slice(6);if(n===`[DONE]`)continue;let r;try{r=JSON.parse(n)}catch(e){x?.error(`Error parsing ChatCompletions stream chunk`,{error:e instanceof Error?e.message:String(e),line:t});continue}if(r.error){let e=Jn(r.error);yield{type:`error`,data:{type:e.type,message:e.message,raw:r.error}};return}let i=S.handleChunk(r);for(let e of i)yield e}}for(let e of S.finalize())yield e}catch(e){if(c?.aborted)return;x?.error(`Error in ChatCompletions streaming request`,{error:e instanceof Error?e.message:String(e)}),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function Jn(e){if(typeof e==`string`)return{type:`UPSTREAM_STREAM_ERROR`,message:e};let t=e.type??(e.code===void 0?void 0:String(e.code))??`UPSTREAM_STREAM_ERROR`;return{type:t,message:e.message??t}}const Yn={"api.openrouter.ai":`openrouter`,"api.together.ai":`together`,"api.together.xyz":`together`,"openrouter.ai":`openrouter`};function Xn(e,t,n){let r=typeof t==`string`?t:t?.apiKey,i=typeof t==`string`?n:t,a=X(i?.maxRetries??2,`maxRetries`,{min:0}),o=i?.timeoutMs===void 0?void 0:X(i.timeoutMs,`timeoutMs`,{min:1}),s=i?.vendor??Zn(e);return{name:`ChatCompletions`,resolveProviderToolName(e){return wn(e,s)},async createGenerationRequest(t,n){return await Wn({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,vendor:s,...n})},createStreamingRequest(t,n){return qn({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,vendor:s,...n})}}}function Zn(e){try{return Yn[new URL(e).hostname.toLowerCase()]}catch{return}}function Qn(e,t,n){let r={};return t&&(r.systemInstruction=t),e&&e.length>0&&(r.tools=e.map(e=>({functionDeclarations:[{name:e.name,description:e.description,parametersJsonSchema:l.toJSONSchema(e.schema)}]}))),n&&Object.assign(r,n),r}const $n={web_search:`googleSearch`,code_execution:`codeExecution`};function er(e){return $n[e]??e}function tr(e,t){if(!(!t||t.length===0)){e.tools||=[];for(let n of t){let t=n.nativeName??er(n.name);e.tools.push({[t]:n.config??{}})}}}function nr(e,t,n,r){if(t===!1)throw Error(`Gemini does not support disabling parallel tool calls`);if(e===void 0)return{};if(e===`auto`)return{toolConfig:{functionCallingConfig:{mode:S.AUTO}}};if(e===`none`)return{toolConfig:{functionCallingConfig:{mode:S.NONE}}};if(e===`required`){if(!n||n.length===0)throw Error(`Gemini requires function tools for required tool choice`);return{toolConfig:{functionCallingConfig:{mode:S.ANY}}}}if(n?.some(t=>t.name===e.name))return{toolConfig:{functionCallingConfig:{mode:S.ANY,allowedFunctionNames:[e.name]}}};throw r?.some(t=>t.name===e.name)?Error(`Gemini does not support provider tool choice: ${e.name}`):Error(`Tool choice references an unavailable tool: ${e.name}`)}function rr(e){return e===!0?{thinkingConfig:{thinkingBudget:8192,includeThoughts:!0}}:e===!1?{thinkingConfig:{thinkingBudget:0}}:{}}async function ir(e,t={model:``}){return(await Promise.all(e.map(e=>ar(e,t)))).filter(e=>e!==void 0)}async function ar(e,t){switch(e.role){case`tool`:return or(e,t);case`assistant`:return sr(e);case`user`:return cr(e,t)}}async function or(e,t){return{role:`user`,parts:(await Promise.all(e.content.map(async e=>{let n=typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
16
- `),r={functionResponse:{id:e.id??void 0,name:e.name,response:{output:n}}};return typeof e.content==`string`?[r]:[r,...await Promise.all(e.content.filter(e=>e.type===`file`).map(e=>ur(e.file,t,`tool-result`)))]}))).flat(1)}}function sr(e){let t=[],n=e.content.filter(e=>e.type===`text`);if(n.length>0)for(let e of n){let n=e.text;if(!n)continue;let r={text:n};e.providerMetadata?.thoughtSignature&&(r.thoughtSignature=e.providerMetadata.thoughtSignature),t.push(r)}let r=e.content.filter(e=>e.type===`tool-call`);return r.length>0&&t.push(...r.map(e=>{let t={functionCall:{id:e.id??void 0,name:e.name,args:e.parameters}};return e.providerMetadata?.thoughtSignature&&(t.thoughtSignature=e.providerMetadata.thoughtSignature),t})),{role:`model`,parts:t}}async function cr(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>lr(e,t)))).filter(e=>e!==null)}}async function lr(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?ur(e.file,t,`user-message`):null}async function ur(e,t,n){if(e.kind===`text`){let r=await Q(e,{provider:`gemini`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Gemini text source: ${r.type}`);return{text:fr(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`&&e.mimeType!==`application/pdf`)throw Error(`Gemini document file support is limited to PDFs. Received ${e.mimeType}`);return dr(await Q(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function dr(e,t){if(e.type===`base64`)return{inlineData:{mimeType:e.mimeType??t.mimeType,data:e.data}};if(e.type===`url`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.url}};if(e.type===`gemini-file-uri`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.uri}};throw Error(`Unsupported Gemini file source: ${e.type}`)}function fr(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function pr(e){switch(e){case x.STOP:return[!0,`stop`];case x.MAX_TOKENS:return[!0,`length`];case x.FINISH_REASON_UNSPECIFIED:case x.SAFETY:case x.RECITATION:case x.LANGUAGE:case x.OTHER:case x.BLOCKLIST:case x.PROHIBITED_CONTENT:case x.SPII:case x.MALFORMED_FUNCTION_CALL:case x.IMAGE_SAFETY:return[!1,`error`]}return[!1,`error`]}async function mr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v={...rr(c),...l===void 0?{}:{maxOutputTokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{topP:d},...f===void 0?{}:{stopSequences:Array.isArray(f)?f:[f]},...nr(p,m,a,o),...h},y;try{Z(g,`Generate aborted`);let e=await ir(r,{model:n,fileResolver:s?.fileResolver,signal:g}),c=Qn(a,i,v);p!==`none`&&tr(c,o);let l={contents:e,config:c};_?.debug(`Gemini request`,{request:At(l)});let u=await Et(t.models.generateContent({model:n,...l}),g,`Generate aborted`);Z(g,`Generate aborted`),y=hr(u,{span:_})}catch(e){Z(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),y=Tt(e)}return _?.debug(`Gemini response`,{result:y}),y}function hr(e,t){let{span:n}=t,r=e.usageMetadata?.promptTokenCount??0,i=be({in:r,out:(e.usageMetadata?.totalTokenCount??r)-r},{cachedIn:e.usageMetadata?.cachedContentTokenCount,reasoningOut:e.usageMetadata?.thoughtsTokenCount});if(!e)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};if(e.promptFeedback&&e.promptFeedback.blockReason)return{type:`error`,error:{type:`Blocked`,message:`Response blocked by Google AI: ${e.promptFeedback.blockReason}, ${e.promptFeedback.blockReasonMessage}`},usage:i,raw:e};if(!e.candidates||e.candidates.length===0)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};e.candidates.length>1&&n?.warn(`We received ${e.candidates.length} response candidates`);let a=e.candidates[0],o=a.content?.parts||[],[s,c]=pr(a.finishReason);if(s){let t=[];for(let e=0;e<o.length;e++){let n=o[e];if(n.text)if(n.thought)t.push({type:`thinking`,summary:n.text,...n.thoughtSignature?{continuity:{provider:`gemini`,thoughtSignature:n.thoughtSignature}}:{}});else{let r=_r(a,e);gr(t,{type:`text`,text:n.text,...r.length>0?{citations:r}:{},...n.thoughtSignature?{providerMetadata:{thoughtSignature:n.thoughtSignature}}:{}})}}let n=o.filter(e=>e.functionCall),r=n.length>0?n.map(e=>({call:e.functionCall,thoughtSignature:e.thoughtSignature})):(e.functionCalls??[]).map(e=>({call:e,thoughtSignature:void 0}));if(r.length>0)for(let{call:e,thoughtSignature:n}of r)if(e.args==null)t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:{},...n?{providerMetadata:{thoughtSignature:n}}:{}});else if(typeof e.args!=`object`||Array.isArray(e.args))throw Error(`Invalid tool call arguments for ${e.name}: expected object, got ${typeof e.args}`);else t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:e.args,...n?{providerMetadata:{thoughtSignature:n}}:{}});return{type:`success`,id:e.responseId??``,model:e.modelVersion??``,role:`assistant`,finishReason:r.length>0?`function_call`:c,content:t,text:F(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function gr(e,t){let n=e[e.length-1];if(n?.type===`text`&&!n.citations?.length&&!n.providerMetadata&&!t.citations?.length&&!t.providerMetadata){n.text+=t.text;return}e.push(t)}function _r(e,t){let n=[],r=e.groundingMetadata,i=r?.groundingChunks??[];for(let e of r?.groundingSupports??[])if(!(e.segment?.partIndex!==void 0&&e.segment.partIndex!==t))for(let t of e.groundingChunkIndices??[]){let r=i[t];r&&n.push(vr(r,e))}for(let t of e.citationMetadata?.citations??[])n.push({source:t.uri?{type:`web`,title:t.title,url:t.uri}:{type:`unknown`},outputSpan:{start:t.startIndex,end:t.endIndex},providerMetadata:{license:t.license,publicationDate:t.publicationDate}});return n}function vr(e,t){let n=t.segment;return e.web?{source:{type:`web`,title:e.web.title,url:e.web.uri},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{outputText:n?.text,confidenceScores:t.confidenceScores}}:e.retrievedContext?{source:{type:`retrieved-context`,title:e.retrievedContext.title,uri:e.retrievedContext.uri,citedText:e.retrievedContext.text,locator:{type:`page`,start:e.retrievedContext.pageNumber,end:e.retrievedContext.pageNumber}},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{documentName:e.retrievedContext.documentName,outputText:n?.text,confidenceScores:t.confidenceScores}}:e.maps?{source:{type:`web`,title:e.maps.title,url:e.maps.uri,citedText:e.maps.text},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{placeId:e.maps.placeId,outputText:n?.text,confidenceScores:t.confidenceScores}}:{source:{type:`unknown`},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{chunk:e,outputText:n?.text,confidenceScores:t.confidenceScores}}}function yr(){let e=0,t=-1,n=!1,r=``,i=``,a=0,o=0,s=0,c=0,l=null,u=new Map;function d(e){t<0||(l===`text`?e.push({type:`text-complete`,data:{index:t}}):l===`thinking`&&e.push({type:`thinking-complete`,data:{index:t}}),l=null,t=-1)}function f(f){let p=[];r||(r=f.responseId||`gemini-${Date.now()}`,i=f.modelVersion||`gemini`,p.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}})),f.usageMetadata&&(a=f.usageMetadata.promptTokenCount||0,o=(f.usageMetadata.totalTokenCount||0)-a,s=f.usageMetadata.cachedContentTokenCount||0,c=f.usageMetadata.thoughtsTokenCount||0);let m=f.candidates?.[0];if(!m)return p;let h=m.content?.parts||[];for(let r=0;r<h.length;r++){let i=h[r],a=`thought`in i&&i.thought===!0,o=Object.keys(i),s=o.length===1&&`text`in i&&!i.text;if(!(`thoughtSignature`in i&&!i.text&&!i.functionCall||o.length===2&&`text`in i&&`thoughtSignature`in i&&!i.text||s)&&(a&&i.text?(l!==`thinking`&&(d(p),t=e++,l=`thinking`,p.push({type:`thinking-start`,data:{index:t,...i.thoughtSignature?{continuity:{provider:`gemini`,thoughtSignature:i.thoughtSignature}}:{}}})),p.push({type:`thinking-summary-delta`,data:{index:t,text:i.text}})):i.text&&!a?(l!==`text`&&(d(p),t=e++,l=`text`,p.push({type:`text-start`,data:{index:t}})),u.set(r,t),p.push({type:`text-delta`,data:{text:i.text,index:t}})):i.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(i))}`),i.functionCall)){d(p),n=!0;let t=e++,r=i.functionCall.id||`tool-${t}`,a=i.functionCall.name??``;p.push({type:`tool-call-start`,data:{index:t,id:r,name:a}});let o=i.functionCall.args??{},s=JSON.stringify(o);p.push({type:`tool-call-args-delta`,data:{index:t,id:r,name:a,delta:s,accumulated:s}});let c={index:t,id:r,name:a,arguments:o},l=i;l.thoughtSignature&&(c.providerMetadata={thoughtSignature:l.thoughtSignature}),p.push({type:`tool-call-complete`,data:c})}}for(let{partIndex:e,citation:n}of br(m)){let r=e===void 0?t:u.get(e);if(r===void 0||r<0){console.warn(`[Gemini] received citation without a resolvable text part`,{citation:n});continue}p.push({type:`text-citation`,data:{index:r,citation:n}})}if(m.finishReason&&m.finishReason!==x.FINISH_REASON_UNSPECIFIED){d(p);let[e,t]=pr(m.finishReason),r=n?`function_call`:t;!e&&!n?p.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${m.finishReason}`,usage:be({in:a,out:o},{cachedIn:s,reasoningOut:c}),raw:f}}):p.push({type:`complete`,data:{finishReason:r,usage:be({in:a,out:o},{cachedIn:s,reasoningOut:c})}})}return p}return{handleChunk:f}}function br(e){let t=[],n=e.groundingMetadata,r=n?.groundingChunks??[];for(let e of n?.groundingSupports??[])for(let n of e.groundingChunkIndices??[]){let i=r[n];i&&t.push({partIndex:e.segment?.partIndex,citation:xr(i,e)})}for(let n of e.citationMetadata?.citations??[])t.push({citation:{source:n.uri?{type:`web`,title:n.title,url:n.uri}:{type:`unknown`},outputSpan:{start:n.startIndex,end:n.endIndex},providerMetadata:{license:n.license,publicationDate:n.publicationDate}}});return t}function xr(e,t){let n=t.segment;return e.web?{source:{type:`web`,title:e.web.title,url:e.web.uri},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{outputText:n?.text,confidenceScores:t.confidenceScores}}:e.retrievedContext?{source:{type:`retrieved-context`,title:e.retrievedContext.title,uri:e.retrievedContext.uri,citedText:e.retrievedContext.text,locator:{type:`page`,start:e.retrievedContext.pageNumber,end:e.retrievedContext.pageNumber}},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{documentName:e.retrievedContext.documentName,outputText:n?.text,confidenceScores:t.confidenceScores}}:{source:{type:`unknown`},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{chunk:e,outputText:n?.text,confidenceScores:t.confidenceScores}}}async function*Sr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span,v=Qn(a,i,{...rr(l),...u===void 0?{}:{maxOutputTokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{topP:f},...p===void 0?{}:{stopSequences:Array.isArray(p)?p:[p]},...nr(m,h,a,o),...g});m!==`none`&&tr(v,o);let y=yr();try{let e={contents:await ir(r,{model:n,fileResolver:s?.fileResolver,signal:c}),config:v};_?.debug(`Gemini streaming request`,{request:At(e)});let i=await t.models.generateContentStream({model:n,...e});for await(let e of i){let t=y.handleChunk(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;_?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function Cr(e,t={}){let n=new C({apiKey:e,httpOptions:{retryOptions:{attempts:wr(t.maxRetries)},...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}}});return{name:`Gemini`,resolveProviderToolName(e){return er(e)},async createGenerationRequest(e,t){return await mr({client:n,model:e,...t})},createStreamingRequest(e,t){return Sr({client:n,model:e,...t})}}}function wr(e=2){return X(e,`maxRetries`,{min:0})+1}const Tr={Models:r,DefaultModel:n};async function Er(e){let{provider:t,model:n,messages:r,system:i,tools:a,providerTools:o,span:s,fileResolver:c,...l}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,providerTools:o,runtime:{span:s,fileResolver:c},...l})}async function Dr(e){if(`instruct`in e){let{instruct:t,messages:n,...r}=e,i=he(t),a=await Or({...r,messages:[...n??[],i.message]},k());if(!a.ok)return a;try{return{...a,response:i.parse(a.final)}}catch(e){return{ok:!1,messages:a.messages,final:a.final,usage:a.usage,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)}}}}return Or(e,k())}async function Or(e,t){let{provider:n,model:r,messages:i,system:a,onToolCall:o,maxIterations:s,span:c,fileResolver:l,reasoning:u,maxOutputTokens:d,temperature:f,topP:p,stop:m,toolChoice:h,parallelToolCalls:g,providerOptions:_,signal:v=new AbortController().signal}=e,y=Ie(Fe(e),{provider:n,model:r,span:c,configuration:t}),b=[...i],x=[],S=K(),C=0,w,T=e=>{b.push(e),x.push(e)},E=e=>(c?.setResult({kind:`llm`,model:r,request:{messages:i},response:{content:e.ok?e.final.content:null},usage:xe(e.usage),finishReason:e.ok?e.final.finishReason:void 0}),c?.end(e.ok?`ok`:`error`),e),D=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??r,request:{messages:b},response:{content:t.content},usage:xe(t.usage),finishReason:t.finishReason}),e.end()};try{for(;;){if(Z(v,`Generate aborted`),s!==void 0&&C>=s)return E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${s})`}}},usage:S});C+=1;let e=c?.startSpan(`turn-${C}`,{type:`llm`}),t=y.executable(),i=t.length>0?t.map(e=>({name:e.name,description:e.description,schema:e.schema})):void 0,O=y.provider(),k;try{k=await Er({provider:n,model:r,messages:b,system:a,tools:i,providerTools:O.length>0?O:void 0,span:e,fileResolver:l,reasoning:u,maxOutputTokens:d,temperature:f,topP:p,stop:m,toolChoice:h,parallelToolCalls:g,providerOptions:_,signal:v}),Z(v,`Generate aborted`)}catch(t){throw t instanceof Error&&t.name===`AbortError`&&e?.end(`ok`),t}if(ke(S,k,{provider:n.name,model:k.type===`error`?r:k.model??r}),k.type!==`error`&&Ae(e,k.content),D(e,k),k.type===`error`)return E({ok:!1,messages:x,error:{kind:`model`,error:k},usage:S});let A={role:`assistant`,id:k.id,model:k.model,content:k.content,finishReason:k.finishReason};if(T(A),w=A,k.finishReason!==`function_call`)return E({ok:!0,response:w,messages:x,final:w,usage:S});let j=I(k.content);if(j.length===0)return E({ok:!0,response:w,messages:x,final:w,usage:S});let{results:M,usage:N}=await Le(j,o,v,y,c);q(S,N),Z(v,`Generate aborted`),M.length>0&&T({role:`tool`,id:crypto.randomUUID(),content:M})}}catch(e){throw e instanceof P?(c?.end(`error`),new P(e.message,{toolName:e.toolName,messages:e.messages??x,partial:e.partial??w,usage:_e(S,e.usage),cause:e.cause})):e instanceof M?(c?.end(`ok`),new M(`Generate aborted`,{reason:e.reason,messages:e.messages??x,partial:e.partial,usage:_e(S,e.usage)})):e instanceof Error&&e.name===`AbortError`?(c?.end(`ok`),new M(`Generate aborted`,{reason:v.reason,messages:x,usage:S})):e}}function kr(e){if(e&&e.length>0)return e.map(e=>({type:`function`,strict:!0,name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}))}const Ar={web_search:`web_search_preview`,code_execution:`code_interpreter`};function jr(e){return Ar[e]??e}function Mr(e){return e?.map(e=>({type:e.nativeName??jr(e.name),...e.config}))}function Nr(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,name:e.name}};let r=n?.find(t=>t.name===e.name);if(r)return{tool_choice:{type:r.nativeName??jr(r.name)}};throw Error(`Tool choice references an unavailable tool: ${e.name}`)}function Pr(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`none`}}:{}}async function Fr(e,t={model:``}){return(await Promise.all(e.map(e=>Ir(e,t)))).flat(1)}async function Ir(e,t){switch(e.role){case`tool`:return Lr(e,t);case`assistant`:return Rr(e);default:return zr(e,t)}}async function Lr(e,t){return Promise.all(e.content.map(async e=>({type:`function_call_output`,call_id:e.id,output:typeof e.content==`string`?e.content:await Promise.all(e.content.map(e=>e.type===`text`?Promise.resolve({type:`input_text`,text:e.text}):Vr(e.file,t,`tool-result`)))})))}function Rr(e){let t=[],n=F(e.content);n&&t.push({role:e.role,content:n});let r=e.content.filter(e=>e.type===`thinking`);for(let e of r)e.continuity?.provider===`openai`&&t.push({type:`reasoning`,id:e.id,summary:e.summary?[{type:`summary_text`,text:e.summary}]:[],...e.text?{content:[{type:`reasoning_text`,text:e.text}]}:{},encrypted_content:e.continuity.encrypted});let i=e.content.filter(e=>e.type===`tool-call`);for(let e of i)t.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.parameters)});let a=e.content.filter(e=>e.type===`provider-tool`);for(let e of a)e.output!=null&&t.push(e.output);return t}async function zr(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>Br(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function Br(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?Vr(e.file,t,`user-message`):(e.type,null)}async function Vr(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:Hr(await Q(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e),detail:`auto`};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`OpenAI file inputs currently support PDF documents. Received ${e.mimeType}`);return Ur(await Q(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}let r=await Q(e,{provider:`openai`,model:t.model,accepted:[`text`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return r.type===`text`?{type:`input_text`,text:r.content}:Ur(r,e)}function Hr(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported OpenAI image source: ${e.type}`)}function Ur(e,t){if(e.type===`url`)return{type:`input_file`,file_url:e.url};if(e.type===`base64`)return{type:`input_file`,filename:e.name??t.name,file_data:`data:${e.mimeType??t.mimeType};base64,${e.data}`};throw Error(`Unsupported OpenAI file source: ${e.type}`)}async function Wr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v;try{if(Z(g,`Generate aborted`),f!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let e=[...kr(a)??[],...Mr(o)??[]],y={model:n,input:await Fr(r,{model:n,fileResolver:s?.fileResolver,signal:g}),...i&&{instructions:i},...e.length>0?{tools:e}:{},...Pr(c),...l===void 0?{}:{max_output_tokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Nr(p,a,o),...m===void 0?{}:{parallel_tool_calls:m},...h};_?.debug(`OpenAI ResponsesAPI request`,{request:At(y)});let b=await Et(t.responses.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);Z(g,`Generate aborted`),v=Gr(b)}catch(e){Z(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),v=Tt(e)}return _?.debug(`OpenAI ResponsesAPI response`,{result:v}),v}function Gr(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:Jr(e.usage),raw:e};let t=e.output?.filter(e=>e.type===`reasoning`)?.map(e=>e),n=[];if(t&&t.length>0)for(let e of t)(e.summary?.[0]?.text||e.content?.[0]?.text||e.encrypted_content)&&n.push({type:`thinking`,id:e.id,...e.content?.[0]?.text?{text:e.content[0].text}:{},...e.summary?.[0]?.text?{summary:e.summary[0].text}:{},...e.encrypted_content?{continuity:{provider:`openai`,encrypted:e.encrypted_content}}:{}});let r=Kr(e);r.length>0?n.push(...r):e.output_text&&n.push({type:`text`,text:e.output_text});let i=e.output?.filter(e=>e.type===`function_call`);if(i&&i.length>0)for(let e of i){let t=e;try{n.push({type:`tool-call`,id:t.call_id||t.id||``,name:t.name||``,parameters:t.arguments?JSON.parse(t.arguments):{}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${t.arguments}`)}}return{type:`success`,id:e.id,model:e.model||``,role:`assistant`,finishReason:e.incomplete_details?`error`:i&&i.length>0?`function_call`:`stop`,content:n,text:F(n),usage:Jr(e.usage),raw:e}}function Kr(e){let t=[];for(let n of e.output??[])if(n.type===`message`)for(let e of n.content??[]){if(e.type!==`output_text`)continue;let n=(e.annotations??[]).map(qr).filter(e=>e!==null);t.push({type:`text`,text:e.text,...n.length>0?{citations:n}:{}})}return t}function qr(e){if(!e||typeof e!=`object`)return null;let t=e;switch(t.type){case`url_citation`:return{source:{type:`web`,title:t.title,url:t.url},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type}};case`file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};case`container_file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type,containerId:t.container_id}};case`file_path`:return{source:{type:`document`,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};default:return{source:{type:`unknown`},providerMetadata:t}}}function Jr(e){return be({in:e?.input_tokens??0,out:e?.output_tokens??0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}function Yr(){let e=``,t=``,n=0,r=-1,i=!1,a=new Map,o=new Map,s=new Map,c=new Set([`web_search_call`,`file_search_call`,`code_interpreter_call`]),l=new Map;function u(u){let d=[];switch(u.type){case`response.created`:e=u.response.id||`openai-${Date.now()}`,t=u.response.model,d.push({type:`start`,id:e,data:{model:t,timestamp:Date.now()}});break;case`response.output_text.delta`:{let e=Xr(u.item_id,u.content_index);r===-1&&(r=n++,a.set(e,r),d.push({type:`text-start`,data:{index:r}})),d.push({type:`text-delta`,data:{text:u.delta,index:r}});break}case`response.output_text.done`:{let e=Xr(u.item_id,u.content_index);a.set(e,r),r>=0&&(d.push({type:`text-complete`,data:{index:r}}),r=-1);break}case`response.output_text.annotation.added`:{let e=Zr(u.annotation);if(!e)break;let t=a.get(Xr(u.item_id,u.content_index));t===void 0&&console.warn(`[OpenAI] received text annotation without a resolved text part; falling back to current part`,{itemId:u.item_id,contentIndex:u.content_index}),d.push({type:`text-citation`,data:{index:t??r,citation:e}});break}case`response.function_call_arguments.delta`:{let e=u.item_id;if(!l.has(e)){let t=o.get(e),r=t?.name||``,i=t?.callId||e,a=n++;l.set(e,{id:e,callId:i,name:r,argumentsBuffer:``,partIdx:a}),d.push({type:`tool-call-start`,data:{index:a,id:i,name:r}})}let t=l.get(e);t.argumentsBuffer+=u.delta,d.push({type:`tool-call-args-delta`,data:{index:t.partIdx,id:t.callId,name:t.name,delta:u.delta,accumulated:t.argumentsBuffer}});break}case`response.function_call_arguments.done`:{i=!0;let e=u.item_id,t=l.get(e),n=u.name||t?.name||``;if(t){try{let e=u.arguments?JSON.parse(u.arguments):{};d.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.callId,name:n,arguments:e}})}catch(e){throw Error(`Failed to parse function call arguments for ${n}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${u.arguments}`)}l.delete(e)}break}case`response.completed`:{let e=u.response.usage;d.push({type:`complete`,data:{finishReason:u.response.incomplete_details?`error`:i?`function_call`:`stop`,usage:be({in:e?.input_tokens||0,out:e?.output_tokens||0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}});break}case`response.failed`:d.push({type:`error`,data:{type:`RESPONSES_API_ERROR`,message:`Response failed: ${u.response.status}`,raw:u}});break;case`response.output_item.added`:if(u.item?.type===`reasoning`){let e=u.item;r=n++,d.push({type:`thinking-start`,data:{index:r,id:e.id,...e.encrypted_content?{continuity:{provider:`openai`,encrypted:e.encrypted_content}}:{}}})}else if(u.item?.type===`function_call`){let e=u.item,t=e.id||e.call_id;t&&o.set(t,{name:e.name||``,callId:e.call_id||t})}else if(u.item&&c.has(u.item.type)){let e=u.item,t=n++;s.set(e.id,t),d.push({type:`provider-tool-start`,data:{index:t,id:e.id,name:e.type}})}break;case`response.output_item.done`:if(u.item?.type===`reasoning`&&r>=0)d.push({type:`thinking-complete`,data:{index:r}}),r=-1;else if(u.item&&c.has(u.item.type)){let e=u.item,t=s.get(e.id);t!==void 0&&(d.push({type:`provider-tool-complete`,data:{index:t,id:e.id,name:e.type,output:u.item}}),s.delete(e.id))}break;case`response.reasoning_text.delta`:u.delta&&d.push({type:`thinking-delta`,data:{index:r,text:u.delta}});break;case`response.reasoning_summary_text.delta`:u.delta&&d.push({type:`thinking-summary-delta`,data:{index:r,text:u.delta}});break;case`response.in_progress`:case`response.content_part.added`:case`response.content_part.done`:case`response.reasoning_summary_part.added`:case`response.reasoning_summary_part.done`:case`response.reasoning_summary_text.done`:case`response.reasoning_text.done`:case`response.web_search_call.in_progress`:case`response.web_search_call.searching`:case`response.web_search_call.completed`:break;default:console.log(`[OpenAI] unhandled stream event: ${u.type}`)}return d}return{handleEvent:u}}function Xr(e,t){return`${e}:${t}`}function Zr(e){if(!e||typeof e!=`object`)return null;let t=e;switch(t.type){case`url_citation`:return{source:{type:`web`,title:t.title,url:t.url},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type}};case`file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};case`container_file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type,containerId:t.container_id}};case`file_path`:return{source:{type:`document`,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};default:return{source:{type:`unknown`},providerMetadata:t}}}async function*Qr(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.span;if(p!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let v=[...kr(a)??[],...Mr(o)??[]],y=Yr();try{let e={model:n,input:await Fr(r,{model:n,fileResolver:s?.fileResolver,signal:c}),...i&&{instructions:i},stream:!0,...v.length>0?{tools:v}:{},...Pr(l),...u===void 0?{}:{max_output_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Nr(m,a,o),...h===void 0?{}:{parallel_tool_calls:h},...g};_?.debug(`OpenAI ResponsesAPI streaming request`,{request:At(e)});let p=t.responses.stream(e,...c?[{signal:c}]:[]);for await(let e of p){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;_?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function $r(e,t={}){let n=new w({apiKey:e,maxRetries:X(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:X(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`OpenAI`,resolveProviderToolName(e){return jr(e)},async createGenerationRequest(e,t){return await Wr({client:n,model:e,...t})},createStreamingRequest(e,t){return Qr({client:n,model:e,...t})}}}const ei={Models:a,DefaultModel:o};function ti(e){return{kind:`agent`,name:e.name,description:e.description,schema:e.schema,async execute(t,n){let r=await e.createAgent(t,n),i=ni(e.prompt,t),a=r.on(e=>n.emit({type:`turn-event`,event:e})),o;try{o=await r.send(i,{...e.request,signal:n.signal}).final}catch(t){throw ri(t,e.name)}finally{a()}if(o.usage&&n.reportUsage?.(o.usage),!o.ok)throw Error(`Subagent failed: ${JSON.stringify(o.error)}`);let s=o.response;return typeof s==`string`?s:JSON.stringify(s)}}}function ni(e,t){return typeof e==`function`?e(t):typeof e==`string`?e:`Complete this delegated task. Input: ${JSON.stringify(t)}`}function ri(e,t){return e instanceof P?new P(e.message,{toolName:t,usage:e.usage,cause:e}):e instanceof M?new M(e.message,{reason:e.reason,usage:e.usage}):e}const ii=new TextEncoder;function ai(e,t={}){let n=t.maxItems??50,r=Math.max(1,t.maxConcurrency??8),i=Math.max(0,t.maxResultBytes??20971520),a=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:a,async execute(t,n){return oi(await pi(t.items,r,n.signal,async(t,r)=>{try{return{index:r,input:t,ok:!0,output:await e.execute(t,n)}}catch(e){if(e instanceof P||e instanceof M)throw e;return{index:r,input:t,ok:!1,error:{type:`execution`,message:e instanceof Error?e.message:String(e)}}}}),i)}}}function oi(e,t){let n=[],r=t;for(let i of e){let e=i.ok?{index:i.index,ok:!0}:{index:i.index,ok:!1,error:i.error},a=`<<result ${JSON.stringify(e)}>>\n`,o=li({type:`text`,text:a});if(o>r){si(n,ui({result:i,reason:`header`,attemptedBytes:o,remainingBytes:r,maxBytes:t}),1/0);continue}if(si(n,a,r),r-=o,!i.ok||i.output==null)continue;let s=ci(i.output);if(s>r){si(n,ui({result:i,reason:`output`,attemptedBytes:s,remainingBytes:r,maxBytes:t}),1/0);continue}if(typeof i.output==`string`){si(n,i.output,r),r-=li(n[n.length-1]);continue}for(let e of i.output)n.push(e),r-=li(e)}return n}function si(e,t,n){return ii.encode(t).length>n?!1:(e.push({type:`text`,text:t}),!0)}function ci(e){return typeof e==`string`?li({type:`text`,text:e}):e.reduce((e,t)=>e+li(t),0)}function li(e){if(e.type===`text`)return ii.encode(e.text).length;let t=e.file.source;switch(t.type){case`text`:return ii.encode(t.content).length;case`base64`:return ii.encode(t.data).length;case`url`:return ii.encode(t.url).length;case`ref`:return e.file.size??ii.encode(`${e.file.name}:${e.file.mimeType}`).length}}function ui({result:e,reason:t,attemptedBytes:n,remainingBytes:r,maxBytes:i}){return`<<result ${e.index} omitted: ${t} ${di(n)} exceeds remaining budget ${di(r)} of ${di(i)}; input ${fi(e.input)}>>`}function di(e){return e===1?`1 byte`:`${e} bytes`}function fi(e){try{return JSON.stringify(e)}catch{return String(e)}}async function pi(e,t,n,r){let i=Array(e.length),a=0,o=!1,s=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:s},async()=>{for(;!o&&a<e.length;){if(n.aborted)throw o=!0,new M(`Operation aborted`,{reason:n.reason});let t=a++;try{i[t]=await r(e[t],t)}catch(e){throw o=!0,e}}})),i}const mi={trace:0,debug:1,info:2,warn:3,error:4};var hi=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 mi[e]>=mi[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 gi(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,t);let n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatSpanName(e);this.output(`${r}${n}START ${i}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.visibleDepths.get(e.spanId)??0,n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatDuration(e),a=this.formatSpanName(e),o=e.status===`error`?` [ERROR]`:``;if(this.output(`${r}${n}END ${a}${i}${o}`),e.result?.kind===`llm`){let t=e.result,i=[`model=${t.model}`];if(t.finishReason&&i.push(`finishReason=${t.finishReason}`),t.usage&&(t.usage.inputTokens!==void 0&&i.push(`inputTokens=${t.usage.inputTokens}`),t.usage.outputTokens!==void 0&&i.push(`outputTokens=${t.usage.outputTokens}`),t.usage.cachedInputTokens!==void 0&&i.push(`cachedInputTokens=${t.usage.cachedInputTokens}`),t.usage.cacheWriteInputTokens!==void 0&&i.push(`cacheWriteInputTokens=${t.usage.cacheWriteInputTokens}`),t.usage.reasoningOutputTokens!==void 0&&i.push(`reasoningOutputTokens=${t.usage.reasoningOutputTokens}`)),this.output(`${r}${n} INFO LLM complete ${i.join(` `)}`),this.shouldShowEvent(`debug`)&&t.response.content){let e=(typeof t.response.content==`string`?t.response.content:JSON.stringify(t.response.content,null,2)).split(`
17
- `);for(let t of e)this.output(`${r}${n} DEBUG ${t}`)}}}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,t){if(!this.shouldShowEvent(t.level))return;this.spans.set(e.spanId,e);let n;if(this.isSpanVisible(e))n=this.visibleDepths.get(e.spanId)??0;else{let t=this.findVisibleAncestor(e);n=t?this.visibleDepths.get(t.spanId)??0:0}let r=this.formatIndent(n+1),i=this.formatTimestamp(),a=t.level.toUpperCase().padEnd(5),o=this.markdown&&t.attributes?.markdown===!0,s=t.attributes?Object.entries(t.attributes).filter(([e])=>e!==`markdown`):[],c=t.name;o&&(c=this.renderMarkdown(c));let l=`${i}${r}${a} ${c}`;if(s.length>0){let e=s.map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(` `);l+=` ${e}`}this.output(l)}};function gi(e){return _i(E.lexer(e))}function _i(e=[]){return e.map(e=>vi(e)).filter(e=>e.length>0).join(`
18
- `)}function vi(e){switch(e.type){case`space`:return``;case`heading`:return T.bold($(e.tokens));case`paragraph`:return $(e.tokens);case`blockquote`:return wi(_i(e.tokens),`> `);case`code`:return(e.lang?T.dim(`${e.lang}\n`):``)+T.yellow(e.text);case`list`:return bi(e)?Si(e):e.raw;case`hr`:return T.dim(`-`.repeat(40));case`table`:return xi(e)?Ci(e):e.raw;case`html`:return e.text;case`text`:return e.tokens?$(e.tokens):Ei(e.text);default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function $(e=[]){return e.map(e=>yi(e)).join(``)}function yi(e){switch(e.type){case`text`:case`escape`:return Ei(e.text);case`strong`:return T.bold($(e.tokens));case`em`:return T.italic($(e.tokens));case`codespan`:return T.yellow(e.text);case`del`:return T.strikethrough($(e.tokens));case`link`:{let t=$(e.tokens);return e.href&&e.href!==e.text?`${T.blue.underline(t)} ${T.dim(`(${e.href})`)}`:T.blue.underline(t)}case`image`:return e.text?`${e.text} (${e.href})`:e.href;case`br`:return`
19
- `;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function bi(e){return e.type===`list`&&`items`in e&&Array.isArray(e.items)}function xi(e){return e.type===`table`&&`header`in e&&`rows`in e}function Si(e){return e.items.map((t,n)=>{let r=e.ordered?`${Number(e.start||1)+n}. `:`- `,i=t.task?`[${t.checked?`x`:` `}] `:``,a=_i(t.tokens).trimEnd();return r+i+Ti(a,r.length+i.length)}).join(`
20
- `)}function Ci(e){let t=e.header.map(e=>$(e.tokens)).join(` | `),n=e.rows.map(e=>e.map(e=>$(e.tokens)).join(` | `));return[T.bold(t),...n].join(`
21
- `)}function wi(e,t){return e.split(`
12
+ `,[,r]=B(this.schema);for(let[e,t]of _e(this.schema))n+=`\n- ${e}: ${t}`;return n+=`\n\nExample:\n${JSON.stringify(r,null,2)}\n\n`,n+t}};function Et(e){let t=Math.max(0,...Array.from(e.matchAll(/`+/g),e=>e[0].length));return"`".repeat(Math.max(3,t+1))}var Dt=class e extends A{constructor(t,n){super(t,{code:`TASK_ERROR`,id:n?.id,details:{taskType:n?.taskType,taskIndex:n?.taskIndex,...n?.details},cause:n?.cause}),Object.setPrototypeOf(this,e.prototype)}};function 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 Ot(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 M(t,{reason:e.reason})}function kt(e,t,n=`Operation aborted`){return t?t.aborted?Promise.reject(new M(n,{reason:t.reason})):new Promise((r,i)=>{let a=()=>{t.removeEventListener(`abort`,a),i(new M(n,{reason:t.reason}))};t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,a),r(e)},e=>{t.removeEventListener(`abort`,a),i(e)})}):e}function At(e,t,n=`[redacted]`){return jt(e,null,t,n)}function jt(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=>jt(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=jt(a,t,n,r);return i}const Mt=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function Z(e){return At(e,Mt,`[redacted-file-value]`)}function Nt(e){return Array.isArray(e)?e:[e]}const Pt=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 Ft({type:`base64`,data:n.data},e,t);if(n.type===`text`)return Ft({type:`text`,content:n.content},e,t);if(n.type===`url`)return Ft({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return Ft(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function Ft(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 It=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function Lt(e){return e.startsWith(`text/`)||It.has(e)}function Rt(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(Lt(t))return{kind:`text`,mimeType:t};{let n=y(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function zt(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>Pt)throw Error(`File too large: ${r.size} bytes. Maximum allowed: ${Pt} bytes`);let i=n.split(`/`).pop()||``,a=Rt(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 Bt(e,t={model:``}){return Promise.all(e.map(e=>Vt(e,t)))}async function Vt(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 rn(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 Ht(r.file,t,`user-message`));return{role:`user`,content:n}}}async function Ht(e,t,n){if(e.kind===`image`)return{type:`image`,source:Wt(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:Gt(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 Ut(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 Wt(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:Ut(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function Gt(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 Kt(e,t=``){return e===!0?qt(t)?{thinking:{type:`adaptive`},output_config:{effort:`high`}}:{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function qt(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 Jt(e){return e.map(e=>{let t=l.toJSONSchema(e.schema);if(!nn(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}const Yt={web_search:`web_search_20250305`};function Xt(e){return Yt[e]??e}function Zt(e){return(e??[]).map(e=>({type:e.nativeName??Xt(e.name),name:e.name,...e.config}))}function Qt(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 $t(e){let t=[];for(let n of e)if(n.type===`text`){let e=n.citations?.map(en);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 en(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 tn(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 nn(e){return e&&typeof e==`object`&&e.type===`object`}async function rn(e,t){return Promise.all(e.map(async e=>e.type===`text`?{type:`text`,text:e.text}:Ht(e.file,t,`tool-result`)))}async function an(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 Bt(r,{model:n,fileResolver:s?.fileResolver,signal:g}),y={model:n,max_tokens:l??16e3,messages:e,...i&&{system:i},...f&&{stop_sequences:Nt(f)},...(a||o)&&{tools:[...a?Jt(a):[],...Zt(o)]},...Kt(c,n),...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Qt(p,m,a,o),...h};_?.debug(`Anthropic request`,{request:Z(y)});let b=await kt(t.messages.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=on(b)}catch(e){X(g,`Generate aborted`),v=Ot(e)}return _?.debug(`Anthropic response`,{result:v}),v}function on(e){let t=tn(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:cn(e.usage),raw:e};if(t===`function_call`){let t=$t(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:I(t),usage:cn(e.usage),raw:e}}if(e.type==`message`){let n=$t(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:I(n),usage:cn(e.usage),raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:cn(e.usage),raw:e}}function sn(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)}function cn(e){return W({in:sn(e),out:e.output_tokens},{cachedIn:e.cache_read_input_tokens??void 0,cacheWriteIn:e.cache_creation_input_tokens??void 0})}function ln(){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:tn(s.delta.stop_reason),usage:W({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:en(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: ${ae(e.argumentsBuffer)}`)}o.delete(s.index)}}e.delete(s.index);break}}return c}return{handleEvent:s}}async function*un(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?Jt(a):[],...Zt(o)],y=ln();try{let e=await Bt(r,{model:n,fileResolver:s?.fileResolver,signal:c}),b={model:n,max_tokens:u??dn(n),messages:e,...i&&{system:i},...p&&{stop_sequences:Nt(p)},...v.length>0&&{tools:v},...Kt(l,n),...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Qt(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 dn(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 fn(e,t={}){let n=new m({apiKey:e,maxRetries:Y(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`anthropic`,resolveProviderToolName(e){return Xt(e)},async createGenerationRequest(e,t){return await an({client:n,model:e,...t})},createStreamingRequest(e,t){return un({client:n,model:e,...t})}}}const pn={Models:i,DefaultModel:s};async function mn(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=hn(t.signal,r);try{let r=await kt(e({signal:a.signal}),a.signal,`Request aborted`);if(!gn(r.status)||i>=n)return r;let o=_n(r,i);t.onRetry?.({attempt:i+1,delayMs:o,status:r.status}),await yn(o,t.signal),i+=1}catch(e){if(X(t.signal,`Request aborted`),i>=n)throw e;let r=_n(void 0,i);t.onRetry?.({attempt:i+1,delayMs:r,error:e}),await yn(r,t.signal),i+=1}finally{a.cleanup()}}}function hn(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 gn(e){return e===408||e===409||e===429||e>=500}function _n(e,t){let n=vn(e);if(n!==void 0)return n;let r=Math.min(500*2**t,8e3);return r+Math.floor(Math.random()*r*.25)}function vn(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 yn(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 bn={web_search:`openrouter:web_search`};function xn(e){return bn[e]}function Sn(e,t){let n=[];for(let r of e){let e=r.nativeName??xn(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 Cn(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 wn(e){let t=e.outputSpan;return!t||t.start===void 0&&t.end===void 0?!1:t.start!==0||t.end!==0}function Tn(e){return e===!0?{reasoning:{enabled:!0}}:e===!1?{reasoning:{enabled:!1}}:{}}function En(e){if(e.kind===`document`)throw Error(`Together Chat Completions does not support PDF file parts`)}function Dn(e,t){switch(t){case`openrouter`:return xn(e);default:return}}async function On(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>In(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function kn(e,t){return t===`together`?Tn(e):An(e)}function An(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`none`}:{}}function jn(e){return W({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 Nn(e,t,n){if(!(!e||e.length===0)){if(!t){n?.(`providerTools not supported by ChatCompletions provider`);return}switch(t){case`openrouter`:return Sn(e,n)}}}function Pn(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,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 Fn(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 In(e,t){switch(e.role){case`tool`:return Ln(e,t);case`assistant`:return Rn(e);default:return zn(e,t)}}async function Ln(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await Vn(e.content,t),tool_call_id:e.id})))}function Rn(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 zn(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>Bn(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 Bn(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?Hn(e.file,t,`user-message`):null}async function Vn(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(Gn(r.file,e.content,e.name,e.mimeType));continue}t.warn?.(`ChatCompletions omitted unsupported tool-result file`,{model:t.model,kind:r.file.kind,name:r.file.name,mimeType:r.file.mimeType}),n.push(Kn(r.file))}return n.join(`
13
+ `)}async function Hn(e,t,n){if(t.vendor===`together`&&En(e),e.kind===`text`){let r=await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${r.type}`);return{type:`text`,text:Gn(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:Wn(r,e)}}}return{type:`image_url`,image_url:{url:Un(await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}}}function Un(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions image source: ${e.type}`)}function Wn(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 Gn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function Kn(e){return[`Tool result attachment unavailable.`,`File: ${e.name}`,`MIME type: ${e.mimeType}`,``,`This tool returned a file of kind "${e.kind}", but Chat Completions tool-result messages support text only. The file content was not included. Continue without the file or ask for it to be attached in a user message.`].join(`
14
+ `)}async function qn(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,apiKey:c,vendor:l,maxRetries:u,timeoutMs:d,reasoning:f,maxOutputTokens:p,temperature:m,topP:h,stop:g,toolChoice:_,parallelToolCalls:v,providerOptions:y,signal:b}=e,x=s?.span,S;try{X(b,`Generate aborted`);let e=await On(r,i,{model:n,vendor:l,fileResolver:s?.fileResolver,signal:b,warn:x?.warn.bind(x)}),C=Mn(a),w=Nn(o,l,x?.warn.bind(x)),T=[...C??[],...w??[]],E={model:n,messages:e,...T.length>0?{tools:T}:{},...kn(f,l),...p===void 0?{}:{max_tokens:p},...m===void 0?{}:{temperature:m},...h===void 0?{}:{top_p:h},...g===void 0?{}:{stop:g},...Pn(_,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:Z(E)});let D={"Content-Type":`application/json`};c&&(D.Authorization=`Bearer ${c}`);let O=await mn(({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 kt(O.json(),b,`Generate aborted`);X(b,`Generate aborted`),S=Jn(k)}catch(e){X(b,`Generate aborted`),x?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),S=Ot(e)}return x?.trace(`ChatCompletions response`,{result:S}),S}function Jn(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(Cn).filter(e=>e!==null),a=i.filter(wn),o=i.filter(e=>!wn(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`)?Fn(`tool_calls`):Fn(t.finish_reason);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:s,content:n,text:I(n),usage:jn(e.usage),raw:e}}function Yn(){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=jn(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(Cn).filter(e=>e!==null),r=a===`text`?e.filter(wn):[];for(let e of r)u.push({type:`text-citation`,data:{index:n,citation:e}});let i=e.filter(e=>!r.includes(e));i.length>0&&(c(u),u.push({type:`citation`,data:{index:t++,citations:i}}))}if(f.tool_calls){c(u);for(let n of f.tool_calls){let r=n.index;if(!e.has(r)){let i=t++,a=n.id||`tool-${i}`;e.set(r,{id:a,name:n.function?.name||``,argumentsBuffer:``,partIdx:i}),u.push({type:`tool-call-start`,data:{index:i,id:a,name:n.function?.name||``}})}let i=e.get(r);n.id&&(i.id=n.id),n.function?.name&&(i.name=n.function.name),n.function?.arguments&&(i.argumentsBuffer+=n.function.arguments,u.push({type:`tool-call-args-delta`,data:{index:i.partIdx,id:i.id,name:i.name,delta:n.function.arguments,accumulated:i.argumentsBuffer}}))}}if(d.finish_reason&&o===void 0){c(u);for(let[,t]of e)try{let e=t.argumentsBuffer?JSON.parse(t.argumentsBuffer):{};u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.id,name:t.name,arguments:e}})}catch(e){let n=e instanceof Error?e.message:String(e);u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.id,name:t.name,arguments:{},error:{type:`invalid-arguments`,message:`Failed to parse tool call arguments for ${t.name}: ${n}`,raw:ae(t.argumentsBuffer)}}})}e.clear(),o=Fn(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*Xn(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,apiKey:l,vendor:u,maxRetries:d,timeoutMs:f,reasoning:p,maxOutputTokens:m,temperature:h,topP:g,stop:_,toolChoice:v,parallelToolCalls:y,providerOptions:b}=e,x=s?.span,S=Yn();try{let e=await On(r,i,{model:n,vendor:u,fileResolver:s?.fileResolver,signal:c,warn:x?.warn.bind(x)}),C=Mn(a),w=Nn(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}:{},...kn(p,u),...m===void 0?{}:{max_tokens:m},...h===void 0?{}:{temperature:h},...g===void 0?{}:{top_p:g},..._===void 0?{}:{stop:_},...Pn(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:Z(E)});let D={"Content-Type":`application/json`};l&&(D.Authorization=`Bearer ${l}`);let O=await mn(({signal:e})=>fetch(`${t}/chat/completions`,{method:`POST`,headers:D,body:JSON.stringify(E),signal:e}),{maxRetries:d,timeoutMs:f,signal:c,onRetry:e=>x?.warn(`ChatCompletions streaming request retry`,{attempt:e.attempt,maxRetries:d,timeoutMs:f,delayMs:e.delayMs,status:e.status,error:e.error instanceof Error?e.error.message:void 0})});if(!O.ok){let e=await O.text().catch(()=>``);throw Error(`HTTP error! status: ${O.status}${e?` - ${e}`:``}`)}if(!O.body)throw Error(`Response body is null`);let k=O.body.getReader(),A=new TextDecoder,j=``;for(;;){let{done:e,value:t}=await k.read();if(e)break;j+=A.decode(t,{stream:!0});let n=j.split(`
15
+ `);j=n.pop()||``;for(let e of n){let t=e.trim();if(!t||t.startsWith(`:`)||!t.startsWith(`data: `))continue;let n=t.slice(6);if(n===`[DONE]`)continue;let r;try{r=JSON.parse(n)}catch(e){x?.error(`Error parsing ChatCompletions stream chunk`,{error:e instanceof Error?e.message:String(e),line:t});continue}if(r.error){let e=Zn(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 Zn(e){if(typeof e==`string`)return{type:`UPSTREAM_STREAM_ERROR`,message:e};let t=e.type??(e.code===void 0?void 0:String(e.code))??`UPSTREAM_STREAM_ERROR`;return{type:t,message:e.message??t}}const Qn={"api.openrouter.ai":`openrouter`,"api.together.ai":`together`,"api.together.xyz":`together`,"openrouter.ai":`openrouter`};function $n(e,t,n){let r=typeof t==`string`?t:t?.apiKey,i=typeof t==`string`?n:t,a=Y(i?.maxRetries??2,`maxRetries`,{min:0}),o=i?.timeoutMs===void 0?void 0:Y(i.timeoutMs,`timeoutMs`,{min:1}),s=i?.vendor??er(e);return{name:`ChatCompletions`,resolveProviderToolName(e){return Dn(e,s)},async createGenerationRequest(t,n){return await qn({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,vendor:s,...n})},createStreamingRequest(t,n){return Xn({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,vendor:s,...n})}}}function er(e){try{return Qn[new URL(e).hostname.toLowerCase()]}catch{return}}function tr(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 nr={web_search:`googleSearch`,code_execution:`codeExecution`};function rr(e){return nr[e]??e}function ir(e,t){if(!(!t||t.length===0)){e.tools||=[];for(let n of t){let t=n.nativeName??rr(n.name);e.tools.push({[t]:n.config??{}})}}}function ar(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 or(e){return e===!0?{thinkingConfig:{thinkingBudget:8192,includeThoughts:!0}}:e===!1?{thinkingConfig:{thinkingBudget:0}}:{}}async function sr(e,t={model:``}){return(await Promise.all(e.map(e=>cr(e,t)))).filter(e=>e!==void 0)}async function cr(e,t){switch(e.role){case`tool`:return lr(e,t);case`assistant`:return ur(e);case`user`:return dr(e,t)}}async function lr(e,t){return{role:`user`,parts:(await Promise.all(e.content.map(async e=>{let n=typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
16
+ `),r={functionResponse:{id:e.id??void 0,name:e.name,response:{output:n}}};return typeof e.content==`string`?[r]:[r,...await Promise.all(e.content.filter(e=>e.type===`file`).map(e=>pr(e.file,t,`tool-result`)))]}))).flat(1)}}function ur(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 dr(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>fr(e,t)))).filter(e=>e!==null)}}async function fr(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?pr(e.file,t,`user-message`):null}async function pr(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:hr(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 mr(await Q(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function mr(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 hr(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function gr(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 _r(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={...or(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]},...ar(p,m,a,o),...h},y;try{X(g,`Generate aborted`);let e=await sr(r,{model:n,fileResolver:s?.fileResolver,signal:g}),c=tr(a,i,v);p!==`none`&&ir(c,o);let l={contents:e,config:c};_?.debug(`Gemini request`,{request:Z(l)});let u=await kt(t.models.generateContent({model:n,...l}),g,`Generate aborted`);X(g,`Generate aborted`),y=vr(u,{span:_})}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),y=Ot(e)}return _?.debug(`Gemini response`,{result:y}),y}function vr(e,t){let{span:n}=t,r=e.usageMetadata?.promptTokenCount??0,i=W({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]=gr(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=br(a,e);yr(t,{type:`text`,text:n.text,...r.length>0?{citations:r}:{},...n.thoughtSignature?{providerMetadata:{thoughtSignature:n.thoughtSignature}}:{}})}}let n=o.filter(e=>e.functionCall),r=n.length>0?n.map(e=>({call:e.functionCall,thoughtSignature:e.thoughtSignature})):(e.functionCalls??[]).map(e=>({call:e,thoughtSignature:void 0}));if(r.length>0)for(let{call:e,thoughtSignature:n}of r)if(e.args==null)t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:{},...n?{providerMetadata:{thoughtSignature:n}}:{}});else if(typeof e.args!=`object`||Array.isArray(e.args))throw Error(`Invalid tool call arguments for ${e.name}: expected object, got ${typeof e.args}`);else t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:e.args,...n?{providerMetadata:{thoughtSignature:n}}:{}});return{type:`success`,id:e.responseId??``,model:e.modelVersion??``,role:`assistant`,finishReason:r.length>0?`function_call`:c,content:t,text:I(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function yr(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 br(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(xr(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 xr(e,t){let n=t.segment;return e.web?{source:{type:`web`,title:e.web.title,url:e.web.uri},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{outputText:n?.text,confidenceScores:t.confidenceScores}}:e.retrievedContext?{source:{type:`retrieved-context`,title:e.retrievedContext.title,uri:e.retrievedContext.uri,citedText:e.retrievedContext.text,locator:{type:`page`,start:e.retrievedContext.pageNumber,end:e.retrievedContext.pageNumber}},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{documentName:e.retrievedContext.documentName,outputText:n?.text,confidenceScores:t.confidenceScores}}: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 Sr(){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 Cr(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]=gr(m.finishReason),r=n?`function_call`:t;!e&&!n?p.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${m.finishReason}`,usage:W({in:a,out:o},{cachedIn:s,reasoningOut:c}),raw:f}}):p.push({type:`complete`,data:{finishReason:r,usage:W({in:a,out:o},{cachedIn:s,reasoningOut:c})}})}return p}return{handleChunk:f}}function Cr(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:wr(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 wr(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*Tr(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=tr(a,i,{...or(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]},...ar(m,h,a,o),...g});m!==`none`&&ir(v,o);let y=Sr();try{let e={contents:await sr(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 Er(e,t={}){let n=new C({apiKey:e,httpOptions:{retryOptions:{attempts:Dr(t.maxRetries)},...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}}});return{name:`Gemini`,resolveProviderToolName(e){return rr(e)},async createGenerationRequest(e,t){return await _r({client:n,model:e,...t})},createStreamingRequest(e,t){return Tr({client:n,model:e,...t})}}}function Dr(e=2){return Y(e,`maxRetries`,{min:0})+1}const Or={Models:r,DefaultModel:n};async function kr(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 Ar(e){if(je(e),`instruct`in e){let{instruct:t,messages:n,...r}=e,i=xe(t),a=await jr({...r,messages:[...n??[],i.message]},k());if(!a.ok)return a;try{return{...a,response:i.parse(a.final)}}catch(e){return{ok:!1,messages:a.messages,final:a.final,usage:a.usage,...a.stopped?{stopped:a.stopped}:{},error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)}}}}return jr(e,k())}async function jr(e,t){let{provider:n,model:r,messages:i,system:a,onToolCall:o,maxIterations:s,maxContextTokens:c,span:l,fileResolver:u,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v,signal:y=new AbortController().signal}=e,b=Be(ze(e),{provider:n,model:r,span:l,configuration:t}),x=[...i],S=[],C=V(),w=0,T,E=e=>{x.push(e),S.push(e)},D=e=>(l?.setResult({kind:`llm`,model:r,request:{messages:i},response:{content:e.ok?e.final.content:null},usage:Te(e.usage),finishReason:e.ok?e.final.finishReason:void 0}),l?.end(e.ok?`ok`:`error`),e),O=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??r,request:{messages:x},response:{content:t.content},usage:Te(t.usage),finishReason:t.finishReason}),e.end()};try{for(;;){X(y,`Generate aborted`),w+=1;let e=l?.startSpan(`turn-${w}`,{type:`llm`}),t=b.executable(),i=t.length>0?t.map(e=>({name:e.name,description:e.description,schema:e.schema})):void 0,k=b.provider(),A;try{A=await kr({provider:n,model:r,messages:x,system:a,tools:i,providerTools:k.length>0?k:void 0,span:e,fileResolver:u,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v,signal:y}),X(y,`Generate aborted`)}catch(t){throw t instanceof Error&&t.name===`AbortError`&&e?.end(`ok`),t}if(Ne(C,A,{provider:n.name,model:A.type===`error`?r:A.model??r}),A.type!==`error`&&Pe(e,A.content),O(e,A),A.type===`error`)return D({ok:!1,messages:S,error:{kind:`model`,error:A},usage:C});let j={role:`assistant`,id:A.id,model:A.model,content:A.content,finishReason:A.finishReason};if(E(j),T=j,A.finishReason!==`function_call`)return D({ok:!0,response:T,messages:S,final:T,usage:C});let M=te(A.content);if(M.length===0)return D({ok:!0,response:T,messages:S,final:T,usage:C});let{results:N,usage:P}=await Ve(M,o,y,b,l);H(C,P),X(y,`Generate aborted`),N.length>0&&E({role:`tool`,id:crypto.randomUUID(),content:N});let F=Me(w,A.usage,{maxIterations:s,maxContextTokens:c});if(F)return D({ok:!0,response:j,messages:S,final:j,usage:C,stopped:F})}}catch(e){throw e instanceof P?(l?.end(`error`),new P(e.message,{toolName:e.toolName,messages:e.messages??S,partial:e.partial??T,usage:U(C,e.usage),cause:e.cause})):e instanceof M?(l?.end(`ok`),new M(`Generate aborted`,{reason:e.reason,messages:e.messages??S,partial:e.partial,usage:U(C,e.usage)})):e instanceof Error&&e.name===`AbortError`?(l?.end(`ok`),new M(`Generate aborted`,{reason:y.reason,messages:S,usage:C})):e}}function Mr(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 Nr={web_search:`web_search_preview`,code_execution:`code_interpreter`};function Pr(e){return Nr[e]??e}function Fr(e){return e?.map(e=>({type:e.nativeName??Pr(e.name),...e.config}))}function Ir(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,name:e.name}};let r=n?.find(t=>t.name===e.name);if(r)return{tool_choice:{type:r.nativeName??Pr(r.name)}};throw Error(`Tool choice references an unavailable tool: ${e.name}`)}function Lr(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`none`}}:{}}async function Rr(e,t={model:``}){return(await Promise.all(e.map(e=>zr(e,t)))).flat(1)}async function zr(e,t){switch(e.role){case`tool`:return Br(e,t);case`assistant`:return Vr(e);default:return Hr(e,t)}}async function Br(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}):Wr(e.file,t,`tool-result`)))})))}function Vr(e){let t=[],n=I(e.content);n&&t.push({role:e.role,content:n});let r=e.content.filter(e=>e.type===`thinking`);for(let e of r)e.continuity?.provider===`openai`&&t.push({type:`reasoning`,id:e.id,summary:e.summary?[{type:`summary_text`,text:e.summary}]:[],...e.text?{content:[{type:`reasoning_text`,text:e.text}]}:{},encrypted_content:e.continuity.encrypted});let i=e.content.filter(e=>e.type===`tool-call`);for(let e of i)t.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.parameters)});let a=e.content.filter(e=>e.type===`provider-tool`);for(let e of a)e.output!=null&&t.push(e.output);return t}async function Hr(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>Ur(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function Ur(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?Wr(e.file,t,`user-message`):(e.type,null)}async function Wr(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:Gr(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 Kr(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}:Kr(r,e)}function Gr(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 Kr(e,t){if(e.type===`url`)return{type:`input_file`,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 qr(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=[...Mr(a)??[],...Fr(o)??[]],y={model:n,input:await Rr(r,{model:n,fileResolver:s?.fileResolver,signal:g}),...i&&{instructions:i},...e.length>0?{tools:e}:{},...Lr(c),...l===void 0?{}:{max_output_tokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Ir(p,a,o),...m===void 0?{}:{parallel_tool_calls:m},...h};_?.debug(`OpenAI ResponsesAPI request`,{request:Z(y)});let b=await kt(t.responses.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=Jr(b)}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),v=Ot(e)}return _?.debug(`OpenAI ResponsesAPI response`,{result:v}),v}function Jr(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:Zr(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=Yr(e);r.length>0?n.push(...r):e.output_text&&n.push({type:`text`,text:e.output_text});let i=e.output?.filter(e=>e.type===`function_call`);if(i&&i.length>0)for(let e of i){let t=e;try{n.push({type:`tool-call`,id:t.call_id||t.id||``,name:t.name||``,parameters:t.arguments?JSON.parse(t.arguments):{}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${t.arguments}`)}}return{type:`success`,id:e.id,model:e.model||``,role:`assistant`,finishReason:e.incomplete_details?`error`:i&&i.length>0?`function_call`:`stop`,content:n,text:I(n),usage:Zr(e.usage),raw:e}}function Yr(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(Xr).filter(e=>e!==null);t.push({type:`text`,text:e.text,...n.length>0?{citations:n}:{}})}return t}function Xr(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 Zr(e){return W({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 Qr(){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=$r(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=$r(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=ei(u.annotation);if(!e)break;let t=a.get($r(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:W({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 $r(e,t){return`${e}:${t}`}function ei(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*ti(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=[...Mr(a)??[],...Fr(o)??[]],y=Qr();try{let e={model:n,input:await Rr(r,{model:n,fileResolver:s?.fileResolver,signal:c}),...i&&{instructions:i},stream:!0,...v.length>0?{tools:v}:{},...Lr(l),...u===void 0?{}:{max_output_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Ir(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 ni(e,t={}){let n=new w({apiKey:e,maxRetries:Y(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`OpenAI`,resolveProviderToolName(e){return Pr(e)},async createGenerationRequest(e,t){return await qr({client:n,model:e,...t})},createStreamingRequest(e,t){return ti({client:n,model:e,...t})}}}const ri={Models:a,DefaultModel:o};function ii(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=ai(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 oi(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 ai(e,t){return typeof e==`function`?e(t):typeof e==`string`?e:`Complete this delegated task. Input: ${JSON.stringify(t)}`}function oi(e,t){return e instanceof P?new P(e.message,{toolName:t,usage:e.usage,cause:e}):e instanceof M?new M(e.message,{reason:e.reason,usage:e.usage}):e}const si=new TextEncoder;function ci(e,t={}){let n=t.maxItems??50,r=Math.max(1,t.maxConcurrency??8),i=Math.max(0,t.maxResultBytes??20971520),a=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:a,async execute(t,n){return li(await gi(t.items,r,n.signal,async(t,r)=>{try{return{index:r,input:t,ok:!0,output:await e.execute(t,n)}}catch(e){if(e instanceof P||e instanceof M)throw e;return{index:r,input:t,ok:!1,error:{type:`execution`,message:e instanceof Error?e.message:String(e)}}}}),i)}}}function li(e,t){let n=[],r=t;for(let i of e){let e=i.ok?{index:i.index,ok:!0}:{index:i.index,ok:!1,error:i.error},a=`<<result ${JSON.stringify(e)}>>\n`,o=fi({type:`text`,text:a});if(o>r){ui(n,pi({result:i,reason:`header`,attemptedBytes:o,remainingBytes:r,maxBytes:t}),1/0);continue}if(ui(n,a,r),r-=o,!i.ok||i.output==null)continue;let s=di(i.output);if(s>r){ui(n,pi({result:i,reason:`output`,attemptedBytes:s,remainingBytes:r,maxBytes:t}),1/0);continue}if(typeof i.output==`string`){ui(n,i.output,r),r-=fi(n[n.length-1]);continue}for(let e of i.output)n.push(e),r-=fi(e)}return n}function ui(e,t,n){return si.encode(t).length>n?!1:(e.push({type:`text`,text:t}),!0)}function di(e){return typeof e==`string`?fi({type:`text`,text:e}):e.reduce((e,t)=>e+fi(t),0)}function fi(e){if(e.type===`text`)return si.encode(e.text).length;let t=e.file.source;switch(t.type){case`text`:return si.encode(t.content).length;case`base64`:return si.encode(t.data).length;case`url`:return si.encode(t.url).length;case`ref`:return e.file.size??si.encode(`${e.file.name}:${e.file.mimeType}`).length}}function pi({result:e,reason:t,attemptedBytes:n,remainingBytes:r,maxBytes:i}){return`<<result ${e.index} omitted: ${t} ${mi(n)} exceeds remaining budget ${mi(r)} of ${mi(i)}; input ${hi(e.input)}>>`}function mi(e){return e===1?`1 byte`:`${e} bytes`}function hi(e){try{return JSON.stringify(e)}catch{return String(e)}}async function gi(e,t,n,r){let i=Array(e.length),a=0,o=!1,s=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:s},async()=>{for(;!o&&a<e.length;){if(n.aborted)throw o=!0,new M(`Operation aborted`,{reason:n.reason});let t=a++;try{i[t]=await r(e[t],t)}catch(e){throw o=!0,e}}})),i}const _i={trace:0,debug:1,info:2,warn:3,error:4};var vi=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 _i[e]>=_i[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 yi(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,t);let n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatSpanName(e);this.output(`${r}${n}START ${i}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.visibleDepths.get(e.spanId)??0,n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatDuration(e),a=this.formatSpanName(e),o=e.status===`error`?` [ERROR]`:``;if(this.output(`${r}${n}END ${a}${i}${o}`),e.result?.kind===`llm`){let t=e.result,i=[`model=${t.model}`];if(t.finishReason&&i.push(`finishReason=${t.finishReason}`),t.usage&&(t.usage.inputTokens!==void 0&&i.push(`inputTokens=${t.usage.inputTokens}`),t.usage.outputTokens!==void 0&&i.push(`outputTokens=${t.usage.outputTokens}`),t.usage.cachedInputTokens!==void 0&&i.push(`cachedInputTokens=${t.usage.cachedInputTokens}`),t.usage.cacheWriteInputTokens!==void 0&&i.push(`cacheWriteInputTokens=${t.usage.cacheWriteInputTokens}`),t.usage.reasoningOutputTokens!==void 0&&i.push(`reasoningOutputTokens=${t.usage.reasoningOutputTokens}`)),this.output(`${r}${n} INFO LLM complete ${i.join(` `)}`),this.shouldShowEvent(`debug`)&&t.response.content){let e=(typeof t.response.content==`string`?t.response.content:JSON.stringify(t.response.content,null,2)).split(`
17
+ `);for(let t of e)this.output(`${r}${n} DEBUG ${t}`)}}}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,t){if(!this.shouldShowEvent(t.level))return;this.spans.set(e.spanId,e);let n;if(this.isSpanVisible(e))n=this.visibleDepths.get(e.spanId)??0;else{let t=this.findVisibleAncestor(e);n=t?this.visibleDepths.get(t.spanId)??0:0}let r=this.formatIndent(n+1),i=this.formatTimestamp(),a=t.level.toUpperCase().padEnd(5),o=this.markdown&&t.attributes?.markdown===!0,s=t.attributes?Object.entries(t.attributes).filter(([e])=>e!==`markdown`):[],c=t.name;o&&(c=this.renderMarkdown(c));let l=`${i}${r}${a} ${c}`;if(s.length>0){let e=s.map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(` `);l+=` ${e}`}this.output(l)}};function yi(e){return bi(E.lexer(e))}function bi(e=[]){return e.map(e=>xi(e)).filter(e=>e.length>0).join(`
18
+ `)}function xi(e){switch(e.type){case`space`:return``;case`heading`:return T.bold($(e.tokens));case`paragraph`:return $(e.tokens);case`blockquote`:return Di(bi(e.tokens),`> `);case`code`:return(e.lang?T.dim(`${e.lang}\n`):``)+T.yellow(e.text);case`list`:return Ci(e)?Ti(e):e.raw;case`hr`:return T.dim(`-`.repeat(40));case`table`:return wi(e)?Ei(e):e.raw;case`html`:return e.text;case`text`:return e.tokens?$(e.tokens):ki(e.text);default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function $(e=[]){return e.map(e=>Si(e)).join(``)}function Si(e){switch(e.type){case`text`:case`escape`:return ki(e.text);case`strong`:return T.bold($(e.tokens));case`em`:return T.italic($(e.tokens));case`codespan`:return T.yellow(e.text);case`del`:return T.strikethrough($(e.tokens));case`link`:{let t=$(e.tokens);return e.href&&e.href!==e.text?`${T.blue.underline(t)} ${T.dim(`(${e.href})`)}`:T.blue.underline(t)}case`image`:return e.text?`${e.text} (${e.href})`:e.href;case`br`:return`
19
+ `;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function Ci(e){return e.type===`list`&&`items`in e&&Array.isArray(e.items)}function wi(e){return e.type===`table`&&`header`in e&&`rows`in e}function Ti(e){return e.items.map((t,n)=>{let r=e.ordered?`${Number(e.start||1)+n}. `:`- `,i=t.task?`[${t.checked?`x`:` `}] `:``,a=bi(t.tokens).trimEnd();return r+i+Oi(a,r.length+i.length)}).join(`
20
+ `)}function Ei(e){let t=e.header.map(e=>$(e.tokens)).join(` | `),n=e.rows.map(e=>e.map(e=>$(e.tokens)).join(` | `));return[T.bold(t),...n].join(`
21
+ `)}function Di(e,t){return e.split(`
22
22
  `).map(e=>t+e).join(`
23
- `)}function Ti(e,t){let[n=``,...r]=e.split(`
23
+ `)}function Oi(e,t){let[n=``,...r]=e.split(`
24
24
  `);if(r.length===0)return n;let i=` `.repeat(t);return[n,...r.map(e=>i+e)].join(`
25
- `)}function Ei(e){return e.replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/g,`&`)}export{st as Agent,un as Anthropic,M as AxleAbortError,N as AxleAgentAbortError,A as AxleError,Ve as AxleStopReason,P as AxleToolFatalError,Tr as Gemini,Ze as History,St as Instruct,_t as InstructVariableError,z as LogWriter,mt as MCP,ei as OpenAI,hi as SimpleWriter,wt as TaskError,we as ToolRegistry,tt as Tracer,e as TurnAccumulator,qe as TurnEventBuilder,q as addStats,ln as anthropic,De as braveWebSearch,Xn as chatCompletions,O as configureAxle,gt as createAgentConfig,ti as createAgentTool,Xe as createHandle,K as createStats,ie as estimateContextUsage,Cr as gemini,Dr as generate,Er as generateTurn,It as loadFileContent,_e as mergeStats,$r as openai,ai as parallelize,pe as parseResponse,We as stream};
25
+ `)}function ki(e){return e.replace(/&quot;/g,`"`).replace(/&#39;/g,`'`).replace(/&lt;/g,`<`).replace(/&gt;/g,`>`).replace(/&amp;/g,`&`)}export{ut as Agent,pn as Anthropic,M as AxleAbortError,N as AxleAgentAbortError,A as AxleError,Ge as AxleStopReason,P as AxleToolFatalError,Or as Gemini,et as History,Tt as Instruct,bt as InstructVariableError,oe as LogWriter,_t as MCP,ri as OpenAI,vi as SimpleWriter,Dt as TaskError,De as ToolRegistry,it as Tracer,e as TurnAccumulator,$e as TurnEventBuilder,H as addStats,fn as anthropic,Ae as braveWebSearch,$n as chatCompletions,O as configureAxle,yt as createAgentConfig,ii as createAgentTool,V as createStats,ce as estimateContextUsage,Er as gemini,Ar as generate,kr as generateTurn,zt as loadFileContent,U as mergeStats,ni as openai,ci as parallelize,ye as parseResponse,Ze as stream,F as validateCompactedMessages};
package/dist/ui.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as TurnPart, C as SubagentAction, D as ToolAction, E as TimingInfo, L as Citation, O as Turn, R as CitationOutputSpan, S as ProviderToolAction, T as ThinkingPart, Y as ThinkingContinuity, _ as Annotation, _t as TokenStats, a as UnknownEvent, b as CitationPart, ct as FileInfo, f as AnnotationEvent, g as ActionResult, gt as Stats, h as ActionPart, i as TurnAccumulatorState, j as TurnStatus, k as TurnMetadata, m as TurnEvent, n as TurnAccumulator, p as AnnotationTarget, q as DocumentLocator, r as TurnAccumulatorResult, t as AccumulatableEvent, v as AnnotationPlacement, vt as UsageEntry, w as TextPart, x as FilePart, y as AnnotationStatus, z as CitationSource } from "./accumulator-yYlD8Bfm.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 };
1
+ import { A as TurnMetadata, B as Citation, C as ProviderToolAction, D as TimingInfo, E as ThinkingPart, H as CitationSource, M as TurnStatus, N as CompactionRecord, O as ToolAction, Q as ThinkingContinuity, S as FilePart, T as TextPart, V as CitationOutputSpan, X as DocumentLocator, _ as Annotation, a as UnknownEvent, b as CitationPart, bt as TokenStats, dt as FileInfo, f as AnnotationEvent, g as ActionResult, h as ActionPart, i as TurnAccumulatorState, j as TurnPart, k as Turn, m as TurnEvent, n as TurnAccumulator, p as AnnotationTarget, r as TurnAccumulatorResult, t as AccumulatableEvent, v as AnnotationPlacement, w as SubagentAction, x as CompactionPart, xt as UsageEntry, y as AnnotationStatus, yt as Stats } from "./accumulator-BQ_1i4qv.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 CompactionPart, type CompactionRecord, 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-BnFn9yqM.js";export{e as TurnAccumulator};
1
+ import{t as e}from"./accumulator-jZHrnyOF.js";export{e as TurnAccumulator};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fifthrevision/axle",
3
- "version": "0.25.5",
3
+ "version": "0.26.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/johncch/axle.git"
@@ -1 +0,0 @@
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};