@fifthrevision/axle 0.22.1 → 0.23.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{accumulator-BNYePirr.d.ts → accumulator-C4O3UCxY.d.ts} +85 -83
- package/dist/index.d.ts +70 -41
- package/dist/index.js +18 -16
- package/dist/ui.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,87 @@
|
|
|
1
1
|
import { ZodObject, z } from "zod";
|
|
2
2
|
|
|
3
|
+
//#region src/observability/types.d.ts
|
|
4
|
+
type SpanStatus = "ok" | "error" | "cancelled";
|
|
5
|
+
type EventLevel = "trace" | "debug" | "info" | "warn" | "error";
|
|
6
|
+
type SpanType = string;
|
|
7
|
+
interface SpanEvent {
|
|
8
|
+
name: string;
|
|
9
|
+
timestamp: number;
|
|
10
|
+
level: EventLevel;
|
|
11
|
+
attributes?: Record<string, unknown>;
|
|
12
|
+
}
|
|
13
|
+
interface SpanData {
|
|
14
|
+
traceId: string;
|
|
15
|
+
spanId: string;
|
|
16
|
+
parentSpanId?: string;
|
|
17
|
+
name: string;
|
|
18
|
+
type?: SpanType;
|
|
19
|
+
startTime: number;
|
|
20
|
+
endTime?: number;
|
|
21
|
+
status: SpanStatus;
|
|
22
|
+
attributes: Record<string, unknown>;
|
|
23
|
+
events: SpanEvent[];
|
|
24
|
+
result?: SpanResult;
|
|
25
|
+
}
|
|
26
|
+
interface SpanOptions {
|
|
27
|
+
type?: SpanType;
|
|
28
|
+
attributes?: Record<string, unknown>;
|
|
29
|
+
}
|
|
30
|
+
type SpanResult = LLMResult | ToolResult;
|
|
31
|
+
interface LLMResult {
|
|
32
|
+
kind: "llm";
|
|
33
|
+
model: string;
|
|
34
|
+
request: LLMRequest;
|
|
35
|
+
response: LLMResponse;
|
|
36
|
+
usage?: TokenUsage;
|
|
37
|
+
finishReason?: string;
|
|
38
|
+
}
|
|
39
|
+
interface LLMRequest {
|
|
40
|
+
messages: unknown[];
|
|
41
|
+
system?: string;
|
|
42
|
+
tools?: unknown[];
|
|
43
|
+
}
|
|
44
|
+
interface LLMResponse {
|
|
45
|
+
content: unknown;
|
|
46
|
+
}
|
|
47
|
+
interface TokenUsage {
|
|
48
|
+
inputTokens?: number;
|
|
49
|
+
outputTokens?: number;
|
|
50
|
+
totalTokens?: number;
|
|
51
|
+
cachedInputTokens?: number;
|
|
52
|
+
cacheWriteInputTokens?: number;
|
|
53
|
+
reasoningOutputTokens?: number;
|
|
54
|
+
}
|
|
55
|
+
interface ToolResult {
|
|
56
|
+
kind: "tool";
|
|
57
|
+
name: string;
|
|
58
|
+
input: unknown;
|
|
59
|
+
output: unknown;
|
|
60
|
+
}
|
|
61
|
+
interface TraceWriter {
|
|
62
|
+
onSpanStart(span: SpanData): void;
|
|
63
|
+
onSpanUpdate?(span: SpanData): void;
|
|
64
|
+
onSpanEnd(span: SpanData): void;
|
|
65
|
+
onEvent?(span: SpanData, event: SpanEvent): void;
|
|
66
|
+
flush?(): Promise<void>;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Tracing context for a span. Created by Tracer.startSpan().
|
|
70
|
+
* Can create child spans and log events within the span's scope.
|
|
71
|
+
*/
|
|
72
|
+
interface Span {
|
|
73
|
+
startSpan(name: string, options?: SpanOptions): Span;
|
|
74
|
+
end(status?: SpanStatus): void;
|
|
75
|
+
trace(message: string, attributes?: Record<string, unknown>): void;
|
|
76
|
+
debug(message: string, attributes?: Record<string, unknown>): void;
|
|
77
|
+
info(message: string, attributes?: Record<string, unknown>): void;
|
|
78
|
+
warn(message: string, attributes?: Record<string, unknown>): void;
|
|
79
|
+
error(message: string, attributes?: Record<string, unknown>): void;
|
|
80
|
+
setAttribute(key: string, value: unknown): void;
|
|
81
|
+
setAttributes(attributes: Record<string, unknown>): void;
|
|
82
|
+
setResult(result: SpanResult): void;
|
|
83
|
+
}
|
|
84
|
+
//#endregion
|
|
3
85
|
//#region src/types.d.ts
|
|
4
86
|
/**
|
|
5
87
|
* Usage reported by a provider response.
|
|
@@ -167,86 +249,6 @@ interface StreamProviderToolCompleteChunk extends StreamChunk {
|
|
|
167
249
|
}
|
|
168
250
|
type AnyStreamChunk = StreamStartChunk | StreamCompleteChunk | StreamErrorChunk | StreamTextStartChunk | StreamTextDeltaChunk | StreamTextCitationChunk | StreamCitationChunk | StreamTextCompleteChunk | StreamThinkingStartChunk | StreamThinkingDeltaChunk | StreamThinkingSummaryDeltaChunk | StreamThinkingMetadataChunk | StreamThinkingCompleteChunk | StreamToolCallStartChunk | StreamToolCallArgsDeltaChunk | StreamToolCallCompleteChunk | StreamProviderToolStartChunk | StreamProviderToolCompleteChunk;
|
|
169
251
|
//#endregion
|
|
170
|
-
//#region src/tracer/types.d.ts
|
|
171
|
-
type SpanStatus = "ok" | "error";
|
|
172
|
-
type EventLevel = "debug" | "info" | "warn" | "error";
|
|
173
|
-
type SpanType = string;
|
|
174
|
-
interface SpanEvent {
|
|
175
|
-
name: string;
|
|
176
|
-
timestamp: number;
|
|
177
|
-
level: EventLevel;
|
|
178
|
-
attributes?: Record<string, unknown>;
|
|
179
|
-
}
|
|
180
|
-
interface SpanData {
|
|
181
|
-
traceId: string;
|
|
182
|
-
spanId: string;
|
|
183
|
-
parentSpanId?: string;
|
|
184
|
-
name: string;
|
|
185
|
-
type?: SpanType;
|
|
186
|
-
startTime: number;
|
|
187
|
-
endTime?: number;
|
|
188
|
-
status: SpanStatus;
|
|
189
|
-
attributes: Record<string, unknown>;
|
|
190
|
-
events: SpanEvent[];
|
|
191
|
-
result?: SpanResult;
|
|
192
|
-
}
|
|
193
|
-
interface SpanOptions {
|
|
194
|
-
type?: SpanType;
|
|
195
|
-
}
|
|
196
|
-
type SpanResult = LLMResult | ToolResult;
|
|
197
|
-
interface LLMResult {
|
|
198
|
-
kind: "llm";
|
|
199
|
-
model: string;
|
|
200
|
-
request: LLMRequest;
|
|
201
|
-
response: LLMResponse;
|
|
202
|
-
usage?: TokenUsage;
|
|
203
|
-
finishReason?: string;
|
|
204
|
-
}
|
|
205
|
-
interface LLMRequest {
|
|
206
|
-
messages: unknown[];
|
|
207
|
-
system?: string;
|
|
208
|
-
tools?: unknown[];
|
|
209
|
-
}
|
|
210
|
-
interface LLMResponse {
|
|
211
|
-
content: unknown;
|
|
212
|
-
}
|
|
213
|
-
interface TokenUsage {
|
|
214
|
-
inputTokens?: number;
|
|
215
|
-
outputTokens?: number;
|
|
216
|
-
totalTokens?: number;
|
|
217
|
-
cachedInputTokens?: number;
|
|
218
|
-
cacheWriteInputTokens?: number;
|
|
219
|
-
reasoningOutputTokens?: number;
|
|
220
|
-
}
|
|
221
|
-
interface ToolResult {
|
|
222
|
-
kind: "tool";
|
|
223
|
-
name: string;
|
|
224
|
-
input: unknown;
|
|
225
|
-
output: unknown;
|
|
226
|
-
}
|
|
227
|
-
interface TraceWriter {
|
|
228
|
-
onSpanStart(span: SpanData): void;
|
|
229
|
-
onSpanUpdate?(span: SpanData): void;
|
|
230
|
-
onSpanEnd(span: SpanData): void;
|
|
231
|
-
onEvent?(span: SpanData, event: SpanEvent): void;
|
|
232
|
-
flush?(): Promise<void>;
|
|
233
|
-
}
|
|
234
|
-
/**
|
|
235
|
-
* Tracing context for a span. Created by Tracer.startSpan().
|
|
236
|
-
* Can create child spans and log events within the span's scope.
|
|
237
|
-
*/
|
|
238
|
-
interface TracingContext {
|
|
239
|
-
startSpan(name: string, options?: SpanOptions): TracingContext;
|
|
240
|
-
end(status?: SpanStatus): void;
|
|
241
|
-
debug(message: string, attributes?: Record<string, unknown>): void;
|
|
242
|
-
info(message: string, attributes?: Record<string, unknown>): void;
|
|
243
|
-
warn(message: string, attributes?: Record<string, unknown>): void;
|
|
244
|
-
error(message: string, attributes?: Record<string, unknown>): void;
|
|
245
|
-
setAttribute(key: string, value: unknown): void;
|
|
246
|
-
setAttributes(attributes: Record<string, unknown>): void;
|
|
247
|
-
setResult(result: SpanResult): void;
|
|
248
|
-
}
|
|
249
|
-
//#endregion
|
|
250
252
|
//#region src/utils/file.d.ts
|
|
251
253
|
type FileKind = "image" | "document" | "text";
|
|
252
254
|
type TextSource = {
|
|
@@ -358,7 +360,7 @@ declare function loadFileContent(filePath: string, encoding: "base64"): Promise<
|
|
|
358
360
|
*/
|
|
359
361
|
interface ProviderRuntime {
|
|
360
362
|
/** Request-scoped tracing span used by provider adapters. */
|
|
361
|
-
|
|
363
|
+
span?: Span;
|
|
362
364
|
/** Resolves file references before provider-specific request conversion. */
|
|
363
365
|
fileResolver?: FileResolver;
|
|
364
366
|
}
|
|
@@ -779,7 +781,7 @@ interface ToolContext {
|
|
|
779
781
|
registry: ToolRegistry;
|
|
780
782
|
signal: AbortSignal;
|
|
781
783
|
emit: (chunk: string) => void;
|
|
782
|
-
|
|
784
|
+
span?: Span;
|
|
783
785
|
}
|
|
784
786
|
interface ExecutableTool<TSchema extends ZodObject<any> = ZodObject<any>> {
|
|
785
787
|
type?: "function";
|
|
@@ -1193,4 +1195,4 @@ declare class TurnAccumulator<TAnnotation extends Annotation = Annotation, THost
|
|
|
1193
1195
|
private handled;
|
|
1194
1196
|
}
|
|
1195
1197
|
//#endregion
|
|
1196
|
-
export { ContextUsage as $, ToolRegistry as A, ContentPartCitation as B, TurnMetadata as C, ProviderTool as D, ExecutableTool as E, AxleUserMessage as F, ContentPartToolCall as G, ContentPartProviderTool as H, Citation as I, ThinkingContinuity as J, DocumentLocator as K, CitationOutputSpan as L, AxleMessage as M, AxleToolCallMessage as N, ToolContext as O, AxleToolCallResult as P, AxleStopReason as Q, CitationSource as R, Turn as S, TurnStatus as T, ContentPartText as U, ContentPartFile as V, ContentPartThinking as W, AIProvider as X, ToolResultPart as Y, AxleModelRequestOptions as Z, SubagentAction as _,
|
|
1198
|
+
export { ContextUsage as $, ToolRegistry as A, ContentPartCitation as B, TurnMetadata as C, SpanResult as Ct, ProviderTool as D, ToolResult as Dt, ExecutableTool as E, TokenUsage as Et, AxleUserMessage as F, ContentPartToolCall as G, ContentPartProviderTool as H, Citation as I, ThinkingContinuity as J, DocumentLocator as K, CitationOutputSpan as L, AxleMessage as M, AxleToolCallMessage as N, ToolContext as O, TraceWriter as Ot, AxleToolCallResult as P, AxleStopReason as Q, CitationSource as R, Turn as S, SpanOptions as St, TurnStatus as T, SpanType as Tt, ContentPartText as U, ContentPartFile as V, ContentPartThinking as W, AIProvider as X, ToolResultPart as Y, AxleModelRequestOptions as Z, SubagentAction as _, LLMResponse as _t, UnknownEvent as a, DeferredFileInfo as at, TimingInfo as b, SpanData as bt, TurnEvent as c, FileProviderId as ct, Annotation as d, FileResolver as dt, ModelError as et, AnnotationPlacement as f, ResolvedFileSource as ft, ProviderToolAction as g, LLMRequest as gt, FilePart as h, EventLevel as ht, TurnAccumulatorState as i, ToolChoice as it, AxleAssistantMessage as j, ToolDefinition as k, ActionPart as l, FileResolveFormat as lt, CitationPart as m, Stats as mt, TurnAccumulator as n, ProviderClientOptions as nt, AnnotationEvent as o, FileInfo as ot, AnnotationStatus as p, loadFileContent as pt, MessageMetadata as q, TurnAccumulatorResult as r, ProviderOptions as rt, AnnotationTarget as s, FileKind as st, AccumulatableEvent as t, ModelResult as tt, ActionResult as u, FileResolveRequest as ut, TextPart as v, LLMResult as vt, TurnPart as w, SpanStatus as wt, ToolAction as x, SpanEvent as xt, ThinkingPart as y, Span as yt, ContentPart as z };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $ as ContextUsage, A as ToolRegistry, B as ContentPartCitation, C as TurnMetadata, D as ProviderTool, E as ExecutableTool, F as AxleUserMessage, G as ContentPartToolCall, H as ContentPartProviderTool, I as Citation, J as ThinkingContinuity, K as DocumentLocator, L as CitationOutputSpan, M as AxleMessage, N as AxleToolCallMessage, O as ToolContext, P as AxleToolCallResult, Q as AxleStopReason, R as CitationSource, S as Turn, T as TurnStatus, U as ContentPartText, V as ContentPartFile, W as ContentPartThinking, X as AIProvider, Y as ToolResultPart, Z as AxleModelRequestOptions, _ as SubagentAction, _t as
|
|
1
|
+
import { $ as ContextUsage, A as ToolRegistry, B as ContentPartCitation, C as TurnMetadata, Ct as SpanResult, D as ProviderTool, Dt as ToolResult, E as ExecutableTool, Et as TokenUsage, F as AxleUserMessage, G as ContentPartToolCall, H as ContentPartProviderTool, I as Citation, J as ThinkingContinuity, K as DocumentLocator, L as CitationOutputSpan, M as AxleMessage, N as AxleToolCallMessage, O as ToolContext, Ot as TraceWriter, P as AxleToolCallResult, Q as AxleStopReason, R as CitationSource, S as Turn, St as SpanOptions, T as TurnStatus, Tt as SpanType, U as ContentPartText, V as ContentPartFile, W as ContentPartThinking, X as AIProvider, Y as ToolResultPart, Z as AxleModelRequestOptions, _ as SubagentAction, _t as LLMResponse, at as DeferredFileInfo, bt as SpanData, c as TurnEvent, ct as FileProviderId, d as Annotation, dt as FileResolver, et as ModelError, f as AnnotationPlacement, ft as ResolvedFileSource, g as ProviderToolAction, gt as LLMRequest, h as FilePart, ht as EventLevel, i as TurnAccumulatorState, it as ToolChoice, j as AxleAssistantMessage, k as ToolDefinition, l as ActionPart, lt as FileResolveFormat, m as CitationPart, mt as Stats, n as TurnAccumulator, nt as ProviderClientOptions, o as AnnotationEvent, ot as FileInfo, p as AnnotationStatus, pt as loadFileContent, q as MessageMetadata, r as TurnAccumulatorResult, rt as ProviderOptions, s as AnnotationTarget, st as FileKind, t as AccumulatableEvent, tt as ModelResult, u as ActionResult, ut as FileResolveRequest, v as TextPart, vt as LLMResult, w as TurnPart, wt as SpanStatus, x as ToolAction, xt as SpanEvent, y as ThinkingPart, yt as Span, z as ContentPart } from "./accumulator-C4O3UCxY.js";
|
|
2
2
|
import * as z$2 from "zod";
|
|
3
3
|
|
|
4
4
|
//#region src/mcp/MCP.d.ts
|
|
@@ -26,22 +26,22 @@ declare class MCP {
|
|
|
26
26
|
get name(): string | undefined;
|
|
27
27
|
get connected(): boolean;
|
|
28
28
|
connect(options?: {
|
|
29
|
-
|
|
29
|
+
span?: Span;
|
|
30
30
|
signal?: AbortSignal;
|
|
31
31
|
}): Promise<void>;
|
|
32
32
|
listTools(options?: {
|
|
33
33
|
prefix?: string;
|
|
34
|
-
|
|
34
|
+
span?: Span;
|
|
35
35
|
signal?: AbortSignal;
|
|
36
36
|
}): Promise<ExecutableTool[]>;
|
|
37
37
|
listToolDefinitions(options?: {
|
|
38
38
|
prefix?: string;
|
|
39
|
-
|
|
39
|
+
span?: Span;
|
|
40
40
|
signal?: AbortSignal;
|
|
41
41
|
}): Promise<ToolDefinition[]>;
|
|
42
42
|
refreshTools(): Promise<ExecutableTool[]>;
|
|
43
43
|
close(options?: {
|
|
44
|
-
|
|
44
|
+
span?: Span;
|
|
45
45
|
}): Promise<void>;
|
|
46
46
|
private fetchTools;
|
|
47
47
|
private assertConnected;
|
|
@@ -130,7 +130,7 @@ interface MemoryContext {
|
|
|
130
130
|
/** Newly produced messages to record after a turn completes. */
|
|
131
131
|
newMessages?: AxleMessage[];
|
|
132
132
|
/** Optional tracing context. */
|
|
133
|
-
|
|
133
|
+
span?: Span;
|
|
134
134
|
}
|
|
135
135
|
interface RecallResult {
|
|
136
136
|
systemSuffix?: string;
|
|
@@ -141,6 +141,44 @@ interface AgentMemory {
|
|
|
141
141
|
tools?(): ExecutableTool[];
|
|
142
142
|
}
|
|
143
143
|
//#endregion
|
|
144
|
+
//#region src/observability/log.d.ts
|
|
145
|
+
interface LogEntry {
|
|
146
|
+
level: EventLevel;
|
|
147
|
+
message: string;
|
|
148
|
+
fields?: Record<string, unknown>;
|
|
149
|
+
}
|
|
150
|
+
type LogFn = (entry: LogEntry) => void;
|
|
151
|
+
/**
|
|
152
|
+
* Projects a tracer's diagnostics into flat, correlated host log entries:
|
|
153
|
+
* leveled messages emitted within a span, and every span's completion as a line
|
|
154
|
+
* carrying its name, `type`, `spanId`, and `parentSpanId` — enough to
|
|
155
|
+
* reconstruct the trace skeleton from the log stream alone. The full span tree
|
|
156
|
+
* also reaches a real span exporter via a separate writer.
|
|
157
|
+
*/
|
|
158
|
+
declare class LogWriter implements TraceWriter {
|
|
159
|
+
private readonly log;
|
|
160
|
+
constructor(log: LogFn);
|
|
161
|
+
onSpanStart(): void;
|
|
162
|
+
onSpanEnd(span: SpanData): void;
|
|
163
|
+
onEvent(span: SpanData, event: SpanEvent): void;
|
|
164
|
+
}
|
|
165
|
+
//#endregion
|
|
166
|
+
//#region src/observability/tracer.d.ts
|
|
167
|
+
interface TracerOptions {
|
|
168
|
+
minLevel?: EventLevel;
|
|
169
|
+
writers?: TraceWriter[];
|
|
170
|
+
}
|
|
171
|
+
declare class Tracer {
|
|
172
|
+
private rec;
|
|
173
|
+
constructor(options?: TracerOptions);
|
|
174
|
+
get minLevel(): EventLevel;
|
|
175
|
+
set minLevel(level: EventLevel);
|
|
176
|
+
addWriter(writer: TraceWriter): void;
|
|
177
|
+
removeWriter(writer: TraceWriter): void;
|
|
178
|
+
startSpan(name: string, options?: SpanOptions): Span;
|
|
179
|
+
flush(): Promise<void>;
|
|
180
|
+
}
|
|
181
|
+
//#endregion
|
|
144
182
|
//#region src/providers/helpers.d.ts
|
|
145
183
|
type ToolCallResult = {
|
|
146
184
|
type: "success";
|
|
@@ -228,11 +266,28 @@ interface AgentConfig extends Omit<AxleModelRequestOptions, "signal"> {
|
|
|
228
266
|
mcps?: MCP[];
|
|
229
267
|
/** Optional memory implementation. */
|
|
230
268
|
memory?: AgentMemory;
|
|
231
|
-
/**
|
|
232
|
-
|
|
269
|
+
/** Observability: structured logging and optional span tracing. */
|
|
270
|
+
observability?: ObservabilityOptions;
|
|
233
271
|
/** Optional file resolver for request file references. */
|
|
234
272
|
fileResolver?: FileResolver;
|
|
235
273
|
}
|
|
274
|
+
/**
|
|
275
|
+
* Observability configuration for an `Agent`.
|
|
276
|
+
*
|
|
277
|
+
* Provide `log` for a structured, level-filtered log sink (the common case);
|
|
278
|
+
* Axle creates and owns a tracer behind the scenes. Provide `trace` to bring
|
|
279
|
+
* your own — a `Tracer` (each send is its own root) or a `Span` (sends nest
|
|
280
|
+
* under it); Axle attaches its spans but never ends or flushes what you pass.
|
|
281
|
+
* `level` governs only the tracer Axle creates from `log`.
|
|
282
|
+
*/
|
|
283
|
+
interface ObservabilityOptions {
|
|
284
|
+
/** Minimum level emitted. Default "info"; use "debug" in development. */
|
|
285
|
+
level?: EventLevel;
|
|
286
|
+
/** Structured log sink. Axle creates and owns a tracer when `trace` is absent. */
|
|
287
|
+
log?: LogFn;
|
|
288
|
+
/** Bring your own: a Tracer (per-send roots) or a Span to nest sends under. */
|
|
289
|
+
trace?: Tracer | Span;
|
|
290
|
+
}
|
|
236
291
|
/**
|
|
237
292
|
* Serializable provider reference for an agent definition.
|
|
238
293
|
*
|
|
@@ -377,7 +432,6 @@ declare class Agent {
|
|
|
377
432
|
readonly provider: AIProvider;
|
|
378
433
|
readonly model: string;
|
|
379
434
|
readonly history: History;
|
|
380
|
-
readonly tracer?: TracingContext;
|
|
381
435
|
readonly name?: string;
|
|
382
436
|
readonly fileResolver?: FileResolver;
|
|
383
437
|
readonly requestOptions: Omit<AxleModelRequestOptions, "signal">;
|
|
@@ -387,6 +441,8 @@ declare class Agent {
|
|
|
387
441
|
private mcps;
|
|
388
442
|
private resolvedMcps;
|
|
389
443
|
private memory?;
|
|
444
|
+
private spanParent?;
|
|
445
|
+
private ownedTracer?;
|
|
390
446
|
private eventCallbacks;
|
|
391
447
|
private sendQueue;
|
|
392
448
|
/**
|
|
@@ -651,7 +707,7 @@ interface GenerateParams extends AxleModelRequestOptions {
|
|
|
651
707
|
registry?: ToolRegistry;
|
|
652
708
|
onToolCall?: ToolCallCallback;
|
|
653
709
|
maxIterations?: number;
|
|
654
|
-
|
|
710
|
+
span?: Span;
|
|
655
711
|
fileResolver?: FileResolver;
|
|
656
712
|
}
|
|
657
713
|
interface GenerateInstructParams<TSchema extends OutputSchema | undefined> extends Omit<GenerateParams, "messages"> {
|
|
@@ -670,7 +726,7 @@ interface GenerateTurnParams extends AxleModelRequestOptions {
|
|
|
670
726
|
system?: string;
|
|
671
727
|
tools?: Array<ToolDefinition>;
|
|
672
728
|
providerTools?: Array<ProviderTool>;
|
|
673
|
-
|
|
729
|
+
span?: Span;
|
|
674
730
|
fileResolver?: FileResolver;
|
|
675
731
|
}
|
|
676
732
|
declare function generateTurn(props: GenerateTurnParams): Promise<ModelResult>;
|
|
@@ -794,7 +850,7 @@ interface StreamParams extends AxleModelRequestOptions {
|
|
|
794
850
|
registry?: ToolRegistry;
|
|
795
851
|
onToolCall?: ToolCallCallback;
|
|
796
852
|
maxIterations?: number;
|
|
797
|
-
|
|
853
|
+
span?: Span;
|
|
798
854
|
fileResolver?: FileResolver;
|
|
799
855
|
}
|
|
800
856
|
interface StreamHandle {
|
|
@@ -888,34 +944,7 @@ declare class TurnEventBuilder {
|
|
|
888
944
|
private closeOpenParts;
|
|
889
945
|
}
|
|
890
946
|
//#endregion
|
|
891
|
-
//#region src/
|
|
892
|
-
/**
|
|
893
|
-
* Root tracer that manages writers and creates spans.
|
|
894
|
-
* Use startSpan() to create TracingContext instances for hierarchical tracing.
|
|
895
|
-
* All logging happens within spans - the Tracer itself is just configuration and factory.
|
|
896
|
-
*/
|
|
897
|
-
declare class Tracer {
|
|
898
|
-
private writers;
|
|
899
|
-
private _minLevel;
|
|
900
|
-
get minLevel(): EventLevel;
|
|
901
|
-
set minLevel(level: EventLevel);
|
|
902
|
-
addWriter(writer: TraceWriter): void;
|
|
903
|
-
removeWriter(writer: TraceWriter): void;
|
|
904
|
-
startSpan(name: string, options?: SpanOptions): TracingContext;
|
|
905
|
-
flush(): Promise<void>;
|
|
906
|
-
/** @internal */
|
|
907
|
-
_notifySpanEnd(spanData: SpanData): void;
|
|
908
|
-
/** @internal */
|
|
909
|
-
_notifySpanUpdate(spanData: SpanData): void;
|
|
910
|
-
/** @internal */
|
|
911
|
-
_notifyEvent(spanData: SpanData, event: SpanEvent): void;
|
|
912
|
-
/** @internal */
|
|
913
|
-
_notifySpanStart(spanData: SpanData): void;
|
|
914
|
-
/** @internal */
|
|
915
|
-
_shouldLog(level: EventLevel): boolean;
|
|
916
|
-
}
|
|
917
|
-
//#endregion
|
|
918
|
-
//#region src/tracer/writers/simple.d.ts
|
|
947
|
+
//#region src/observability/writers/simple.d.ts
|
|
919
948
|
interface SimpleWriterOptions {
|
|
920
949
|
/** Minimum event level to display (default: "info") */
|
|
921
950
|
minLevel?: EventLevel;
|
|
@@ -973,4 +1002,4 @@ interface FileStore {
|
|
|
973
1002
|
declare function createStats(): Stats;
|
|
974
1003
|
declare function addStats(total: Stats, usage?: Stats): void;
|
|
975
1004
|
//#endregion
|
|
976
|
-
export { type AIProvider, type AccumulatableEvent, type ActionPart, type ActionResult, Agent, type AgentConfig, type AgentDefinition, type AgentDefinitionRequestOptions, type AgentDefinitionResolver, type AgentErrorResult, type AgentHandle, type AgentMemory, type AgentResult, type AgentSession, type Annotation, type AnnotationEvent, type AnnotationPlacement, type AnnotationStatus, type AnnotationTarget, Anthropic, AxleAbortError, AxleAgentAbortError, type AxleAssistantMessage, AxleError, type AxleMessage, type AxleModelRequestOptions, AxleStopReason, type AxleToolCallMessage, type AxleToolCallResult, AxleToolFatalError, type AxleUserMessage, type ChatCompletionsOptions, type Citation, type CitationOutputSpan, type CitationPart, type CitationSource, type ContentPart, type ContentPartCitation, type ContentPartFile, type ContentPartProviderTool, type ContentPartText, type ContentPartThinking, type ContentPartToolCall, type ContextUsage, type DeferredFileInfo, type DocumentLocator, type EventLevel, type ExecutableTool, type FileInfo, type FileKind, type FilePart, type FileProviderId, type FileResolveFormat, type FileResolveRequest, type FileResolver, type FileStore, Gemini, type GenerateInstructParams, type GenerateInstructResult, type GenerateParams, type Handle, History, Instruct, type InstructInputs, type InstructOptions, type InstructResponse, InstructVariableError, type InstructVarsMode, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MaybePromise, type MemoryContext, type MessageMetadata, OpenAI, type OutputSchema, type ParsedSchema, type ProviderClientOptions, type ProviderDefinition, type ProviderOptions, type ProviderTool, type ProviderToolAction, type ProviderToolDefinitionRef, type RecallResult, type ResolvedAgentDefinition, type ResolvedFileSource, type SavedAgent, type SendMessageOptions, SimpleWriter, type SimpleWriterOptions, type SpanData, type SpanOptions, type SpanType, type Stats, type StreamEvent, type StreamEventCallback, type StreamHandle, type StreamInstructHandle, type StreamInstructParams, type StreamInstructResult, type StreamParams, type StreamResult, type SubagentAction, TaskError, type TextPart, type ThinkingContinuity, type ThinkingPart, type ToolAction, type ToolChoice, type ToolContext, type ToolDefinition, type ToolDefinitionRef, ToolRegistry, type ToolResultPart, type TraceWriter, Tracer, type
|
|
1005
|
+
export { type AIProvider, type AccumulatableEvent, type ActionPart, type ActionResult, Agent, type AgentConfig, type AgentDefinition, type AgentDefinitionRequestOptions, type AgentDefinitionResolver, type AgentErrorResult, type AgentHandle, type AgentMemory, type AgentResult, type AgentSession, type Annotation, type AnnotationEvent, type AnnotationPlacement, type AnnotationStatus, type AnnotationTarget, Anthropic, AxleAbortError, AxleAgentAbortError, type AxleAssistantMessage, AxleError, type AxleMessage, type AxleModelRequestOptions, AxleStopReason, type AxleToolCallMessage, type AxleToolCallResult, AxleToolFatalError, type AxleUserMessage, type ChatCompletionsOptions, type Citation, type CitationOutputSpan, type CitationPart, type CitationSource, type ContentPart, type ContentPartCitation, type ContentPartFile, type ContentPartProviderTool, type ContentPartText, type ContentPartThinking, type ContentPartToolCall, type ContextUsage, type DeferredFileInfo, type DocumentLocator, type EventLevel, type ExecutableTool, type FileInfo, type FileKind, type FilePart, type FileProviderId, type FileResolveFormat, type FileResolveRequest, type FileResolver, type FileStore, Gemini, type GenerateInstructParams, type GenerateInstructResult, type GenerateParams, type Handle, History, Instruct, type InstructInputs, type InstructOptions, type InstructResponse, InstructVariableError, type InstructVarsMode, type LLMRequest, type LLMResponse, type LLMResult, type LogEntry, type LogFn, LogWriter, MCP, type MCPConfig, type MCPHttpConfig, type MCPStdioConfig, type MaybePromise, type MemoryContext, type MessageMetadata, type ObservabilityOptions, OpenAI, type OutputSchema, type ParsedSchema, type ProviderClientOptions, type ProviderDefinition, type ProviderOptions, type ProviderTool, type ProviderToolAction, type ProviderToolDefinitionRef, type RecallResult, type ResolvedAgentDefinition, type ResolvedFileSource, type SavedAgent, type SendMessageOptions, SimpleWriter, type SimpleWriterOptions, type Span, type SpanData, type SpanEvent, type SpanOptions, type SpanResult, type SpanStatus, type SpanType, type Stats, type StreamEvent, type StreamEventCallback, type StreamHandle, type StreamInstructHandle, type StreamInstructParams, type StreamInstructResult, type StreamParams, type StreamResult, type SubagentAction, TaskError, type TextPart, type ThinkingContinuity, type ThinkingPart, type TokenUsage, type ToolAction, type ToolChoice, type ToolContext, type ToolDefinition, type ToolDefinitionRef, ToolRegistry, type ToolResult, type ToolResultPart, type TraceWriter, Tracer, type TracerOptions, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, TurnEventBuilder, type TurnEventCallback, type TurnMetadata, type TurnPart, type TurnStatus, addStats, anthropic, chatCompletions, createAgentConfig, createHandle, createStats, estimateContextUsage, gemini, generate, generateTurn, loadFileContent, openai, parseResponse, stream };
|
package/dist/index.js
CHANGED
|
@@ -1,22 +1,24 @@
|
|
|
1
|
-
import{t as e}from"./accumulator-BLjnX0uz.js";import{d as t,i as n,o as r,p as i,r as a,t as o,u as s}from"./models-Cx50YJNx.js";import*as c from"zod";import l from"zod";import{Client as u}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as d}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as f}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import p from"@anthropic-ai/sdk";import"glob";import m from"mime";import{access as h,readFile as g,stat as _}from"node:fs/promises";import{extname as v,resolve as y}from"node:path";import{FinishReason as b,FunctionCallingConfigMode as x,GoogleGenAI as S}from"@google/genai";import C from"openai";import w from"chalk";import{marked as T}from"marked";var E=class e extends Error{code;id;details;constructor(t,n){super(t,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||`AXLE_ERROR`,this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id?{id:this.id}:{},...this.details?{details:this.details}:{},...this.cause?{cause:D(this.cause)}:{}}}};function D(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:D(e.cause)}:{}}:e}var O=class e extends E{reason;messages;partial;usage;constructor(t=`Operation aborted`,n){super(t,{code:`ABORTED`,details:{reason:n?.reason,usage:n?.usage}}),this.name=`AbortError`,this.reason=n?.reason,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),reason:this.reason,...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}},k=class e extends O{turn;constructor(t=`Agent send aborted`,n){super(t,n),this.turn=n?.turn,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.turn?{turn:this.turn}:{}}}},A=class e extends E{toolName;messages;partial;usage;constructor(t=`Fatal tool error`,n){super(t,{code:`TOOL_FATAL_ERROR`,details:{toolName:n?.toolName,usage:n?.usage},cause:n?.cause}),this.toolName=n?.toolName,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.toolName?{toolName:this.toolName}:{},...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}};function j(e){let
|
|
1
|
+
import{t as e}from"./accumulator-BLjnX0uz.js";import{d as t,i as n,o as r,p as i,r as a,t as o,u as s}from"./models-Cx50YJNx.js";import*as c from"zod";import l from"zod";import{Client as u}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as d}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as f}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import p from"@anthropic-ai/sdk";import"glob";import m from"mime";import{access as h,readFile as g,stat as _}from"node:fs/promises";import{extname as v,resolve as y}from"node:path";import{FinishReason as b,FunctionCallingConfigMode as x,GoogleGenAI as S}from"@google/genai";import C from"openai";import w from"chalk";import{marked as T}from"marked";var E=class e extends Error{code;id;details;constructor(t,n){super(t,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||`AXLE_ERROR`,this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id?{id:this.id}:{},...this.details?{details:this.details}:{},...this.cause?{cause:D(this.cause)}:{}}}};function D(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:D(e.cause)}:{}}:e}var O=class e extends E{reason;messages;partial;usage;constructor(t=`Operation aborted`,n){super(t,{code:`ABORTED`,details:{reason:n?.reason,usage:n?.usage}}),this.name=`AbortError`,this.reason=n?.reason,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),reason:this.reason,...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}},k=class e extends O{turn;constructor(t=`Agent send aborted`,n){super(t,n),this.turn=n?.turn,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.turn?{turn:this.turn}:{}}}},A=class e extends E{toolName;messages;partial;usage;constructor(t=`Fatal tool error`,n){super(t,{code:`TOOL_FATAL_ERROR`,details:{toolName:n?.toolName,usage:n?.usage},cause:n?.cause}),this.toolName=n?.toolName,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.toolName?{toolName:this.toolName}:{},...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}};function j(e){let{text:t,files:n}=e,r=[];if(t&&r.push({type:`text`,text:t}),n)for(let e of n)r.push({type:`file`,file:e});return r}function M(e){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
2
|
|
|
3
|
-
`)}function V(e){return e.filter(e=>e.type===`tool-call`)}function H(e){if(e instanceof c.ZodString)return[`string`,`Your answer`];if(e instanceof c.ZodNumber)return[`number`,42];if(e instanceof c.ZodBoolean)return[`boolean`,!0];if(e instanceof c.ZodEnum){let t=e.options;return[t.map(U).join(` | `),t[0]]}if(e instanceof c.ZodLiteral){let t=e.value;return[U(t),t]}if(e instanceof c.ZodArray){let t=e.element;if(t instanceof c.ZodString)return[`string array`,[`answer 1`,`answer 2`,`third answer`]];if(t instanceof c.ZodNumber)return[`number array`,[42,59,3.14]];if(t instanceof c.ZodBoolean)return[`boolean array`,[!0,!1,!1]];if(t instanceof c.ZodObject){let[,e]=H(t);return[`object array`,[e,e]]}else if(t instanceof c.ZodEnum||t instanceof c.ZodLiteral){let[e,n]=H(t);return[`${e} array`,[n]]}return[`array`,[]]}if(e instanceof c.ZodObject){let t=e.shape,n={};for(let[e,r]of Object.entries(t)){let[,t]=H(r);n[e]=t}return[`JSON object`,n]}if(e instanceof c.ZodOptional){let[t,n]=H(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function re(e){if(e instanceof c.ZodObject)return Object.entries(e.shape).map(([e,t])=>{let[n]=H(t);return[e,n]});let[t]=H(e);return[[`response`,t]]}function U(e){return typeof e==`string`?JSON.stringify(e):String(e)}function ie(e,t){if(!t)return e;let n=ae(e);try{return t.parse(n)}catch(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Validation failed: ${t}`)}throw e}}function ae(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i),r=n?n[1].trim():t;try{return JSON.parse(r)}catch(e){throw Error(`Cannot parse response as JSON: ${e.message}`)}}function oe(e,t={}){if(typeof e==`string`)return{message:{role:`user`,id:crypto.randomUUID(),content:[{type:`text`,text:e}],...t.metadata?{metadata:t.metadata}:{}},parse:e=>se(e,void 0)};let n=e.render(),r=e.files,i=e.schema,a=t.metadata??e.metadata;return{message:{role:`user`,id:crypto.randomUUID(),content:z({text:n,files:r}),...a?{metadata:a}:{}},parse:e=>se(e,i)}}function se(e,t){return e?ie(B(e.content),t):null}function W(){return{in:0,out:0}}function ce(e,t){t&&(e.in+=t.in??0,e.out+=t.out??0,ue(e,`cachedIn`,t.cachedIn),ue(e,`cacheWriteIn`,t.cacheWriteIn),ue(e,`reasoningOut`,t.reasoningOut))}function G(e,t){return{...e,...de(`cachedIn`,t.cachedIn),...de(`cacheWriteIn`,t.cacheWriteIn),...de(`reasoningOut`,t.reasoningOut)}}function le(e){if(e)return{inputTokens:e.in,outputTokens:e.out,...e.cachedIn===void 0?{}:{cachedInputTokens:e.cachedIn},...e.cacheWriteIn===void 0?{}:{cacheWriteInputTokens:e.cacheWriteIn},...e.reasoningOut===void 0?{}:{reasoningOutputTokens:e.reasoningOut}}}function ue(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function de(e,t){return typeof t==`number`?{[e]:t}:{}}var fe=class{tools=new Map;mcpTools=new Map;providerTools=new Map;constructor(e){e?.tools&&this.add(e.tools),e?.providerTools&&this.addProvider(e.providerTools)}add(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new E(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.tools.set(e.name,e)}}addMcp(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new E(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.mcpTools.set(e.name,e)}}addProvider(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new E(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.providerTools.set(e.name,e)}}remove(e){let t=this.tools.delete(e),n=this.mcpTools.delete(e),r=this.providerTools.delete(e);return t||n||r}has(e){return this.tools.has(e)||this.mcpTools.has(e)||this.providerTools.has(e)}get(e){return this.tools.get(e)??this.mcpTools.get(e)}getProvider(e){return this.providerTools.get(e)}executable(){return[...this.tools.values(),...this.mcpTools.values()]}local(){return[...this.tools.values()]}mcp(){return[...this.mcpTools.values()]}provider(){return[...this.providerTools.values()]}get size(){return this.tools.size+this.mcpTools.size+this.providerTools.size}};function pe(e,t){ce(e,t.usage)}function me(e){return JSON.stringify({error:e})}function he(e){let t=e.tools!==void 0||e.providerTools!==void 0;if(e.registry&&t)throw new E("Cannot specify both `registry` and `tools` / `providerTools`. Use one or the other.",{code:`TOOL_OPTIONS_CONFLICT`});return e.registry?e.registry:new fe({tools:e.tools,providerTools:e.providerTools})}async function ge(e,t=async()=>null,n,r,i){let a=[],o=()=>{throw new O(`Operation aborted`,{reason:n.reason})};for(let s of e){n.aborted&&o();let e=i?.startSpan(s.name,{type:`tool`}),c={signal:n,tracer:e,registry:r,emit:()=>{}},l;try{l=await t(s.name,s.parameters,c),n.aborted&&(e?.end(`ok`),o())}catch(t){if(t instanceof A)throw e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`fatal`,message:t.message}}),e?.end(`error`),t;(n.aborted||t instanceof O||t instanceof Error&&t.name===`AbortError`)&&(e?.end(`ok`),o()),l={type:`error`,error:{type:`exception`,message:t instanceof Error?t.message:String(t)}}}if(l==null){let t=r.get(s.name);if(t)try{let n=await t.execute(s.parameters,c);e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:n}),e?.end(`ok`),a.push({id:s.id,name:s.name,content:n});continue}catch(t){if(t instanceof A)throw e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`fatal`,message:t.message}}),e?.end(`error`),t;(n.aborted||t instanceof O||t instanceof Error&&t.name===`AbortError`)&&(e?.end(`ok`),o()),l={type:`error`,error:{type:`execution`,message:t instanceof Error?t.message:String(t)}}}}if(l==null){let t=`Tool not found: ${s.name}`;e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`not-found`,message:t}}),e?.end(`error`),a.push({id:s.id,name:s.name,content:me({type:`not-found`,message:t}),isError:!0});continue}l.type===`success`?(e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:l.content}),e?.end(`ok`),a.push({id:s.id,name:s.name,content:l.content})):(e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:l.error}),e?.end(`error`),a.push({id:s.id,name:s.name,content:me(l.error),isError:!0}))}return{results:a}}let _e=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function K(e,t){for(let n of e)n(t)}function ve(e){return{type:`error`,error:{type:`not-found`,message:`Tool not found: ${e}`}}}function ye(e){return{name:e.name,description:e.description,schema:e.schema}}function be(e){let t=[],n,r;if(`instruct`in e){let{instruct:t,messages:i,...a}=e,o=oe(t);r=o.parse,n={...a,messages:[...i??[],o.message]}}else n=e;let i=new AbortController,a=n.signal?AbortSignal.any([i.signal,n.signal]):i.signal,{promise:o,resolve:s,reject:c}=Promise.withResolvers();return Promise.resolve().then(()=>xe(n,a,t).then(e=>{if(r&&e.ok){try{s({...e,response:r(e.final)})}catch(t){s({ok:!1,messages:e.messages,final:e.final,usage:e.usage,error:{kind:`parse`,error:t,message:t instanceof Error?t.message:String(t)}})}return}s(e)},c)),{on(e){t.push(e)},cancel(e){i.abort(e)},get final(){return o}}}async function xe(e,t,n){let{provider:r,model:i,messages:a,system:o,onToolCall:s,maxIterations:c,tracer:l,fileResolver:u,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}=e,y=he(e),b=[...a],x=[],S=W(),C=0,w=0,T=e=>{b.push(e),x.push(e)},E=e=>{e.ok||K(n,{type:`error`,error:e.error});let t=e.ok?e.final.content:null,r=e.ok?e.final.finishReason:void 0;return l?.setResult({kind:`llm`,model:i,request:{messages:a},response:{content:t??null},usage:le(e.usage),finishReason:r}),l?.end(e.ok?`ok`:`error`),e},D=(e,n,r,i)=>{i();let a=e.length?{role:`assistant`,id:n,model:r,content:e,finishReason:`cancelled`}:void 0;throw a&&T(a),l?.end(`ok`),new O(`Stream aborted`,{reason:t.reason,messages:x,partial:a,usage:S})};for(;;){if(t.aborted&&D([],``,``,()=>{}),c!==void 0&&w>=c)return E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${c})`}}},usage:S});w+=1;let e=l?.startSpan(`turn-${w}`,{type:`llm`}),a=y?.executable()??[],k=a.length>0?a.map(ye):void 0,j=y?.provider()??[],ee=r.createStreamingRequest(i,{messages:b,system:o,tools:k,providerTools:j.length>0?j:void 0,runtime:{tracer:e,fileResolver:u},signal:t,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}),M=[],te=``,N=``,P=null,ne=W(),F=-1,I=null,L=``,R=new Map,z=new Map,B=new Map,V=-1,H=()=>{I!==null&&F>=0&&(K(n,{type:I===`text`?`text:end`:`thinking:end`,index:F,final:L}),I=null,L=``,F=-1)};for await(let r of ee){switch(r.type){case`start`:te=r.id,N=r.data.model,K(n,{type:`turn:start`,id:te,model:N});break;case`text-start`:H(),M.push({type:`text`,text:``}),V=M.length-1,F=C++,z.set(r.data.index,V),B.set(r.data.index,F),I=`text`,L=``,K(n,{type:`text:start`,index:F});break;case`text-delta`:{let e=M[V];e.text+=r.data.text,L=e.text,K(n,{type:`text:delta`,index:F,delta:r.data.text,accumulated:L});break}case`text-citation`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??F,i=M[e];if(!i||i.type!==`text`)break;i.citations=[...i.citations??[],r.data.citation],K(n,{type:`text:citation`,index:t,citation:r.data.citation,citations:i.citations});break}case`citation`:{H();let e=C++;M.push({type:`citation`,citations:r.data.citations,...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),V=M.length-1,z.set(r.data.index,V),B.set(r.data.index,e),K(n,{type:`citation`,index:e,citations:r.data.citations,providerMetadata:r.data.providerMetadata});break}case`text-complete`:H();break;case`thinking-start`:H(),M.push({type:`thinking`,text:``,...r.data.id?{id:r.data.id}:{},...r.data.redacted===void 0?{}:{redacted:r.data.redacted},...r.data.continuity?{continuity:r.data.continuity}:{},...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),V=M.length-1,F=C++,z.set(r.data.index,V),B.set(r.data.index,F),I=`thinking`,L=``,K(n,{type:`thinking:start`,index:F,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break;case`thinking-delta`:{let e=M[V];e.text=(e.text??``)+r.data.text,L=e.text,K(n,{type:`thinking:delta`,index:F,delta:r.data.text,accumulated:L});break}case`thinking-summary-delta`:{let e=M[V];e.summary=(e.summary??``)+r.data.text,L=e.summary,K(n,{type:`thinking:summary-delta`,index:F,delta:r.data.text,accumulated:L});break}case`thinking-metadata`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??F,i=M[e];if(!i||i.type!==`thinking`)break;r.data.redacted!==void 0&&(i.redacted=r.data.redacted),r.data.continuity&&(i.continuity=r.data.continuity),r.data.providerMetadata&&(i.providerMetadata=r.data.providerMetadata),K(n,{type:`thinking:update`,index:t,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break}case`thinking-complete`:H();break;case`tool-call-start`:{H();let e=C++;M.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),V=M.length-1,z.set(r.data.index,V),B.set(r.data.index,e),R.set(r.data.id,e),K(n,{type:`tool:request`,index:e,id:r.data.id,name:r.data.name});break}case`tool-call-args-delta`:K(n,{type:`tool:args-delta`,index:R.get(r.data.id)??-1,id:r.data.id,name:r.data.name,delta:r.data.delta,accumulated:r.data.accumulated});break;case`tool-call-complete`:{let e=M[z.get(r.data.index)??V];if(!e||e.type!==`tool-call`)break;r.data.id&&(e.id=r.data.id),r.data.name&&(e.name=r.data.name),e.parameters=r.data.arguments,r.data.providerMetadata&&(e.providerMetadata=r.data.providerMetadata);break}case`provider-tool-start`:{H();let e=C++;M.push({type:`provider-tool`,id:r.data.id,name:r.data.name}),V=M.length-1,z.set(r.data.index,V),B.set(r.data.index,e),K(n,{type:`provider-tool:start`,index:e,id:r.data.id,name:r.data.name});break}case`provider-tool-complete`:{let e=z.get(r.data.index)??V,t=B.get(r.data.index)??r.data.index,i=M[e];i&&i.type===`provider-tool`&&r.data.output!=null&&(i.output=r.data.output),K(n,{type:`provider-tool:complete`,index:t,id:r.data.id,name:r.data.name,output:r.data.output});break}case`complete`:H(),P=r.data.finishReason,ne=r.data.usage;break;case`error`:return H(),ce(S,r.data.usage),e?.end(`error`),E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:r.data.type,message:r.data.message}}},usage:S});default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.aborted)break}if(t.aborted&&(e?.end(`ok`),D(M,te,N,H)),P===null)return H(),e?.end(`error`),E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:S});ce(S,ne);let re={kind:`llm`,model:N,request:{messages:b},response:{content:M},usage:le(ne),finishReason:P};e?.setResult(re),e?.end();let U={role:`assistant`,id:te,model:N,content:M,finishReason:P};if(T(U),K(n,{type:`turn:complete`,message:U,usage:ne}),P!==`function_call`)return E({ok:!0,response:U,messages:x,final:U,usage:S});let ie=M.filter(e=>e.type===`tool-call`);if(ie.length===0)return E({ok:!0,response:U,messages:x,final:U,usage:S});if(t.aborted)throw l?.end(`ok`),new O(`Stream aborted`,{reason:t.reason,messages:x,usage:S});let ae=crypto.randomUUID();K(n,{type:`tool-results:start`,id:ae});let oe=0,se=async(e,t,r)=>{let i=ie[oe++],a=R.get(i.id)??-1;K(n,{type:`tool:exec-start`,index:a,id:i.id,name:e,parameters:t});let o={...r,emit:t=>{K(n,{type:`tool:exec-delta`,index:a,id:i.id,name:e,chunk:t})}},c=y.get(e),l=(s?await s(e,t,o):c?{type:`success`,content:await c.execute(t,o)}:null)??ve(e);return K(n,{type:`tool:exec-complete`,index:a,id:i.id,name:e,result:l}),l},G;try{({results:G}=await ge(ie,se,t,y,l))}catch(e){throw e instanceof A?(l?.end(`error`),new A(e.message,{toolName:e.toolName,messages:e.messages??x,partial:e.partial??U,usage:e.usage??S,cause:e.cause})):e instanceof O?(l?.end(`ok`),new O(`Stream aborted`,{reason:e.reason,messages:e.messages??x,partial:e.partial,usage:e.usage??S})):e}if(G.length>0){let e={role:`tool`,id:ae,content:G};T(e),K(n,{type:`tool-results:complete`,message:e})}}}function q(e=new Date){return{start:e.toISOString()}}function J(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var Se=class{currentTurnId=null;currentTurnTiming;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage=W();createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=J(q(r),r),a=()=>({...i});if(typeof e.content==`string`)n.push({id:crypto.randomUUID(),type:`text`,text:e.content,timing:a()});else for(let t of e.content)t.type===`text`?n.push({id:crypto.randomUUID(),type:`text`,text:t.text,...t.citations?{citations:t.citations}:{},...t.providerMetadata?{providerMetadata:t.providerMetadata}:{},timing:a()}):t.type===`file`&&n.push({id:crypto.randomUUID(),type:`file`,file:t.file,timing:a()});return[{type:`turn:user`,turn:{id:t,owner:`user`,parts:n,status:`complete`,timing:i,...e.metadata?{metadata:e.metadata}:{}}}]}startAgentTurn(){let e=crypto.randomUUID();return this.currentTurnId=e,this.currentTurnTiming=q(),this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage=W(),{type:`turn:start`,turnId:e,timing:this.currentTurnTiming}}handleStreamEvent(e){let t=this.currentTurnId;if(!t)return[];let n=[];switch(e.type){case`turn:start`:break;case`text:start`:{this.closeOpenParts(n);let e=crypto.randomUUID(),r={id:e,type:`text`,text:``,timing:q()};this.currentTextPart={id:e,timing:r.timing},n.push({type:`part:start`,turnId:t,part:r});break}case`text:delta`:this.currentTextPart&&n.push({type:`text:delta`,turnId:t,partId:this.currentTextPart.id,delta:e.delta});break;case`text:end`:if(this.currentTextPart){let e=J(this.currentTextPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:e}),this.currentTextPart=null}break;case`citation`:{this.closeOpenParts(n);let r=J(q()),i={id:crypto.randomUUID(),type:`citation`,citations:e.citations,...e.providerMetadata?{providerMetadata:e.providerMetadata}:{},timing:r};n.push({type:`part:start`,turnId:t,part:i}),n.push({type:`part:end`,turnId:t,partId:i.id,timing:r});break}case`thinking:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i={id:r,type:`thinking`,text:``,timing:q(),...e.redacted===void 0?{}:{redacted:e.redacted},...e.continuity?{continuity:e.continuity}:{},...e.providerMetadata?{providerMetadata:e.providerMetadata}:{}};this.currentThinkingPart={id:r,timing:i.timing},n.push({type:`part:start`,turnId:t,part:i});break}case`thinking:delta`:this.currentThinkingPart&&n.push({type:`thinking:delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`text:citation`:this.currentTextPart&&n.push({type:`text:citation`,turnId:t,partId:this.currentTextPart.id,citation:e.citation});break;case`thinking:summary-delta`:this.currentThinkingPart&&n.push({type:`thinking:summary-delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`thinking:update`:this.currentThinkingPart&&n.push({type:`thinking:update`,turnId:t,partId:this.currentThinkingPart.id,redacted:e.redacted,continuity:e.continuity,providerMetadata:e.providerMetadata});break;case`thinking:end`:if(this.currentThinkingPart){let e=J(this.currentThinkingPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:e}),this.currentThinkingPart=null}break;case`tool:request`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=q(),a={id:r,type:`action`,kind:`tool`,status:`pending`,timing:i,detail:{name:e.name,parameters:{}}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i}),n.push({type:`part:start`,turnId:t,part:a});break}case`tool:args-delta`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:args-delta`,turnId:t,partId:r.partId,delta:e.delta,accumulated:e.accumulated});break}case`tool:exec-start`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:running`,turnId:t,partId:r.partId,parameters:e.parameters});break}case`tool:exec-delta`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:progress`,turnId:t,partId:r.partId,chunk:e.chunk});break}case`tool:exec-complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=J(r.timing);r.timing=i,e.result.type===`success`?n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.result.content},timing:i}):n.push({type:`action:error`,turnId:t,partId:r.partId,error:e.result.error,timing:i})}break}case`provider-tool:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=q(),a={id:r,type:`action`,kind:`provider-tool`,status:`running`,timing:i,detail:{name:e.name}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i}),n.push({type:`part:start`,turnId:t,part:a}),n.push({type:`action:running`,turnId:t,partId:r});break}case`provider-tool:complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=J(r.timing);r.timing=i,n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.output},timing:i})}break}case`turn:complete`:this.closeOpenParts(n),ce(this.accumulatedUsage,e.usage);break;case`tool-results:start`:case`tool-results:complete`:break;case`error`:{let t=e.error,r=t.kind===`model`?t.error.error.message:t.kind===`tool`?`Tool error (${t.error.name}): ${t.error.message}`:`Parse error: ${t.message}`;n.push({type:`error`,error:{type:t.kind,message:r}});break}}return n}finalizeTurn(e=`complete`){let t=this.currentTurnId;if(!t)return[];let n=[];this.closeOpenParts(n);let r=J(this.currentTurnTiming);return n.push({type:`turn:end`,turnId:t,status:e,usage:{...this.accumulatedUsage},timing:r}),this.currentTurnId=null,this.currentTurnTiming=void 0,n}closeOpenParts(e){let t=this.currentTurnId;t&&(this.currentTextPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:J(this.currentTextPart.timing)}),null),this.currentThinkingPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:J(this.currentThinkingPart.timing)}),null))}};function Ce(e){return Array.isArray(e)?e:[e]}function we(e){return e.then(()=>{},()=>{})}function Te(e,t,n){let r=new AbortController,i=n?AbortSignal.any([n,r.signal]):r.signal,a=e.then(()=>t(i));return{handle:{cancel:e=>r.abort(e),get final(){return a}},settled:we(a)}}var Ee=class{_turns=[];_log=[];_sessionAnnotations=[];constructor(e){e?.turns&&(this._turns=[...e.turns]),e?.log&&(this._log=[...e.log]),e?.sessionAnnotations&&(this._sessionAnnotations=[...e.sessionAnnotations])}get turns(){return[...this._turns]}get log(){return[...this._log]}get sessionAnnotations(){return[...this._sessionAnnotations]}addTurn(e){this._turns.push(e)}replaceTurns(e){this._turns=[...e]}replaceLog(e){this._log=[...e]}replaceSessionAnnotations(e=[]){this._sessionAnnotations=[...e]}appendToLog(e){Array.isArray(e)?this._log.push(...e):this._log.push(e)}latestTurn(){return this._turns[this._turns.length-1]}toString(){return JSON.stringify({turns:this._turns,sessionAnnotations:this._sessionAnnotations})}};function De(e,t){return{...e,...t,providerOptions:e?.providerOptions||t?.providerOptions?{...e?.providerOptions,...t?.providerOptions}:void 0}}var Oe=class{provider;model;history;tracer;name;fileResolver;requestOptions;registry;sessionId;system;mcps=[];resolvedMcps=new WeakSet;memory;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e,t){if(this.provider=e.provider,this.model=e.model,this.sessionId=e.sessionId??crypto.randomUUID(),this.history=new Ee,this.tracer=e.tracer,this.system=e.system,this.name=e.name,this.fileResolver=e.fileResolver,this.requestOptions={reasoning:e.reasoning,maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,stop:e.stop,toolChoice:e.toolChoice,parallelToolCalls:e.parallelToolCalls,providerOptions:e.providerOptions},this.registry=new fe({tools:e.tools,providerTools:e.providerTools}),e.mcps&&(this.mcps=[...e.mcps]),e.memory){this.memory=e.memory;let t=e.memory.tools?.();t&&this.registry.add(t)}t&&this.restore(t)}addMcp(e){this.mcps.push(e)}addMcps(e){this.mcps.push(...e)}hasTools(){return this.registry.size>0||this.mcps.length>0}on(e){this.eventCallbacks.push(e)}context(){return j({system:this.system,messages:this.history.log,tools:this.toToolDefinitions(this.registry.local()),providerTools:this.registry.provider(),mcpTools:this.toToolDefinitions(this.registry.mcp())})}snapshot(){let e=this.history.sessionAnnotations;return{version:1,sessionId:this.sessionId,messages:this.history.log,turns:this.history.turns,sessionAnnotations:e.length>0?e:void 0}}restore(e){if(e.version!==1)throw new E(`Unsupported agent session version: ${e.version}`);this.sessionId=e.sessionId,this.history.replaceLog(e.messages),this.history.replaceTurns(e.turns??[]),this.history.replaceSessionAnnotations(e.sessionAnnotations??[])}send(e,t){let{fileResolver:n,metadata:r,...i}=t??{},a=oe(e,{metadata:r}),o=De(this.requestOptions,i),{handle:s,settled:c}=Te(this.sendQueue,e=>this.run(a,e,n,o),i.signal);return this.sendQueue=c,s}async resolveMcpTools(e){for(let t of this.mcps){if(this.resolvedMcps.has(t))continue;let n=await t.listTools({prefix:t.name,tracer:this.tracer,signal:e});this.registry.addMcp(n),this.resolvedMcps.add(t)}}emitEvent(e){for(let t of this.eventCallbacks)t(e)}toToolDefinitions(e){return e.map(e=>({name:e.name,description:e.description,schema:e.schema}))}async run(t,n,r,i){let a=new Se,o=new e({turns:this.history.turns,sessionAnnotations:this.history.sessionAnnotations}),s,c=e=>{let t=o.apply(e);t.handled&&(this.history.replaceTurns(t.state.turns),this.history.replaceSessionAnnotations(t.state.sessionAnnotations??[])),this.emitEvent(e)},l=()=>s?o.state.turns.find(e=>e.id===s):void 0,u=W();if(n.aborted)throw new k(`Agent send aborted`,{reason:n.reason,usage:u});try{await this.resolveMcpTools(n)}catch(e){throw n.aborted||e instanceof O||e instanceof Error&&e.name===`AbortError`?new k(`Agent send aborted`,{reason:e instanceof O?e.reason:n.reason,usage:u}):e}let d=this.system,f=[...this.history.log,t.message];if(this.memory){let e=await this.memory.recall({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:f,tracer:this.tracer});e.systemSuffix&&(d=(d??``)+`
|
|
3
|
+
`)}function N(e){return e.filter(e=>e.type===`thinking`).map(e=>e.text??``).join(`
|
|
4
4
|
|
|
5
|
-
`+e.systemSuffix)}if(n.aborted)throw new k(`Agent send aborted`,{reason:n.reason,usage:u});this.history.appendToLog(t.message);for(let e of a.createUserTurn(t.message))c(e);let p=a.startAgentTurn();s=p.turnId,c(p);let{signal:m,...h}=i??{},g=be({provider:this.provider,model:this.model,messages:f,system:d,registry:this.registry,tracer:this.tracer,fileResolver:r??this.fileResolver,...h,signal:n,onToolCall:async(e,t,n)=>{let r=this.registry.get(e);if(!r)return null;try{return{type:`success`,content:await r.execute(t,n)}}catch(e){if(e instanceof A)throw e;return{type:`error`,error:{type:`execution`,message:e instanceof Error?e.message:String(e)}}}}});g.on(e=>{let t=a.handleStreamEvent(e);for(let e of t)c(e)});let _;try{_=await g.final}catch(e){if(e instanceof A){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=a.finalizeTurn(`error`);for(let e of t)c(e);throw new A(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:e.usage??u,cause:e.cause})}if(e instanceof O){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=a.finalizeTurn(`cancelled`);for(let e of t)c(e);throw new k(`Agent send aborted`,{reason:e.reason,messages:e.messages,partial:e.partial,turn:l(),usage:e.usage??u})}throw e}let v=_.ok?`complete`:`error`;_.messages.length>0&&this.history.appendToLog(_.messages);let y=a.finalizeTurn(v);for(let e of y)c(e);let b=_.usage??u,x=l();if(!_.ok)return{ok:!1,error:_.error,turn:x,usage:b};let S;try{S=t.parse(_.final)}catch(e){return{ok:!1,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)},turn:x,usage:b}}if(!x)throw new E(`Agent turn missing after send`);if(this.memory)try{await this.memory.record({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:this.history.log,newMessages:_.messages,tracer:this.tracer})}catch(e){this.tracer?.warn(`memory record failed`,{error:e instanceof Error?e.message:String(e)})}return{ok:!0,response:S,turn:x,usage:b}}};function ke(e){try{let t=l.fromJSONSchema(e);return t instanceof l.ZodObject?t.strict():l.object({}).passthrough()}catch{return l.object({}).passthrough()}}function Ae(e,t,n){return e.map(e=>Me(e,t,n))}function je(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=ke(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function Me(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=ke(e.inputSchema);return{name:r,description:e.description??``,schema:i,async execute(n,i){let a;try{a=await t.callTool({name:e.name,arguments:n},void 0,{signal:i.signal})}catch(t){throw i.signal.aborted||t instanceof Error&&t.name===`AbortError`?t:new A(`MCP tool call failed: ${e.name}`,{toolName:r,cause:t})}if(`isError`in a&&a.isError)throw Error(Pe(a.content));return Ne(a.content)}}}function Ne(e){return e.some(e=>e.type===`image`)?e.filter(e=>e.type===`text`||e.type===`image`).map(e=>{if(e.type===`text`)return{type:`text`,text:e.text};let t=e;return{type:`file`,file:{kind:`image`,mimeType:t.mimeType,name:`mcp-image`,source:{type:`base64`,data:t.data}}}}):e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
`)}function ee(e){return e.filter(e=>e.type===`tool-call`)}function te(e){return e.filter(e=>e.type===`provider-tool`)}function ne(e){let t=[];for(let n of e)(n.type===`text`&&n.citations||n.type===`citation`)&&t.push(...n.citations);return t}function re(e,t=500){return e.length>t?`${e.slice(0,t)}… (${e.length} chars)`:e}function P(e,t=600){if(e.length<=t)return e;let n=Math.floor(t/2);return`${e.slice(0,n)}…[${e.length} chars]…${e.slice(-n)}`}var F=class{log;constructor(e){this.log=e}onSpanStart(){}onSpanEnd(e){let t=e.status===`error`?`error`:e.type===`tool`||e.type===`workflow`?`info`:`debug`;this.log({level:t,message:e.name,fields:{...e.attributes,type:e.type,status:e.status,traceId:e.traceId,spanId:e.spanId,...e.parentSpanId?{parentSpanId:e.parentSpanId}:{},...e.endTime===void 0?{}:{durationMs:Math.round(e.endTime-e.startTime)}}})}onEvent(e,t){this.log({level:t.level,message:t.name,fields:{traceId:e.traceId,spanId:e.spanId,name:e.name,...t.attributes}})}};function I(e,t,n){if(!n)return;let r=re(n);e?.info(t,{text:r}),r!==n&&e?.debug(t,{text:n})}function ie(e){let t=U(e.system??``),n=V(e.tools),r=V(e.mcpTools),i=oe(e.providerTools),a=e.messages.reduce((e,t)=>e+L(t),0),o=t+n+r+i+a;return{total:o,system:t,tools:n,mcpTools:r,providerTools:i,messages:a,...e.limit===void 0?{}:{limit:e.limit,free:Math.max(0,e.limit-o)}}}function L(e){switch(e.role){case`user`:return R(e.content);case`assistant`:return R(e.content);case`tool`:return e.content.reduce((e,t)=>e+B(t),0)}}function R(e){return typeof e==`string`?U(e):e.reduce((e,t)=>e+z(t),0)}function z(e){switch(e.type){case`text`:return U(e.text);case`thinking`:return U(e.summary??e.text??``);case`tool-call`:return U(e.name)+H(e.parameters);case`provider-tool`:return U(e.name)+H(e.input)+H(e.output);case`citation`:return H(e.citations);case`file`:return H(e.file)}}function B(e){return U(e.name)+ae(e.content)}function ae(e){return typeof e==`string`?U(e):e.reduce((e,t)=>t.type===`text`?e+U(t.text):e+H(t.file),0)}function V(e){let t=e?.map(se)??[];return t.length===0?0:H({tools:t})}function oe(e){return!e||e.length===0?0:H({providerTools:e})}function se(e){try{return{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}catch{return{name:e.name,description:e.description}}}function H(e){return e==null?0:U(JSON.stringify(e))}function U(e){return e?Math.ceil(e.length/3):0}function W(e){if(e instanceof c.ZodString)return[`string`,`Your answer`];if(e instanceof c.ZodNumber)return[`number`,42];if(e instanceof c.ZodBoolean)return[`boolean`,!0];if(e instanceof c.ZodEnum){let t=e.options;return[t.map(le).join(` | `),t[0]]}if(e instanceof c.ZodLiteral){let t=e.value;return[le(t),t]}if(e instanceof c.ZodArray){let t=e.element;if(t instanceof c.ZodString)return[`string array`,[`answer 1`,`answer 2`,`third answer`]];if(t instanceof c.ZodNumber)return[`number array`,[42,59,3.14]];if(t instanceof c.ZodBoolean)return[`boolean array`,[!0,!1,!1]];if(t instanceof c.ZodObject){let[,e]=W(t);return[`object array`,[e,e]]}else if(t instanceof c.ZodEnum||t instanceof c.ZodLiteral){let[e,n]=W(t);return[`${e} array`,[n]]}return[`array`,[]]}if(e instanceof c.ZodObject){let t=e.shape,n={};for(let[e,r]of Object.entries(t)){let[,t]=W(r);n[e]=t}return[`JSON object`,n]}if(e instanceof c.ZodOptional){let[t,n]=W(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function ce(e){if(e instanceof c.ZodObject)return Object.entries(e.shape).map(([e,t])=>{let[n]=W(t);return[e,n]});let[t]=W(e);return[[`response`,t]]}function le(e){return typeof e==`string`?JSON.stringify(e):String(e)}function ue(e,t){if(!t)return e;let n=de(e);try{return t.parse(n)}catch(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Validation failed: ${t}`)}throw e}}function de(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i),r=n?n[1].trim():t;try{return JSON.parse(r)}catch(e){throw Error(`Cannot parse response as JSON: ${e.message}`)}}function fe(e,t={}){if(typeof e==`string`)return{message:{role:`user`,id:crypto.randomUUID(),content:[{type:`text`,text:e}],...t.metadata?{metadata:t.metadata}:{}},parse:e=>pe(e,void 0)};let n=e.render(),r=e.files,i=e.schema,a=t.metadata??e.metadata;return{message:{role:`user`,id:crypto.randomUUID(),content:j({text:n,files:r}),...a?{metadata:a}:{}},parse:e=>pe(e,i)}}function pe(e,t){return e?ue(M(e.content),t):null}function G(){return{in:0,out:0}}function me(e,t){t&&(e.in+=t.in??0,e.out+=t.out??0,ge(e,`cachedIn`,t.cachedIn),ge(e,`cacheWriteIn`,t.cacheWriteIn),ge(e,`reasoningOut`,t.reasoningOut))}function K(e,t){return{...e,..._e(`cachedIn`,t.cachedIn),..._e(`cacheWriteIn`,t.cacheWriteIn),..._e(`reasoningOut`,t.reasoningOut)}}function he(e){if(e)return{inputTokens:e.in,outputTokens:e.out,...e.cachedIn===void 0?{}:{cachedInputTokens:e.cachedIn},...e.cacheWriteIn===void 0?{}:{cacheWriteInputTokens:e.cacheWriteIn},...e.reasoningOut===void 0?{}:{reasoningOutputTokens:e.reasoningOut}}}function ge(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function _e(e,t){return typeof t==`number`?{[e]:t}:{}}var ve=class{tools=new Map;mcpTools=new Map;providerTools=new Map;constructor(e){e?.tools&&this.add(e.tools),e?.providerTools&&this.addProvider(e.providerTools)}add(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new E(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.tools.set(e.name,e)}}addMcp(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new E(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.mcpTools.set(e.name,e)}}addProvider(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new E(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.providerTools.set(e.name,e)}}remove(e){let t=this.tools.delete(e),n=this.mcpTools.delete(e),r=this.providerTools.delete(e);return t||n||r}has(e){return this.tools.has(e)||this.mcpTools.has(e)||this.providerTools.has(e)}get(e){return this.tools.get(e)??this.mcpTools.get(e)}getProvider(e){return this.providerTools.get(e)}executable(){return[...this.tools.values(),...this.mcpTools.values()]}local(){return[...this.tools.values()]}mcp(){return[...this.mcpTools.values()]}provider(){return[...this.providerTools.values()]}get size(){return this.tools.size+this.mcpTools.size+this.providerTools.size}};function ye(e,t){me(e,t.usage)}function be(e,t){if(!e)return;I(e,`text`,M(t));let n=N(t);n&&e.debug(`thinking`,{thinking:n});for(let n of te(t))e.info(n.name,{type:`provider-tool`,input:n.input}),n.output!==void 0&&e.trace(n.name,{type:`provider-tool`,output:n.output});xe(e,ne(t))}function xe(e,t){if(t.length===0)return;let n=Se(t);e.info(`citations`,{count:t.length,sources:n.slice(0,8),...n.length>8?{more:n.length-8}:{}}),n.length>8&&e.debug(`citations`,{sources:n}),e.setAttribute(`citationCount`,t.length)}function Se(e){let t=new Set,n=[];for(let{source:r}of e){let e=Ce(r),i=`title`in r?r.title:void 0,a=e??i??r.type;t.has(a)||(t.add(a),n.push({type:r.type,...i?{title:i}:{},...e?{url:e}:{}}))}return n}function Ce(e){switch(e.type){case`web`:case`search-result`:return e.url;case`retrieved-context`:return e.uri;case`document`:return e.fileId;default:return}}function we(e){return JSON.stringify({error:e})}function Te(e){let t=e.tools!==void 0||e.providerTools!==void 0;if(e.registry&&t)throw new E("Cannot specify both `registry` and `tools` / `providerTools`. Use one or the other.",{code:`TOOL_OPTIONS_CONFLICT`});return e.registry?e.registry:new ve({tools:e.tools,providerTools:e.providerTools})}async function Ee(e,t=async()=>null,n,r,i){let a=[],o=()=>{throw new O(`Operation aborted`,{reason:n.reason})};for(let s of e){n.aborted&&o();let e=i?.startSpan(s.name,{type:`tool`}),c={signal:n,span:e,registry:r,emit:()=>{}},l;try{l=await t(s.name,s.parameters,c),n.aborted&&(e?.end(`ok`),o())}catch(t){if(t instanceof A)throw e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`fatal`,message:t.message}}),e?.end(`error`),t;(n.aborted||t instanceof O||t instanceof Error&&t.name===`AbortError`)&&(e?.end(`ok`),o()),l={type:`error`,error:{type:`exception`,message:t instanceof Error?t.message:String(t)}}}if(l==null){let t=r.get(s.name);if(t)try{let n=await t.execute(s.parameters,c);e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:n}),e?.end(`ok`),a.push({id:s.id,name:s.name,content:n});continue}catch(t){if(t instanceof A)throw e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`fatal`,message:t.message}}),e?.end(`error`),t;(n.aborted||t instanceof O||t instanceof Error&&t.name===`AbortError`)&&(e?.end(`ok`),o()),l={type:`error`,error:{type:`execution`,message:t instanceof Error?t.message:String(t)}}}}if(l==null){let t=`Tool not found: ${s.name}`;e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`not-found`,message:t}}),e?.end(`error`),a.push({id:s.id,name:s.name,content:we({type:`not-found`,message:t}),isError:!0});continue}l.type===`success`?(e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:l.content}),e?.end(`ok`),a.push({id:s.id,name:s.name,content:l.content})):(e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:l.error}),e?.end(`error`),a.push({id:s.id,name:s.name,content:we(l.error),isError:!0}))}return{results:a}}let De=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function q(e,t){for(let n of e)n(t)}function Oe(e){return{type:`error`,error:{type:`not-found`,message:`Tool not found: ${e}`}}}function ke(e){return{name:e.name,description:e.description,schema:e.schema}}function Ae(e){let t=[],n,r;if(`instruct`in e){let{instruct:t,messages:i,...a}=e,o=fe(t);r=o.parse,n={...a,messages:[...i??[],o.message]}}else n=e;let i=new AbortController,a=n.signal?AbortSignal.any([i.signal,n.signal]):i.signal,{promise:o,resolve:s,reject:c}=Promise.withResolvers();return Promise.resolve().then(()=>je(n,a,t).then(e=>{if(r&&e.ok){try{s({...e,response:r(e.final)})}catch(t){s({ok:!1,messages:e.messages,final:e.final,usage:e.usage,error:{kind:`parse`,error:t,message:t instanceof Error?t.message:String(t)}})}return}s(e)},c)),{on(e){t.push(e)},cancel(e){i.abort(e)},get final(){return o}}}async function je(e,t,n){let{provider:r,model:i,messages:a,system:o,onToolCall:s,maxIterations:c,span:l,fileResolver:u,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}=e,y=Te(e),b=[...a],x=[],S=G(),C=0,w=0,T=e=>{b.push(e),x.push(e)},E=e=>{e.ok||q(n,{type:`error`,error:e.error});let t=e.ok?e.final.content:null,r=e.ok?e.final.finishReason:void 0;return l?.setResult({kind:`llm`,model:i,request:{messages:a},response:{content:t??null},usage:he(e.usage),finishReason:r}),l?.end(e.ok?`ok`:`error`),e},D=(e,n,r,i)=>{i();let a=e.length?{role:`assistant`,id:n,model:r,content:e,finishReason:`cancelled`}:void 0;throw a&&T(a),l?.end(`ok`),new O(`Stream aborted`,{reason:t.reason,messages:x,partial:a,usage:S})};for(;;){if(t.aborted&&D([],``,``,()=>{}),c!==void 0&&w>=c)return E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${c})`}}},usage:S});w+=1;let e=l?.startSpan(`turn-${w}`,{type:`llm`}),a=y?.executable()??[],k=a.length>0?a.map(ke):void 0,j=y?.provider()??[],M=r.createStreamingRequest(i,{messages:b,system:o,tools:k,providerTools:j.length>0?j:void 0,runtime:{span:e,fileResolver:u},signal:t,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}),N=[],ee=``,te=``,ne=null,re=G(),P=-1,F=null,I=``,ie=new Map,L=new Map,R=new Map,z=-1,B=()=>{F!==null&&P>=0&&(q(n,{type:F===`text`?`text:end`:`thinking:end`,index:P,final:I}),F=null,I=``,P=-1)};for await(let r of M){switch(r.type){case`start`:ee=r.id,te=r.data.model,q(n,{type:`turn:start`,id:ee,model:te});break;case`text-start`:B(),N.push({type:`text`,text:``}),z=N.length-1,P=C++,L.set(r.data.index,z),R.set(r.data.index,P),F=`text`,I=``,q(n,{type:`text:start`,index:P});break;case`text-delta`:{let e=N[z];e.text+=r.data.text,I=e.text,q(n,{type:`text:delta`,index:P,delta:r.data.text,accumulated:I});break}case`text-citation`:{let e=L.get(r.data.index)??z,t=R.get(r.data.index)??P,i=N[e];if(!i||i.type!==`text`)break;i.citations=[...i.citations??[],r.data.citation],q(n,{type:`text:citation`,index:t,citation:r.data.citation,citations:i.citations});break}case`citation`:{B();let e=C++;N.push({type:`citation`,citations:r.data.citations,...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),z=N.length-1,L.set(r.data.index,z),R.set(r.data.index,e),q(n,{type:`citation`,index:e,citations:r.data.citations,providerMetadata:r.data.providerMetadata});break}case`text-complete`:B();break;case`thinking-start`:B(),N.push({type:`thinking`,text:``,...r.data.id?{id:r.data.id}:{},...r.data.redacted===void 0?{}:{redacted:r.data.redacted},...r.data.continuity?{continuity:r.data.continuity}:{},...r.data.providerMetadata?{providerMetadata:r.data.providerMetadata}:{}}),z=N.length-1,P=C++,L.set(r.data.index,z),R.set(r.data.index,P),F=`thinking`,I=``,q(n,{type:`thinking:start`,index:P,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break;case`thinking-delta`:{let e=N[z];e.text=(e.text??``)+r.data.text,I=e.text,q(n,{type:`thinking:delta`,index:P,delta:r.data.text,accumulated:I});break}case`thinking-summary-delta`:{let e=N[z];e.summary=(e.summary??``)+r.data.text,I=e.summary,q(n,{type:`thinking:summary-delta`,index:P,delta:r.data.text,accumulated:I});break}case`thinking-metadata`:{let e=L.get(r.data.index)??z,t=R.get(r.data.index)??P,i=N[e];if(!i||i.type!==`thinking`)break;r.data.redacted!==void 0&&(i.redacted=r.data.redacted),r.data.continuity&&(i.continuity=r.data.continuity),r.data.providerMetadata&&(i.providerMetadata=r.data.providerMetadata),q(n,{type:`thinking:update`,index:t,redacted:r.data.redacted,continuity:r.data.continuity,providerMetadata:r.data.providerMetadata});break}case`thinking-complete`:B();break;case`tool-call-start`:{B();let e=C++;N.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),z=N.length-1,L.set(r.data.index,z),R.set(r.data.index,e),ie.set(r.data.id,e),q(n,{type:`tool:request`,index:e,id:r.data.id,name:r.data.name});break}case`tool-call-args-delta`:q(n,{type:`tool:args-delta`,index:ie.get(r.data.id)??-1,id:r.data.id,name:r.data.name,delta:r.data.delta,accumulated:r.data.accumulated});break;case`tool-call-complete`:{let e=N[L.get(r.data.index)??z];if(!e||e.type!==`tool-call`)break;r.data.id&&(e.id=r.data.id),r.data.name&&(e.name=r.data.name),e.parameters=r.data.arguments,r.data.providerMetadata&&(e.providerMetadata=r.data.providerMetadata);break}case`provider-tool-start`:{B();let e=C++;N.push({type:`provider-tool`,id:r.data.id,name:r.data.name}),z=N.length-1,L.set(r.data.index,z),R.set(r.data.index,e),q(n,{type:`provider-tool:start`,index:e,id:r.data.id,name:r.data.name});break}case`provider-tool-complete`:{let e=L.get(r.data.index)??z,t=R.get(r.data.index)??r.data.index,i=N[e];i&&i.type===`provider-tool`&&r.data.output!=null&&(i.output=r.data.output),q(n,{type:`provider-tool:complete`,index:t,id:r.data.id,name:r.data.name,output:r.data.output});break}case`complete`:B(),ne=r.data.finishReason,re=r.data.usage;break;case`error`:return B(),me(S,r.data.usage),e?.end(`error`),E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:r.data.type,message:r.data.message}}},usage:S});default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.aborted)break}if(t.aborted&&(e?.end(`ok`),D(N,ee,te,B)),ne===null)return B(),e?.end(`error`),E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:S});me(S,re);let ae={kind:`llm`,model:te,request:{messages:b},response:{content:N},usage:he(re),finishReason:ne};be(e,N),e?.setResult(ae),e?.end();let V={role:`assistant`,id:ee,model:te,content:N,finishReason:ne};if(T(V),q(n,{type:`turn:complete`,message:V,usage:re}),ne!==`function_call`)return E({ok:!0,response:V,messages:x,final:V,usage:S});let oe=N.filter(e=>e.type===`tool-call`);if(oe.length===0)return E({ok:!0,response:V,messages:x,final:V,usage:S});if(t.aborted)throw l?.end(`ok`),new O(`Stream aborted`,{reason:t.reason,messages:x,usage:S});let se=crypto.randomUUID();q(n,{type:`tool-results:start`,id:se});let H=0,U=async(e,t,r)=>{let i=oe[H++],a=ie.get(i.id)??-1;q(n,{type:`tool:exec-start`,index:a,id:i.id,name:e,parameters:t});let o={...r,emit:t=>{q(n,{type:`tool:exec-delta`,index:a,id:i.id,name:e,chunk:t})}},c=y.get(e),l=(s?await s(e,t,o):c?{type:`success`,content:await c.execute(t,o)}:null)??Oe(e);return q(n,{type:`tool:exec-complete`,index:a,id:i.id,name:e,result:l}),l},W;try{({results:W}=await Ee(oe,U,t,y,l))}catch(e){throw e instanceof A?(l?.end(`error`),new A(e.message,{toolName:e.toolName,messages:e.messages??x,partial:e.partial??V,usage:e.usage??S,cause:e.cause})):e instanceof O?(l?.end(`ok`),new O(`Stream aborted`,{reason:e.reason,messages:e.messages??x,partial:e.partial,usage:e.usage??S})):e}if(W.length>0){let e={role:`tool`,id:se,content:W};T(e),q(n,{type:`tool-results:complete`,message:e})}}}function Me(e=new Date){return{start:e.toISOString()}}function J(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var Ne=class{currentTurnId=null;currentTurnTiming;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage=G();createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=J(Me(r),r),a=()=>({...i});if(typeof e.content==`string`)n.push({id:crypto.randomUUID(),type:`text`,text:e.content,timing:a()});else for(let t of e.content)t.type===`text`?n.push({id:crypto.randomUUID(),type:`text`,text:t.text,...t.citations?{citations:t.citations}:{},...t.providerMetadata?{providerMetadata:t.providerMetadata}:{},timing:a()}):t.type===`file`&&n.push({id:crypto.randomUUID(),type:`file`,file:t.file,timing:a()});return[{type:`turn:user`,turn:{id:t,owner:`user`,parts:n,status:`complete`,timing:i,...e.metadata?{metadata:e.metadata}:{}}}]}startAgentTurn(){let e=crypto.randomUUID();return this.currentTurnId=e,this.currentTurnTiming=Me(),this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage=G(),{type:`turn:start`,turnId:e,timing:this.currentTurnTiming}}handleStreamEvent(e){let t=this.currentTurnId;if(!t)return[];let n=[];switch(e.type){case`turn:start`:break;case`text:start`:{this.closeOpenParts(n);let e=crypto.randomUUID(),r={id:e,type:`text`,text:``,timing:Me()};this.currentTextPart={id:e,timing:r.timing},n.push({type:`part:start`,turnId:t,part:r});break}case`text:delta`:this.currentTextPart&&n.push({type:`text:delta`,turnId:t,partId:this.currentTextPart.id,delta:e.delta});break;case`text:end`:if(this.currentTextPart){let e=J(this.currentTextPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:e}),this.currentTextPart=null}break;case`citation`:{this.closeOpenParts(n);let r=J(Me()),i={id:crypto.randomUUID(),type:`citation`,citations:e.citations,...e.providerMetadata?{providerMetadata:e.providerMetadata}:{},timing:r};n.push({type:`part:start`,turnId:t,part:i}),n.push({type:`part:end`,turnId:t,partId:i.id,timing:r});break}case`thinking:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i={id:r,type:`thinking`,text:``,timing:Me(),...e.redacted===void 0?{}:{redacted:e.redacted},...e.continuity?{continuity:e.continuity}:{},...e.providerMetadata?{providerMetadata:e.providerMetadata}:{}};this.currentThinkingPart={id:r,timing:i.timing},n.push({type:`part:start`,turnId:t,part:i});break}case`thinking:delta`:this.currentThinkingPart&&n.push({type:`thinking:delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`text:citation`:this.currentTextPart&&n.push({type:`text:citation`,turnId:t,partId:this.currentTextPart.id,citation:e.citation});break;case`thinking:summary-delta`:this.currentThinkingPart&&n.push({type:`thinking:summary-delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`thinking:update`:this.currentThinkingPart&&n.push({type:`thinking:update`,turnId:t,partId:this.currentThinkingPart.id,redacted:e.redacted,continuity:e.continuity,providerMetadata:e.providerMetadata});break;case`thinking:end`:if(this.currentThinkingPart){let e=J(this.currentThinkingPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:e}),this.currentThinkingPart=null}break;case`tool:request`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=Me(),a={id:r,type:`action`,kind:`tool`,status:`pending`,timing:i,detail:{name:e.name,parameters:{}}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i}),n.push({type:`part:start`,turnId:t,part:a});break}case`tool:args-delta`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:args-delta`,turnId:t,partId:r.partId,delta:e.delta,accumulated:e.accumulated});break}case`tool:exec-start`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:running`,turnId:t,partId:r.partId,parameters:e.parameters});break}case`tool:exec-delta`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:progress`,turnId:t,partId:r.partId,chunk:e.chunk});break}case`tool:exec-complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=J(r.timing);r.timing=i,e.result.type===`success`?n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.result.content},timing:i}):n.push({type:`action:error`,turnId:t,partId:r.partId,error:e.result.error,timing:i})}break}case`provider-tool:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=Me(),a={id:r,type:`action`,kind:`provider-tool`,status:`running`,timing:i,detail:{name:e.name}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i}),n.push({type:`part:start`,turnId:t,part:a}),n.push({type:`action:running`,turnId:t,partId:r});break}case`provider-tool:complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=J(r.timing);r.timing=i,n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.output},timing:i})}break}case`turn:complete`:this.closeOpenParts(n),me(this.accumulatedUsage,e.usage);break;case`tool-results:start`:case`tool-results:complete`:break;case`error`:{let t=e.error,r=t.kind===`model`?t.error.error.message:t.kind===`tool`?`Tool error (${t.error.name}): ${t.error.message}`:`Parse error: ${t.message}`;n.push({type:`error`,error:{type:t.kind,message:r}});break}}return n}finalizeTurn(e=`complete`){let t=this.currentTurnId;if(!t)return[];let n=[];this.closeOpenParts(n);let r=J(this.currentTurnTiming);return n.push({type:`turn:end`,turnId:t,status:e,usage:{...this.accumulatedUsage},timing:r}),this.currentTurnId=null,this.currentTurnTiming=void 0,n}closeOpenParts(e){let t=this.currentTurnId;t&&(this.currentTextPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:J(this.currentTextPart.timing)}),null),this.currentThinkingPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:J(this.currentThinkingPart.timing)}),null))}};function Pe(e){return Array.isArray(e)?e:[e]}function Fe(e){return e.then(()=>{},()=>{})}function Ie(e,t,n){let r=new AbortController,i=n?AbortSignal.any([n,r.signal]):r.signal,a=e.then(()=>t(i));return{handle:{cancel:e=>r.abort(e),get final(){return a}},settled:Fe(a)}}var Le=class{_turns=[];_log=[];_sessionAnnotations=[];constructor(e){e?.turns&&(this._turns=[...e.turns]),e?.log&&(this._log=[...e.log]),e?.sessionAnnotations&&(this._sessionAnnotations=[...e.sessionAnnotations])}get turns(){return[...this._turns]}get log(){return[...this._log]}get sessionAnnotations(){return[...this._sessionAnnotations]}addTurn(e){this._turns.push(e)}replaceTurns(e){this._turns=[...e]}replaceLog(e){this._log=[...e]}replaceSessionAnnotations(e=[]){this._sessionAnnotations=[...e]}appendToLog(e){Array.isArray(e)?this._log.push(...e):this._log.push(e)}latestTurn(){return this._turns[this._turns.length-1]}toString(){return JSON.stringify({turns:this._turns,sessionAnnotations:this._sessionAnnotations})}};const Re={trace:0,debug:1,info:2,warn:3,error:4},ze=()=>performance.timeOrigin+performance.now();var Be=class{writers=[];minLevel=`info`;addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}shouldLog(e){return Re[e]>=Re[this.minLevel]}spanStart(e){for(let t of this.writers)t.onSpanStart(e)}spanEnd(e){for(let t of this.writers)t.onSpanEnd(e)}spanUpdate(e){for(let t of this.writers)t.onSpanUpdate?.(e)}event(e,t){for(let n of this.writers)n.onEvent?.(e,t)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}},Ve=class{rec=new Be;constructor(e){e?.minLevel&&(this.rec.minLevel=e.minLevel);for(let t of e?.writers??[])this.rec.addWriter(t)}get minLevel(){return this.rec.minLevel}set minLevel(e){this.rec.minLevel=e}addWriter(e){this.rec.addWriter(e)}removeWriter(e){this.rec.removeWriter(e)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:ze(),status:`ok`,attributes:{...t?.attributes??{}},events:[]};return this.rec.spanStart(n),new He(n,this.rec)}flush(){return this.rec.flush()}},He=class e{data;rec;ended=!1;constructor(e,t){this.data=e,this.rec=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:ze(),status:`ok`,attributes:{...n?.attributes??{}},events:[]};return this.rec.spanStart(r),new e(r,this.rec)}end(e=`ok`){this.ended||(this.ended=!0,this.data.endTime=ze(),this.data.status=e,this.rec.spanEnd(this.data))}addEvent(e,t,n){if(this.ended||!this.rec.shouldLog(t))return;let r={name:e,timestamp:ze(),level:t,attributes:n};this.data.events.push(r),this.rec.event(this.data,r)}trace(e,t){this.addEvent(e,`trace`,t)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,this.rec.spanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.rec.spanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.rec.spanUpdate(this.data))}};function Ue(e){if(!e)return{};let{trace:t,log:n,level:r}=e;if(t)return n&&console.warn(`[axle] observability.log is ignored when observability.trace is set; add a LogWriter to your tracer's writers instead`),{parent:t};if(n){let e=new Ve({minLevel:r,writers:[new F(n)]});return{parent:e,owned:e}}return{}}function We(e){return Ge(e)?`cancelled`:`error`}function Ge(e){return e instanceof O||e instanceof k||e instanceof Error&&e.name===`AbortError`}function Ke(e,t){return{...e,...t,providerOptions:e?.providerOptions||t?.providerOptions?{...e?.providerOptions,...t?.providerOptions}:void 0}}var qe=class{provider;model;history;name;fileResolver;requestOptions;registry;sessionId;system;mcps=[];resolvedMcps=new WeakSet;memory;spanParent;ownedTracer;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e,t){this.provider=e.provider,this.model=e.model,this.sessionId=e.sessionId??crypto.randomUUID(),this.history=new Le;let n=Ue(e.observability);if(this.spanParent=n.parent,this.ownedTracer=n.owned,this.system=e.system,this.name=e.name,this.fileResolver=e.fileResolver,this.requestOptions={reasoning:e.reasoning,maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,stop:e.stop,toolChoice:e.toolChoice,parallelToolCalls:e.parallelToolCalls,providerOptions:e.providerOptions},this.registry=new ve({tools:e.tools,providerTools:e.providerTools}),e.mcps&&(this.mcps=[...e.mcps]),e.memory){this.memory=e.memory;let t=e.memory.tools?.();t&&this.registry.add(t)}t&&this.restore(t)}addMcp(e){this.mcps.push(e)}addMcps(e){this.mcps.push(...e)}hasTools(){return this.registry.size>0||this.mcps.length>0}on(e){this.eventCallbacks.push(e)}context(){return ie({system:this.system,messages:this.history.log,tools:this.toToolDefinitions(this.registry.local()),providerTools:this.registry.provider(),mcpTools:this.toToolDefinitions(this.registry.mcp())})}snapshot(){let e=this.history.sessionAnnotations;return{version:1,sessionId:this.sessionId,messages:this.history.log,turns:this.history.turns,sessionAnnotations:e.length>0?e:void 0}}restore(e){if(e.version!==1)throw new E(`Unsupported agent session version: ${e.version}`);this.sessionId=e.sessionId,this.history.replaceLog(e.messages),this.history.replaceTurns(e.turns??[]),this.history.replaceSessionAnnotations(e.sessionAnnotations??[])}send(e,t){let{fileResolver:n,metadata:r,...i}=t??{},a=fe(e,{metadata:r}),o=Ke(this.requestOptions,i),{handle:s,settled:c}=Ie(this.sendQueue,async e=>{let t=this.spanParent?.startSpan(`agent.send`,{type:`workflow`,attributes:{sessionId:this.sessionId,...this.name?{agentName:this.name}:{}}});I(t,`message`,M(a.message.content));let r=`ok`;try{let i=await this.run(a,{signal:e,fileResolver:n,requestOptions:o,span:t});return i.ok||(r=`error`),t?.setAttributes({inputTokens:i.usage.in,outputTokens:i.usage.out}),i}catch(e){throw r=We(e),t?.error(e instanceof Error?e.message:String(e)),e}finally{t?.end(r),await this.ownedTracer?.flush()}},i.signal);return this.sendQueue=c,s}async resolveMcpTools(e,t){for(let n of this.mcps){if(this.resolvedMcps.has(n))continue;let r=await n.listTools({prefix:n.name,span:t,signal:e});this.registry.addMcp(r),this.resolvedMcps.add(n)}}emitEvent(e){for(let t of this.eventCallbacks)t(e)}toToolDefinitions(e){return e.map(e=>({name:e.name,description:e.description,schema:e.schema}))}async run(t,n){let{signal:r,fileResolver:i,requestOptions:a}=n,o=n.span,s=new Ne,c=new e({turns:this.history.turns,sessionAnnotations:this.history.sessionAnnotations}),l,u=e=>{let t=c.apply(e);t.handled&&(this.history.replaceTurns(t.state.turns),this.history.replaceSessionAnnotations(t.state.sessionAnnotations??[])),this.emitEvent(e)},d=()=>l?c.state.turns.find(e=>e.id===l):void 0,f=G();if(r.aborted)throw new k(`Agent send aborted`,{reason:r.reason,usage:f});try{await this.resolveMcpTools(r,o)}catch(e){throw r.aborted||e instanceof O||e instanceof Error&&e.name===`AbortError`?new k(`Agent send aborted`,{reason:e instanceof O?e.reason:r.reason,usage:f}):e}let p=this.system,m=[...this.history.log,t.message];if(this.memory){let e=await this.memory.recall({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:m,span:o});e.systemSuffix&&(p=(p??``)+`
|
|
6
|
+
|
|
7
|
+
`+e.systemSuffix)}if(r.aborted)throw new k(`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=Ae({provider:this.provider,model:this.model,messages:m,system:p,registry:this.registry,span:g,fileResolver:i??this.fileResolver,...v,signal:r,onToolCall:async(e,t,n)=>{let r=this.registry.get(e);if(!r)return null;try{return{type:`success`,content:await r.execute(t,n)}}catch(e){if(e instanceof A)throw e;return{type:`error`,error:{type:`execution`,message:e instanceof Error?e.message:String(e)}}}}});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=We(e),e instanceof A){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 A(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:e.usage??f,cause:e.cause})}if(e instanceof O){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 k(`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 D;try{D=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 E(`Agent turn missing after send`);if(this.memory)try{await this.memory.record({agentName:this.name,sessionId:this.sessionId,system:this.system,messages:this.history.log,newMessages:b.messages,span:o})}catch(e){o?.warn(`memory record failed`,{error:e instanceof Error?e.message:String(e)})}return{ok:!0,response:D,turn:T,usage:w}}};function Je(e){try{let t=l.fromJSONSchema(e);return t instanceof l.ZodObject?t.strict():l.object({}).passthrough()}catch{return l.object({}).passthrough()}}function Ye(e,t,n){return e.map(e=>Ze(e,t,n))}function Xe(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=Je(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function Ze(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=Je(e.inputSchema);return{name:r,description:e.description??``,schema:i,async execute(n,i){let a;try{a=await t.callTool({name:e.name,arguments:n},void 0,{signal:i.signal})}catch(t){throw i.signal.aborted||t instanceof Error&&t.name===`AbortError`?t:new A(`MCP tool call failed: ${e.name}`,{toolName:r,cause:t})}if(`isError`in a&&a.isError)throw Error($e(a.content));return Qe(a.content)}}}function Qe(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 $e(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
9
|
+
`)||`MCP tool execution error`}var et=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 u({name:`axle`,version:`1.0.0`}),this.config.transport===`stdio`?this.transport=new d({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new f(new URL(this.config.url),{requestInit:this.config.headers?{headers:this.config.headers}:void 0});try{await this.client.connect(this.transport,{signal:e?.signal}),this._connected=!0,t?.end(`ok`)}catch(e){throw t?.end(`error`),e}}async listTools(e){let t=this.assertConnected();return Ye(await this.fetchTools(t,e?.span,e?.signal),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return Xe(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 tt(e){return e?.map(e=>({type:`provider`,name:e.name,config:e.config}))}async function nt(e,t){if(e.version!==1)throw new E(`Unsupported agent definition version: ${e.version}`);let n=await t(e),r=e.model??n.model;if(!r)throw new E(`AgentDefinition requires a model or model resolver`);if(e.tools?.length&&!n.tools)throw new E(`AgentDefinition includes tools but resolver did not return tools`);return{provider:n.provider,model:r,system:e.system,name:e.name,tools:n.tools,providerTools:n.providerTools??tt(e.providerTools),mcps:n.mcps??e.mcps?.map(e=>new et(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 rt=class e extends E{missingVariables;constructor(t){super(it(t),{code:`INSTRUCT_VARIABLE_ERROR`,details:{missingVariables:t}}),this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),missingVariables:this.missingVariables}}};function it(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var at=class e extends Error{missingVariables;constructor(t){super(st(t)),this.name=`MissingVariablesError`,this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}};function ot(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 at(e)}return e}function st(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var ct=class e{prompt;inputs={};files=[];textReferences=[];vars;metadata;schema;constructor(e){this.prompt=e.prompt,this.schema=e.schema,this.vars=e.vars??`required`,this.metadata=e.metadata}clone(){let t=new e({prompt:this.prompt,schema:this.schema,vars:this.vars,metadata:this.metadata});return t.inputs={...this.inputs},t.files=[...this.files],t.textReferences=this.textReferences.map(e=>({...e})),t}withInputs(e){let t=this.clone();return t.inputs={...t.inputs,...e},t}withInput(e,t){return this.withInputs({[e]:t})}setInputs(e){this.inputs={...e}}addInput(e,t){this.inputs[e]=t}addFile(e,t){if(typeof e==`string`){this.textReferences.push({content:e,name:t?.name});return}if(e.kind===`text`&&e.source.type===`text`){this.textReferences.push({content:e.source.content,name:t?.name??e.name});return}this.files.push(t?.name?{...e,name:t.name}:e)}hasFiles(){return this.files.length>0}render(e={}){let t;try{t=ot(this.prompt,this.inputs,{strict:(e.vars??this.vars)===`required`})}catch(e){throw e instanceof at?new rt(e.missingVariables):e}if(this.textReferences.length>0)for(let[e,n]of this.textReferences.entries()){let r=n.name?`: ${n.name}`:``;t+=`\n\n## Reference ${e+1}${r}\n\n\`\`\`${n.content}'''`}if(!this.schema)return t;let n=`# Output Format Instructions
|
|
8
10
|
|
|
9
11
|
Return only valid JSON matching this schema. Do not wrap it in markdown. Do not include prose before or after the JSON.
|
|
10
|
-
`,[,r]=H(this.schema);for(let[e,t]of re(this.schema))n+=`\n- ${e}: ${t}`;return n+=`\n\nExample:\n${JSON.stringify(r,null,2)}\n\n`,n+t}},We=class e extends E{constructor(t,n){super(t,{code:`TASK_ERROR`,id:n?.id,details:{taskType:n?.taskType,taskIndex:n?.taskIndex,...n?.details},cause:n?.cause}),Object.setPrototypeOf(this,e.prototype)}};function Y(e,t,n={}){if(!Number.isInteger(e))throw Error(`${t} must be an integer`);if(n.min!==void 0&&e<n.min)throw Error(`${t} must be an integer greater than or equal to ${n.min}`);return e}function Ge(e){if(e==null)return{type:`error`,error:{type:`Undetermined`,message:`Unknown error occurred`},usage:{in:0,out:0},raw:e};if(e instanceof Error)return{type:`error`,error:{type:e.name||`Error`,message:e.message||`Unexpected error`},usage:{in:0,out:0},raw:e};if(typeof e==`object`){let t=e,n=t?.error?.error?.type||t?.error?.type||t?.type||t?.code||t?.status||`Undetermined`,r=t?.error?.error?.message||t?.error?.message||t?.message||t?.error||`Unexpected error`;return{type:`error`,error:{type:String(n),message:String(r)},usage:{in:0,out:0},raw:e}}return{type:`error`,error:{type:`Undetermined`,message:String(e)},usage:{in:0,out:0},raw:e}}function X(e,t=`Operation aborted`){if(e?.aborted)throw new O(t,{reason:e.reason})}function Ke(e,t,n=`Operation aborted`){return t?t.aborted?Promise.reject(new O(n,{reason:t.reason})):new Promise((r,i)=>{let a=()=>{t.removeEventListener(`abort`,a),i(new O(n,{reason:t.reason}))};t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,a),r(e)},e=>{t.removeEventListener(`abort`,a),i(e)})}):e}function qe(e,t,n=`[redacted]`){return Je(e,null,t,n)}function Je(e,t,n,r){if(typeof e!=`object`||!e)return typeof e==`string`&&t&&n.has(t)?r:e;if(Array.isArray(e))return e.map(e=>Je(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=Je(a,t,n,r);return i}const Ye=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function Z(e){return qe(e,Ye,`[redacted-file-value]`)}const Xe=20*1024*1024;async function Q(e,t){if(t.signal?.aborted)throw new DOMException(`File resolution aborted`,`AbortError`);let{source:n}=e;if(n.type===`base64`)return Ze({type:`base64`,data:n.data},e,t);if(n.type===`text`)return Ze({type:`text`,content:n.content},e,t);if(n.type===`url`)return Ze({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return Ze(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function Ze(e,t,n){if(n.accepted.includes(e.type))return{...e,mimeType:e.mimeType??t.mimeType,name:e.name??t.name};throw Error(`File source '${e.type}' is not supported for ${n.provider} ${t.kind} file '${t.name}'. Accepted: ${n.accepted.join(`, `)}`)}const Qe=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function $e(e){return e.startsWith(`text/`)||Qe.has(e)}function et(e){let t=m.getType(e);if(!t){let t=v(e).toLowerCase();throw Error(`Unsupported file type: ${t||`(no extension)`}`)}if(t.startsWith(`image/`))return{kind:`image`,mimeType:t};if(t===`application/pdf`)return{kind:`document`,mimeType:t};if($e(t))return{kind:`text`,mimeType:t};{let n=v(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function tt(e,t){let n=y(e);try{await h(n)}catch{throw Error(`File not found: ${e}`)}let r=await _(n);if(r.size>Xe)throw Error(`File too large: ${r.size} bytes. Maximum allowed: ${Xe} bytes`);let i=n.split(`/`).pop()||``,a=et(n);if((t||(a.kind===`text`?`utf-8`:`base64`))===`utf-8`){if(a.kind!==`text`)throw Error(`Cannot read ${a.kind} file as text: ${e}`);let t=await g(n,`utf-8`);return{kind:`text`,mimeType:a.mimeType,size:r.size,name:i,source:{type:`text`,content:t}}}else{if(a.kind===`text`)throw Error(`Cannot read text file as binary: ${e}`);let t=(await g(n)).toString(`base64`);return{kind:a.kind,mimeType:a.mimeType,size:r.size,name:i,source:{type:`base64`,data:t}}}}async function nt(e,t={model:``}){return Promise.all(e.map(e=>rt(e,t)))}async function rt(e,t){if(e.role===`assistant`){let t=[];for(let n of e.content)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`thinking`){let e=n.continuity?.provider===`anthropic`?n.continuity:void 0;n.redacted?t.push({type:`redacted_thinking`,data:e?.redactedData??n.text??``}):e?.signature&&t.push({type:`thinking`,thinking:n.text??``,signature:e.signature})}else n.type===`tool-call`?t.push({type:`tool_use`,id:n.id,name:n.name,input:n.parameters}):n.type===`provider-tool`&&(t.push({type:`server_tool_use`,id:n.id,name:n.name,input:n.input??{}}),n.output!=null&&t.push({type:`web_search_tool_result`,tool_use_id:n.id,content:n.output}));return{role:`assistant`,content:t}}if(e.role===`tool`)return{role:`user`,content:await Promise.all(e.content.map(async e=>({type:`tool_result`,tool_use_id:e.id,content:typeof e.content==`string`?e.content:await _t(e.content,t),...e.isError?{is_error:!0}:{}})))};if(typeof e.content==`string`)return{role:`user`,content:e.content};{let n=[];for(let r of e.content)r.type===`text`?n.push({type:`text`,text:r.text}):r.type===`file`&&n.push(await it(r.file,t,`user-message`));return{role:`user`,content:n}}}async function it(e,t,n){if(e.kind===`image`)return{type:`image`,source:ot(await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`Anthropic only supports PDF document files. Received ${e.mimeType}`);let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`document`,source:st(r),title:r.name??e.name,citations:{enabled:!0}}}let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Anthropic text source: ${r.type}`);return n===`tool-result`?{type:`text`,text:r.content}:{type:`document`,source:{type:`text`,media_type:`text/plain`,data:r.content},title:r.name??e.name,citations:{enabled:!0}}}function at(e){if(e===`image/jpeg`||e===`image/png`||e===`image/gif`||e===`image/webp`)return e;throw Error(`Anthropic does not support image MIME type: ${e}. Supported types: image/jpeg, image/png, image/gif, image/webp.`)}function ot(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:at(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function st(e){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:`application/pdf`,data:e.data};throw Error(`Unsupported Anthropic PDF source: ${e.type}`)}function ct(e){return e===!0?{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function lt(e){return e.map(e=>{let t=l.toJSONSchema(e.schema);if(!gt(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}const ut={web_search:`web_search_20250305`};function dt(e){return(e??[]).map(e=>({type:ut[e.name]??e.name,name:e.name,...e.config}))}function ft(e,t,n,r){if(e===void 0&&t!==!1)return{};let i=t===!1?{disable_parallel_tool_use:!0}:{};if(e===void 0||e===`auto`)return{tool_choice:{type:`auto`,...i}};if(e===`required`)return{tool_choice:{type:`any`,...i}};if(e===`none`)return{tool_choice:{type:`none`}};if(!(n?.some(t=>t.name===e.name)||r?.some(t=>t.name===e.name)))throw Error(`Tool choice references an unavailable tool: ${e.name}`);return{tool_choice:{type:`tool`,name:e.name,...i}}}function pt(e){let t=[];for(let n of e)if(n.type===`text`){let e=n.citations?.map(mt);t.push({type:`text`,text:n.text,...e&&e.length>0?{citations:e}:{}})}else if(n.type===`thinking`){let e=n.thinking.length===0&&!!n.signature;t.push({type:`thinking`,...n.thinking?{text:n.thinking}:{},redacted:e,continuity:{provider:`anthropic`,signature:n.signature}})}else if(n.type===`redacted_thinking`)t.push({type:`thinking`,redacted:!0,continuity:{provider:`anthropic`,redactedData:n.data}});else if(n.type===`tool_use`){if(typeof n.input!=`object`||n.input===null||Array.isArray(n.input))throw Error(`Invalid tool call input for ${n.name}: expected object, got ${typeof n.input}`);t.push({type:`tool-call`,id:n.id,name:n.name,parameters:n.input})}return t}function mt(e){switch(e.type){case`char_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`char`,start:e.start_char_index,end:e.end_char_index}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`page_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`page`,start:e.start_page_number,end:e.end_page_number}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`content_block_location`:return{source:{type:`document`,title:e.document_title??void 0,fileId:e.file_id??void 0,citedText:e.cited_text,locator:{type:`block`,start:e.start_block_index,end:e.end_block_index}},providerMetadata:{type:e.type,documentIndex:e.document_index}};case`web_search_result_location`:return{source:{type:`web`,title:e.title??void 0,url:e.url,citedText:e.cited_text},providerMetadata:{type:e.type,encryptedIndex:e.encrypted_index}};case`search_result_location`:return{source:{type:`search-result`,title:e.title??void 0,url:e.source,citedText:e.cited_text,locator:{type:`block`,start:e.start_block_index,end:e.end_block_index}},providerMetadata:{type:e.type,searchResultIndex:e.search_result_index}}}}function ht(e){switch(e){case`max_tokens`:return`length`;case`end_turn`:return`stop`;case`stop_sequence`:return`stop`;case`tool_use`:return`function_call`;default:return`error`}}function gt(e){return e&&typeof e==`object`&&e.type===`object`}async function _t(e,t){return Promise.all(e.map(async e=>e.type===`text`?{type:`text`,text:e.text}:it(e.file,t,`tool-result`)))}async function vt(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.tracer,v;try{X(g,`Generate aborted`);let e=await nt(r,{model:n,fileResolver:s?.fileResolver,signal:g}),y={model:n,max_tokens:l??16e3,messages:e,...i&&{system:i},...f&&{stop_sequences:Ce(f)},...(a||o)&&{tools:[...a?lt(a):[],...dt(o)]},...ct(c),...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...ft(p,m,a,o),...h};_?.debug(`Anthropic request`,{request:Z(y)});let b=await Ke(t.messages.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=yt(b)}catch(e){X(g,`Generate aborted`),v=Ge(e)}return _?.debug(`Anthropic response`,{result:v}),v}function yt(e){let t=ht(e.stop_reason);if(t===`error`)return{type:`error`,error:{type:`Uncaught error`,message:`Stop reason is not recognized or unhandled: ${e.stop_reason}`},usage:xt(e.usage),raw:e};if(t===`function_call`){let t=pt(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:B(t),usage:xt(e.usage),raw:e}}if(e.type==`message`){let n=pt(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:B(n),usage:xt(e.usage),raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:xt(e.usage),raw:e}}function bt(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)}function xt(e){return G({in:bt(e),out:e.output_tokens},{cachedIn:e.cache_read_input_tokens??void 0,cacheWriteIn:e.cache_creation_input_tokens??void 0})}function St(){let e=new Map,t=new Map,n=0,r=0,i=0,a=0,o=new Map;function s(s){let c=[];switch(s.type){case`message_start`:n=(s.message.usage?.input_tokens??0)+(s.message.usage?.cache_creation_input_tokens??0)+(s.message.usage?.cache_read_input_tokens??0),a=s.message.usage?.cache_creation_input_tokens??0,i=s.message.usage?.cache_read_input_tokens??0,c.push({type:`start`,id:s.message.id,data:{model:s.message.model,timestamp:Date.now()}});break;case`message_delta`:s.usage&&(r=s.usage.output_tokens??r,s.usage.input_tokens!=null&&(n=s.usage.input_tokens+(s.usage.cache_creation_input_tokens??a)+(s.usage.cache_read_input_tokens??i)),a=s.usage.cache_creation_input_tokens??a,i=s.usage.cache_read_input_tokens??i),s.delta.stop_reason&&c.push({type:`complete`,data:{finishReason:ht(s.delta.stop_reason),usage:G({in:n,out:r},{cachedIn:i,cacheWriteIn:a})}});case`message_stop`:break;case`content_block_start`:if(s.content_block.type===`text`)e.set(s.index,`text`),c.push({type:`text-start`,data:{index:s.index}});else if(s.content_block.type===`tool_use`){e.set(s.index,`tool`);let t=s.content_block;o.set(s.index,{id:t.id,name:t.name,argumentsBuffer:``}),c.push({type:`tool-call-start`,data:{index:s.index,id:t.id,name:t.name}})}else if(s.content_block.type===`thinking`){e.set(s.index,`thinking`);let t=s.content_block.thinking.length===0&&!!s.content_block.signature;c.push({type:`thinking-start`,data:{index:s.index,redacted:t,continuity:{provider:`anthropic`,signature:s.content_block.signature}}})}else if(s.content_block.type===`redacted_thinking`)e.set(s.index,`thinking`),c.push({type:`thinking-start`,data:{index:s.index,redacted:!0,continuity:{provider:`anthropic`,redactedData:s.content_block.data}}});else if(s.content_block.type===`server_tool_use`){e.set(s.index,`provider-tool`);let n=s.content_block;t.set(n.id,{index:s.index,name:n.name}),c.push({type:`provider-tool-start`,data:{index:s.index,id:n.id,name:n.name}})}else if(s.content_block.type===`web_search_tool_result`){let e=s.content_block,n=t.get(e.tool_use_id);n&&(c.push({type:`provider-tool-complete`,data:{index:n.index,id:e.tool_use_id,name:n.name,output:e.content}}),t.delete(e.tool_use_id))}break;case`content_block_delta`:if(s.delta.type===`text_delta`)c.push({type:`text-delta`,data:{text:s.delta.text,index:s.index}});else if(s.delta.type===`input_json_delta`){let e=o.get(s.index);e&&(e.argumentsBuffer+=s.delta.partial_json,c.push({type:`tool-call-args-delta`,data:{index:s.index,id:e.id,name:e.name,delta:s.delta.partial_json,accumulated:e.argumentsBuffer}}))}else s.delta.type===`thinking_delta`?c.push({type:`thinking-delta`,data:{text:s.delta.thinking,index:s.index}}):s.delta.type===`signature_delta`?c.push({type:`thinking-metadata`,data:{index:s.index,continuity:{provider:`anthropic`,signature:s.delta.signature}}}):s.delta.type===`citations_delta`&&(e.get(s.index)!==`text`&&console.warn(`[Anthropic] received citation delta outside a text block`,{index:s.index,blockType:e.get(s.index)}),c.push({type:`text-citation`,data:{index:s.index,citation:mt(s.delta.citation)}}));break;case`content_block_stop`:{let t=e.get(s.index);if(t===`text`)c.push({type:`text-complete`,data:{index:s.index}});else if(t===`thinking`)c.push({type:`thinking-complete`,data:{index:s.index}});else if(t!==`provider-tool`&&t===`tool`){let e=o.get(s.index);if(e){try{let t=e.argumentsBuffer?JSON.parse(e.argumentsBuffer):{};c.push({type:`tool-call-complete`,data:{index:s.index,id:e.id,name:e.name,arguments:t}})}catch(t){throw Error(`Failed to parse tool call arguments for ${e.name}: ${t instanceof Error?t.message:String(t)}\nRaw buffer: ${e.argumentsBuffer}`)}o.delete(s.index)}}e.delete(s.index);break}}return c}return{handleEvent:s}}async function*Ct(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.tracer,v=[...a?lt(a):[],...dt(o)],y=St();try{let e=await nt(r,{model:n,fileResolver:s?.fileResolver,signal:c}),b={model:n,max_tokens:u??wt(n),messages:e,...i&&{system:i},...p&&{stop_sequences:Ce(p)},...v.length>0&&{tools:v},...ct(l),...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...ft(m,h,a,o),...g};_?.debug(`Anthropic streaming request`,{request:Z(b)});let x=await t.messages.create({...b,stream:!0},{signal:c});for await(let e of x){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function wt(e){return e in t?t[e]:e.includes(`opus`)?e.match(/opus-4-[6-9]|opus-[5-9]/)?128e3:64e3:e.includes(`sonnet`)||e.includes(`haiku`)?e.match(/claude-3-[0-5]-/)?8192:64e3:16384}function Tt(e,t={}){let n=new p({apiKey:e,maxRetries:Y(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`anthropic`,async createGenerationRequest(e,t){return await vt({client:n,model:e,...t})},createStreamingRequest(e,t){return Ct({client:n,model:e,...t})}}}const Et={Models:i,DefaultModel:s};async function Dt(e,t={}){let n=Y(t.maxRetries??2,`maxRetries`,{min:0}),r=t.timeoutMs===void 0?void 0:Y(t.timeoutMs,`timeoutMs`,{min:1}),i=0;for(;;){X(t.signal,`Request aborted`);let a=Ot(t.signal,r);try{let r=await Ke(e({signal:a.signal}),a.signal,`Request aborted`);if(!kt(r.status)||i>=n)return r;let o=At(r,i);t.onRetry?.({attempt:i+1,delayMs:o,status:r.status}),await Mt(o,t.signal),i+=1}catch(e){if(X(t.signal,`Request aborted`),i>=n)throw e;let r=At(void 0,i);t.onRetry?.({attempt:i+1,delayMs:r,error:e}),await Mt(r,t.signal),i+=1}finally{a.cleanup()}}}function Ot(e,t){if(t===void 0)return{signal:e,cleanup:()=>{}};let n=new AbortController,r=setTimeout(()=>{n.abort(new DOMException(`Request timed out after ${t}ms`,`TimeoutError`))},t),i=()=>{n.abort(e?.reason)};return e?.aborted?i():e?.addEventListener(`abort`,i,{once:!0}),{signal:n.signal,cleanup:()=>{clearTimeout(r),e?.removeEventListener(`abort`,i)}}}function kt(e){return e===408||e===409||e===429||e>=500}function At(e,t){let n=jt(e);if(n!==void 0)return n;let r=Math.min(500*2**t,8e3);return r+Math.floor(Math.random()*r*.25)}function jt(e){let t=e?.headers.get(`retry-after-ms`);if(t){let e=Number.parseFloat(t);if(Number.isFinite(e)&&e>=0)return e}let n=e?.headers.get(`retry-after`);if(!n)return;let r=Number.parseFloat(n);if(Number.isFinite(r)&&r>=0)return r*1e3;let i=Date.parse(n);if(Number.isFinite(i))return Math.max(i-Date.now(),0)}async function Mt(e,t){if(e<=0){X(t,`Request aborted`);return}await new Promise((n,r)=>{let i,a=()=>{clearTimeout(i),t?.removeEventListener(`abort`,o)},o=()=>{a(),r(new DOMException(`Request aborted`,`AbortError`))},s=()=>{a(),n()};if(t?.aborted){o();return}i=setTimeout(s,e),t?.addEventListener(`abort`,o,{once:!0})}),X(t,`Request aborted`)}const Nt={web_search:`openrouter:web_search`};function Pt(e,t){let n=[];for(let r of e){let e=Nt[r.name];if(!e){t?.(`providerTool not supported by ChatCompletions provider vendor`,{vendor:`openrouter`,name:r.name});continue}n.push({type:e,...r.config?{parameters:r.config}:{}})}return n.length>0?n:void 0}function Ft(e){switch(e.type){case`url_citation`:{let t=e.url_citation;return t?.url?{source:{type:`web`,title:t.title,url:t.url,citedText:t.content},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:e.type}}:null}default:return null}}function It(e){let t=e.outputSpan;return!t||t.start===void 0&&t.end===void 0?!1:t.start!==0||t.end!==0}async function Lt(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>Wt(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function Rt(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`none`}:{}}function zt(e){return G({in:e?.prompt_tokens||0,out:e?.completion_tokens||0},{cachedIn:e?.prompt_tokens_details?.cached_tokens??e?.input_tokens_details?.cached_tokens,cacheWriteIn:e?.prompt_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.input_tokens_details?.cache_creation_tokens,reasoningOut:e?.completion_tokens_details?.reasoning_tokens??e?.output_tokens_details?.reasoning_tokens})}function Bt(e){if(e&&e.length>0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}}))}function Vt(e,t,n){if(!(!e||e.length===0)){if(!t){n?.(`providerTools not supported by ChatCompletions provider`);return}switch(t){case`openrouter`:return Pt(e,n)}}}function Ht(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,function:{name:e.name}}};throw n?.some(t=>t.name===e.name)?Error(`ChatCompletions does not support provider tool choice: ${e.name}`):Error(`Tool choice references an unavailable tool: ${e.name}`)}function Ut(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`function_call`;case`content_filter`:case`error`:return`error`;default:return`stop`}}async function Wt(e,t){switch(e.role){case`tool`:return Gt(e,t);case`assistant`:return Kt(e);default:return qt(e,t)}}async function Gt(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await Yt(e.content,t),tool_call_id:e.id})))}function Kt(e){let t=e.content.filter(e=>e.type===`tool-call`),n=e.content.filter(e=>e.type===`text`),r=t.length>0?t.map(e=>({type:`function`,id:e.id,function:{name:e.name,arguments:JSON.stringify(e.parameters)}})):void 0;return{role:`assistant`,content:n.map(e=>e.text).join(``),...r&&{tool_calls:r}}}async function qt(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>Jt(e,t)))).filter(e=>e!==null);return n.every(e=>e.type===`text`)?{role:`user`,content:n.map(e=>e.text).join(``)}:{role:`user`,content:n}}async function Jt(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?Xt(e.file,t,`user-message`):null}async function Yt(e,t){let n=[];for(let r of e){if(r.type===`text`){n.push(r.text);continue}if(r.file.kind===`text`){let e=await Q(r.file,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:`tool-result`,resolver:t.fileResolver,signal:t.signal});if(e.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${e.type}`);n.push($t(r.file,e.content,e.name,e.mimeType));continue}throw Error(`ChatCompletions tool results do not support file parts other than text`)}return n.join(`
|
|
11
|
-
`)}async function
|
|
12
|
-
`);j=n.pop()||``;for(let e of n){let t=e.trim();if(!t||t.startsWith(`:`)||!t.startsWith(`data: `))continue;let n=t.slice(6);if(n===`[DONE]`)continue;let r;try{r=JSON.parse(n)}catch(e){x?.error(`Error parsing ChatCompletions stream chunk`,{error:e instanceof Error?e.message:String(e),line:t});continue}if(r.error){let e=
|
|
13
|
-
`),r={functionResponse:{id:e.id??void 0,name:e.name,response:{output:n}}};return typeof e.content==`string`?[r]:[r,...await Promise.all(e.content.filter(e=>e.type===`file`).map(e=>vn(e.file,t,`tool-result`)))]}))).flat(1)}}function hn(e){let t=[],n=e.content.filter(e=>e.type===`text`);if(n.length>0)for(let e of n){let n=e.text;if(!n)continue;let r={text:n};e.providerMetadata?.thoughtSignature&&(r.thoughtSignature=e.providerMetadata.thoughtSignature),t.push(r)}let r=e.content.filter(e=>e.type===`tool-call`);return r.length>0&&t.push(...r.map(e=>{let t={functionCall:{id:e.id??void 0,name:e.name,args:e.parameters}};return e.providerMetadata?.thoughtSignature&&(t.thoughtSignature=e.providerMetadata.thoughtSignature),t})),{role:`model`,parts:t}}async function gn(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>_n(e,t)))).filter(e=>e!==null)}}async function _n(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?vn(e.file,t,`user-message`):null}async function vn(e,t,n){if(e.kind===`text`){let r=await Q(e,{provider:`gemini`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Gemini text source: ${r.type}`);return{text:bn(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`&&e.mimeType!==`application/pdf`)throw Error(`Gemini document file support is limited to PDFs. Received ${e.mimeType}`);return yn(await Q(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function yn(e,t){if(e.type===`base64`)return{inlineData:{mimeType:e.mimeType??t.mimeType,data:e.data}};if(e.type===`url`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.url}};if(e.type===`gemini-file-uri`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.uri}};throw Error(`Unsupported Gemini file source: ${e.type}`)}function bn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function xn(e){switch(e){case b.STOP:return[!0,`stop`];case b.MAX_TOKENS:return[!0,`length`];case b.FINISH_REASON_UNSPECIFIED:case b.SAFETY:case b.RECITATION:case b.LANGUAGE:case b.OTHER:case b.BLOCKLIST:case b.PROHIBITED_CONTENT:case b.SPII:case b.MALFORMED_FUNCTION_CALL:case b.IMAGE_SAFETY:return[!1,`error`]}return[!1,`error`]}async function Sn(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.tracer,v={...dn(c),...l===void 0?{}:{maxOutputTokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{topP:d},...f===void 0?{}:{stopSequences:Array.isArray(f)?f:[f]},...un(p,m,a,o),...h},y;try{X(g,`Generate aborted`);let e=await fn(r,{model:n,fileResolver:s?.fileResolver,signal:g}),c=sn(a,i,v);p!==`none`&&ln(c,o);let l={contents:e,config:c};_?.debug(`Gemini request`,{request:Z(l)});let u=await Ke(t.models.generateContent({model:n,...l}),g,`Generate aborted`);X(g,`Generate aborted`),y=Cn(u,{tracer:_})}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),y=Ge(e)}return _?.debug(`Gemini response`,{result:y}),y}function Cn(e,t){let{tracer:n}=t,r=e.usageMetadata?.promptTokenCount??0,i=G({in:r,out:(e.usageMetadata?.totalTokenCount??r)-r},{cachedIn:e.usageMetadata?.cachedContentTokenCount,reasoningOut:e.usageMetadata?.thoughtsTokenCount});if(!e)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};if(e.promptFeedback&&e.promptFeedback.blockReason)return{type:`error`,error:{type:`Blocked`,message:`Response blocked by Google AI: ${e.promptFeedback.blockReason}, ${e.promptFeedback.blockReasonMessage}`},usage:i,raw:e};if(!e.candidates||e.candidates.length===0)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};e.candidates.length>1&&n?.warn(`We received ${e.candidates.length} response candidates`);let a=e.candidates[0],o=a.content?.parts||[],[s,c]=xn(a.finishReason);if(s){let t=[];for(let e=0;e<o.length;e++){let n=o[e];if(n.text)if(n.thought)t.push({type:`thinking`,summary:n.text,...n.thoughtSignature?{continuity:{provider:`gemini`,thoughtSignature:n.thoughtSignature}}:{}});else{let r=Tn(a,e);wn(t,{type:`text`,text:n.text,...r.length>0?{citations:r}:{},...n.thoughtSignature?{providerMetadata:{thoughtSignature:n.thoughtSignature}}:{}})}}let n=o.filter(e=>e.functionCall),r=n.length>0?n.map(e=>({call:e.functionCall,thoughtSignature:e.thoughtSignature})):(e.functionCalls??[]).map(e=>({call:e,thoughtSignature:void 0}));if(r.length>0)for(let{call:e,thoughtSignature:n}of r)if(e.args==null)t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:{},...n?{providerMetadata:{thoughtSignature:n}}:{}});else if(typeof e.args!=`object`||Array.isArray(e.args))throw Error(`Invalid tool call arguments for ${e.name}: expected object, got ${typeof e.args}`);else t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:e.args,...n?{providerMetadata:{thoughtSignature:n}}:{}});return{type:`success`,id:e.responseId??``,model:e.modelVersion??``,role:`assistant`,finishReason:r.length>0?`function_call`:c,content:t,text:B(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function wn(e,t){let n=e[e.length-1];if(n?.type===`text`&&!n.citations?.length&&!n.providerMetadata&&!t.citations?.length&&!t.providerMetadata){n.text+=t.text;return}e.push(t)}function Tn(e,t){let n=[],r=e.groundingMetadata,i=r?.groundingChunks??[];for(let e of r?.groundingSupports??[])if(!(e.segment?.partIndex!==void 0&&e.segment.partIndex!==t))for(let t of e.groundingChunkIndices??[]){let r=i[t];r&&n.push(En(r,e))}for(let t of e.citationMetadata?.citations??[])n.push({source:t.uri?{type:`web`,title:t.title,url:t.uri}:{type:`unknown`},outputSpan:{start:t.startIndex,end:t.endIndex},providerMetadata:{license:t.license,publicationDate:t.publicationDate}});return n}function En(e,t){let n=t.segment;return e.web?{source:{type:`web`,title:e.web.title,url:e.web.uri},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{outputText:n?.text,confidenceScores:t.confidenceScores}}:e.retrievedContext?{source:{type:`retrieved-context`,title:e.retrievedContext.title,uri:e.retrievedContext.uri,citedText:e.retrievedContext.text,locator:{type:`page`,start:e.retrievedContext.pageNumber,end:e.retrievedContext.pageNumber}},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{documentName:e.retrievedContext.documentName,outputText:n?.text,confidenceScores:t.confidenceScores}}:e.maps?{source:{type:`web`,title:e.maps.title,url:e.maps.uri,citedText:e.maps.text},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{placeId:e.maps.placeId,outputText:n?.text,confidenceScores:t.confidenceScores}}:{source:{type:`unknown`},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{chunk:e,outputText:n?.text,confidenceScores:t.confidenceScores}}}function Dn(){let e=0,t=-1,n=!1,r=``,i=``,a=0,o=0,s=0,c=0,l=null,u=new Map;function d(e){t<0||(l===`text`?e.push({type:`text-complete`,data:{index:t}}):l===`thinking`&&e.push({type:`thinking-complete`,data:{index:t}}),l=null,t=-1)}function f(f){let p=[];r||(r=f.responseId||`gemini-${Date.now()}`,i=f.modelVersion||`gemini`,p.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}})),f.usageMetadata&&(a=f.usageMetadata.promptTokenCount||0,o=(f.usageMetadata.totalTokenCount||0)-a,s=f.usageMetadata.cachedContentTokenCount||0,c=f.usageMetadata.thoughtsTokenCount||0);let m=f.candidates?.[0];if(!m)return p;let h=m.content?.parts||[];for(let r=0;r<h.length;r++){let i=h[r],a=`thought`in i&&i.thought===!0,o=Object.keys(i),s=o.length===1&&`text`in i&&!i.text;if(!(`thoughtSignature`in i&&!i.text&&!i.functionCall||o.length===2&&`text`in i&&`thoughtSignature`in i&&!i.text||s)&&(a&&i.text?(l!==`thinking`&&(d(p),t=e++,l=`thinking`,p.push({type:`thinking-start`,data:{index:t,...i.thoughtSignature?{continuity:{provider:`gemini`,thoughtSignature:i.thoughtSignature}}:{}}})),p.push({type:`thinking-summary-delta`,data:{index:t,text:i.text}})):i.text&&!a?(l!==`text`&&(d(p),t=e++,l=`text`,p.push({type:`text-start`,data:{index:t}})),u.set(r,t),p.push({type:`text-delta`,data:{text:i.text,index:t}})):i.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(i))}`),i.functionCall)){d(p),n=!0;let t=e++,r=i.functionCall.id||`tool-${t}`,a=i.functionCall.name??``;p.push({type:`tool-call-start`,data:{index:t,id:r,name:a}});let o=i.functionCall.args??{},s=JSON.stringify(o);p.push({type:`tool-call-args-delta`,data:{index:t,id:r,name:a,delta:s,accumulated:s}});let c={index:t,id:r,name:a,arguments:o},l=i;l.thoughtSignature&&(c.providerMetadata={thoughtSignature:l.thoughtSignature}),p.push({type:`tool-call-complete`,data:c})}}for(let{partIndex:e,citation:n}of On(m)){let r=e===void 0?t:u.get(e);if(r===void 0||r<0){console.warn(`[Gemini] received citation without a resolvable text part`,{citation:n});continue}p.push({type:`text-citation`,data:{index:r,citation:n}})}if(m.finishReason&&m.finishReason!==b.FINISH_REASON_UNSPECIFIED){d(p);let[e,t]=xn(m.finishReason),r=n?`function_call`:t;!e&&!n?p.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${m.finishReason}`,usage:G({in:a,out:o},{cachedIn:s,reasoningOut:c}),raw:f}}):p.push({type:`complete`,data:{finishReason:r,usage:G({in:a,out:o},{cachedIn:s,reasoningOut:c})}})}return p}return{handleChunk:f}}function On(e){let t=[],n=e.groundingMetadata,r=n?.groundingChunks??[];for(let e of n?.groundingSupports??[])for(let n of e.groundingChunkIndices??[]){let i=r[n];i&&t.push({partIndex:e.segment?.partIndex,citation:kn(i,e)})}for(let n of e.citationMetadata?.citations??[])t.push({citation:{source:n.uri?{type:`web`,title:n.title,url:n.uri}:{type:`unknown`},outputSpan:{start:n.startIndex,end:n.endIndex},providerMetadata:{license:n.license,publicationDate:n.publicationDate}}});return t}function kn(e,t){let n=t.segment;return e.web?{source:{type:`web`,title:e.web.title,url:e.web.uri},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{outputText:n?.text,confidenceScores:t.confidenceScores}}:e.retrievedContext?{source:{type:`retrieved-context`,title:e.retrievedContext.title,uri:e.retrievedContext.uri,citedText:e.retrievedContext.text,locator:{type:`page`,start:e.retrievedContext.pageNumber,end:e.retrievedContext.pageNumber}},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{documentName:e.retrievedContext.documentName,outputText:n?.text,confidenceScores:t.confidenceScores}}:{source:{type:`unknown`},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{chunk:e,outputText:n?.text,confidenceScores:t.confidenceScores}}}async function*An(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.tracer,v=sn(a,i,{...dn(l),...u===void 0?{}:{maxOutputTokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{topP:f},...p===void 0?{}:{stopSequences:Array.isArray(p)?p:[p]},...un(m,h,a,o),...g});m!==`none`&&ln(v,o);let y=Dn();try{let e={contents:await fn(r,{model:n,fileResolver:s?.fileResolver,signal:c}),config:v};_?.debug(`Gemini streaming request`,{request:Z(e)});let i=await t.models.generateContentStream({model:n,...e});for await(let e of i){let t=y.handleChunk(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;_?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function jn(e,t={}){let n=new S({apiKey:e,httpOptions:{retryOptions:{attempts:Mn(t.maxRetries)},...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}}});return{name:`Gemini`,async createGenerationRequest(e,t){return await Sn({client:n,model:e,...t})},createStreamingRequest(e,t){return An({client:n,model:e,...t})}}}function Mn(e=2){return Y(e,`maxRetries`,{min:0})+1}const Nn={Models:r,DefaultModel:n};async function Pn(e){let{provider:t,model:n,messages:r,system:i,tools:a,providerTools:o,tracer:s,fileResolver:c,...l}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,providerTools:o,runtime:{tracer:s,fileResolver:c},...l})}async function Fn(e){if(`instruct`in e){let{instruct:t,messages:n,...r}=e,i=oe(t),a=await In({...r,messages:[...n??[],i.message]});if(!a.ok)return a;try{return{...a,response:i.parse(a.final)}}catch(e){return{ok:!1,messages:a.messages,final:a.final,usage:a.usage,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)}}}}return In(e)}async function In(e){let{provider:t,model:n,messages:r,system:i,onToolCall:a,maxIterations:o,tracer:s,fileResolver:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_=new AbortController().signal}=e,v=he(e),y=[...r],b=[],x=W(),S=0,C,w=e=>{y.push(e),b.push(e)},T=e=>(s?.setResult({kind:`llm`,model:n,request:{messages:r},response:{content:e.ok?e.final.content:null},usage:le(e.usage),finishReason:e.ok?e.final.finishReason:void 0}),s?.end(e.ok?`ok`:`error`),e),E=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??n,request:{messages:y},response:{content:t.content},usage:le(t.usage),finishReason:t.finishReason}),e.end()};try{for(;;){if(X(_,`Generate aborted`),o!==void 0&&S>=o)return T({ok:!1,messages:b,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${o})`}}},usage:x});S+=1;let e=s?.startSpan(`turn-${S}`,{type:`llm`}),r=v.executable(),D=r.length>0?r.map(e=>({name:e.name,description:e.description,schema:e.schema})):void 0,O=v.provider(),k;try{k=await Pn({provider:t,model:n,messages:y,system:i,tools:D,providerTools:O.length>0?O:void 0,tracer:e,fileResolver:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_}),X(_,`Generate aborted`)}catch(t){throw t instanceof Error&&t.name===`AbortError`&&e?.end(`ok`),t}if(pe(x,k),E(e,k),k.type===`error`)return T({ok:!1,messages:b,error:{kind:`model`,error:k},usage:x});let A={role:`assistant`,id:k.id,model:k.model,content:k.content,finishReason:k.finishReason};if(w(A),C=A,k.finishReason!==`function_call`)return T({ok:!0,response:C,messages:b,final:C,usage:x});let j=V(k.content);if(j.length===0)return T({ok:!0,response:C,messages:b,final:C,usage:x});let{results:ee}=await ge(j,a,_,v,s);X(_,`Generate aborted`),ee.length>0&&w({role:`tool`,id:crypto.randomUUID(),content:ee})}}catch(e){throw e instanceof A?(s?.end(`error`),new A(e.message,{toolName:e.toolName,messages:e.messages??b,partial:e.partial??C,usage:e.usage??x,cause:e.cause})):e instanceof O?(s?.end(`ok`),new O(`Generate aborted`,{reason:e.reason,messages:e.messages??b,partial:e.partial,usage:e.usage??x})):e instanceof Error&&e.name===`AbortError`?(s?.end(`ok`),new O(`Generate aborted`,{reason:_.reason,messages:b,usage:x})):e}}function Ln(e){if(e&&e.length>0)return e.map(e=>({type:`function`,strict:!0,name:e.name,description:e.description,parameters:l.toJSONSchema(e.schema)}))}const Rn={web_search:`web_search_preview`,code_execution:`code_interpreter`};function zn(e){return e?.map(e=>({type:Rn[e.name]??e.name,...e.config}))}function Bn(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,name:e.name}};let r=n?.find(t=>t.name===e.name);if(r)return{tool_choice:{type:Rn[r.name]??r.name}};throw Error(`Tool choice references an unavailable tool: ${e.name}`)}function Vn(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`none`}}:{}}async function Hn(e,t={model:``}){return(await Promise.all(e.map(e=>Un(e,t)))).flat(1)}async function Un(e,t){switch(e.role){case`tool`:return Wn(e,t);case`assistant`:return Gn(e);default:return Kn(e,t)}}async function Wn(e,t){return Promise.all(e.content.map(async e=>({type:`function_call_output`,call_id:e.id,output:typeof e.content==`string`?e.content:await Promise.all(e.content.map(e=>e.type===`text`?Promise.resolve({type:`input_text`,text:e.text}):Jn(e.file,t,`tool-result`)))})))}function Gn(e){let t=[],n=B(e.content);n&&t.push({role:e.role,content:n});let r=e.content.filter(e=>e.type===`thinking`);for(let e of r)e.continuity?.provider===`openai`&&t.push({type:`reasoning`,id:e.id,summary:e.summary?[{type:`summary_text`,text:e.summary}]:[],...e.text?{content:[{type:`reasoning_text`,text:e.text}]}:{},encrypted_content:e.continuity.encrypted});let i=e.content.filter(e=>e.type===`tool-call`);for(let e of i)t.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.parameters)});let a=e.content.filter(e=>e.type===`provider-tool`);for(let e of a)e.output!=null&&t.push(e.output);return t}async function Kn(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>qn(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function qn(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?Jn(e.file,t,`user-message`):(e.type,null)}async function Jn(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:Yn(await Q(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e),detail:`auto`};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`OpenAI file inputs currently support PDF documents. Received ${e.mimeType}`);return Xn(await Q(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}let r=await Q(e,{provider:`openai`,model:t.model,accepted:[`text`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return r.type===`text`?{type:`input_text`,text:r.content}:Xn(r,e)}function Yn(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported OpenAI image source: ${e.type}`)}function Xn(e,t){if(e.type===`url`)return{type:`input_file`,filename:e.name??t.name,file_url:e.url};if(e.type===`base64`)return{type:`input_file`,filename:e.name??t.name,file_data:`data:${e.mimeType??t.mimeType};base64,${e.data}`};throw Error(`Unsupported OpenAI file source: ${e.type}`)}async function Zn(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.tracer,v;try{if(X(g,`Generate aborted`),f!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let e=[...Ln(a)??[],...zn(o)??[]],y={model:n,input:await Hn(r,{model:n,fileResolver:s?.fileResolver,signal:g}),...i&&{instructions:i},...e.length>0?{tools:e}:{},...Vn(c),...l===void 0?{}:{max_output_tokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Bn(p,a,o),...m===void 0?{}:{parallel_tool_calls:m},...h};_?.debug(`OpenAI ResponsesAPI request`,{request:Z(y)});let b=await Ke(t.responses.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=Qn(b)}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),v=Ge(e)}return _?.debug(`OpenAI ResponsesAPI response`,{result:v}),v}function Qn(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:tr(e.usage),raw:e};let t=e.output?.filter(e=>e.type===`reasoning`)?.map(e=>e),n=[];if(t&&t.length>0)for(let e of t)(e.summary?.[0]?.text||e.content?.[0]?.text||e.encrypted_content)&&n.push({type:`thinking`,id:e.id,...e.content?.[0]?.text?{text:e.content[0].text}:{},...e.summary?.[0]?.text?{summary:e.summary[0].text}:{},...e.encrypted_content?{continuity:{provider:`openai`,encrypted:e.encrypted_content}}:{}});let r=$n(e);r.length>0?n.push(...r):e.output_text&&n.push({type:`text`,text:e.output_text});let i=e.output?.filter(e=>e.type===`function_call`);if(i&&i.length>0)for(let e of i){let t=e;try{n.push({type:`tool-call`,id:t.call_id||t.id||``,name:t.name||``,parameters:t.arguments?JSON.parse(t.arguments):{}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${t.arguments}`)}}return{type:`success`,id:e.id,model:e.model||``,role:`assistant`,finishReason:e.incomplete_details?`error`:i&&i.length>0?`function_call`:`stop`,content:n,text:B(n),usage:tr(e.usage),raw:e}}function $n(e){let t=[];for(let n of e.output??[])if(n.type===`message`)for(let e of n.content??[]){if(e.type!==`output_text`)continue;let n=(e.annotations??[]).map(er).filter(e=>e!==null);t.push({type:`text`,text:e.text,...n.length>0?{citations:n}:{}})}return t}function er(e){if(!e||typeof e!=`object`)return null;let t=e;switch(t.type){case`url_citation`:return{source:{type:`web`,title:t.title,url:t.url},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type}};case`file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};case`container_file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type,containerId:t.container_id}};case`file_path`:return{source:{type:`document`,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};default:return{source:{type:`unknown`},providerMetadata:t}}}function tr(e){return G({in:e?.input_tokens??0,out:e?.output_tokens??0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}function nr(){let e=``,t=``,n=0,r=-1,i=!1,a=new Map,o=new Map,s=new Map,c=new Set([`web_search_call`,`file_search_call`,`code_interpreter_call`]),l=new Map;function u(u){let d=[];switch(u.type){case`response.created`:e=u.response.id||`openai-${Date.now()}`,t=u.response.model,d.push({type:`start`,id:e,data:{model:t,timestamp:Date.now()}});break;case`response.output_text.delta`:{let e=rr(u.item_id,u.content_index);r===-1&&(r=n++,a.set(e,r),d.push({type:`text-start`,data:{index:r}})),d.push({type:`text-delta`,data:{text:u.delta,index:r}});break}case`response.output_text.done`:{let e=rr(u.item_id,u.content_index);a.set(e,r),r>=0&&(d.push({type:`text-complete`,data:{index:r}}),r=-1);break}case`response.output_text.annotation.added`:{let e=ir(u.annotation);if(!e)break;let t=a.get(rr(u.item_id,u.content_index));t===void 0&&console.warn(`[OpenAI] received text annotation without a resolved text part; falling back to current part`,{itemId:u.item_id,contentIndex:u.content_index}),d.push({type:`text-citation`,data:{index:t??r,citation:e}});break}case`response.function_call_arguments.delta`:{let e=u.item_id;if(!l.has(e)){let t=o.get(e),r=t?.name||``,i=t?.callId||e,a=n++;l.set(e,{id:e,callId:i,name:r,argumentsBuffer:``,partIdx:a}),d.push({type:`tool-call-start`,data:{index:a,id:i,name:r}})}let t=l.get(e);t.argumentsBuffer+=u.delta,d.push({type:`tool-call-args-delta`,data:{index:t.partIdx,id:t.callId,name:t.name,delta:u.delta,accumulated:t.argumentsBuffer}});break}case`response.function_call_arguments.done`:{i=!0;let e=u.item_id,t=l.get(e),n=u.name||t?.name||``;if(t){try{let e=u.arguments?JSON.parse(u.arguments):{};d.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.callId,name:n,arguments:e}})}catch(e){throw Error(`Failed to parse function call arguments for ${n}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${u.arguments}`)}l.delete(e)}break}case`response.completed`:{let e=u.response.usage;d.push({type:`complete`,data:{finishReason:u.response.incomplete_details?`error`:i?`function_call`:`stop`,usage:G({in:e?.input_tokens||0,out:e?.output_tokens||0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}});break}case`response.failed`:d.push({type:`error`,data:{type:`RESPONSES_API_ERROR`,message:`Response failed: ${u.response.status}`,raw:u}});break;case`response.output_item.added`:if(u.item?.type===`reasoning`){let e=u.item;r=n++,d.push({type:`thinking-start`,data:{index:r,id:e.id,...e.encrypted_content?{continuity:{provider:`openai`,encrypted:e.encrypted_content}}:{}}})}else if(u.item?.type===`function_call`){let e=u.item,t=e.id||e.call_id;t&&o.set(t,{name:e.name||``,callId:e.call_id||t})}else if(u.item&&c.has(u.item.type)){let e=u.item,t=n++;s.set(e.id,t),d.push({type:`provider-tool-start`,data:{index:t,id:e.id,name:e.type}})}break;case`response.output_item.done`:if(u.item?.type===`reasoning`&&r>=0)d.push({type:`thinking-complete`,data:{index:r}}),r=-1;else if(u.item&&c.has(u.item.type)){let e=u.item,t=s.get(e.id);t!==void 0&&(d.push({type:`provider-tool-complete`,data:{index:t,id:e.id,name:e.type,output:u.item}}),s.delete(e.id))}break;case`response.reasoning_text.delta`:u.delta&&d.push({type:`thinking-delta`,data:{index:r,text:u.delta}});break;case`response.reasoning_summary_text.delta`:u.delta&&d.push({type:`thinking-summary-delta`,data:{index:r,text:u.delta}});break;case`response.in_progress`:case`response.content_part.added`:case`response.content_part.done`:case`response.reasoning_summary_part.added`:case`response.reasoning_summary_part.done`:case`response.reasoning_summary_text.done`:case`response.reasoning_text.done`:case`response.web_search_call.in_progress`:case`response.web_search_call.searching`:case`response.web_search_call.completed`:break;default:console.log(`[OpenAI] unhandled stream event: ${u.type}`)}return d}return{handleEvent:u}}function rr(e,t){return`${e}:${t}`}function ir(e){if(!e||typeof e!=`object`)return null;let t=e;switch(t.type){case`url_citation`:return{source:{type:`web`,title:t.title,url:t.url},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type}};case`file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};case`container_file_citation`:return{source:{type:`document`,title:t.filename,fileId:t.file_id},outputSpan:{start:t.start_index,end:t.end_index},providerMetadata:{type:t.type,containerId:t.container_id}};case`file_path`:return{source:{type:`document`,fileId:t.file_id},providerMetadata:{type:t.type,index:t.index}};default:return{source:{type:`unknown`},providerMetadata:t}}}async function*ar(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.tracer;if(p!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let v=[...Ln(a)??[],...zn(o)??[]],y=nr();try{let e={model:n,input:await Hn(r,{model:n,fileResolver:s?.fileResolver,signal:c}),...i&&{instructions:i},stream:!0,...v.length>0?{tools:v}:{},...Vn(l),...u===void 0?{}:{max_output_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Bn(m,a,o),...h===void 0?{}:{parallel_tool_calls:h},...g};_?.debug(`OpenAI ResponsesAPI streaming request`,{request:Z(e)});let p=t.responses.stream(e,...c?[{signal:c}]:[]);for await(let e of p){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;_?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function or(e,t={}){let n=new C({apiKey:e,maxRetries:Y(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`OpenAI`,async createGenerationRequest(e,t){return await Zn({client:n,model:e,...t})},createStreamingRequest(e,t){return ar({client:n,model:e,...t})}}}const sr={Models:a,DefaultModel:o},cr={debug:0,info:1,warn:2,error:3};var lr=class{writers=[];_minLevel=`info`;get minLevel(){return this._minLevel}set minLevel(e){this._minLevel=e}addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.writers.forEach(e=>e.onSpanStart(n)),new ur(n,this)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}_notifySpanEnd(e){this.writers.forEach(t=>t.onSpanEnd(e))}_notifySpanUpdate(e){this.writers.forEach(t=>t.onSpanUpdate?.(e))}_notifyEvent(e,t){this.writers.forEach(n=>n.onEvent?.(e,t))}_notifySpanStart(e){this.writers.forEach(t=>t.onSpanStart(e))}_shouldLog(e){return cr[e]>=cr[this._minLevel]}},ur=class e{data;tracer;ended=!1;constructor(e,t){this.data=e,this.tracer=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.tracer._notifySpanStart(r),new e(r,this.tracer)}end(e=`ok`){this.ended||(this.ended=!0,this.data.endTime=performance.now(),this.data.status=e,this.tracer._notifySpanEnd(this.data))}addEvent(e,t,n){if(this.ended||!this.tracer._shouldLog(t))return;let r={name:e,timestamp:performance.now(),level:t,attributes:n};this.data.events.push(r),this.tracer._notifyEvent(this.data,r)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,this.tracer._notifySpanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.tracer._notifySpanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.tracer._notifySpanUpdate(this.data))}};const dr={debug:0,info:1,warn:2,error:3};var fr=class{minLevel;showInternal;showTimestamp;showDuration;markdown;output;spans=new Map;visibleDepths=new Map;constructor(e={}){this.minLevel=e.minLevel??`info`,this.showInternal=e.showInternal??!1,this.showTimestamp=e.showTimestamp??!0,this.showDuration=e.showDuration??!0,this.markdown=e.markdown??!1,this.output=e.output??console.log}shouldShowEvent(e){return dr[e]>=dr[this.minLevel]}isSpanVisible(e){return!(e.type===`internal`&&!this.showInternal)}findVisibleAncestor(e){let t=e.parentSpanId;for(;t;){let e=this.spans.get(t);if(!e)break;if(this.isSpanVisible(e))return e;t=e.parentSpanId}return null}calculateVisibleDepth(e){if(!this.isSpanVisible(e))return-1;let t=this.findVisibleAncestor(e);return t?(this.visibleDepths.get(t.spanId)??0)+1:0}formatTimestamp(){if(!this.showTimestamp)return``;let e=new Date;return`[${e.toTimeString().slice(0,8)}.${e.getMilliseconds().toString().padStart(3,`0`)}] `}formatDuration(e){if(!this.showDuration||!e.endTime)return``;let t=e.endTime-e.startTime;return t<1e3?` (${Math.round(t)}ms)`:` (${(t/1e3).toFixed(2)}s)`}formatIndent(e){return` `.repeat(e)}formatSpanName(e){return e.type?`[${e.type}] ${e.name}`:e.name}renderMarkdown(e){return pr(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,t);let n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatSpanName(e);this.output(`${r}${n}START ${i}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.visibleDepths.get(e.spanId)??0,n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatDuration(e),a=this.formatSpanName(e),o=e.status===`error`?` [ERROR]`:``;if(this.output(`${r}${n}END ${a}${i}${o}`),e.result?.kind===`llm`){let t=e.result,i=[`model=${t.model}`];if(t.finishReason&&i.push(`finishReason=${t.finishReason}`),t.usage&&(t.usage.inputTokens!==void 0&&i.push(`inputTokens=${t.usage.inputTokens}`),t.usage.outputTokens!==void 0&&i.push(`outputTokens=${t.usage.outputTokens}`),t.usage.cachedInputTokens!==void 0&&i.push(`cachedInputTokens=${t.usage.cachedInputTokens}`),t.usage.cacheWriteInputTokens!==void 0&&i.push(`cacheWriteInputTokens=${t.usage.cacheWriteInputTokens}`),t.usage.reasoningOutputTokens!==void 0&&i.push(`reasoningOutputTokens=${t.usage.reasoningOutputTokens}`)),this.output(`${r}${n} INFO LLM complete ${i.join(` `)}`),this.shouldShowEvent(`debug`)&&t.response.content){let e=(typeof t.response.content==`string`?t.response.content:JSON.stringify(t.response.content,null,2)).split(`
|
|
14
|
-
`);for(let t of e)this.output(`${r}${n} DEBUG ${t}`)}}}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,t){if(!this.shouldShowEvent(t.level))return;this.spans.set(e.spanId,e);let n;if(this.isSpanVisible(e))n=this.visibleDepths.get(e.spanId)??0;else{let t=this.findVisibleAncestor(e);n=t?this.visibleDepths.get(t.spanId)??0:0}let r=this.formatIndent(n+1),i=this.formatTimestamp(),a=t.level.toUpperCase().padEnd(5),o=this.markdown&&t.attributes?.markdown===!0,s=t.attributes?Object.entries(t.attributes).filter(([e])=>e!==`markdown`):[],c=t.name;o&&(c=this.renderMarkdown(c));let l=`${i}${r}${a} ${c}`;if(s.length>0){let e=s.map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(` `);l+=` ${e}`}this.output(l)}};function
|
|
15
|
-
`)}function
|
|
16
|
-
`;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function
|
|
17
|
-
`)}function
|
|
18
|
-
`)}function
|
|
12
|
+
`,[,r]=W(this.schema);for(let[e,t]of ce(this.schema))n+=`\n- ${e}: ${t}`;return n+=`\n\nExample:\n${JSON.stringify(r,null,2)}\n\n`,n+t}},lt=class e extends E{constructor(t,n){super(t,{code:`TASK_ERROR`,id:n?.id,details:{taskType:n?.taskType,taskIndex:n?.taskIndex,...n?.details},cause:n?.cause}),Object.setPrototypeOf(this,e.prototype)}};function Y(e,t,n={}){if(!Number.isInteger(e))throw Error(`${t} must be an integer`);if(n.min!==void 0&&e<n.min)throw Error(`${t} must be an integer greater than or equal to ${n.min}`);return e}function ut(e){if(e==null)return{type:`error`,error:{type:`Undetermined`,message:`Unknown error occurred`},usage:{in:0,out:0},raw:e};if(e instanceof Error)return{type:`error`,error:{type:e.name||`Error`,message:e.message||`Unexpected error`},usage:{in:0,out:0},raw:e};if(typeof e==`object`){let t=e,n=t?.error?.error?.type||t?.error?.type||t?.type||t?.code||t?.status||`Undetermined`,r=t?.error?.error?.message||t?.error?.message||t?.message||t?.error||`Unexpected error`;return{type:`error`,error:{type:String(n),message:String(r)},usage:{in:0,out:0},raw:e}}return{type:`error`,error:{type:`Undetermined`,message:String(e)},usage:{in:0,out:0},raw:e}}function X(e,t=`Operation aborted`){if(e?.aborted)throw new O(t,{reason:e.reason})}function dt(e,t,n=`Operation aborted`){return t?t.aborted?Promise.reject(new O(n,{reason:t.reason})):new Promise((r,i)=>{let a=()=>{t.removeEventListener(`abort`,a),i(new O(n,{reason:t.reason}))};t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,a),r(e)},e=>{t.removeEventListener(`abort`,a),i(e)})}):e}function ft(e,t,n=`[redacted]`){return pt(e,null,t,n)}function pt(e,t,n,r){if(typeof e!=`object`||!e)return typeof e==`string`&&t&&n.has(t)?r:e;if(Array.isArray(e))return e.map(e=>pt(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=pt(a,t,n,r);return i}const mt=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function Z(e){return ft(e,mt,`[redacted-file-value]`)}const ht=20*1024*1024;async function Q(e,t){if(t.signal?.aborted)throw new DOMException(`File resolution aborted`,`AbortError`);let{source:n}=e;if(n.type===`base64`)return gt({type:`base64`,data:n.data},e,t);if(n.type===`text`)return gt({type:`text`,content:n.content},e,t);if(n.type===`url`)return gt({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return gt(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function gt(e,t,n){if(n.accepted.includes(e.type))return{...e,mimeType:e.mimeType??t.mimeType,name:e.name??t.name};throw Error(`File source '${e.type}' is not supported for ${n.provider} ${t.kind} file '${t.name}'. Accepted: ${n.accepted.join(`, `)}`)}const _t=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function vt(e){return e.startsWith(`text/`)||_t.has(e)}function yt(e){let t=m.getType(e);if(!t){let t=v(e).toLowerCase();throw Error(`Unsupported file type: ${t||`(no extension)`}`)}if(t.startsWith(`image/`))return{kind:`image`,mimeType:t};if(t===`application/pdf`)return{kind:`document`,mimeType:t};if(vt(t))return{kind:`text`,mimeType:t};{let n=v(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function bt(e,t){let n=y(e);try{await h(n)}catch{throw Error(`File not found: ${e}`)}let r=await _(n);if(r.size>ht)throw Error(`File too large: ${r.size} bytes. Maximum allowed: ${ht} bytes`);let i=n.split(`/`).pop()||``,a=yt(n);if((t||(a.kind===`text`?`utf-8`:`base64`))===`utf-8`){if(a.kind!==`text`)throw Error(`Cannot read ${a.kind} file as text: ${e}`);let t=await g(n,`utf-8`);return{kind:`text`,mimeType:a.mimeType,size:r.size,name:i,source:{type:`text`,content:t}}}else{if(a.kind===`text`)throw Error(`Cannot read text file as binary: ${e}`);let t=(await g(n)).toString(`base64`);return{kind:a.kind,mimeType:a.mimeType,size:r.size,name:i,source:{type:`base64`,data:t}}}}async function xt(e,t={model:``}){return Promise.all(e.map(e=>St(e,t)))}async function St(e,t){if(e.role===`assistant`){let t=[];for(let n of e.content)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`thinking`){let e=n.continuity?.provider===`anthropic`?n.continuity:void 0;n.redacted?t.push({type:`redacted_thinking`,data:e?.redactedData??n.text??``}):e?.signature&&t.push({type:`thinking`,thinking:n.text??``,signature:e.signature})}else n.type===`tool-call`?t.push({type:`tool_use`,id:n.id,name:n.name,input:n.parameters}):n.type===`provider-tool`&&(t.push({type:`server_tool_use`,id:n.id,name:n.name,input:n.input??{}}),n.output!=null&&t.push({type:`web_search_tool_result`,tool_use_id:n.id,content:n.output}));return{role:`assistant`,content:t}}if(e.role===`tool`)return{role:`user`,content:await Promise.all(e.content.map(async e=>({type:`tool_result`,tool_use_id:e.id,content:typeof e.content==`string`?e.content:await Lt(e.content,t),...e.isError?{is_error:!0}:{}})))};if(typeof e.content==`string`)return{role:`user`,content:e.content};{let n=[];for(let r of e.content)r.type===`text`?n.push({type:`text`,text:r.text}):r.type===`file`&&n.push(await Ct(r.file,t,`user-message`));return{role:`user`,content:n}}}async function Ct(e,t,n){if(e.kind===`image`)return{type:`image`,source:Tt(await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`Anthropic only supports PDF document files. Received ${e.mimeType}`);let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`document`,source:Et(r),title:r.name??e.name,citations:{enabled:!0}}}let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Anthropic text source: ${r.type}`);return n===`tool-result`?{type:`text`,text:r.content}:{type:`document`,source:{type:`text`,media_type:`text/plain`,data:r.content},title:r.name??e.name,citations:{enabled:!0}}}function wt(e){if(e===`image/jpeg`||e===`image/png`||e===`image/gif`||e===`image/webp`)return e;throw Error(`Anthropic does not support image MIME type: ${e}. Supported types: image/jpeg, image/png, image/gif, image/webp.`)}function Tt(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:wt(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function Et(e){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:`application/pdf`,data:e.data};throw Error(`Unsupported Anthropic PDF source: ${e.type}`)}function Dt(e,t=``){return e===!0?Ot(t)?{thinking:{type:`adaptive`},output_config:{effort:`high`}}:{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function Ot(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 kt(e){return e.map(e=>{let t=l.toJSONSchema(e.schema);if(!It(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}const At={web_search:`web_search_20250305`};function jt(e){return(e??[]).map(e=>({type:At[e.name]??e.name,name:e.name,...e.config}))}function Mt(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 Nt(e){let t=[];for(let n of e)if(n.type===`text`){let e=n.citations?.map(Pt);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 Pt(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 Ft(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 It(e){return e&&typeof e==`object`&&e.type===`object`}async function Lt(e,t){return Promise.all(e.map(async e=>e.type===`text`?{type:`text`,text:e.text}:Ct(e.file,t,`tool-result`)))}async function Rt(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.span,v;try{X(g,`Generate aborted`);let e=await xt(r,{model:n,fileResolver:s?.fileResolver,signal:g}),y={model:n,max_tokens:l??16e3,messages:e,...i&&{system:i},...f&&{stop_sequences:Pe(f)},...(a||o)&&{tools:[...a?kt(a):[],...jt(o)]},...Dt(c,n),...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...Mt(p,m,a,o),...h};_?.debug(`Anthropic request`,{request:Z(y)});let b=await dt(t.messages.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=zt(b)}catch(e){X(g,`Generate aborted`),v=ut(e)}return _?.debug(`Anthropic response`,{result:v}),v}function zt(e){let t=Ft(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:Vt(e.usage),raw:e};if(t===`function_call`){let t=Nt(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:M(t),usage:Vt(e.usage),raw:e}}if(e.type==`message`){let n=Nt(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:M(n),usage:Vt(e.usage),raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:Vt(e.usage),raw:e}}function Bt(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)}function Vt(e){return K({in:Bt(e),out:e.output_tokens},{cachedIn:e.cache_read_input_tokens??void 0,cacheWriteIn:e.cache_creation_input_tokens??void 0})}function Ht(){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:Ft(s.delta.stop_reason),usage:K({in:n,out:r},{cachedIn:i,cacheWriteIn:a})}});case`message_stop`:break;case`content_block_start`:if(s.content_block.type===`text`)e.set(s.index,`text`),c.push({type:`text-start`,data:{index:s.index}});else if(s.content_block.type===`tool_use`){e.set(s.index,`tool`);let t=s.content_block;o.set(s.index,{id:t.id,name:t.name,argumentsBuffer:``}),c.push({type:`tool-call-start`,data:{index:s.index,id:t.id,name:t.name}})}else if(s.content_block.type===`thinking`){e.set(s.index,`thinking`);let t=s.content_block.thinking.length===0&&!!s.content_block.signature;c.push({type:`thinking-start`,data:{index:s.index,redacted:t,continuity:{provider:`anthropic`,signature:s.content_block.signature}}})}else if(s.content_block.type===`redacted_thinking`)e.set(s.index,`thinking`),c.push({type:`thinking-start`,data:{index:s.index,redacted:!0,continuity:{provider:`anthropic`,redactedData:s.content_block.data}}});else if(s.content_block.type===`server_tool_use`){e.set(s.index,`provider-tool`);let n=s.content_block;t.set(n.id,{index:s.index,name:n.name}),c.push({type:`provider-tool-start`,data:{index:s.index,id:n.id,name:n.name}})}else if(s.content_block.type===`web_search_tool_result`){let e=s.content_block,n=t.get(e.tool_use_id);n&&(c.push({type:`provider-tool-complete`,data:{index:n.index,id:e.tool_use_id,name:n.name,output:e.content}}),t.delete(e.tool_use_id))}break;case`content_block_delta`:if(s.delta.type===`text_delta`)c.push({type:`text-delta`,data:{text:s.delta.text,index:s.index}});else if(s.delta.type===`input_json_delta`){let e=o.get(s.index);e&&(e.argumentsBuffer+=s.delta.partial_json,c.push({type:`tool-call-args-delta`,data:{index:s.index,id:e.id,name:e.name,delta:s.delta.partial_json,accumulated:e.argumentsBuffer}}))}else s.delta.type===`thinking_delta`?c.push({type:`thinking-delta`,data:{text:s.delta.thinking,index:s.index}}):s.delta.type===`signature_delta`?c.push({type:`thinking-metadata`,data:{index:s.index,continuity:{provider:`anthropic`,signature:s.delta.signature}}}):s.delta.type===`citations_delta`&&(e.get(s.index)!==`text`&&console.warn(`[Anthropic] received citation delta outside a text block`,{index:s.index,blockType:e.get(s.index)}),c.push({type:`text-citation`,data:{index:s.index,citation:Pt(s.delta.citation)}}));break;case`content_block_stop`:{let t=e.get(s.index);if(t===`text`)c.push({type:`text-complete`,data:{index:s.index}});else if(t===`thinking`)c.push({type:`thinking-complete`,data:{index:s.index}});else if(t!==`provider-tool`&&t===`tool`){let e=o.get(s.index);if(e){try{let t=e.argumentsBuffer?JSON.parse(e.argumentsBuffer):{};c.push({type:`tool-call-complete`,data:{index:s.index,id:e.id,name:e.name,arguments:t}})}catch(t){throw Error(`Failed to parse tool call arguments for ${e.name}: ${t instanceof Error?t.message:String(t)}\nRaw buffer: ${P(e.argumentsBuffer)}`)}o.delete(s.index)}}e.delete(s.index);break}}return c}return{handleEvent:s}}async function*Ut(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?kt(a):[],...jt(o)],y=Ht();try{let e=await xt(r,{model:n,fileResolver:s?.fileResolver,signal:c}),b={model:n,max_tokens:u??Wt(n),messages:e,...i&&{system:i},...p&&{stop_sequences:Pe(p)},...v.length>0&&{tools:v},...Dt(l,n),...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...Mt(m,h,a,o),...g};_?.debug(`Anthropic streaming request`,{request:Z(b)});let x=await t.messages.create({...b,stream:!0},{signal:c});for await(let e of x){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function Wt(e){return e in t?t[e]:e.includes(`opus`)?e.match(/opus-4-[6-9]|opus-[5-9]/)?128e3:64e3:e.includes(`sonnet`)||e.includes(`haiku`)?e.match(/claude-3-[0-5]-/)?8192:64e3:16384}function Gt(e,t={}){let n=new p({apiKey:e,maxRetries:Y(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`anthropic`,async createGenerationRequest(e,t){return await Rt({client:n,model:e,...t})},createStreamingRequest(e,t){return Ut({client:n,model:e,...t})}}}const Kt={Models:i,DefaultModel:s};async function qt(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=Jt(t.signal,r);try{let r=await dt(e({signal:a.signal}),a.signal,`Request aborted`);if(!Yt(r.status)||i>=n)return r;let o=Xt(r,i);t.onRetry?.({attempt:i+1,delayMs:o,status:r.status}),await Qt(o,t.signal),i+=1}catch(e){if(X(t.signal,`Request aborted`),i>=n)throw e;let r=Xt(void 0,i);t.onRetry?.({attempt:i+1,delayMs:r,error:e}),await Qt(r,t.signal),i+=1}finally{a.cleanup()}}}function Jt(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 Yt(e){return e===408||e===409||e===429||e>=500}function Xt(e,t){let n=Zt(e);if(n!==void 0)return n;let r=Math.min(500*2**t,8e3);return r+Math.floor(Math.random()*r*.25)}function Zt(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 Qt(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 $t={web_search:`openrouter:web_search`};function en(e,t){let n=[];for(let r of e){let e=$t[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 tn(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 nn(e){let t=e.outputSpan;return!t||t.start===void 0&&t.end===void 0?!1:t.start!==0||t.end!==0}async function rn(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>dn(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function an(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`none`}:{}}function on(e){return K({in:e?.prompt_tokens||0,out:e?.completion_tokens||0},{cachedIn:e?.prompt_tokens_details?.cached_tokens??e?.input_tokens_details?.cached_tokens,cacheWriteIn:e?.prompt_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.input_tokens_details?.cache_creation_tokens,reasoningOut:e?.completion_tokens_details?.reasoning_tokens??e?.output_tokens_details?.reasoning_tokens})}function sn(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 cn(e,t,n){if(!(!e||e.length===0)){if(!t){n?.(`providerTools not supported by ChatCompletions provider`);return}switch(t){case`openrouter`:return en(e,n)}}}function ln(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 un(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 dn(e,t){switch(e.role){case`tool`:return fn(e,t);case`assistant`:return pn(e);default:return mn(e,t)}}async function fn(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await gn(e.content,t),tool_call_id:e.id})))}function pn(e){let t=e.content.filter(e=>e.type===`tool-call`),n=e.content.filter(e=>e.type===`text`),r=t.length>0?t.map(e=>({type:`function`,id:e.id,function:{name:e.name,arguments:JSON.stringify(e.parameters)}})):void 0;return{role:`assistant`,content:n.map(e=>e.text).join(``),...r&&{tool_calls:r}}}async function mn(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>hn(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 hn(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?_n(e.file,t,`user-message`):null}async function gn(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(bn(r.file,e.content,e.name,e.mimeType));continue}throw Error(`ChatCompletions tool results do not support file parts other than text`)}return n.join(`
|
|
13
|
+
`)}async function _n(e,t,n){if(e.kind===`text`){let r=await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${r.type}`);return{type:`text`,text:bn(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:yn(r,e)}}}return{type:`image_url`,image_url:{url:vn(await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}}}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 image source: ${e.type}`)}function yn(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions file source: ${e.type}`)}function bn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}async function xn(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,apiKey:c,providerToolVendor:l,maxRetries:u,timeoutMs:d,reasoning:f,maxOutputTokens:p,temperature:m,topP:h,stop:g,toolChoice:_,parallelToolCalls:v,providerOptions:y,signal:b}=e,x=s?.span,S;try{X(b,`Generate aborted`);let e=await rn(r,i,{model:n,fileResolver:s?.fileResolver,signal:b}),C=sn(a),w=cn(o,l,x?.warn.bind(x)),T=[...C??[],...w??[]],E={model:n,messages:e,...T.length>0?{tools:T}:{},...an(f),...p===void 0?{}:{max_tokens:p},...m===void 0?{}:{temperature:m},...h===void 0?{}:{top_p:h},...g===void 0?{}:{stop:g},...ln(_,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 qt(({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 dt(O.json(),b,`Generate aborted`);X(b,`Generate aborted`),S=Sn(k)}catch(e){X(b,`Generate aborted`),x?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),S=ut(e)}return x?.trace(`ChatCompletions response`,{result:S}),S}function Sn(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(tn).filter(e=>e!==null),a=i.filter(nn),o=i.filter(e=>!nn(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`)?un(`tool_calls`):un(t.finish_reason);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:s,content:n,text:M(n),usage:on(e.usage),raw:e}}function Cn(){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(tn).filter(e=>e!==null),r=a===`text`?e.filter(nn):[];for(let e of r)u.push({type:`text-citation`,data:{index:n,citation:e}});let i=e.filter(e=>!r.includes(e));i.length>0&&(c(u),u.push({type:`citation`,data:{index:t++,citations:i}}))}if(f.tool_calls){c(u);for(let n of f.tool_calls){let r=n.index;if(!e.has(r)){let i=t++,a=n.id||`tool-${i}`;e.set(r,{id:a,name:n.function?.name||``,argumentsBuffer:``,partIdx:i}),u.push({type:`tool-call-start`,data:{index:i,id:a,name:n.function?.name||``}})}let i=e.get(r);n.id&&(i.id=n.id),n.function?.name&&(i.name=n.function.name),n.function?.arguments&&(i.argumentsBuffer+=n.function.arguments,u.push({type:`tool-call-args-delta`,data:{index:i.partIdx,id:i.id,name:i.name,delta:n.function.arguments,accumulated:i.argumentsBuffer}}))}}if(d.finish_reason&&o===void 0){c(u);for(let[,t]of e)try{let e=t.argumentsBuffer?JSON.parse(t.argumentsBuffer):{};u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.id,name:t.name,arguments:e}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw buffer: ${P(t.argumentsBuffer)}`)}e.clear(),o=un(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*wn(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,apiKey:l,providerToolVendor:u,maxRetries:d,timeoutMs:f,reasoning:p,maxOutputTokens:m,temperature:h,topP:g,stop:_,toolChoice:v,parallelToolCalls:y,providerOptions:b}=e,x=s?.span,S=Cn();try{let e=await rn(r,i,{model:n,fileResolver:s?.fileResolver,signal:c}),C=sn(a),w=cn(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}:{},...an(p),...m===void 0?{}:{max_tokens:m},...h===void 0?{}:{temperature:h},...g===void 0?{}:{top_p:g},..._===void 0?{}:{stop:_},...ln(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 qt(({signal:e})=>fetch(`${t}/chat/completions`,{method:`POST`,headers:D,body:JSON.stringify(E),signal:e}),{maxRetries:d,timeoutMs:f,signal:c,onRetry:e=>x?.warn(`ChatCompletions streaming request retry`,{attempt:e.attempt,maxRetries:d,timeoutMs:f,delayMs:e.delayMs,status:e.status,error:e.error instanceof Error?e.error.message:void 0})});if(!O.ok){let e=await O.text().catch(()=>``);throw Error(`HTTP error! status: ${O.status}${e?` - ${e}`:``}`)}if(!O.body)throw Error(`Response body is null`);let k=O.body.getReader(),A=new TextDecoder,j=``;for(;;){let{done:e,value:t}=await k.read();if(e)break;j+=A.decode(t,{stream:!0});let n=j.split(`
|
|
14
|
+
`);j=n.pop()||``;for(let e of n){let t=e.trim();if(!t||t.startsWith(`:`)||!t.startsWith(`data: `))continue;let n=t.slice(6);if(n===`[DONE]`)continue;let r;try{r=JSON.parse(n)}catch(e){x?.error(`Error parsing ChatCompletions stream chunk`,{error:e instanceof Error?e.message:String(e),line:t});continue}if(r.error){let e=Tn(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 Tn(e){if(typeof e==`string`)return{type:`UPSTREAM_STREAM_ERROR`,message:e};let t=e.type??(e.code===void 0?void 0:String(e.code))??`UPSTREAM_STREAM_ERROR`;return{type:t,message:e.message??t}}function En(e,t,n){let r=typeof t==`string`?t:t?.apiKey,i=typeof t==`string`?n:t,a=Y(i?.maxRetries??2,`maxRetries`,{min:0}),o=i?.timeoutMs===void 0?void 0:Y(i.timeoutMs,`timeoutMs`,{min:1}),s=i?.providerToolVendor;return{name:`ChatCompletions`,async createGenerationRequest(t,n){return await xn({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,providerToolVendor:s,...n})},createStreamingRequest(t,n){return wn({baseUrl:e,model:t,apiKey:r,maxRetries:a,timeoutMs:o,providerToolVendor:s,...n})}}}function Dn(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 On={web_search:`googleSearch`,code_execution:`codeExecution`};function kn(e,t){if(!(!t||t.length===0)){e.tools||=[];for(let n of t){let t=On[n.name]??n.name;e.tools.push({[t]:n.config??{}})}}}function An(e,t,n,r){if(t===!1)throw Error(`Gemini does not support disabling parallel tool calls`);if(e===void 0)return{};if(e===`auto`)return{toolConfig:{functionCallingConfig:{mode:x.AUTO}}};if(e===`none`)return{toolConfig:{functionCallingConfig:{mode:x.NONE}}};if(e===`required`){if(!n||n.length===0)throw Error(`Gemini requires function tools for required tool choice`);return{toolConfig:{functionCallingConfig:{mode:x.ANY}}}}if(n?.some(t=>t.name===e.name))return{toolConfig:{functionCallingConfig:{mode:x.ANY,allowedFunctionNames:[e.name]}}};throw r?.some(t=>t.name===e.name)?Error(`Gemini does not support provider tool choice: ${e.name}`):Error(`Tool choice references an unavailable tool: ${e.name}`)}function jn(e){return e===!0?{thinkingConfig:{thinkingBudget:8192,includeThoughts:!0}}:e===!1?{thinkingConfig:{thinkingBudget:0}}:{}}async function Mn(e,t={model:``}){return(await Promise.all(e.map(e=>Nn(e,t)))).filter(e=>e!==void 0)}async function Nn(e,t){switch(e.role){case`tool`:return Pn(e,t);case`assistant`:return Fn(e);case`user`:return In(e,t)}}async function Pn(e,t){return{role:`user`,parts:(await Promise.all(e.content.map(async e=>{let n=typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
15
|
+
`),r={functionResponse:{id:e.id??void 0,name:e.name,response:{output:n}}};return typeof e.content==`string`?[r]:[r,...await Promise.all(e.content.filter(e=>e.type===`file`).map(e=>Rn(e.file,t,`tool-result`)))]}))).flat(1)}}function Fn(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 In(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>Ln(e,t)))).filter(e=>e!==null)}}async function Ln(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?Rn(e.file,t,`user-message`):null}async function Rn(e,t,n){if(e.kind===`text`){let r=await Q(e,{provider:`gemini`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Gemini text source: ${r.type}`);return{text:Bn(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`&&e.mimeType!==`application/pdf`)throw Error(`Gemini document file support is limited to PDFs. Received ${e.mimeType}`);return zn(await Q(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function zn(e,t){if(e.type===`base64`)return{inlineData:{mimeType:e.mimeType??t.mimeType,data:e.data}};if(e.type===`url`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.url}};if(e.type===`gemini-file-uri`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.uri}};throw Error(`Unsupported Gemini file source: ${e.type}`)}function Bn(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function Vn(e){switch(e){case b.STOP:return[!0,`stop`];case b.MAX_TOKENS:return[!0,`length`];case b.FINISH_REASON_UNSPECIFIED:case b.SAFETY:case b.RECITATION:case b.LANGUAGE:case b.OTHER:case b.BLOCKLIST:case b.PROHIBITED_CONTENT:case b.SPII:case b.MALFORMED_FUNCTION_CALL:case b.IMAGE_SAFETY:return[!1,`error`]}return[!1,`error`]}async function Hn(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={...jn(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]},...An(p,m,a,o),...h},y;try{X(g,`Generate aborted`);let e=await Mn(r,{model:n,fileResolver:s?.fileResolver,signal:g}),c=Dn(a,i,v);p!==`none`&&kn(c,o);let l={contents:e,config:c};_?.debug(`Gemini request`,{request:Z(l)});let u=await dt(t.models.generateContent({model:n,...l}),g,`Generate aborted`);X(g,`Generate aborted`),y=Un(u,{span:_})}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),y=ut(e)}return _?.debug(`Gemini response`,{result:y}),y}function Un(e,t){let{span:n}=t,r=e.usageMetadata?.promptTokenCount??0,i=K({in:r,out:(e.usageMetadata?.totalTokenCount??r)-r},{cachedIn:e.usageMetadata?.cachedContentTokenCount,reasoningOut:e.usageMetadata?.thoughtsTokenCount});if(!e)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};if(e.promptFeedback&&e.promptFeedback.blockReason)return{type:`error`,error:{type:`Blocked`,message:`Response blocked by Google AI: ${e.promptFeedback.blockReason}, ${e.promptFeedback.blockReasonMessage}`},usage:i,raw:e};if(!e.candidates||e.candidates.length===0)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};e.candidates.length>1&&n?.warn(`We received ${e.candidates.length} response candidates`);let a=e.candidates[0],o=a.content?.parts||[],[s,c]=Vn(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=Gn(a,e);Wn(t,{type:`text`,text:n.text,...r.length>0?{citations:r}:{},...n.thoughtSignature?{providerMetadata:{thoughtSignature:n.thoughtSignature}}:{}})}}let n=o.filter(e=>e.functionCall),r=n.length>0?n.map(e=>({call:e.functionCall,thoughtSignature:e.thoughtSignature})):(e.functionCalls??[]).map(e=>({call:e,thoughtSignature:void 0}));if(r.length>0)for(let{call:e,thoughtSignature:n}of r)if(e.args==null)t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:{},...n?{providerMetadata:{thoughtSignature:n}}:{}});else if(typeof e.args!=`object`||Array.isArray(e.args))throw Error(`Invalid tool call arguments for ${e.name}: expected object, got ${typeof e.args}`);else t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:e.args,...n?{providerMetadata:{thoughtSignature:n}}:{}});return{type:`success`,id:e.responseId??``,model:e.modelVersion??``,role:`assistant`,finishReason:r.length>0?`function_call`:c,content:t,text:M(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${c}`},usage:i,raw:e}}function Wn(e,t){let n=e[e.length-1];if(n?.type===`text`&&!n.citations?.length&&!n.providerMetadata&&!t.citations?.length&&!t.providerMetadata){n.text+=t.text;return}e.push(t)}function Gn(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(Kn(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 Kn(e,t){let n=t.segment;return e.web?{source:{type:`web`,title:e.web.title,url:e.web.uri},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{outputText:n?.text,confidenceScores:t.confidenceScores}}:e.retrievedContext?{source:{type:`retrieved-context`,title:e.retrievedContext.title,uri:e.retrievedContext.uri,citedText:e.retrievedContext.text,locator:{type:`page`,start:e.retrievedContext.pageNumber,end:e.retrievedContext.pageNumber}},outputSpan:{start:n?.startIndex,end:n?.endIndex},providerMetadata:{documentName:e.retrievedContext.documentName,outputText:n?.text,confidenceScores:t.confidenceScores}}: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 qn(){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 Jn(m)){let r=e===void 0?t:u.get(e);if(r===void 0||r<0){console.warn(`[Gemini] received citation without a resolvable text part`,{citation:n});continue}p.push({type:`text-citation`,data:{index:r,citation:n}})}if(m.finishReason&&m.finishReason!==b.FINISH_REASON_UNSPECIFIED){d(p);let[e,t]=Vn(m.finishReason),r=n?`function_call`:t;!e&&!n?p.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${m.finishReason}`,usage:K({in:a,out:o},{cachedIn:s,reasoningOut:c}),raw:f}}):p.push({type:`complete`,data:{finishReason:r,usage:K({in:a,out:o},{cachedIn:s,reasoningOut:c})}})}return p}return{handleChunk:f}}function Jn(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:Yn(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 Yn(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*Xn(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=Dn(a,i,{...jn(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]},...An(m,h,a,o),...g});m!==`none`&&kn(v,o);let y=qn();try{let e={contents:await Mn(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 Zn(e,t={}){let n=new S({apiKey:e,httpOptions:{retryOptions:{attempts:Qn(t.maxRetries)},...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}}});return{name:`Gemini`,async createGenerationRequest(e,t){return await Hn({client:n,model:e,...t})},createStreamingRequest(e,t){return Xn({client:n,model:e,...t})}}}function Qn(e=2){return Y(e,`maxRetries`,{min:0})+1}const $n={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 tr(e){if(`instruct`in e){let{instruct:t,messages:n,...r}=e,i=fe(t),a=await nr({...r,messages:[...n??[],i.message]});if(!a.ok)return a;try{return{...a,response:i.parse(a.final)}}catch(e){return{ok:!1,messages:a.messages,final:a.final,usage:a.usage,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)}}}}return nr(e)}async function nr(e){let{provider:t,model:n,messages:r,system:i,onToolCall:a,maxIterations:o,span:s,fileResolver:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_=new AbortController().signal}=e,v=Te(e),y=[...r],b=[],x=G(),S=0,C,w=e=>{y.push(e),b.push(e)},T=e=>(s?.setResult({kind:`llm`,model:n,request:{messages:r},response:{content:e.ok?e.final.content:null},usage:he(e.usage),finishReason:e.ok?e.final.finishReason:void 0}),s?.end(e.ok?`ok`:`error`),e),E=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??n,request:{messages:y},response:{content:t.content},usage:he(t.usage),finishReason:t.finishReason}),e.end()};try{for(;;){if(X(_,`Generate aborted`),o!==void 0&&S>=o)return T({ok:!1,messages:b,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${o})`}}},usage:x});S+=1;let e=s?.startSpan(`turn-${S}`,{type:`llm`}),r=v.executable(),D=r.length>0?r.map(e=>({name:e.name,description:e.description,schema:e.schema})):void 0,O=v.provider(),k;try{k=await er({provider:t,model:n,messages:y,system:i,tools:D,providerTools:O.length>0?O:void 0,span:e,fileResolver:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_}),X(_,`Generate aborted`)}catch(t){throw t instanceof Error&&t.name===`AbortError`&&e?.end(`ok`),t}if(ye(x,k),k.type!==`error`&&be(e,k.content),E(e,k),k.type===`error`)return T({ok:!1,messages:b,error:{kind:`model`,error:k},usage:x});let A={role:`assistant`,id:k.id,model:k.model,content:k.content,finishReason:k.finishReason};if(w(A),C=A,k.finishReason!==`function_call`)return T({ok:!0,response:C,messages:b,final:C,usage:x});let j=ee(k.content);if(j.length===0)return T({ok:!0,response:C,messages:b,final:C,usage:x});let{results:M}=await Ee(j,a,_,v,s);X(_,`Generate aborted`),M.length>0&&w({role:`tool`,id:crypto.randomUUID(),content:M})}}catch(e){throw e instanceof A?(s?.end(`error`),new A(e.message,{toolName:e.toolName,messages:e.messages??b,partial:e.partial??C,usage:e.usage??x,cause:e.cause})):e instanceof O?(s?.end(`ok`),new O(`Generate aborted`,{reason:e.reason,messages:e.messages??b,partial:e.partial,usage:e.usage??x})):e instanceof Error&&e.name===`AbortError`?(s?.end(`ok`),new O(`Generate aborted`,{reason:_.reason,messages:b,usage:x})):e}}function rr(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 ir={web_search:`web_search_preview`,code_execution:`code_interpreter`};function ar(e){return e?.map(e=>({type:ir[e.name]??e.name,...e.config}))}function or(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:ir[r.name]??r.name}};throw Error(`Tool choice references an unavailable tool: ${e.name}`)}function sr(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`none`}}:{}}async function cr(e,t={model:``}){return(await Promise.all(e.map(e=>lr(e,t)))).flat(1)}async function lr(e,t){switch(e.role){case`tool`:return ur(e,t);case`assistant`:return dr(e);default:return fr(e,t)}}async function ur(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}):mr(e.file,t,`tool-result`)))})))}function dr(e){let t=[],n=M(e.content);n&&t.push({role:e.role,content:n});let r=e.content.filter(e=>e.type===`thinking`);for(let e of r)e.continuity?.provider===`openai`&&t.push({type:`reasoning`,id:e.id,summary:e.summary?[{type:`summary_text`,text:e.summary}]:[],...e.text?{content:[{type:`reasoning_text`,text:e.text}]}:{},encrypted_content:e.continuity.encrypted});let i=e.content.filter(e=>e.type===`tool-call`);for(let e of i)t.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.parameters)});let a=e.content.filter(e=>e.type===`provider-tool`);for(let e of a)e.output!=null&&t.push(e.output);return t}async function fr(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>pr(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function pr(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?mr(e.file,t,`user-message`):(e.type,null)}async function mr(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 gr(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}:gr(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 gr(e,t){if(e.type===`url`)return{type:`input_file`,filename:e.name??t.name,file_url:e.url};if(e.type===`base64`)return{type:`input_file`,filename:e.name??t.name,file_data:`data:${e.mimeType??t.mimeType};base64,${e.data}`};throw Error(`Unsupported OpenAI file source: ${e.type}`)}async function _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;try{if(X(g,`Generate aborted`),f!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let e=[...rr(a)??[],...ar(o)??[]],y={model:n,input:await cr(r,{model:n,fileResolver:s?.fileResolver,signal:g}),...i&&{instructions:i},...e.length>0?{tools:e}:{},...sr(c),...l===void 0?{}:{max_output_tokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...or(p,a,o),...m===void 0?{}:{parallel_tool_calls:m},...h};_?.debug(`OpenAI ResponsesAPI request`,{request:Z(y)});let b=await dt(t.responses.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);X(g,`Generate aborted`),v=vr(b)}catch(e){X(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),v=ut(e)}return _?.debug(`OpenAI ResponsesAPI response`,{result:v}),v}function vr(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:xr(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:M(n),usage:xr(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(br).filter(e=>e!==null);t.push({type:`text`,text:e.text,...n.length>0?{citations:n}:{}})}return t}function br(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 xr(e){return K({in:e?.input_tokens??0,out:e?.output_tokens??0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}function Sr(){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=Cr(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=Cr(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=wr(u.annotation);if(!e)break;let t=a.get(Cr(u.item_id,u.content_index));t===void 0&&console.warn(`[OpenAI] received text annotation without a resolved text part; falling back to current part`,{itemId:u.item_id,contentIndex:u.content_index}),d.push({type:`text-citation`,data:{index:t??r,citation:e}});break}case`response.function_call_arguments.delta`:{let e=u.item_id;if(!l.has(e)){let t=o.get(e),r=t?.name||``,i=t?.callId||e,a=n++;l.set(e,{id:e,callId:i,name:r,argumentsBuffer:``,partIdx:a}),d.push({type:`tool-call-start`,data:{index:a,id:i,name:r}})}let t=l.get(e);t.argumentsBuffer+=u.delta,d.push({type:`tool-call-args-delta`,data:{index:t.partIdx,id:t.callId,name:t.name,delta:u.delta,accumulated:t.argumentsBuffer}});break}case`response.function_call_arguments.done`:{i=!0;let e=u.item_id,t=l.get(e),n=u.name||t?.name||``;if(t){try{let e=u.arguments?JSON.parse(u.arguments):{};d.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.callId,name:n,arguments:e}})}catch(e){throw Error(`Failed to parse function call arguments for ${n}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${u.arguments}`)}l.delete(e)}break}case`response.completed`:{let e=u.response.usage;d.push({type:`complete`,data:{finishReason:u.response.incomplete_details?`error`:i?`function_call`:`stop`,usage:K({in:e?.input_tokens||0,out:e?.output_tokens||0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}});break}case`response.failed`:d.push({type:`error`,data:{type:`RESPONSES_API_ERROR`,message:`Response failed: ${u.response.status}`,raw:u}});break;case`response.output_item.added`:if(u.item?.type===`reasoning`){let e=u.item;r=n++,d.push({type:`thinking-start`,data:{index:r,id:e.id,...e.encrypted_content?{continuity:{provider:`openai`,encrypted:e.encrypted_content}}:{}}})}else if(u.item?.type===`function_call`){let e=u.item,t=e.id||e.call_id;t&&o.set(t,{name:e.name||``,callId:e.call_id||t})}else if(u.item&&c.has(u.item.type)){let e=u.item,t=n++;s.set(e.id,t),d.push({type:`provider-tool-start`,data:{index:t,id:e.id,name:e.type}})}break;case`response.output_item.done`:if(u.item?.type===`reasoning`&&r>=0)d.push({type:`thinking-complete`,data:{index:r}}),r=-1;else if(u.item&&c.has(u.item.type)){let e=u.item,t=s.get(e.id);t!==void 0&&(d.push({type:`provider-tool-complete`,data:{index:t,id:e.id,name:e.type,output:u.item}}),s.delete(e.id))}break;case`response.reasoning_text.delta`:u.delta&&d.push({type:`thinking-delta`,data:{index:r,text:u.delta}});break;case`response.reasoning_summary_text.delta`:u.delta&&d.push({type:`thinking-summary-delta`,data:{index:r,text:u.delta}});break;case`response.in_progress`:case`response.content_part.added`:case`response.content_part.done`:case`response.reasoning_summary_part.added`:case`response.reasoning_summary_part.done`:case`response.reasoning_summary_text.done`:case`response.reasoning_text.done`:case`response.web_search_call.in_progress`:case`response.web_search_call.searching`:case`response.web_search_call.completed`:break;default:console.log(`[OpenAI] unhandled stream event: ${u.type}`)}return d}return{handleEvent:u}}function Cr(e,t){return`${e}:${t}`}function wr(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*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;if(p!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let v=[...rr(a)??[],...ar(o)??[]],y=Sr();try{let e={model:n,input:await cr(r,{model:n,fileResolver:s?.fileResolver,signal:c}),...i&&{instructions:i},stream:!0,...v.length>0?{tools:v}:{},...sr(l),...u===void 0?{}:{max_output_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...or(m,a,o),...h===void 0?{}:{parallel_tool_calls:h},...g};_?.debug(`OpenAI ResponsesAPI streaming request`,{request:Z(e)});let p=t.responses.stream(e,...c?[{signal:c}]:[]);for await(let e of p){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;_?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function Er(e,t={}){let n=new C({apiKey:e,maxRetries:Y(t.maxRetries??2,`maxRetries`,{min:0}),...t.timeoutMs===void 0?{}:{timeout:Y(t.timeoutMs,`timeoutMs`,{min:1})}});return{name:`OpenAI`,async createGenerationRequest(e,t){return await _r({client:n,model:e,...t})},createStreamingRequest(e,t){return Tr({client:n,model:e,...t})}}}const Dr={Models:a,DefaultModel:o},Or={trace:0,debug:1,info:2,warn:3,error:4};var kr=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 Or[e]>=Or[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 Ar(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,t);let n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatSpanName(e);this.output(`${r}${n}START ${i}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.visibleDepths.get(e.spanId)??0,n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatDuration(e),a=this.formatSpanName(e),o=e.status===`error`?` [ERROR]`:``;if(this.output(`${r}${n}END ${a}${i}${o}`),e.result?.kind===`llm`){let t=e.result,i=[`model=${t.model}`];if(t.finishReason&&i.push(`finishReason=${t.finishReason}`),t.usage&&(t.usage.inputTokens!==void 0&&i.push(`inputTokens=${t.usage.inputTokens}`),t.usage.outputTokens!==void 0&&i.push(`outputTokens=${t.usage.outputTokens}`),t.usage.cachedInputTokens!==void 0&&i.push(`cachedInputTokens=${t.usage.cachedInputTokens}`),t.usage.cacheWriteInputTokens!==void 0&&i.push(`cacheWriteInputTokens=${t.usage.cacheWriteInputTokens}`),t.usage.reasoningOutputTokens!==void 0&&i.push(`reasoningOutputTokens=${t.usage.reasoningOutputTokens}`)),this.output(`${r}${n} INFO LLM complete ${i.join(` `)}`),this.shouldShowEvent(`debug`)&&t.response.content){let e=(typeof t.response.content==`string`?t.response.content:JSON.stringify(t.response.content,null,2)).split(`
|
|
16
|
+
`);for(let t of e)this.output(`${r}${n} DEBUG ${t}`)}}}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,t){if(!this.shouldShowEvent(t.level))return;this.spans.set(e.spanId,e);let n;if(this.isSpanVisible(e))n=this.visibleDepths.get(e.spanId)??0;else{let t=this.findVisibleAncestor(e);n=t?this.visibleDepths.get(t.spanId)??0:0}let r=this.formatIndent(n+1),i=this.formatTimestamp(),a=t.level.toUpperCase().padEnd(5),o=this.markdown&&t.attributes?.markdown===!0,s=t.attributes?Object.entries(t.attributes).filter(([e])=>e!==`markdown`):[],c=t.name;o&&(c=this.renderMarkdown(c));let l=`${i}${r}${a} ${c}`;if(s.length>0){let e=s.map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(` `);l+=` ${e}`}this.output(l)}};function Ar(e){return jr(T.lexer(e))}function jr(e=[]){return e.map(e=>Mr(e)).filter(e=>e.length>0).join(`
|
|
17
|
+
`)}function Mr(e){switch(e.type){case`space`:return``;case`heading`:return w.bold($(e.tokens));case`paragraph`:return $(e.tokens);case`blockquote`:return Rr(jr(e.tokens),`> `);case`code`:return(e.lang?w.dim(`${e.lang}\n`):``)+w.yellow(e.text);case`list`:return Pr(e)?Ir(e):e.raw;case`hr`:return w.dim(`-`.repeat(40));case`table`:return Fr(e)?Lr(e):e.raw;case`html`:return e.text;case`text`:return e.tokens?$(e.tokens):Br(e.text);default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function $(e=[]){return e.map(e=>Nr(e)).join(``)}function Nr(e){switch(e.type){case`text`:case`escape`:return Br(e.text);case`strong`:return w.bold($(e.tokens));case`em`:return w.italic($(e.tokens));case`codespan`:return w.yellow(e.text);case`del`:return w.strikethrough($(e.tokens));case`link`:{let t=$(e.tokens);return e.href&&e.href!==e.text?`${w.blue.underline(t)} ${w.dim(`(${e.href})`)}`:w.blue.underline(t)}case`image`:return e.text?`${e.text} (${e.href})`:e.href;case`br`:return`
|
|
18
|
+
`;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function Pr(e){return e.type===`list`&&`items`in e&&Array.isArray(e.items)}function Fr(e){return e.type===`table`&&`header`in e&&`rows`in e}function Ir(e){return e.items.map((t,n)=>{let r=e.ordered?`${Number(e.start||1)+n}. `:`- `,i=t.task?`[${t.checked?`x`:` `}] `:``,a=jr(t.tokens).trimEnd();return r+i+zr(a,r.length+i.length)}).join(`
|
|
19
|
+
`)}function Lr(e){let t=e.header.map(e=>$(e.tokens)).join(` | `),n=e.rows.map(e=>e.map(e=>$(e.tokens)).join(` | `));return[w.bold(t),...n].join(`
|
|
20
|
+
`)}function Rr(e,t){return e.split(`
|
|
19
21
|
`).map(e=>t+e).join(`
|
|
20
|
-
`)}function
|
|
22
|
+
`)}function zr(e,t){let[n=``,...r]=e.split(`
|
|
21
23
|
`);if(r.length===0)return n;let i=` `.repeat(t);return[n,...r.map(e=>i+e)].join(`
|
|
22
|
-
`)}function
|
|
24
|
+
`)}function Br(e){return e.replace(/"/g,`"`).replace(/'/g,`'`).replace(/</g,`<`).replace(/>/g,`>`).replace(/&/g,`&`)}export{qe as Agent,Kt as Anthropic,O as AxleAbortError,k as AxleAgentAbortError,E as AxleError,De as AxleStopReason,A as AxleToolFatalError,$n as Gemini,Le as History,ct as Instruct,rt as InstructVariableError,F as LogWriter,et as MCP,Dr as OpenAI,kr as SimpleWriter,lt as TaskError,ve as ToolRegistry,Ve as Tracer,e as TurnAccumulator,Ne as TurnEventBuilder,me as addStats,Gt as anthropic,En as chatCompletions,nt as createAgentConfig,Ie as createHandle,G as createStats,ie as estimateContextUsage,Zn as gemini,tr as generate,er as generateTurn,bt as loadFileContent,Er as openai,ue as parseResponse,Ae as stream};
|
package/dist/ui.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as TurnMetadata, I as Citation, J as ThinkingContinuity, K as DocumentLocator, L as CitationOutputSpan, R as CitationSource, S as Turn, T as TurnStatus, _ as SubagentAction, a as UnknownEvent, b as TimingInfo, c as TurnEvent, d as Annotation, f as AnnotationPlacement, g as ProviderToolAction, h as FilePart, i as TurnAccumulatorState, l as ActionPart, m as CitationPart, n as TurnAccumulator, o as AnnotationEvent, ot as FileInfo, p as AnnotationStatus, r as TurnAccumulatorResult, s as AnnotationTarget, t as AccumulatableEvent, u as ActionResult, v as TextPart, w as TurnPart, x as ToolAction,
|
|
1
|
+
import { C as TurnMetadata, I as Citation, J as ThinkingContinuity, K as DocumentLocator, L as CitationOutputSpan, R as CitationSource, S as Turn, T as TurnStatus, _ as SubagentAction, a as UnknownEvent, b as TimingInfo, c as TurnEvent, d as Annotation, f as AnnotationPlacement, g as ProviderToolAction, h as FilePart, i as TurnAccumulatorState, l as ActionPart, m as CitationPart, mt as Stats, n as TurnAccumulator, o as AnnotationEvent, ot as FileInfo, p as AnnotationStatus, r as TurnAccumulatorResult, s as AnnotationTarget, t as AccumulatableEvent, u as ActionResult, v as TextPart, w as TurnPart, x as ToolAction, y as ThinkingPart } from "./accumulator-C4O3UCxY.js";
|
|
2
2
|
export { type AccumulatableEvent, type ActionPart, type ActionResult, type Annotation, type AnnotationEvent, type AnnotationPlacement, type AnnotationStatus, type AnnotationTarget, type Citation, type CitationOutputSpan, type CitationPart, type CitationSource, type DocumentLocator, type FileInfo, type FilePart, type ProviderToolAction, type Stats, type SubagentAction, type TextPart, type ThinkingContinuity, type ThinkingPart, type TimingInfo, type ToolAction, type Turn, TurnAccumulator, type TurnAccumulatorResult, type TurnAccumulatorState, type TurnEvent, type TurnMetadata, type TurnPart, type TurnStatus, type UnknownEvent };
|