@codeworksh/aikit 0.1.0 → 0.2.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/index.mjs ADDED
@@ -0,0 +1,2342 @@
1
+ import { Filesystem, NamedError, lazy } from "@codeworksh/utils";
2
+ import { Type } from "@sinclair/typebox";
3
+ import { uuidv7 } from "uuidv7";
4
+ import { keys, mapValues, pick, pipe } from "remeda";
5
+ import Anthropic from "@anthropic-ai/sdk";
6
+ import { parse } from "partial-json";
7
+ import Ajv from "ajv";
8
+ import addFormats from "ajv-formats";
9
+ //#region src/provider/provider.ts
10
+ let Provider;
11
+ (function(_Provider) {
12
+ const KnownProviderEnum = _Provider.KnownProviderEnum = {
13
+ anthropic: "anthropic",
14
+ openai: "openai"
15
+ };
16
+ const KnownProviderSchema = _Provider.KnownProviderSchema = Type.Union([Type.Literal(KnownProviderEnum.anthropic), Type.Literal(KnownProviderEnum.openai)]);
17
+ _Provider.Info = Type.Object({
18
+ id: KnownProviderSchema,
19
+ name: Type.String(),
20
+ env: Type.Array(Type.String()),
21
+ key: Type.Optional(Type.String()),
22
+ options: Type.Optional(Type.Record(Type.String(), Type.Any()))
23
+ });
24
+ _Provider.ReasoningEffortMapSchema = Type.Object({
25
+ minimal: Type.Optional(Type.String()),
26
+ low: Type.Optional(Type.String()),
27
+ medium: Type.Optional(Type.String()),
28
+ high: Type.Optional(Type.String()),
29
+ xhigh: Type.Optional(Type.String())
30
+ });
31
+ _Provider.OpenRouterRoutingSchema = Type.Object({
32
+ only: Type.Optional(Type.Array(Type.String())),
33
+ order: Type.Optional(Type.Array(Type.String()))
34
+ });
35
+ _Provider.VercelGatewayRoutingSchema = Type.Object({
36
+ only: Type.Optional(Type.Array(Type.String())),
37
+ order: Type.Optional(Type.Array(Type.String()))
38
+ });
39
+ })(Provider || (Provider = {}));
40
+ //#endregion
41
+ //#region src/model/catalog.ts
42
+ let ModelCatalog;
43
+ (function(_ModelCatalog) {
44
+ function modelsDevURL() {
45
+ return process.env.OPENCODE_MODELS_URL || "https://models.dev";
46
+ }
47
+ function modelsDevPath() {
48
+ return process.env.CODEWORK_AIKIT_MODELS_PATH;
49
+ }
50
+ const modelsDevData = _ModelCatalog.modelsDevData = lazy(async () => {
51
+ const path = modelsDevPath();
52
+ if (path) {
53
+ const result = await Filesystem.readJson(path).catch(() => void 0);
54
+ if (result) return result;
55
+ }
56
+ const json = await fetch(`${modelsDevURL()}/api.json`).then((x) => x.text());
57
+ return JSON.parse(json);
58
+ });
59
+ async function get() {
60
+ return modelsDevData();
61
+ }
62
+ _ModelCatalog.get = get;
63
+ async function refresh() {
64
+ const result = await fetch(`${modelsDevURL()}/api.json`, { signal: AbortSignal.timeout(10 * 1e3) }).catch(() => void 0);
65
+ if (!result?.ok) return;
66
+ const json = await result.text();
67
+ const path = modelsDevPath();
68
+ if (path) await Filesystem.write(path, json);
69
+ modelsDevData.reset();
70
+ }
71
+ _ModelCatalog.refresh = refresh;
72
+ ModelCatalog.refresh();
73
+ setInterval(async () => {
74
+ await ModelCatalog.refresh();
75
+ }, 60 * 1e3 * 60).unref();
76
+ })(ModelCatalog || (ModelCatalog = {}));
77
+ //#endregion
78
+ //#region src/model/model.ts
79
+ let Model;
80
+ (function(_Model) {
81
+ const KnownProtocolEnum = _Model.KnownProtocolEnum = {
82
+ anthropicMessages: "anthropic-messages",
83
+ openaiCompletions: "openai-completions",
84
+ openaiResponses: "openai-responses"
85
+ };
86
+ _Model.KnownProtocolSchema = Type.Union([
87
+ Type.Literal(KnownProtocolEnum.anthropicMessages),
88
+ Type.Literal(KnownProtocolEnum.openaiCompletions),
89
+ Type.Literal(KnownProtocolEnum.openaiResponses)
90
+ ]);
91
+ const InputSchema = Type.Array(Type.Union([Type.Literal("text"), Type.Literal("image")]));
92
+ const CostSchema = Type.Object({
93
+ input: Type.Number(),
94
+ output: Type.Number(),
95
+ cacheRead: Type.Number(),
96
+ cacheWrite: Type.Number()
97
+ });
98
+ const HeadersSchema = Type.Optional(Type.Record(Type.String(), Type.String()));
99
+ const BaseSchema = _Model.BaseSchema = Type.Object({
100
+ id: Type.String(),
101
+ name: Type.String(),
102
+ provider: Provider.Info,
103
+ baseUrl: Type.String(),
104
+ reasoning: Type.Boolean(),
105
+ input: InputSchema,
106
+ cost: CostSchema,
107
+ contextWindow: Type.Number(),
108
+ maxTokens: Type.Number(),
109
+ headers: HeadersSchema
110
+ });
111
+ const OpenAICompletionsCompatSchema = _Model.OpenAICompletionsCompatSchema = Type.Object({
112
+ supportsStore: Type.Optional(Type.Boolean()),
113
+ supportsDeveloperRole: Type.Optional(Type.Boolean()),
114
+ supportsReasoningEffort: Type.Optional(Type.Boolean()),
115
+ reasoningEffortMap: Type.Optional(Provider.ReasoningEffortMapSchema),
116
+ supportsUsageInStreaming: Type.Optional(Type.Boolean()),
117
+ maxTokensField: Type.Optional(Type.Union([Type.Literal("max_completion_tokens"), Type.Literal("max_tokens")])),
118
+ requiresToolResultName: Type.Optional(Type.Boolean()),
119
+ requiresAssistantAfterToolResult: Type.Optional(Type.Boolean()),
120
+ requiresThinkingAsText: Type.Optional(Type.Boolean()),
121
+ thinkingFormat: Type.Optional(Type.Union([
122
+ Type.Literal("openai"),
123
+ Type.Literal("openrouter"),
124
+ Type.Literal("zai"),
125
+ Type.Literal("qwen"),
126
+ Type.Literal("qwen-chat-template")
127
+ ])),
128
+ openRouterRouting: Type.Optional(Provider.OpenRouterRoutingSchema),
129
+ vercelGatewayRouting: Type.Optional(Provider.VercelGatewayRoutingSchema),
130
+ supportsStrictMode: Type.Optional(Type.Boolean())
131
+ });
132
+ const OpenAIResponsesCompatSchema = _Model.OpenAIResponsesCompatSchema = Type.Object({});
133
+ _Model.OpenAICompatSchema = Type.Union([OpenAICompletionsCompatSchema, OpenAIResponsesCompatSchema]);
134
+ const AnthropicSchema = _Model.AnthropicSchema = Type.Composite([BaseSchema, Type.Object({ protocol: Type.Literal(KnownProtocolEnum.anthropicMessages) })]);
135
+ const OpenAICompletionsSchema = _Model.OpenAICompletionsSchema = Type.Composite([BaseSchema, Type.Object({
136
+ protocol: Type.Literal(KnownProtocolEnum.openaiCompletions),
137
+ compat: Type.Optional(OpenAICompletionsCompatSchema)
138
+ })]);
139
+ const OpenAIResponsesSchema = _Model.OpenAIResponsesSchema = Type.Composite([BaseSchema, Type.Object({
140
+ protocol: Type.Literal(KnownProtocolEnum.openaiResponses),
141
+ compat: Type.Optional(OpenAIResponsesCompatSchema)
142
+ })]);
143
+ _Model.Schema = Type.Union([
144
+ AnthropicSchema,
145
+ OpenAICompletionsSchema,
146
+ OpenAIResponsesSchema
147
+ ]);
148
+ const BUILTINS = keys(Provider.KnownProviderEnum);
149
+ function calculateCost(model, usage) {
150
+ usage.cost.input = usage.input / 1e6 * model.cost.input;
151
+ usage.cost.output = usage.output / 1e6 * model.cost.output;
152
+ usage.cost.cacheRead = usage.cacheRead / 1e6 * model.cost.cacheRead;
153
+ usage.cost.cacheWrite = usage.cacheWrite / 1e6 * model.cost.cacheWrite;
154
+ usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
155
+ }
156
+ _Model.calculateCost = calculateCost;
157
+ function resolveProtocol(providerId) {
158
+ switch (providerId) {
159
+ case Provider.KnownProviderEnum.anthropic: return KnownProtocolEnum.anthropicMessages;
160
+ case Provider.KnownProviderEnum.openai: return KnownProtocolEnum.openaiResponses;
161
+ }
162
+ }
163
+ function normalizeInput(input) {
164
+ const normalized = /* @__PURE__ */ new Set();
165
+ for (const modality of input ?? ["text"]) if (modality === "text" || modality === "image") normalized.add(modality);
166
+ if (normalized.size === 0) normalized.add("text");
167
+ return [...normalized];
168
+ }
169
+ function toProviderInfo(providerId, provider) {
170
+ return {
171
+ id: providerId,
172
+ name: provider.name,
173
+ env: provider.env,
174
+ key: provider.key,
175
+ options: provider.headers
176
+ };
177
+ }
178
+ function toModelValue(providerId, provider, model) {
179
+ const baseUrl = model.baseUrl ?? provider.baseUrl ?? provider.api;
180
+ return {
181
+ id: model.id,
182
+ name: model.name,
183
+ provider: toProviderInfo(providerId, provider),
184
+ baseUrl,
185
+ reasoning: Boolean(model.reasoning),
186
+ input: normalizeInput(model.modalities.input),
187
+ cost: {
188
+ input: model.cost?.input ?? 0,
189
+ output: model.cost?.output ?? 0,
190
+ cacheRead: model.cost?.cache_read ?? 0,
191
+ cacheWrite: model.cost?.cache_write ?? 0
192
+ },
193
+ contextWindow: model.limit?.context ?? 0,
194
+ maxTokens: model.limit?.output ?? 0,
195
+ headers: model.headers ?? provider.headers,
196
+ protocol: resolveProtocol(providerId)
197
+ };
198
+ }
199
+ async function getBuiltInModels() {
200
+ return pipe(await ModelCatalog.get(), pick(BUILTINS), mapValues((provider, providerId) => mapValues(provider.models, (model) => toModelValue(providerId, provider, model))));
201
+ }
202
+ _Model.getBuiltInModels = getBuiltInModels;
203
+ const registry = _Model.registry = lazy(async () => {
204
+ const registry = /* @__PURE__ */ new Map();
205
+ const models = await getBuiltInModels();
206
+ for (const [provider, value] of Object.entries(models)) {
207
+ const providerModels = /* @__PURE__ */ new Map();
208
+ for (const [id, model] of Object.entries(value)) providerModels.set(id, model);
209
+ registry.set(provider, providerModels);
210
+ }
211
+ return registry;
212
+ });
213
+ async function getModel(provider, model) {
214
+ return (await registry()).get(provider)?.get(model);
215
+ }
216
+ _Model.getModel = getModel;
217
+ async function getProviders() {
218
+ const data = await registry();
219
+ return Array.from(data.keys());
220
+ }
221
+ _Model.getProviders = getProviders;
222
+ async function getModels(provider) {
223
+ const models = (await registry()).get(provider);
224
+ return models ? Array.from(models.values()) : [];
225
+ }
226
+ _Model.getModels = getModels;
227
+ function isGpt5OrLater(modelID) {
228
+ const match = /^gpt-(\d+)/.exec(modelID);
229
+ if (!match) return false;
230
+ return Number(match[1]) >= 5;
231
+ }
232
+ function supportsXhigh(model) {
233
+ return isGpt5OrLater(model.id);
234
+ }
235
+ _Model.supportsXhigh = supportsXhigh;
236
+ function modelsAreEqual(a, b) {
237
+ if (!a || !b) return false;
238
+ return a.id === b.id && a.provider.id === b.provider.id;
239
+ }
240
+ _Model.modelsAreEqual = modelsAreEqual;
241
+ })(Model || (Model = {}));
242
+ //#endregion
243
+ //#region src/message/message.ts
244
+ let Message;
245
+ (function(_Message) {
246
+ const TextContentSchema = _Message.TextContentSchema = Type.Object({
247
+ type: Type.Literal("text"),
248
+ text: Type.String(),
249
+ textSignature: Type.Optional(Type.String())
250
+ });
251
+ const ImageContentSchema = _Message.ImageContentSchema = Type.Object({
252
+ type: Type.Literal("image"),
253
+ data: Type.String(),
254
+ mimeType: Type.String()
255
+ });
256
+ const ThinkingContentSchema = _Message.ThinkingContentSchema = Type.Object({
257
+ type: Type.Literal("thinking"),
258
+ thinking: Type.String(),
259
+ thinkingSignature: Type.Optional(Type.String()),
260
+ redacted: Type.Optional(Type.Boolean())
261
+ });
262
+ const ToolCallBaseSchema = _Message.ToolCallBaseSchema = Type.Object({
263
+ type: Type.Literal("toolCall"),
264
+ callID: Type.String(),
265
+ name: Type.String(),
266
+ arguments: Type.Record(Type.String(), Type.Any()),
267
+ thoughtSignature: Type.Optional(Type.String()),
268
+ time: Type.Object({
269
+ start: Type.Number(),
270
+ end: Type.Number()
271
+ })
272
+ });
273
+ const ToolSuccessResult = _Message.ToolSuccessResult = Type.Object({
274
+ content: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),
275
+ details: Type.Optional(Type.Any()),
276
+ isError: Type.Literal(false)
277
+ });
278
+ const ToolErrorResult = _Message.ToolErrorResult = Type.Object({
279
+ content: Type.Array(Type.Union([TextContentSchema, ImageContentSchema])),
280
+ details: Type.Optional(Type.Any()),
281
+ isError: Type.Literal(true)
282
+ });
283
+ const ToolRunningPartial = _Message.ToolRunningPartial = Type.Object({
284
+ content: Type.Optional(Type.Array(Type.Union([TextContentSchema, ImageContentSchema]))),
285
+ details: Type.Optional(Type.Any())
286
+ });
287
+ const ToolStatusEnum = _Message.ToolStatusEnum = {
288
+ pending: "pending",
289
+ running: "running",
290
+ completed: "completed",
291
+ error: "error",
292
+ skipped: "skipped",
293
+ aborted: "aborted"
294
+ };
295
+ const ToolRunningSchema = _Message.ToolRunningSchema = Type.Object({
296
+ status: Type.Literal(ToolStatusEnum.running),
297
+ partial: Type.Optional(ToolRunningPartial)
298
+ });
299
+ const ToolCompletedSchema = _Message.ToolCompletedSchema = Type.Object({
300
+ status: Type.Literal(ToolStatusEnum.completed),
301
+ result: ToolSuccessResult
302
+ });
303
+ const ToolErrorSchema = _Message.ToolErrorSchema = Type.Object({
304
+ status: Type.Literal(ToolStatusEnum.error),
305
+ result: ToolErrorResult
306
+ });
307
+ const ToolSkippedSchema = _Message.ToolSkippedSchema = Type.Object({
308
+ status: Type.Literal(ToolStatusEnum.skipped),
309
+ result: ToolErrorResult
310
+ });
311
+ const ToolAbortedSchema = _Message.ToolAbortedSchema = Type.Object({
312
+ status: Type.Literal(ToolStatusEnum.aborted),
313
+ result: ToolErrorResult
314
+ });
315
+ const ToolCallPendingPart = Type.Intersect([ToolCallBaseSchema, Type.Object({ status: Type.Literal(ToolStatusEnum.pending) })]);
316
+ const ToolCallRunningPart = Type.Composite([ToolCallBaseSchema, ToolRunningSchema]);
317
+ const ToolCallCompletedPart = Type.Composite([ToolCallBaseSchema, ToolCompletedSchema]);
318
+ const ToolCallErrorPart = Type.Composite([ToolCallBaseSchema, ToolErrorSchema]);
319
+ const ToolCallSkippedPart = Type.Composite([ToolCallBaseSchema, ToolSkippedSchema]);
320
+ const ToolCallAbortedPart = Type.Composite([ToolCallBaseSchema, ToolAbortedSchema]);
321
+ const ToolCallSchema = _Message.ToolCallSchema = Type.Union([
322
+ ToolCallPendingPart,
323
+ ToolCallRunningPart,
324
+ ToolCallCompletedPart,
325
+ ToolCallErrorPart,
326
+ ToolCallSkippedPart,
327
+ ToolCallAbortedPart
328
+ ]);
329
+ const UsageSchema = _Message.UsageSchema = Type.Object({
330
+ input: Type.Number(),
331
+ output: Type.Number(),
332
+ cacheRead: Type.Number(),
333
+ cacheWrite: Type.Number(),
334
+ totalTokens: Type.Number(),
335
+ cost: Type.Object({
336
+ input: Type.Number(),
337
+ output: Type.Number(),
338
+ cacheRead: Type.Number(),
339
+ cacheWrite: Type.Number(),
340
+ total: Type.Number()
341
+ })
342
+ });
343
+ const StopReasonSchema = _Message.StopReasonSchema = Type.Union([
344
+ Type.Literal("stop"),
345
+ Type.Literal("length"),
346
+ Type.Literal("toolUse"),
347
+ Type.Literal("error"),
348
+ Type.Literal("aborted")
349
+ ]);
350
+ const UserMessageSchema = _Message.UserMessageSchema = Type.Object({
351
+ messageId: Type.String(),
352
+ role: Type.Literal("user"),
353
+ time: Type.Object({ created: Type.Number() }),
354
+ parts: Type.Array(Type.Union([TextContentSchema, ImageContentSchema]))
355
+ });
356
+ const AssistantMessageSchema = _Message.AssistantMessageSchema = Type.Object({
357
+ role: Type.Literal("assistant"),
358
+ protocol: Model.KnownProtocolSchema,
359
+ provider: Provider.Info,
360
+ model: Type.String(),
361
+ usage: UsageSchema,
362
+ stopReason: StopReasonSchema,
363
+ errorMessage: Type.Optional(Type.String()),
364
+ time: Type.Object({
365
+ created: Type.Number(),
366
+ completed: Type.Number()
367
+ }),
368
+ parts: Type.Array(Type.Union([
369
+ TextContentSchema,
370
+ ImageContentSchema,
371
+ ThinkingContentSchema,
372
+ ToolCallSchema
373
+ ])),
374
+ responseId: Type.Optional(Type.String()),
375
+ messageId: Type.String()
376
+ });
377
+ const MessageSchema = _Message.MessageSchema = Type.Union([UserMessageSchema, AssistantMessageSchema]);
378
+ function createMessageId() {
379
+ return uuidv7();
380
+ }
381
+ _Message.createMessageId = createMessageId;
382
+ function createUserMessage(message) {
383
+ const { messageId = createMessageId(), ...rest } = message;
384
+ return {
385
+ messageId,
386
+ ...rest
387
+ };
388
+ }
389
+ _Message.createUserMessage = createUserMessage;
390
+ function createAssistantMessage(message) {
391
+ const { messageId = createMessageId(), ...rest } = message;
392
+ return {
393
+ messageId,
394
+ ...rest
395
+ };
396
+ }
397
+ _Message.createAssistantMessage = createAssistantMessage;
398
+ const ToolSchema = _Message.ToolSchema = Type.Object({
399
+ name: Type.String(),
400
+ description: Type.String(),
401
+ parameters: Type.Unsafe()
402
+ });
403
+ function defineTool(tool) {
404
+ return tool;
405
+ }
406
+ _Message.defineTool = defineTool;
407
+ _Message.ContextSchema = Type.Object({
408
+ systemPrompt: Type.Optional(Type.String()),
409
+ messages: Type.Array(MessageSchema),
410
+ tools: Type.Optional(Type.Array(ToolSchema))
411
+ });
412
+ function transformMessages(messages, model, normalizeToolCallId) {
413
+ const toolCallIDMap = /* @__PURE__ */ new Map();
414
+ const transformed = [];
415
+ for (const msg of messages) {
416
+ if (msg.role === "user") {
417
+ transformed.push(msg);
418
+ continue;
419
+ }
420
+ const assistantMsg = msg;
421
+ const isSameModel = assistantMsg.provider.id === model.provider.id && assistantMsg.protocol === model.protocol && assistantMsg.model === model.id;
422
+ const parts = assistantMsg.parts.flatMap((block) => {
423
+ if (block.type === "thinking") {
424
+ if (isSameModel && block.thinkingSignature) return block;
425
+ if (!block.thinking || block.thinking.trim() === "") return [];
426
+ if (isSameModel) return block;
427
+ return {
428
+ type: "text",
429
+ text: block.thinking
430
+ };
431
+ }
432
+ if (block.type === "text") {
433
+ if (isSameModel) return block;
434
+ return {
435
+ type: "text",
436
+ text: block.text
437
+ };
438
+ }
439
+ if (block.type === "toolCall") {
440
+ const toolCall = block;
441
+ let normalizedToolCall = toolCall;
442
+ if (!isSameModel && toolCall.thoughtSignature) {
443
+ normalizedToolCall = { ...toolCall };
444
+ delete normalizedToolCall.thoughtSignature;
445
+ }
446
+ const normalizedID = toolCallIDMap.get(block.callID);
447
+ if (normalizedID && normalizedID !== block.callID) normalizedToolCall = {
448
+ ...normalizedToolCall,
449
+ callID: normalizedID
450
+ };
451
+ else if (!isSameModel && normalizeToolCallId) {
452
+ const nextID = normalizeToolCallId(toolCall.callID, model, assistantMsg);
453
+ if (nextID !== toolCall.callID) {
454
+ toolCallIDMap.set(toolCall.callID, nextID);
455
+ normalizedToolCall = {
456
+ ...normalizedToolCall,
457
+ callID: nextID
458
+ };
459
+ }
460
+ }
461
+ return normalizedToolCall;
462
+ }
463
+ return block;
464
+ });
465
+ transformed.push({
466
+ ...assistantMsg,
467
+ parts
468
+ });
469
+ }
470
+ return transformed;
471
+ }
472
+ _Message.transformMessages = transformMessages;
473
+ })(Message || (Message = {}));
474
+ //#endregion
475
+ //#region src/utils/eventstream.ts
476
+ var EventStream = class {
477
+ queue = [];
478
+ waiting = [];
479
+ done = false;
480
+ finalResultPromise;
481
+ resolveFinalResult;
482
+ constructor(isComplete, extractResult) {
483
+ this.isComplete = isComplete;
484
+ this.extractResult = extractResult;
485
+ this.finalResultPromise = new Promise((resolve) => {
486
+ this.resolveFinalResult = resolve;
487
+ });
488
+ }
489
+ push(event) {
490
+ if (this.done) return;
491
+ if (this.isComplete(event)) {
492
+ this.done = true;
493
+ this.resolveFinalResult(this.extractResult(event));
494
+ }
495
+ const waiter = this.waiting.shift();
496
+ if (waiter) waiter({
497
+ value: event,
498
+ done: false
499
+ });
500
+ else this.queue.push(event);
501
+ }
502
+ end(result) {
503
+ this.done = true;
504
+ if (result !== void 0) this.resolveFinalResult(result);
505
+ while (this.waiting.length > 0) this.waiting.shift()({
506
+ value: void 0,
507
+ done: true
508
+ });
509
+ }
510
+ async *[Symbol.asyncIterator]() {
511
+ while (true) if (this.queue.length > 0) yield this.queue.shift();
512
+ else if (this.done) return;
513
+ else {
514
+ const result = await new Promise((resolve) => this.waiting.push(resolve));
515
+ if (result.done) return;
516
+ yield result.value;
517
+ }
518
+ }
519
+ result() {
520
+ return this.finalResultPromise;
521
+ }
522
+ };
523
+ var AssistantMessageEventStream = class extends EventStream {
524
+ constructor() {
525
+ super((event) => event.type === "done" || event.type === "error", (event) => {
526
+ if (event.type === "done") return event.message;
527
+ else if (event.type === "error") return event.error;
528
+ throw new Error("Unexpected event type for final result");
529
+ });
530
+ }
531
+ };
532
+ //#endregion
533
+ //#region src/utils/jsonparse.ts
534
+ /**
535
+ * @description Helper function to parse partial jsons during LLM streaming.
536
+ */
537
+ /**
538
+ * Attempts to parse potentially incomplete JSON during streaming.
539
+ * Always returns a valid object, even if the JSON is incomplete.
540
+ *
541
+ * @param partialJson The partial JSON string from streaming
542
+ * @returns Parsed object or empty object if parsing fails
543
+ */
544
+ function parseStreamingJson(partialJson) {
545
+ if (!partialJson || partialJson.trim() === "") return {};
546
+ try {
547
+ return JSON.parse(partialJson);
548
+ } catch {
549
+ try {
550
+ return parse(partialJson) ?? {};
551
+ } catch {
552
+ return {};
553
+ }
554
+ }
555
+ }
556
+ //#endregion
557
+ //#region src/utils/sanitize.ts
558
+ /**
559
+ * Removes unpaired Unicode surrogate characters from a string.
560
+ *
561
+ * Unpaired surrogates (high surrogates 0xD800-0xDBFF without matching low surrogates 0xDC00-0xDFFF,
562
+ * or vice versa) cause JSON serialization errors in many API providers.
563
+ *
564
+ * Valid emoji and other characters outside the Basic Multilingual Plane use properly paired
565
+ * surrogates and will NOT be affected by this function.
566
+ *
567
+ * @param text - The text to sanitize
568
+ * @returns The sanitized text with unpaired surrogates removed
569
+ *
570
+ * @example
571
+ * // Valid emoji (properly paired surrogates) are preserved
572
+ * sanitizeSurrogates("Hello 🙈 World") // => "Hello 🙈 World"
573
+ *
574
+ * // Unpaired high surrogate is removed
575
+ * const unpaired = String.fromCharCode(0xD83D); // high surrogate without low
576
+ * sanitizeSurrogates(`Text ${unpaired} here`) // => "Text here"
577
+ */
578
+ function sanitizeSurrogates(text) {
579
+ return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "");
580
+ }
581
+ //#endregion
582
+ //#region src/provider/stream.ts
583
+ let Stream;
584
+ (function(_Stream) {
585
+ const ProtocolProviderNotFoundError = _Stream.ProtocolProviderNotFoundError = NamedError.create("ProtocolProviderNotFoundError", Type.Object({ protocol: Model.KnownProtocolSchema }));
586
+ const ProtocolMismatchError = _Stream.ProtocolMismatchError = NamedError.create("ProtocolMismatchError", Type.Object({
587
+ actual: Model.KnownProtocolSchema,
588
+ expected: Model.KnownProtocolSchema
589
+ }));
590
+ const ThinkingLevelEnum = _Stream.ThinkingLevelEnum = {
591
+ off: "off",
592
+ minimal: "minimal",
593
+ low: "low",
594
+ medium: "medium",
595
+ high: "high",
596
+ xhigh: "xhigh"
597
+ };
598
+ const ThinkingLevelSchema = _Stream.ThinkingLevelSchema = Type.Union([
599
+ Type.Literal(ThinkingLevelEnum.off),
600
+ Type.Literal(ThinkingLevelEnum.minimal),
601
+ Type.Literal(ThinkingLevelEnum.low),
602
+ Type.Literal(ThinkingLevelEnum.medium),
603
+ Type.Literal(ThinkingLevelEnum.high),
604
+ Type.Literal(ThinkingLevelEnum.xhigh)
605
+ ]);
606
+ const ThinkingBudgetsSchema = _Stream.ThinkingBudgetsSchema = Type.Object({
607
+ off: Type.Optional(Type.Number()),
608
+ minimal: Type.Optional(Type.Number()),
609
+ low: Type.Optional(Type.Number()),
610
+ medium: Type.Optional(Type.Number()),
611
+ high: Type.Optional(Type.Number())
612
+ });
613
+ const CacheRetentionSchema = _Stream.CacheRetentionSchema = Type.Union([
614
+ Type.Literal("none"),
615
+ Type.Literal("short"),
616
+ Type.Literal("long")
617
+ ]);
618
+ const TransportSchema = _Stream.TransportSchema = Type.Union([
619
+ Type.Literal("sse"),
620
+ Type.Literal("websocket"),
621
+ Type.Literal("auto")
622
+ ]);
623
+ const OptionsSchema = _Stream.OptionsSchema = Type.Object({
624
+ temperature: Type.Optional(Type.Number()),
625
+ maxTokens: Type.Optional(Type.Number()),
626
+ signal: Type.Optional(Type.Unsafe()),
627
+ apiKey: Type.Optional(Type.String()),
628
+ transport: Type.Optional(TransportSchema),
629
+ cacheRetention: Type.Optional(CacheRetentionSchema),
630
+ sessionId: Type.Optional(Type.String()),
631
+ onPayload: Type.Optional(Type.Unsafe()),
632
+ headers: Type.Optional(Type.Record(Type.String(), Type.String())),
633
+ maxRetryDelayMs: Type.Optional(Type.Number()),
634
+ metadata: Type.Optional(Type.Record(Type.String(), Type.Unknown()))
635
+ });
636
+ _Stream.SimpleOptionsSchema = Type.Composite([OptionsSchema, Type.Object({
637
+ reasoning: Type.Optional(ThinkingLevelSchema),
638
+ thinkingBudgets: Type.Optional(ThinkingBudgetsSchema)
639
+ })]);
640
+ function buildBaseOptions(model, options, apiKey) {
641
+ return {
642
+ temperature: options?.temperature,
643
+ maxTokens: options?.maxTokens || Math.min(model.maxTokens, 32e3),
644
+ signal: options?.signal,
645
+ apiKey: apiKey || options?.apiKey,
646
+ transport: options?.transport,
647
+ cacheRetention: options?.cacheRetention,
648
+ sessionId: options?.sessionId,
649
+ headers: options?.headers,
650
+ onPayload: options?.onPayload,
651
+ maxRetryDelayMs: options?.maxRetryDelayMs,
652
+ metadata: options?.metadata
653
+ };
654
+ }
655
+ _Stream.buildBaseOptions = buildBaseOptions;
656
+ function clampReasoning(effort) {
657
+ return effort === ThinkingLevelEnum.xhigh ? ThinkingLevelEnum.high : effort;
658
+ }
659
+ _Stream.clampReasoning = clampReasoning;
660
+ function adjustMaxTokensForThinking(baseMaxTokens, modelMaxTokens, reasoningLevel, customBudgets) {
661
+ const budgets = {
662
+ minimal: 1024,
663
+ low: 2048,
664
+ medium: 8192,
665
+ high: 16384,
666
+ ...customBudgets
667
+ };
668
+ const minOutputTokens = 1024;
669
+ let thinkingBudget = budgets[clampReasoning(reasoningLevel)];
670
+ const maxTokens = Math.min(baseMaxTokens + thinkingBudget, modelMaxTokens);
671
+ if (maxTokens <= thinkingBudget) thinkingBudget = Math.max(0, maxTokens - minOutputTokens);
672
+ return {
673
+ maxTokens,
674
+ thinkingBudget
675
+ };
676
+ }
677
+ _Stream.adjustMaxTokensForThinking = adjustMaxTokensForThinking;
678
+ const protocolProviderRegistry = /* @__PURE__ */ new Map();
679
+ function wrapStream(protocol, stream) {
680
+ return (model, context, options) => {
681
+ if (model.protocol !== protocol) throw new ProtocolMismatchError({
682
+ actual: model.protocol,
683
+ expected: protocol
684
+ });
685
+ return stream(model, context, options);
686
+ };
687
+ }
688
+ function wrapStreamSimple(protocol, streamSimple) {
689
+ return (model, context, options) => {
690
+ if (model.protocol !== protocol) throw new ProtocolMismatchError({
691
+ actual: model.protocol,
692
+ expected: protocol
693
+ });
694
+ return streamSimple(model, context, options);
695
+ };
696
+ }
697
+ function registerProtocolProvider(provider, sourceId) {
698
+ protocolProviderRegistry.set(provider.protocol, {
699
+ provider: {
700
+ protocol: provider.protocol,
701
+ stream: wrapStream(provider.protocol, provider.stream),
702
+ streamSimple: wrapStreamSimple(provider.protocol, provider.streamSimple)
703
+ },
704
+ sourceId
705
+ });
706
+ }
707
+ _Stream.registerProtocolProvider = registerProtocolProvider;
708
+ function getProtocolProvider(protocol) {
709
+ return protocolProviderRegistry.get(protocol)?.provider;
710
+ }
711
+ _Stream.getProtocolProvider = getProtocolProvider;
712
+ function resolveProtocolProvider(model) {
713
+ const provider = getProtocolProvider(model.protocol);
714
+ if (!provider) throw new ProtocolProviderNotFoundError({ protocol: model.protocol });
715
+ return provider;
716
+ }
717
+ _Stream.resolveProtocolProvider = resolveProtocolProvider;
718
+ function stream(model, context, options) {
719
+ return resolveProtocolProvider(model).stream(model, context, options);
720
+ }
721
+ _Stream.stream = stream;
722
+ async function complete(model, context, options) {
723
+ return stream(model, context, options).result();
724
+ }
725
+ _Stream.complete = complete;
726
+ function streamSimple(model, context, options) {
727
+ return resolveProtocolProvider(model).streamSimple(model, context, options);
728
+ }
729
+ _Stream.streamSimple = streamSimple;
730
+ async function completeSimple(model, context, options) {
731
+ return streamSimple(model, context, options).result();
732
+ }
733
+ _Stream.completeSimple = completeSimple;
734
+ function getApiProviders() {
735
+ return Array.from(protocolProviderRegistry.values(), (entry) => entry.provider);
736
+ }
737
+ _Stream.getApiProviders = getApiProviders;
738
+ function unregisterProtocolProviders(sourceId) {
739
+ for (const [api, entry] of protocolProviderRegistry.entries()) if (entry.sourceId === sourceId) protocolProviderRegistry.delete(api);
740
+ }
741
+ _Stream.unregisterProtocolProviders = unregisterProtocolProviders;
742
+ function clearProtocolProviders() {
743
+ protocolProviderRegistry.clear();
744
+ }
745
+ _Stream.clearProtocolProviders = clearProtocolProviders;
746
+ })(Stream || (Stream = {}));
747
+ //#endregion
748
+ //#region src/provider/providers/anthropic/index.ts
749
+ function getEnvApiKey(_provider) {}
750
+ function resolveCacheRetention(cacheRetention) {
751
+ if (cacheRetention) return cacheRetention;
752
+ if (typeof process !== "undefined" && process.env.CODEWORK_CACHE_RETENTION === "long") return "long";
753
+ return "short";
754
+ }
755
+ function getCacheControl(baseUrl, cacheRetention) {
756
+ const retention = resolveCacheRetention(cacheRetention);
757
+ if (retention === "none") return { retention };
758
+ const ttl = retention === "long" && baseUrl.includes("api.anthropic.com") ? "1h" : void 0;
759
+ return {
760
+ retention,
761
+ cacheControl: {
762
+ type: "ephemeral",
763
+ ...ttl && { ttl }
764
+ }
765
+ };
766
+ }
767
+ const claudeCodeVersion = "2.1.2";
768
+ const ccToolLookup = new Map([
769
+ "Read",
770
+ "Write",
771
+ "Edit",
772
+ "Bash",
773
+ "Grep",
774
+ "Glob",
775
+ "AskUserQuestion",
776
+ "EnterPlanMode",
777
+ "ExitPlanMode",
778
+ "KillShell",
779
+ "NotebookEdit",
780
+ "Skill",
781
+ "Task",
782
+ "TaskOutput",
783
+ "TodoWrite",
784
+ "WebFetch",
785
+ "WebSearch"
786
+ ].map((t) => [t.toLowerCase(), t]));
787
+ const toClaudeCodeName = (name) => ccToolLookup.get(name.toLowerCase()) ?? name;
788
+ const fromClaudeCodeName = (name, tools) => {
789
+ if (tools && tools.length > 0) {
790
+ const lowerName = name.toLowerCase();
791
+ const matchedTool = tools.find((tool) => tool.name.toLowerCase() === lowerName);
792
+ if (matchedTool) return matchedTool.name;
793
+ }
794
+ return name;
795
+ };
796
+ function convertContentBlocks(content) {
797
+ if (!content.some((c) => c.type === "image")) return sanitizeSurrogates(content.map((c) => c.text).join("\n"));
798
+ const blocks = content.map((block) => {
799
+ if (block.type === "text") return {
800
+ type: "text",
801
+ text: sanitizeSurrogates(block.text)
802
+ };
803
+ return {
804
+ type: "image",
805
+ source: {
806
+ type: "base64",
807
+ media_type: block.mimeType,
808
+ data: block.data
809
+ }
810
+ };
811
+ });
812
+ if (!blocks.some((b) => b.type === "text")) blocks.unshift({
813
+ type: "text",
814
+ text: "(see attached image)"
815
+ });
816
+ return blocks;
817
+ }
818
+ function mergeHeaders(...headerSources) {
819
+ const merged = {};
820
+ for (const headers of headerSources) if (headers) Object.assign(merged, headers);
821
+ return merged;
822
+ }
823
+ function isOAuthToken(apiKey) {
824
+ return apiKey.includes("sk-ant-oat");
825
+ }
826
+ function createClient(model, apiKey, interleavedThinking, optionsHeaders) {
827
+ const betaFeatures = ["fine-grained-tool-streaming-2025-05-14"];
828
+ if (interleavedThinking) betaFeatures.push("interleaved-thinking-2025-05-14");
829
+ if (isOAuthToken(apiKey)) {
830
+ const defaultHeaders = mergeHeaders({
831
+ accept: "application/json",
832
+ "anthropic-dangerous-direct-browser-access": "true",
833
+ "anthropic-beta": `claude-code-20250219,oauth-2025-04-20,${betaFeatures.join(",")}`,
834
+ "user-agent": `claude-cli/${claudeCodeVersion} (external, cli)`,
835
+ "x-app": "cli"
836
+ }, model.headers, optionsHeaders);
837
+ return {
838
+ client: new Anthropic({
839
+ apiKey: null,
840
+ authToken: apiKey,
841
+ baseURL: model.baseUrl,
842
+ defaultHeaders,
843
+ dangerouslyAllowBrowser: true
844
+ }),
845
+ isOAuthToken: true
846
+ };
847
+ }
848
+ const defaultHeaders = mergeHeaders({
849
+ accept: "application/json",
850
+ "anthropic-dangerous-direct-browser-access": "true",
851
+ "anthropic-beta": betaFeatures.join(",")
852
+ }, model.headers, optionsHeaders);
853
+ return {
854
+ client: new Anthropic({
855
+ apiKey,
856
+ baseURL: model.baseUrl,
857
+ dangerouslyAllowBrowser: true,
858
+ defaultHeaders
859
+ }),
860
+ isOAuthToken: false
861
+ };
862
+ }
863
+ function normalizeToolCallId(id) {
864
+ return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
865
+ }
866
+ function assertReplayableAssistant(message) {
867
+ let sawToolCall = false;
868
+ let sawNonTerminalToolCall = false;
869
+ let sawTerminalToolCall = false;
870
+ for (const part of message.parts) {
871
+ if (part.type === "image") throw new Error("Anthropic replay does not support assistant image parts");
872
+ if (part.type === "toolCall") {
873
+ sawToolCall = true;
874
+ if (part.status === "pending" || part.status === "running") sawNonTerminalToolCall = true;
875
+ else sawTerminalToolCall = true;
876
+ continue;
877
+ }
878
+ if (sawToolCall) throw new Error("Assistant parts after a toolCall are not replayable for Anthropic");
879
+ }
880
+ if (sawToolCall && message.stopReason !== "toolUse") throw new Error("Assistant message with tool calls must have stopReason 'toolUse'");
881
+ if (!sawToolCall && message.stopReason === "toolUse") throw new Error("Assistant message with stopReason 'toolUse' must contain at least one toolCall");
882
+ if (sawTerminalToolCall && sawNonTerminalToolCall) throw new Error("Assistant message cannot mix terminal and non-terminal toolCall states");
883
+ }
884
+ function buildSyntheticToolResult(block) {
885
+ return {
886
+ type: "tool_result",
887
+ tool_use_id: block.callID,
888
+ content: convertContentBlocks([{
889
+ type: "text",
890
+ text: [
891
+ "<result>",
892
+ "No Result Provided",
893
+ "</result>"
894
+ ].join("\n")
895
+ }]),
896
+ is_error: true
897
+ };
898
+ }
899
+ function convertMessages(messages, model, isOAuthToken, cacheControl) {
900
+ const params = [];
901
+ const transformedMessages = Message.transformMessages(messages, model, normalizeToolCallId);
902
+ for (const msg of transformedMessages) {
903
+ if (msg.role === "user") {
904
+ const blocks = msg.parts.map((item) => {
905
+ if (item.type === "text") return {
906
+ type: "text",
907
+ text: sanitizeSurrogates(item.text)
908
+ };
909
+ return {
910
+ type: "image",
911
+ source: {
912
+ type: "base64",
913
+ media_type: item.mimeType,
914
+ data: item.data
915
+ }
916
+ };
917
+ });
918
+ let filteredBlocks = !model.input.includes("image") ? blocks.filter((b) => b.type !== "image") : blocks;
919
+ filteredBlocks = filteredBlocks.filter((b) => b.type === "text" ? b.text.trim().length > 0 : true);
920
+ if (filteredBlocks.length === 0) continue;
921
+ params.push({
922
+ role: "user",
923
+ content: filteredBlocks
924
+ });
925
+ continue;
926
+ }
927
+ if (msg.stopReason === "error" || msg.stopReason === "aborted") continue;
928
+ assertReplayableAssistant(msg);
929
+ const assistantBlocks = [];
930
+ const toolResults = [];
931
+ for (const block of msg.parts) if (block.type === "text") {
932
+ if (block.text.trim().length === 0) continue;
933
+ assistantBlocks.push({
934
+ type: "text",
935
+ text: sanitizeSurrogates(block.text)
936
+ });
937
+ } else if (block.type === "thinking") {
938
+ if (block.thinking.trim().length === 0) continue;
939
+ if (!block.thinkingSignature || block.thinkingSignature.trim().length === 0) assistantBlocks.push({
940
+ type: "text",
941
+ text: sanitizeSurrogates(block.thinking)
942
+ });
943
+ else assistantBlocks.push({
944
+ type: "thinking",
945
+ thinking: sanitizeSurrogates(block.thinking),
946
+ signature: block.thinkingSignature
947
+ });
948
+ } else if (block.type === "toolCall") {
949
+ assistantBlocks.push({
950
+ type: "tool_use",
951
+ id: block.callID,
952
+ name: isOAuthToken ? toClaudeCodeName(block.name) : block.name,
953
+ input: block.arguments ?? {}
954
+ });
955
+ if (block.status === "pending" || block.status === "running") toolResults.push(buildSyntheticToolResult(block));
956
+ else toolResults.push({
957
+ type: "tool_result",
958
+ tool_use_id: block.callID,
959
+ content: convertContentBlocks(block.result.content),
960
+ is_error: block.result.isError
961
+ });
962
+ }
963
+ if (assistantBlocks.length > 0) params.push({
964
+ role: "assistant",
965
+ content: assistantBlocks
966
+ });
967
+ if (toolResults.length > 0) params.push({
968
+ role: "user",
969
+ content: toolResults
970
+ });
971
+ }
972
+ if (cacheControl && params.length > 0) {
973
+ const lastMessage = params[params.length - 1];
974
+ if (lastMessage.role === "user") {
975
+ if (Array.isArray(lastMessage.content)) {
976
+ const lastBlock = lastMessage.content[lastMessage.content.length - 1];
977
+ if (lastBlock && (lastBlock.type === "text" || lastBlock.type === "image" || lastBlock.type === "tool_result")) lastBlock.cache_control = cacheControl;
978
+ } else if (typeof lastMessage.content === "string") lastMessage.content = [{
979
+ type: "text",
980
+ text: lastMessage.content,
981
+ cache_control: cacheControl
982
+ }];
983
+ }
984
+ }
985
+ return params;
986
+ }
987
+ function convertTools(tools, isOAuthToken) {
988
+ if (!tools) return [];
989
+ return tools.map((tool) => {
990
+ const jsonSchema = tool.parameters;
991
+ return {
992
+ name: isOAuthToken ? toClaudeCodeName(tool.name) : tool.name,
993
+ description: tool.description,
994
+ input_schema: {
995
+ type: "object",
996
+ properties: jsonSchema.properties || {},
997
+ required: jsonSchema.required || []
998
+ }
999
+ };
1000
+ });
1001
+ }
1002
+ function mapStopReason(reason) {
1003
+ switch (reason) {
1004
+ case "end_turn": return "stop";
1005
+ case "max_tokens": return "length";
1006
+ case "tool_use": return "toolUse";
1007
+ case "pause_turn":
1008
+ case "stop_sequence": return "stop";
1009
+ case "refusal":
1010
+ case "sensitive": return "error";
1011
+ default: throw new Error("Unhandled Anthropic stop reason");
1012
+ }
1013
+ }
1014
+ function buildParams(model, context, isOAuthToken, options) {
1015
+ const { cacheControl } = getCacheControl(model.baseUrl, options?.cacheRetention);
1016
+ const params = {
1017
+ model: model.id,
1018
+ messages: convertMessages(context.messages, model, isOAuthToken, cacheControl),
1019
+ max_tokens: options?.maxTokens || model.maxTokens / 3 | 0,
1020
+ stream: true
1021
+ };
1022
+ if (isOAuthToken) {
1023
+ params.system = [{
1024
+ type: "text",
1025
+ text: "You are Claude Code, Anthropic's official CLI for Claude.",
1026
+ ...cacheControl ? { cache_control: cacheControl } : {}
1027
+ }];
1028
+ if (context.systemPrompt) params.system.push({
1029
+ type: "text",
1030
+ text: sanitizeSurrogates(context.systemPrompt),
1031
+ ...cacheControl ? { cache_control: cacheControl } : {}
1032
+ });
1033
+ } else if (context.systemPrompt) params.system = [{
1034
+ type: "text",
1035
+ text: sanitizeSurrogates(context.systemPrompt),
1036
+ ...cacheControl ? { cache_control: cacheControl } : {}
1037
+ }];
1038
+ if (options?.temperature !== void 0 && !options?.thinkingEnabled) params.temperature = options.temperature;
1039
+ if (context.tools) params.tools = convertTools(context.tools, isOAuthToken);
1040
+ if (options?.thinkingEnabled && model.reasoning) params.thinking = {
1041
+ type: "enabled",
1042
+ budget_tokens: options.thinkingBudgetTokens || 1024
1043
+ };
1044
+ if (options?.metadata) {
1045
+ const userId = options.metadata.user_id;
1046
+ if (typeof userId === "string") params.metadata = { user_id: userId };
1047
+ }
1048
+ if (options?.toolChoice) params.tool_choice = typeof options.toolChoice === "string" ? { type: options.toolChoice } : options.toolChoice;
1049
+ return params;
1050
+ }
1051
+ const streamAnthropic = (model, context, options) => {
1052
+ const stream = new AssistantMessageEventStream();
1053
+ (async () => {
1054
+ const output = Message.createAssistantMessage({
1055
+ role: "assistant",
1056
+ parts: [],
1057
+ protocol: model.protocol,
1058
+ provider: model.provider,
1059
+ model: model.id,
1060
+ usage: {
1061
+ input: 0,
1062
+ output: 0,
1063
+ cacheRead: 0,
1064
+ cacheWrite: 0,
1065
+ totalTokens: 0,
1066
+ cost: {
1067
+ input: 0,
1068
+ output: 0,
1069
+ cacheRead: 0,
1070
+ cacheWrite: 0,
1071
+ total: 0
1072
+ }
1073
+ },
1074
+ stopReason: "stop",
1075
+ time: {
1076
+ created: Date.now(),
1077
+ completed: Date.now()
1078
+ }
1079
+ });
1080
+ try {
1081
+ let client;
1082
+ let isOAuthToken;
1083
+ if (options?.client) {
1084
+ client = options.client;
1085
+ isOAuthToken = false;
1086
+ } else {
1087
+ const apiKey = options?.apiKey ?? getEnvApiKey(model.provider);
1088
+ if (!apiKey) throw new Error(`No API key for provider: ${model.provider.id}`);
1089
+ const created = createClient(model, apiKey, options?.interleavedThinking ?? true, options?.headers);
1090
+ client = created.client;
1091
+ isOAuthToken = created.isOAuthToken;
1092
+ }
1093
+ let params = buildParams(model, context, isOAuthToken, options);
1094
+ const nextParams = await options?.onPayload?.(params, model);
1095
+ if (nextParams !== void 0) params = nextParams;
1096
+ const anthropicStream = client.messages.stream({
1097
+ ...params,
1098
+ stream: true
1099
+ }, { signal: options?.signal });
1100
+ stream.push({
1101
+ type: "start",
1102
+ partial: output
1103
+ });
1104
+ const blocks = output.parts;
1105
+ for await (const event of anthropicStream) if (event.type === "message_start") {
1106
+ output.responseId = event.message.id;
1107
+ output.usage.input = event.message.usage.input_tokens || 0;
1108
+ output.usage.output = event.message.usage.output_tokens || 0;
1109
+ output.usage.cacheRead = event.message.usage.cache_read_input_tokens || 0;
1110
+ output.usage.cacheWrite = event.message.usage.cache_creation_input_tokens || 0;
1111
+ output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
1112
+ Model.calculateCost(model, output.usage);
1113
+ } else if (event.type === "content_block_start") {
1114
+ if (event.content_block.type === "text") {
1115
+ const block = {
1116
+ type: "text",
1117
+ text: "",
1118
+ index: event.index
1119
+ };
1120
+ output.parts.push(block);
1121
+ stream.push({
1122
+ type: "text.start",
1123
+ partIndex: output.parts.length - 1,
1124
+ partial: output
1125
+ });
1126
+ } else if (event.content_block.type === "thinking") {
1127
+ const block = {
1128
+ type: "thinking",
1129
+ thinking: "",
1130
+ thinkingSignature: "",
1131
+ index: event.index
1132
+ };
1133
+ output.parts.push(block);
1134
+ stream.push({
1135
+ type: "thinking.start",
1136
+ partIndex: output.parts.length - 1,
1137
+ partial: output
1138
+ });
1139
+ } else if (event.content_block.type === "redacted_thinking") {
1140
+ const block = {
1141
+ type: "thinking",
1142
+ thinking: "[Reasoning redacted]",
1143
+ thinkingSignature: event.content_block.data,
1144
+ redacted: true,
1145
+ index: event.index
1146
+ };
1147
+ output.parts.push(block);
1148
+ stream.push({
1149
+ type: "thinking.start",
1150
+ partIndex: output.parts.length - 1,
1151
+ partial: output
1152
+ });
1153
+ } else if (event.content_block.type === "tool_use") {
1154
+ const block = {
1155
+ type: "toolCall",
1156
+ callID: event.content_block.id,
1157
+ name: isOAuthToken ? fromClaudeCodeName(event.content_block.name, context.tools) : event.content_block.name,
1158
+ arguments: event.content_block.input ?? {},
1159
+ partialJson: "",
1160
+ status: "pending",
1161
+ time: {
1162
+ start: Date.now(),
1163
+ end: Date.now()
1164
+ },
1165
+ index: event.index
1166
+ };
1167
+ output.parts.push(block);
1168
+ stream.push({
1169
+ type: "toolcall.start",
1170
+ partIndex: output.parts.length - 1,
1171
+ partial: output
1172
+ });
1173
+ }
1174
+ } else if (event.type === "content_block_delta") {
1175
+ const partIndex = blocks.findIndex((b) => b.index === event.index);
1176
+ const block = blocks[partIndex];
1177
+ if (!block) continue;
1178
+ if (event.delta.type === "text_delta" && block.type === "text") {
1179
+ block.text += event.delta.text;
1180
+ stream.push({
1181
+ type: "text.delta",
1182
+ partIndex,
1183
+ delta: event.delta.text,
1184
+ partial: output
1185
+ });
1186
+ } else if (event.delta.type === "thinking_delta" && block.type === "thinking") {
1187
+ block.thinking += event.delta.thinking;
1188
+ stream.push({
1189
+ type: "thinking.delta",
1190
+ partIndex,
1191
+ delta: event.delta.thinking,
1192
+ partial: output
1193
+ });
1194
+ } else if (event.delta.type === "input_json_delta" && block.type === "toolCall") {
1195
+ block.partialJson += event.delta.partial_json;
1196
+ block.arguments = parseStreamingJson(block.partialJson);
1197
+ stream.push({
1198
+ type: "toolcall.delta",
1199
+ partIndex,
1200
+ delta: event.delta.partial_json,
1201
+ partial: output
1202
+ });
1203
+ } else if (event.delta.type === "signature_delta" && block.type === "thinking") {
1204
+ block.thinkingSignature = block.thinkingSignature || "";
1205
+ block.thinkingSignature += event.delta.signature;
1206
+ }
1207
+ } else if (event.type === "content_block_stop") {
1208
+ const partIndex = blocks.findIndex((b) => b.index === event.index);
1209
+ const block = blocks[partIndex];
1210
+ if (block) {
1211
+ delete block.index;
1212
+ if (block.type === "text") stream.push({
1213
+ type: "text.end",
1214
+ partIndex,
1215
+ content: block.text,
1216
+ partial: output
1217
+ });
1218
+ else if (block.type === "thinking") stream.push({
1219
+ type: "thinking.end",
1220
+ partIndex,
1221
+ content: block.thinking,
1222
+ partial: output
1223
+ });
1224
+ else if (block.type === "toolCall") {
1225
+ block.arguments = parseStreamingJson(block.partialJson);
1226
+ delete block.partialJson;
1227
+ stream.push({
1228
+ type: "toolcall.end",
1229
+ partIndex,
1230
+ toolCall: block,
1231
+ partial: output
1232
+ });
1233
+ }
1234
+ }
1235
+ } else if (event.type === "message_delta") {
1236
+ if (event.delta.stop_reason) output.stopReason = mapStopReason(event.delta.stop_reason);
1237
+ if (event.usage.input_tokens != null) output.usage.input = event.usage.input_tokens;
1238
+ if (event.usage.output_tokens != null) output.usage.output = event.usage.output_tokens;
1239
+ if (event.usage.cache_read_input_tokens != null) output.usage.cacheRead = event.usage.cache_read_input_tokens;
1240
+ if (event.usage.cache_creation_input_tokens != null) output.usage.cacheWrite = event.usage.cache_creation_input_tokens;
1241
+ output.usage.totalTokens = output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite;
1242
+ Model.calculateCost(model, output.usage);
1243
+ }
1244
+ if (options?.signal?.aborted) throw new Error("Request was aborted");
1245
+ if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error("An unknown error occurred");
1246
+ output.time.completed = Date.now();
1247
+ stream.push({
1248
+ type: "done",
1249
+ reason: output.stopReason,
1250
+ message: output
1251
+ });
1252
+ stream.end();
1253
+ } catch (error) {
1254
+ for (const block of output.parts) delete block.index;
1255
+ output.time.completed = Date.now();
1256
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
1257
+ output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
1258
+ stream.push({
1259
+ type: "error",
1260
+ reason: output.stopReason,
1261
+ error: output
1262
+ });
1263
+ stream.end();
1264
+ }
1265
+ })();
1266
+ return stream;
1267
+ };
1268
+ const streamSimpleAnthropic = (model, context, options) => {
1269
+ const apiKey = options?.apiKey || getEnvApiKey(model.provider);
1270
+ if (!apiKey) throw new Error(`No API key for provider: ${model.provider.id}`);
1271
+ const base = Stream.buildBaseOptions(model, options, apiKey);
1272
+ if (!options?.reasoning) return streamAnthropic(model, context, {
1273
+ ...base,
1274
+ thinkingEnabled: false
1275
+ });
1276
+ const adjusted = Stream.adjustMaxTokensForThinking(base.maxTokens || 0, model.maxTokens, options.reasoning, options.thinkingBudgets);
1277
+ return streamAnthropic(model, context, {
1278
+ ...base,
1279
+ maxTokens: adjusted.maxTokens,
1280
+ thinkingEnabled: true,
1281
+ thinkingBudgetTokens: adjusted.thinkingBudget
1282
+ });
1283
+ };
1284
+ //#endregion
1285
+ //#region src/provider/register.ts
1286
+ const providerModules = [["providers/anthropic/index.ts", {
1287
+ protocol: Model.KnownProtocolEnum.anthropicMessages,
1288
+ stream: streamAnthropic,
1289
+ streamSimple: streamSimpleAnthropic
1290
+ }]];
1291
+ for (const [path, provider] of providerModules) Stream.registerProtocolProvider(provider, path);
1292
+ //#endregion
1293
+ //#region src/utils/validation.ts
1294
+ /**
1295
+ * @description Validation powered by ajv, TypeBox natively doesn't provide data validation.
1296
+ */
1297
+ const ajv = new Ajv({
1298
+ allErrors: true,
1299
+ strict: false,
1300
+ coerceTypes: true
1301
+ });
1302
+ addFormats(ajv);
1303
+ /**
1304
+ * Validates tool call arguments against the tool's TypeBox schema
1305
+ */
1306
+ function validateToolArguments(tool, toolExecution) {
1307
+ const validate = ajv.compile(tool.parameters);
1308
+ const args = structuredClone(toolExecution.rawArgs);
1309
+ if (validate(args)) return args;
1310
+ const errors = validate.errors?.map((err) => {
1311
+ return ` - ${err.instancePath ? err.instancePath.substring(1) : err.params?.missingProperty || "root"}: ${err.message}`;
1312
+ }).join("\n") || "Unknown Validation Error";
1313
+ throw new Error([
1314
+ `Validation Failed For Tool "${toolExecution.name}"`,
1315
+ `${errors}\n`,
1316
+ "Received Arguments:",
1317
+ `${JSON.stringify(toolExecution.rawArgs, null, 2)}\n`
1318
+ ].join("\n"));
1319
+ }
1320
+ //#endregion
1321
+ //#region src/agent/loop.ts
1322
+ let Loop;
1323
+ (function(_Loop) {
1324
+ function createAgentStream() {
1325
+ return new EventStream((event) => event.type === "agent.end", (event) => event.type === "agent.end" ? event.messages : []);
1326
+ }
1327
+ const AgentContextError = _Loop.AgentContextError = NamedError.create("AgentContextError", Type.Object({ message: Type.String() }));
1328
+ function snapshotAssistantMessage(message) {
1329
+ return structuredClone(message);
1330
+ }
1331
+ function snapshotAssistantPartEvent(message, partIndex) {
1332
+ const snapshot = snapshotAssistantMessage(message);
1333
+ const part = snapshot.parts[partIndex];
1334
+ if (!part) throw new Error(`Assistant message part at index ${partIndex} was not found`);
1335
+ return {
1336
+ message: snapshot,
1337
+ part
1338
+ };
1339
+ }
1340
+ async function emitEvent(emit, event) {
1341
+ await emit(event);
1342
+ }
1343
+ async function streamAssistantResponse(config, context, emit, streamFn, signal) {
1344
+ let messages = context.messages;
1345
+ if (config.transformContext) messages = await config.transformContext(messages, signal);
1346
+ const llmMessages = await config.convertToLlm(messages);
1347
+ const llmContext = {
1348
+ systemPrompt: context.systemPrompt,
1349
+ messages: llmMessages,
1350
+ tools: context.tools
1351
+ };
1352
+ const streamFunction = streamFn || Stream.streamSimple;
1353
+ const resolvedApiKey = (config.getApiKey ? await config.getApiKey(config.model.provider) : void 0) || config.apiKey;
1354
+ const events = await streamFunction(config.model, llmContext, {
1355
+ ...config,
1356
+ apiKey: resolvedApiKey,
1357
+ signal
1358
+ });
1359
+ let partialMessage = null;
1360
+ let started = false;
1361
+ const ensureMessageStarted = async (message) => {
1362
+ if (started) return;
1363
+ started = true;
1364
+ await emitEvent(emit, {
1365
+ type: "message.start",
1366
+ message: snapshotAssistantMessage(message)
1367
+ });
1368
+ };
1369
+ const emitMessageUpdate = async (message) => {
1370
+ await emitEvent(emit, {
1371
+ type: "message.update",
1372
+ message: snapshotAssistantMessage(message)
1373
+ });
1374
+ };
1375
+ const emitPartStart = async (message, partIndex) => {
1376
+ await emitEvent(emit, {
1377
+ type: "message.part.start",
1378
+ partIndex,
1379
+ ...snapshotAssistantPartEvent(message, partIndex)
1380
+ });
1381
+ };
1382
+ const emitPartUpdate = async (message, partIndex) => {
1383
+ await emitEvent(emit, {
1384
+ type: "message.part.update",
1385
+ partIndex,
1386
+ ...snapshotAssistantPartEvent(message, partIndex),
1387
+ source: "llm"
1388
+ });
1389
+ };
1390
+ const emitPartEnd = async (message, partIndex) => {
1391
+ await emitEvent(emit, {
1392
+ type: "message.part.end",
1393
+ partIndex,
1394
+ ...snapshotAssistantPartEvent(message, partIndex)
1395
+ });
1396
+ };
1397
+ for await (const event of events) switch (event.type) {
1398
+ case "start":
1399
+ partialMessage = event.partial;
1400
+ await ensureMessageStarted(partialMessage);
1401
+ break;
1402
+ case "text.start":
1403
+ case "thinking.start":
1404
+ case "toolcall.start":
1405
+ partialMessage = event.partial;
1406
+ await ensureMessageStarted(partialMessage);
1407
+ await emitPartStart(partialMessage, event.partIndex);
1408
+ break;
1409
+ case "text.delta":
1410
+ case "thinking.delta":
1411
+ case "toolcall.delta":
1412
+ partialMessage = event.partial;
1413
+ await ensureMessageStarted(partialMessage);
1414
+ await emitPartUpdate(partialMessage, event.partIndex);
1415
+ break;
1416
+ case "text.end":
1417
+ case "thinking.end":
1418
+ case "toolcall.end":
1419
+ partialMessage = event.partial;
1420
+ await ensureMessageStarted(partialMessage);
1421
+ await emitPartEnd(partialMessage, event.partIndex);
1422
+ await emitMessageUpdate(partialMessage);
1423
+ break;
1424
+ case "done":
1425
+ await ensureMessageStarted(event.message);
1426
+ await emitEvent(emit, {
1427
+ type: "message.end",
1428
+ message: snapshotAssistantMessage(event.message)
1429
+ });
1430
+ return event.message;
1431
+ case "error":
1432
+ await ensureMessageStarted(event.error);
1433
+ await emitEvent(emit, {
1434
+ type: "message.end",
1435
+ message: snapshotAssistantMessage(event.error)
1436
+ });
1437
+ return event.error;
1438
+ }
1439
+ const finalMessage = await events.result();
1440
+ await ensureMessageStarted(finalMessage);
1441
+ await emitEvent(emit, {
1442
+ type: "message.end",
1443
+ message: snapshotAssistantMessage(finalMessage)
1444
+ });
1445
+ return finalMessage;
1446
+ }
1447
+ async function executeToolCalls(config, currentContext, message, toolCalls, emit, signal) {
1448
+ if (config.toolExecution === "sequential") return executeToolCallsSequential(config, currentContext, message, toolCalls, emit, signal);
1449
+ return executeToolCallsParallel(config, currentContext, message, toolCalls, emit, signal);
1450
+ }
1451
+ async function executeToolCallsSequential(config, currentContext, message, toolCalls, emit, signal) {
1452
+ for (const toolCall of toolCalls) {
1453
+ const toolCallInFlight = {
1454
+ callID: toolCall.callID,
1455
+ name: toolCall.name,
1456
+ rawArgs: toolCall.arguments
1457
+ };
1458
+ await emitEvent(emit, {
1459
+ type: "tool.execution.start",
1460
+ ...toolCallInFlight
1461
+ });
1462
+ const prepared = await prepareToolCall(config, currentContext, message, toolCallInFlight, signal);
1463
+ if (prepared.error) {
1464
+ const error = {
1465
+ status: "error",
1466
+ result: {
1467
+ content: [{
1468
+ type: "text",
1469
+ text: prepared.error.message
1470
+ }],
1471
+ details: prepared.error.details,
1472
+ isError: true
1473
+ }
1474
+ };
1475
+ await emitToolCallTerminalResult(toolCall, prepared.runnable, message, emit, error);
1476
+ } else {
1477
+ const runnable = {
1478
+ toolCall,
1479
+ runnable: prepared.runnable,
1480
+ tool: prepared.tool
1481
+ };
1482
+ const executed = await executeRunnableToolCall(runnable, message, emit, signal);
1483
+ if (executed.error) {
1484
+ const error = {
1485
+ status: "error",
1486
+ result: {
1487
+ content: [{
1488
+ type: "text",
1489
+ text: executed.error.message
1490
+ }],
1491
+ details: executed.error.details,
1492
+ isError: true
1493
+ }
1494
+ };
1495
+ await emitToolCallTerminalResult(runnable.toolCall, runnable.runnable, message, emit, error);
1496
+ } else await finalizeExecutedToolCall(config, currentContext, runnable.toolCall, runnable.runnable, message, emit, executed.result);
1497
+ }
1498
+ }
1499
+ }
1500
+ async function executeToolCallsParallel(config, currentContext, message, toolCalls, emit, signal) {
1501
+ const runnables = [];
1502
+ for (const toolCall of toolCalls) {
1503
+ const toolCallInFlight = {
1504
+ callID: toolCall.callID,
1505
+ name: toolCall.name,
1506
+ rawArgs: toolCall.arguments
1507
+ };
1508
+ await emitEvent(emit, {
1509
+ type: "tool.execution.start",
1510
+ ...toolCallInFlight
1511
+ });
1512
+ const prepared = await prepareToolCall(config, currentContext, message, toolCallInFlight, signal);
1513
+ if (prepared.error) {
1514
+ const error = {
1515
+ status: "error",
1516
+ result: {
1517
+ content: [{
1518
+ type: "text",
1519
+ text: prepared.error.message
1520
+ }],
1521
+ details: prepared.error.details,
1522
+ isError: true
1523
+ }
1524
+ };
1525
+ await emitToolCallTerminalResult(toolCall, prepared.runnable, message, emit, error);
1526
+ } else runnables.push({
1527
+ toolCall,
1528
+ runnable: prepared.runnable,
1529
+ tool: prepared.tool
1530
+ });
1531
+ }
1532
+ const runningExecutions = runnables.map((runnable) => ({
1533
+ runnable,
1534
+ execution: executeRunnableToolCall(runnable, message, emit, signal)
1535
+ }));
1536
+ for (const running of runningExecutions) {
1537
+ const executed = await running.execution;
1538
+ const { runnable } = running;
1539
+ if (executed.error) {
1540
+ const error = {
1541
+ status: "error",
1542
+ result: {
1543
+ content: [{
1544
+ type: "text",
1545
+ text: executed.error.message
1546
+ }],
1547
+ details: executed.error.details,
1548
+ isError: true
1549
+ }
1550
+ };
1551
+ await emitToolCallTerminalResult(runnable.toolCall, runnable.runnable, message, emit, error);
1552
+ } else await finalizeExecutedToolCall(config, currentContext, runnable.toolCall, runnable.runnable, message, emit, executed.result);
1553
+ }
1554
+ }
1555
+ async function prepareToolCall(config, currentContext, assistantMessage, toolCallInFlight, signal) {
1556
+ const tool = currentContext.tools?.find((t) => t.name === toolCallInFlight.name);
1557
+ if (!tool) return {
1558
+ error: {
1559
+ kind: "error",
1560
+ message: `Tool ${toolCallInFlight.name} Not Found`
1561
+ },
1562
+ runnable: toolCallInFlight
1563
+ };
1564
+ try {
1565
+ toolCallInFlight.args = validateToolArguments(tool, toolCallInFlight);
1566
+ if (config.beforeToolExecution) {
1567
+ const beforeResult = await config.beforeToolExecution({
1568
+ context: currentContext,
1569
+ assistantMessage,
1570
+ toolCall: toolCallInFlight
1571
+ }, signal);
1572
+ if (beforeResult?.block) return {
1573
+ error: {
1574
+ kind: "blocked",
1575
+ message: beforeResult?.reason || "Tool Execution was Blocked",
1576
+ details: beforeResult?.details
1577
+ },
1578
+ runnable: toolCallInFlight
1579
+ };
1580
+ }
1581
+ return {
1582
+ runnable: toolCallInFlight,
1583
+ tool
1584
+ };
1585
+ } catch (err) {
1586
+ return {
1587
+ error: {
1588
+ kind: "error",
1589
+ message: err instanceof Error ? err.message : String(err)
1590
+ },
1591
+ runnable: toolCallInFlight
1592
+ };
1593
+ }
1594
+ }
1595
+ async function executeRunnableToolCall(toolCallRunnable, message, emit, signal) {
1596
+ const { toolCall, runnable, tool } = toolCallRunnable;
1597
+ const { partIndex, ...pendingPart } = toolCall;
1598
+ try {
1599
+ return { result: await tool.execute(runnable.callID, runnable.args, signal, async (result) => {
1600
+ const runningResult = {
1601
+ status: "running",
1602
+ partial: result.partial
1603
+ };
1604
+ await emitEvent(emit, {
1605
+ type: "tool.execution.update",
1606
+ ...runnable,
1607
+ ...runningResult
1608
+ });
1609
+ const runningPart = {
1610
+ ...pendingPart,
1611
+ ...runningResult
1612
+ };
1613
+ message.parts[partIndex] = runningPart;
1614
+ await emitEvent(emit, {
1615
+ type: "message.part.update",
1616
+ message,
1617
+ partIndex,
1618
+ part: runningPart,
1619
+ source: "tool"
1620
+ });
1621
+ }) };
1622
+ } catch (err) {
1623
+ return { error: { message: err instanceof Error ? err.message : String(err) } };
1624
+ }
1625
+ }
1626
+ async function emitToolCallTerminalResult(toolCall, runnable, message, emit, result) {
1627
+ const { partIndex, ...pendingPart } = toolCall;
1628
+ const { time } = pendingPart;
1629
+ await emitEvent(emit, {
1630
+ type: "tool.execution.end",
1631
+ ...runnable,
1632
+ ...result
1633
+ });
1634
+ const part = {
1635
+ ...pendingPart,
1636
+ ...result,
1637
+ time: {
1638
+ start: time.start,
1639
+ end: Date.now()
1640
+ }
1641
+ };
1642
+ message.parts[partIndex] = part;
1643
+ await emitEvent(emit, {
1644
+ type: "message.part.start",
1645
+ message,
1646
+ partIndex,
1647
+ part
1648
+ });
1649
+ await emitEvent(emit, {
1650
+ type: "message.part.end",
1651
+ message,
1652
+ partIndex,
1653
+ part
1654
+ });
1655
+ await emitEvent(emit, {
1656
+ type: "message.update",
1657
+ message
1658
+ });
1659
+ }
1660
+ async function finalizeExecutedToolCall(config, currentContext, toolCall, runnable, message, emit, result, signal) {
1661
+ if (config.afterToolExecution) {
1662
+ const afterResult = await config.afterToolExecution({
1663
+ context: currentContext,
1664
+ assistantMessage: message,
1665
+ toolCall: runnable,
1666
+ result
1667
+ }, signal);
1668
+ if (afterResult) {
1669
+ await emitToolCallTerminalResult(toolCall, runnable, message, emit, afterResult);
1670
+ return;
1671
+ }
1672
+ }
1673
+ await emitToolCallTerminalResult(toolCall, runnable, message, emit, result);
1674
+ }
1675
+ /**
1676
+ * Main core loop shared by run and runContinue.
1677
+ */
1678
+ async function runLoop(config, currentContext, newMessages, emit, streamFn, signal) {
1679
+ let firstTurn = true;
1680
+ let pendingMessages = await config.getSteeringMessages?.() || [];
1681
+ while (true) {
1682
+ let hasMoreToolCalls = true;
1683
+ while (hasMoreToolCalls || pendingMessages.length > 0) {
1684
+ if (!firstTurn) await emitEvent(emit, { type: "turn.start" });
1685
+ else firstTurn = false;
1686
+ if (pendingMessages.length > 0) {
1687
+ for (const message of pendingMessages) {
1688
+ await emitEvent(emit, {
1689
+ type: "message.start",
1690
+ message
1691
+ });
1692
+ for (const [partIndex, part] of message.parts.entries()) {
1693
+ await emitEvent(emit, {
1694
+ type: "message.part.start",
1695
+ message,
1696
+ partIndex,
1697
+ part
1698
+ });
1699
+ await emitEvent(emit, {
1700
+ type: "message.part.end",
1701
+ message,
1702
+ partIndex,
1703
+ part
1704
+ });
1705
+ await emitEvent(emit, {
1706
+ type: "message.update",
1707
+ message
1708
+ });
1709
+ }
1710
+ await emitEvent(emit, {
1711
+ type: "message.end",
1712
+ message
1713
+ });
1714
+ currentContext.messages.push(message);
1715
+ newMessages.push(message);
1716
+ }
1717
+ pendingMessages = [];
1718
+ }
1719
+ const message = await streamAssistantResponse(config, currentContext, emit, streamFn, signal);
1720
+ if (message.stopReason === "error" || message.stopReason === "aborted") {
1721
+ currentContext.messages.push(message);
1722
+ newMessages.push(message);
1723
+ await emitEvent(emit, {
1724
+ type: "turn.end",
1725
+ message
1726
+ });
1727
+ await emitEvent(emit, {
1728
+ type: "agent.end",
1729
+ messages: newMessages
1730
+ });
1731
+ return;
1732
+ }
1733
+ const toolCalls = message.parts.map((part, index) => ({
1734
+ ...part,
1735
+ partIndex: index
1736
+ })).filter((part) => part.type === "toolCall" && part.status === "pending");
1737
+ hasMoreToolCalls = toolCalls.length > 0;
1738
+ if (hasMoreToolCalls) await executeToolCalls(config, currentContext, message, toolCalls, emit, signal);
1739
+ currentContext.messages.push(message);
1740
+ newMessages.push(message);
1741
+ await emitEvent(emit, {
1742
+ type: "turn.end",
1743
+ message
1744
+ });
1745
+ pendingMessages = await config.getSteeringMessages?.() || [];
1746
+ }
1747
+ const followUpMessages = await config.getFollowUpMessages?.() || [];
1748
+ if (followUpMessages.length > 0) {
1749
+ pendingMessages = followUpMessages;
1750
+ continue;
1751
+ }
1752
+ break;
1753
+ }
1754
+ await emitEvent(emit, {
1755
+ type: "agent.end",
1756
+ messages: newMessages
1757
+ });
1758
+ }
1759
+ async function runAgentLoop(config, context, prompts, emit, streamFn, signal) {
1760
+ /**
1761
+ * maintain 2 arrays to represent state, `context` the actual full state sent to the LLM,
1762
+ * `newMessages` for intermediate current loop state.
1763
+ * think of newMessages as subset of context.messages for the running current loop.
1764
+ * they do move at the same speed staring with initial user prompts.
1765
+ * */
1766
+ const newMessages = [...prompts];
1767
+ const currentContext = {
1768
+ ...context,
1769
+ messages: [...context.messages, ...prompts]
1770
+ };
1771
+ await emitEvent(emit, { type: "agent.start" });
1772
+ await emitEvent(emit, { type: "turn.start" });
1773
+ for (const prompt of prompts) {
1774
+ await emitEvent(emit, {
1775
+ type: "message.start",
1776
+ message: prompt
1777
+ });
1778
+ for (const [partIndex, part] of prompt.parts.entries()) {
1779
+ await emitEvent(emit, {
1780
+ type: "message.part.start",
1781
+ message: prompt,
1782
+ partIndex,
1783
+ part
1784
+ });
1785
+ await emitEvent(emit, {
1786
+ type: "message.part.end",
1787
+ message: prompt,
1788
+ partIndex,
1789
+ part
1790
+ });
1791
+ }
1792
+ await emitEvent(emit, {
1793
+ type: "message.end",
1794
+ message: prompt
1795
+ });
1796
+ }
1797
+ await runLoop(config, currentContext, newMessages, emit, streamFn, signal);
1798
+ return newMessages;
1799
+ }
1800
+ _Loop.runAgentLoop = runAgentLoop;
1801
+ async function runAgentLoopContinue(config, context, emit, streamFn, signal) {
1802
+ if (context.messages.length === 0) throw new AgentContextError({ message: "connot continue: no messages in context" });
1803
+ if (context.messages[context.messages.length - 1]?.role === "assistant") throw new AgentContextError({ message: "cannot continue from message role: assistant" });
1804
+ const newMessages = [];
1805
+ const currentContext = { ...context };
1806
+ await emitEvent(emit, { type: "agent.start" });
1807
+ await emitEvent(emit, { type: "turn.start" });
1808
+ await runLoop(config, currentContext, newMessages, emit, streamFn, signal);
1809
+ return newMessages;
1810
+ }
1811
+ _Loop.runAgentLoopContinue = runAgentLoopContinue;
1812
+ function run(config, context, prompts, streamFn, signal) {
1813
+ const stream = createAgentStream();
1814
+ runAgentLoop(config, context, prompts, async (event) => {
1815
+ stream.push(event);
1816
+ }, streamFn, signal).then((messages) => {
1817
+ stream.end(messages);
1818
+ });
1819
+ return stream;
1820
+ }
1821
+ _Loop.run = run;
1822
+ function runContinue(config, context, streamFn, signal) {
1823
+ const stream = createAgentStream();
1824
+ runAgentLoopContinue(config, context, async (event) => {
1825
+ stream.push(event);
1826
+ }, streamFn, signal).then((messages) => {
1827
+ stream.end(messages);
1828
+ });
1829
+ return stream;
1830
+ }
1831
+ _Loop.runContinue = runContinue;
1832
+ })(Loop || (Loop = {}));
1833
+ //#endregion
1834
+ //#region src/agent/agent.ts
1835
+ let Agent;
1836
+ (function(_Agent) {
1837
+ _Agent.ToolTerminalResultSchema = Type.Union([Message.ToolCompletedSchema, Message.ToolErrorSchema]);
1838
+ _Agent.ToolResultSchema = Type.Union([
1839
+ Message.ToolRunningSchema,
1840
+ Message.ToolCompletedSchema,
1841
+ Message.ToolErrorSchema
1842
+ ]);
1843
+ function defineTool(tool) {
1844
+ return tool;
1845
+ }
1846
+ _Agent.defineTool = defineTool;
1847
+ _Agent.ToolCallInFlightSchema = Type.Object({
1848
+ callID: Type.String(),
1849
+ name: Type.String(),
1850
+ rawArgs: Type.Record(Type.String(), Type.Unknown()),
1851
+ args: Type.Optional(Type.Unknown())
1852
+ });
1853
+ const ModelNotFoundErr = _Agent.ModelNotFoundErr = NamedError.create("ModelNotFoundErr", Type.Object({
1854
+ message: Type.String(),
1855
+ provider: Type.String(),
1856
+ model: Type.String()
1857
+ }));
1858
+ const ModelNotConfiguredErr = _Agent.ModelNotConfiguredErr = NamedError.create("ModelNotConfiguredErr", Type.Object({ message: Type.String() }));
1859
+ const AgentInStreamingErr = _Agent.AgentInStreamingErr = NamedError.create("AgentInStreamingErr", Type.Object({
1860
+ message: Type.String(),
1861
+ name: Type.String()
1862
+ }));
1863
+ class Instance {
1864
+ _state;
1865
+ listeners = /* @__PURE__ */ new Set();
1866
+ abortController;
1867
+ convertToLlm;
1868
+ transformContext;
1869
+ steeringQueue = [];
1870
+ followUpQueue = [];
1871
+ steeringMode;
1872
+ followUpMode;
1873
+ streamFn;
1874
+ _sessionId;
1875
+ getApiKey;
1876
+ _onPayload;
1877
+ runningPrompt;
1878
+ resolveRunningPrompt;
1879
+ _thinkingBudgets;
1880
+ _transport;
1881
+ _maxRetryDelayMs;
1882
+ _toolExecution;
1883
+ _beforeToolExecution;
1884
+ _afterToolExecution;
1885
+ constructor(name, model, opts = {}) {
1886
+ this._state = {
1887
+ systemPrompt: "",
1888
+ thinkingLevel: "off",
1889
+ tools: [],
1890
+ messages: [],
1891
+ isStreaming: false,
1892
+ streamMessage: null,
1893
+ pendingToolCalls: /* @__PURE__ */ new Set(),
1894
+ error: void 0,
1895
+ ...opts.initialState,
1896
+ name,
1897
+ model
1898
+ };
1899
+ /**
1900
+ * Transformation logic to prepare messages for the LLM.
1901
+ * * @remarks
1902
+ * Currently just forwards messages as-is. Modify this logic when
1903
+ * specific formatting or filtering is required.
1904
+ * A good example is using user message parts with custom content
1905
+ * * @default
1906
+ * forwards messages as is.
1907
+ */
1908
+ this.convertToLlm = opts.convertToLlm || ((messages) => messages);
1909
+ this.transformContext = opts.transformContext;
1910
+ this.steeringMode = opts.steeringMode || "one-at-a-time";
1911
+ this.followUpMode = opts.followUpMode || "one-at-a-time";
1912
+ this.streamFn = opts.streamFn || Stream.streamSimple;
1913
+ this._sessionId = opts.sessionId;
1914
+ this.getApiKey = opts.getApiKey;
1915
+ this._onPayload = opts.onPayload;
1916
+ this._thinkingBudgets = opts.thinkingBudgets;
1917
+ this._transport = opts.transport ?? "sse";
1918
+ this._maxRetryDelayMs = opts.maxRetryDelayMs;
1919
+ this._toolExecution = opts.toolExecution ?? "parallel";
1920
+ this._beforeToolExecution = opts.beforeToolExecution;
1921
+ this._afterToolExecution = opts.afterToolExecution;
1922
+ }
1923
+ /**
1924
+ * Get the current session ID used for provider caching.
1925
+ */
1926
+ get sessionId() {
1927
+ return this._sessionId;
1928
+ }
1929
+ /**
1930
+ * Set the session ID for provider caching.
1931
+ * Call this when switching sessions (new session, branch, resume, etc).
1932
+ */
1933
+ set sessionId(value) {
1934
+ this._sessionId = value;
1935
+ }
1936
+ /**
1937
+ * Get the current thinking budgets.
1938
+ */
1939
+ get thinkingBudgets() {
1940
+ return this._thinkingBudgets;
1941
+ }
1942
+ /**
1943
+ * Set custom thinking budgets for token-based providers.
1944
+ */
1945
+ set thinkingBudgets(value) {
1946
+ this._thinkingBudgets = value;
1947
+ }
1948
+ /**
1949
+ * Get the current preferred transport.
1950
+ */
1951
+ get transport() {
1952
+ return this._transport;
1953
+ }
1954
+ /**
1955
+ * Set the preferred transport.
1956
+ */
1957
+ setTransport(value) {
1958
+ this._transport = value;
1959
+ }
1960
+ /**
1961
+ * Get the current max retry delay in milliseconds.
1962
+ */
1963
+ get maxRetryDelayMs() {
1964
+ return this._maxRetryDelayMs;
1965
+ }
1966
+ /**
1967
+ * Set the maximum delay to wait for server-requested retries.
1968
+ * Set to 0 to disable the cap.
1969
+ */
1970
+ set maxRetryDelayMs(value) {
1971
+ this._maxRetryDelayMs = value;
1972
+ }
1973
+ get toolExecution() {
1974
+ return this._toolExecution;
1975
+ }
1976
+ setToolExecution(value) {
1977
+ this._toolExecution = value;
1978
+ }
1979
+ setBeforeToolExecution(value) {
1980
+ this._beforeToolExecution = value;
1981
+ }
1982
+ setAfterToolExecution(value) {
1983
+ this._afterToolExecution = value;
1984
+ }
1985
+ get state() {
1986
+ return this._state;
1987
+ }
1988
+ subscribe(fn) {
1989
+ this.listeners.add(fn);
1990
+ return () => this.listeners.delete(fn);
1991
+ }
1992
+ setSystemPrompt(v) {
1993
+ this._state.systemPrompt = v;
1994
+ }
1995
+ setModel(m) {
1996
+ this._state.model = m;
1997
+ }
1998
+ setThinkingLevel(l) {
1999
+ this._state.thinkingLevel = l;
2000
+ }
2001
+ setSteeringMode(mode) {
2002
+ this.steeringMode = mode;
2003
+ }
2004
+ getSteeringMode() {
2005
+ return this.steeringMode;
2006
+ }
2007
+ setFollowUpMode(mode) {
2008
+ this.followUpMode = mode;
2009
+ }
2010
+ getFollowUpMode() {
2011
+ return this.followUpMode;
2012
+ }
2013
+ setTools(t) {
2014
+ this._state.tools = t;
2015
+ }
2016
+ replaceMessages(ms) {
2017
+ this._state.messages = ms.slice();
2018
+ }
2019
+ appendMessage(m) {
2020
+ this._state.messages = [...this._state.messages, m];
2021
+ }
2022
+ findMessageIndexById(messageId) {
2023
+ return this._state.messages.findIndex((message) => message.messageId === messageId);
2024
+ }
2025
+ replaceMessageById(message) {
2026
+ const messageIndex = this.findMessageIndexById(message.messageId);
2027
+ if (messageIndex === -1) return false;
2028
+ const messages = this._state.messages.slice();
2029
+ messages[messageIndex] = message;
2030
+ this._state.messages = messages;
2031
+ return true;
2032
+ }
2033
+ upsertMessage(message) {
2034
+ if (this.replaceMessageById(message)) return;
2035
+ this.appendMessage(message);
2036
+ }
2037
+ patchStoredAssistantPart(messageId, partIndex, part) {
2038
+ const messageIndex = this.findMessageIndexById(messageId);
2039
+ if (messageIndex === -1) return false;
2040
+ const messages = this._state.messages.slice();
2041
+ const existing = messages[messageIndex];
2042
+ if (!existing || existing.role !== "assistant") return false;
2043
+ const nextParts = existing.parts.slice();
2044
+ nextParts[partIndex] = part;
2045
+ messages[messageIndex] = {
2046
+ ...existing,
2047
+ parts: nextParts
2048
+ };
2049
+ this._state.messages = messages;
2050
+ return true;
2051
+ }
2052
+ /**
2053
+ * Queue a steering message while the agent is running.
2054
+ * Delivered after the current assistant turn finishes executing its tool calls,
2055
+ * before the next LLM call.
2056
+ */
2057
+ steer(m) {
2058
+ this.steeringQueue.push(m);
2059
+ }
2060
+ /**
2061
+ * Queue a follow-up message to be processed after the agent finishes.
2062
+ * Delivered only when agent has no more tool calls or steering messages.
2063
+ */
2064
+ followUp(m) {
2065
+ this.followUpQueue.push(m);
2066
+ }
2067
+ clearSteeringQueue() {
2068
+ this.steeringQueue = [];
2069
+ }
2070
+ clearFollowUpQueue() {
2071
+ this.followUpQueue = [];
2072
+ }
2073
+ clearAllQueues() {
2074
+ this.steeringQueue = [];
2075
+ this.followUpQueue = [];
2076
+ }
2077
+ hasQueuedMessages() {
2078
+ return this.steeringQueue.length > 0 || this.followUpQueue.length > 0;
2079
+ }
2080
+ dequeueSteeringMessages() {
2081
+ if (this.steeringMode === "one-at-a-time") {
2082
+ if (this.steeringQueue.length > 0) {
2083
+ const first = this.steeringQueue[0];
2084
+ this.steeringQueue = this.steeringQueue.slice(1);
2085
+ return [first];
2086
+ }
2087
+ return [];
2088
+ }
2089
+ const steering = this.steeringQueue.slice();
2090
+ this.steeringQueue = [];
2091
+ return steering;
2092
+ }
2093
+ dequeueFollowUpMessages() {
2094
+ if (this.followUpMode === "one-at-a-time") {
2095
+ if (this.followUpQueue.length > 0) {
2096
+ const first = this.followUpQueue[0];
2097
+ this.followUpQueue = this.followUpQueue.slice(1);
2098
+ return [first];
2099
+ }
2100
+ return [];
2101
+ }
2102
+ const followUp = this.followUpQueue.slice();
2103
+ this.followUpQueue = [];
2104
+ return followUp;
2105
+ }
2106
+ clearMessages() {
2107
+ this._state.messages = [];
2108
+ }
2109
+ abort() {
2110
+ this.abortController?.abort();
2111
+ }
2112
+ waitForIdle() {
2113
+ return this.runningPrompt ?? Promise.resolve();
2114
+ }
2115
+ reset() {
2116
+ this._state.messages = [];
2117
+ this._state.isStreaming = false;
2118
+ this._state.streamMessage = null;
2119
+ this._state.pendingToolCalls = /* @__PURE__ */ new Set();
2120
+ this._state.error = void 0;
2121
+ this.steeringQueue = [];
2122
+ this.followUpQueue = [];
2123
+ }
2124
+ getName() {
2125
+ return this._state.name;
2126
+ }
2127
+ ensureIdle() {
2128
+ if (this._state.isStreaming) throw new AgentInStreamingErr({
2129
+ message: "agent is already processing a prompt. Use steer() or followup() to queue messages, or wait for completion.",
2130
+ name: this._state.name
2131
+ });
2132
+ }
2133
+ async _runLoop(messages, opts) {
2134
+ const model = this._state.model;
2135
+ if (!model) throw new ModelNotConfiguredErr({ message: "no model configured yet" });
2136
+ this.runningPrompt = new Promise((resolve) => {
2137
+ this.resolveRunningPrompt = resolve;
2138
+ });
2139
+ this.abortController = new AbortController();
2140
+ this._state.isStreaming = true;
2141
+ this._state.streamMessage = null;
2142
+ this._state.error = void 0;
2143
+ const reasoning = this.state.thinkingLevel === "off" ? void 0 : this._state.thinkingLevel;
2144
+ const context = {
2145
+ systemPrompt: this._state.systemPrompt,
2146
+ messages: this._state.messages.slice(),
2147
+ tools: this._state.tools
2148
+ };
2149
+ let skipInitialSteeringPoll = opts?.skipInitialSteeringPoll === true;
2150
+ const config = {
2151
+ model,
2152
+ reasoning,
2153
+ sessionId: this._sessionId,
2154
+ onPayload: this._onPayload,
2155
+ transport: this._transport,
2156
+ thinkingBudgets: this._thinkingBudgets,
2157
+ maxRetryDelayMs: this._maxRetryDelayMs,
2158
+ toolExecution: this._toolExecution,
2159
+ beforeToolExecution: this._beforeToolExecution,
2160
+ afterToolExecution: this._afterToolExecution,
2161
+ convertToLlm: this.convertToLlm,
2162
+ transformContext: this.transformContext,
2163
+ getApiKey: this.getApiKey,
2164
+ getSteeringMessages: async () => {
2165
+ if (skipInitialSteeringPoll) {
2166
+ skipInitialSteeringPoll = false;
2167
+ return [];
2168
+ }
2169
+ return this.dequeueSteeringMessages();
2170
+ },
2171
+ getFollowUpMessages: async () => this.dequeueFollowUpMessages()
2172
+ };
2173
+ try {
2174
+ if (messages) await Loop.runAgentLoop(config, context, messages, async (e) => this._processLoopEvent(e), this.streamFn, this.abortController.signal);
2175
+ else await Loop.runAgentLoopContinue(config, context, async (e) => this._processLoopEvent(e), this.streamFn, this.abortController.signal);
2176
+ } catch (err) {
2177
+ const message = Message.createAssistantMessage({
2178
+ role: "assistant",
2179
+ protocol: model.protocol,
2180
+ provider: model.provider,
2181
+ model: model.id,
2182
+ usage: {
2183
+ input: 0,
2184
+ output: 0,
2185
+ cacheRead: 0,
2186
+ cacheWrite: 0,
2187
+ totalTokens: 0,
2188
+ cost: {
2189
+ input: 0,
2190
+ output: 0,
2191
+ cacheRead: 0,
2192
+ cacheWrite: 0,
2193
+ total: 0
2194
+ }
2195
+ },
2196
+ stopReason: this.abortController.signal.aborted ? "aborted" : "error",
2197
+ errorMessage: err?.message || String(err),
2198
+ time: {
2199
+ created: Date.now(),
2200
+ completed: Date.now()
2201
+ },
2202
+ parts: []
2203
+ });
2204
+ this.appendMessage(message);
2205
+ this._state.error = err?.message || String(err);
2206
+ this.emit({
2207
+ type: "agent.end",
2208
+ messages: [message]
2209
+ });
2210
+ } finally {
2211
+ this._state.isStreaming = false;
2212
+ this._state.streamMessage = null;
2213
+ this._state.pendingToolCalls = /* @__PURE__ */ new Set();
2214
+ this.abortController = void 0;
2215
+ this.resolveRunningPrompt?.();
2216
+ this.runningPrompt = void 0;
2217
+ this.resolveRunningPrompt = void 0;
2218
+ }
2219
+ }
2220
+ async loop(messages) {
2221
+ this.ensureIdle();
2222
+ await this._runLoop(messages);
2223
+ }
2224
+ async loopContinue() {
2225
+ this.ensureIdle();
2226
+ await this._runLoop();
2227
+ }
2228
+ async prompt(messages, images) {
2229
+ this.ensureIdle();
2230
+ if (!this._state.model) throw new ModelNotConfiguredErr({ message: "no model configured yet." });
2231
+ const message = Message.createUserMessage({
2232
+ role: "user",
2233
+ time: { created: Date.now() },
2234
+ parts: [...messages, ...images ?? []]
2235
+ });
2236
+ await this.loop([message]);
2237
+ }
2238
+ _processLoopEvent(event) {
2239
+ switch (event.type) {
2240
+ case "message.start":
2241
+ this._state.streamMessage = event.message;
2242
+ break;
2243
+ case "message.part.start":
2244
+ case "message.part.update":
2245
+ case "message.part.end":
2246
+ this._state.streamMessage = event.message;
2247
+ if (event.message.role === "assistant") this.patchStoredAssistantPart(event.message.messageId, event.partIndex, event.part);
2248
+ break;
2249
+ case "message.update":
2250
+ this._state.streamMessage = event.message;
2251
+ this.replaceMessageById(event.message);
2252
+ break;
2253
+ case "message.end":
2254
+ this._state.streamMessage = null;
2255
+ this.upsertMessage(event.message);
2256
+ break;
2257
+ case "tool.execution.start": {
2258
+ const pendingToolCalls = new Set(this._state.pendingToolCalls);
2259
+ pendingToolCalls.add(event.callID);
2260
+ this._state.pendingToolCalls = pendingToolCalls;
2261
+ break;
2262
+ }
2263
+ case "tool.execution.end": {
2264
+ const pendingToolCalls = new Set(this._state.pendingToolCalls);
2265
+ pendingToolCalls.delete(event.callID);
2266
+ this._state.pendingToolCalls = pendingToolCalls;
2267
+ break;
2268
+ }
2269
+ case "turn.end":
2270
+ if (event.message.role === "assistant" && event.message.parts.length > 0) this._state.error = event.message.errorMessage;
2271
+ break;
2272
+ case "agent.end":
2273
+ this._state.isStreaming = false;
2274
+ this._state.streamMessage = null;
2275
+ break;
2276
+ }
2277
+ this.emit(event);
2278
+ }
2279
+ emit(e) {
2280
+ for (const listener of this.listeners) listener(e);
2281
+ }
2282
+ }
2283
+ _Agent.Instance = Instance;
2284
+ async function create(options) {
2285
+ let resolvedModel;
2286
+ if ("provider" in options) {
2287
+ const result = await Model.getModel(options.provider, options.model);
2288
+ if (!result) throw new ModelNotFoundErr({
2289
+ message: "model not found or not configured yet",
2290
+ provider: options.provider,
2291
+ model: options.model
2292
+ });
2293
+ resolvedModel = result;
2294
+ } else resolvedModel = options.model;
2295
+ return new Instance(options.name ?? "main", resolvedModel, options);
2296
+ }
2297
+ _Agent.create = create;
2298
+ })(Agent || (Agent = {}));
2299
+ //#endregion
2300
+ //#region src/agent.ts
2301
+ const agent = {
2302
+ loop: Loop.run,
2303
+ loopContinue: Loop.runContinue
2304
+ };
2305
+ //#endregion
2306
+ //#region src/llm.ts
2307
+ const llmImpl = async (provider, model) => Model.getModel(provider, model);
2308
+ const llm = Object.assign(llmImpl, {
2309
+ model: Model.getModel,
2310
+ models: Model.getModels,
2311
+ providers: Model.getProviders,
2312
+ registry: Model.registry,
2313
+ supportsXhigh: Model.supportsXhigh,
2314
+ modelsAreEqual: Model.modelsAreEqual
2315
+ });
2316
+ //#endregion
2317
+ //#region src/stream.ts
2318
+ const streamImpl = (model, context, options) => Stream.stream(model, context, options);
2319
+ /**
2320
+ * Start a streaming assistant response for a model/context pair.
2321
+ *
2322
+ * This is the main streaming entrypoint.
2323
+ * Attached helpers:
2324
+ *
2325
+ * - `stream.complete(...)` resolves the final assistant message without manually iterating events.
2326
+ * - `stream.simple(...)` uses `Stream.SimpleOptions` for higher-level reasoning controls.
2327
+ * - `stream.completeSimple(...)` is the non-streaming counterpart to `stream.simple(...)`.
2328
+ * - `stream.resolveProtocolProvider(...)` exposes protocol resolution for advanced integrations.
2329
+ */
2330
+ const stream = Object.assign(streamImpl, {
2331
+ complete: Stream.complete,
2332
+ simple: Stream.streamSimple,
2333
+ completeSimple: Stream.completeSimple,
2334
+ resolveProtocolProvider: Stream.resolveProtocolProvider
2335
+ });
2336
+ Stream.complete;
2337
+ Stream.streamSimple;
2338
+ Stream.completeSimple;
2339
+ //#endregion
2340
+ export { Agent, Message, agent, llm, stream };
2341
+
2342
+ //# sourceMappingURL=index.mjs.map