@soiljs/models 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +184 -2
  3. package/dist/anthropic/index.d.ts +16 -0
  4. package/dist/anthropic/index.js +4 -0
  5. package/dist/anthropic/index.js.map +1 -0
  6. package/dist/chunk-4ONHQ7MX.js +10 -0
  7. package/dist/chunk-4ONHQ7MX.js.map +1 -0
  8. package/dist/chunk-5BTK5EOO.js +8 -0
  9. package/dist/chunk-5BTK5EOO.js.map +1 -0
  10. package/dist/chunk-EFJFQCXF.js +1828 -0
  11. package/dist/chunk-EFJFQCXF.js.map +1 -0
  12. package/dist/chunk-IBG2ZBNY.js +12 -0
  13. package/dist/chunk-IBG2ZBNY.js.map +1 -0
  14. package/dist/chunk-LB4ZT5HL.js +10 -0
  15. package/dist/chunk-LB4ZT5HL.js.map +1 -0
  16. package/dist/chunk-OVT5IQM2.js +37 -0
  17. package/dist/chunk-OVT5IQM2.js.map +1 -0
  18. package/dist/chunk-P42EM5RH.js +9 -0
  19. package/dist/chunk-P42EM5RH.js.map +1 -0
  20. package/dist/chunk-Q63QXXJS.js +9 -0
  21. package/dist/chunk-Q63QXXJS.js.map +1 -0
  22. package/dist/chunk-RTZJ6MXU.js +14 -0
  23. package/dist/chunk-RTZJ6MXU.js.map +1 -0
  24. package/dist/chunk-XNDA5XM4.js +10 -0
  25. package/dist/chunk-XNDA5XM4.js.map +1 -0
  26. package/dist/contracts-B5BERDgM.d.ts +180 -0
  27. package/dist/deepseek/index.d.ts +28 -0
  28. package/dist/deepseek/index.js +4 -0
  29. package/dist/deepseek/index.js.map +1 -0
  30. package/dist/gemini/index.d.ts +11 -0
  31. package/dist/gemini/index.js +4 -0
  32. package/dist/gemini/index.js.map +1 -0
  33. package/dist/glm/index.d.ts +30 -0
  34. package/dist/glm/index.js +4 -0
  35. package/dist/glm/index.js.map +1 -0
  36. package/dist/index.d.ts +32 -0
  37. package/dist/index.js +12 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/kimi/index.d.ts +10 -0
  40. package/dist/kimi/index.js +4 -0
  41. package/dist/kimi/index.js.map +1 -0
  42. package/dist/openai/index.d.ts +20 -0
  43. package/dist/openai/index.js +4 -0
  44. package/dist/openai/index.js.map +1 -0
  45. package/dist/openai-compatible/index.d.ts +21 -0
  46. package/dist/openai-compatible/index.js +4 -0
  47. package/dist/openai-compatible/index.js.map +1 -0
  48. package/dist/openrouter/index.d.ts +24 -0
  49. package/dist/openrouter/index.js +4 -0
  50. package/dist/openrouter/index.js.map +1 -0
  51. package/dist/recording/index.d.ts +20 -0
  52. package/dist/recording/index.js +260 -0
  53. package/dist/recording/index.js.map +1 -0
  54. package/package.json +70 -3
@@ -0,0 +1,1828 @@
1
+ // src/error.ts
2
+ var ModelError = class extends Error {
3
+ code;
4
+ retryable;
5
+ statusCode;
6
+ uncertainDelivery;
7
+ constructor(options) {
8
+ super(options.message, options.cause === void 0 ? void 0 : { cause: options.cause });
9
+ this.name = "ModelError";
10
+ this.code = options.code;
11
+ this.retryable = options.retryable ?? false;
12
+ this.statusCode = options.statusCode;
13
+ this.uncertainDelivery = options.uncertainDelivery ?? false;
14
+ }
15
+ };
16
+
17
+ // src/transport/http.ts
18
+ function abortError(signal, dispatched) {
19
+ const timeout = signal.reason instanceof Error && signal.reason.name === "TimeoutError";
20
+ return new ModelError({
21
+ code: timeout ? "timeout" : "aborted",
22
+ message: timeout ? "Model request timed out" : "Model request aborted",
23
+ uncertainDelivery: dispatched,
24
+ retryable: false
25
+ });
26
+ }
27
+ function interruptible(promise, signal) {
28
+ if (signal.aborted) {
29
+ void promise.catch(() => {
30
+ });
31
+ return Promise.reject(abortError(signal, true));
32
+ }
33
+ return new Promise((resolve, reject) => {
34
+ const abort = () => reject(abortError(signal, true));
35
+ signal.addEventListener("abort", abort, { once: true });
36
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
37
+ });
38
+ }
39
+ async function connect(url, body, headers, options, request) {
40
+ if (request.signal?.aborted) throw abortError(request.signal, false);
41
+ if (options.timeoutMs !== void 0 && (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)) {
42
+ throw new ModelError({
43
+ code: "invalid_request",
44
+ message: "timeoutMs must be positive and finite"
45
+ });
46
+ }
47
+ let payload;
48
+ let combined;
49
+ try {
50
+ payload = JSON.stringify(body);
51
+ combined = new Headers(headers);
52
+ new Headers(options.headers).forEach((value, key) => combined.set(key, value));
53
+ combined.set("content-type", "application/json");
54
+ } catch {
55
+ throw new ModelError({
56
+ code: "invalid_request",
57
+ message: "Model request must have valid headers and JSON serializable content"
58
+ });
59
+ }
60
+ if (request.signal?.aborted) throw abortError(request.signal, false);
61
+ const controller = new AbortController();
62
+ const relay = () => controller.abort(request.signal?.reason);
63
+ request.signal?.addEventListener("abort", relay, { once: true });
64
+ const timer = options.timeoutMs === void 0 ? void 0 : setTimeout(
65
+ () => controller.abort(new DOMException("Timeout", "TimeoutError")),
66
+ options.timeoutMs
67
+ );
68
+ const signal = controller.signal;
69
+ const close = () => {
70
+ if (timer !== void 0) clearTimeout(timer);
71
+ request.signal?.removeEventListener("abort", relay);
72
+ controller.abort();
73
+ };
74
+ const failure = (cause) => {
75
+ if (cause instanceof ModelError) {
76
+ if (cause.code === "invalid_response" && !cause.uncertainDelivery)
77
+ return new ModelError({
78
+ code: cause.code,
79
+ message: cause.message,
80
+ uncertainDelivery: true,
81
+ cause
82
+ });
83
+ return cause;
84
+ }
85
+ if (signal.aborted) return abortError(signal, true);
86
+ if (cause instanceof Error && (cause.name === "AbortError" || cause.name === "TimeoutError")) {
87
+ return new ModelError({
88
+ code: cause.name === "TimeoutError" ? "timeout" : "aborted",
89
+ message: "Model request interrupted",
90
+ uncertainDelivery: true
91
+ });
92
+ }
93
+ return new ModelError({
94
+ code: "network_error",
95
+ message: "Model transport failed",
96
+ uncertainDelivery: true,
97
+ cause
98
+ });
99
+ };
100
+ try {
101
+ const pending = (options.fetch ?? globalThis.fetch)(url, {
102
+ method: "POST",
103
+ headers: combined,
104
+ body: payload,
105
+ signal
106
+ });
107
+ void pending.then(
108
+ (response2) => {
109
+ if (signal.aborted) void response2.body?.cancel().catch(() => {
110
+ });
111
+ },
112
+ () => {
113
+ }
114
+ );
115
+ const response = await interruptible(pending, signal);
116
+ if (!response.ok) {
117
+ void response.body?.cancel().catch(() => {
118
+ });
119
+ throw new ModelError({
120
+ code: "http_error",
121
+ message: `Model HTTP request failed (${response.status})`,
122
+ statusCode: response.status,
123
+ retryable: response.status === 408 || response.status === 429 || response.status >= 500,
124
+ uncertainDelivery: response.status === 408 || response.status >= 500
125
+ });
126
+ }
127
+ return { response, signal, close, failure };
128
+ } catch (cause) {
129
+ const error = failure(cause);
130
+ close();
131
+ throw error;
132
+ }
133
+ }
134
+ async function readJson(connection) {
135
+ const body = connection.response.body;
136
+ if (!body)
137
+ throw new ModelError({ code: "invalid_response", message: "Missing model response body" });
138
+ const reader = body.getReader();
139
+ const decoder = new TextDecoder("utf-8", { fatal: true });
140
+ try {
141
+ let text2 = "";
142
+ while (true) {
143
+ const chunk = await interruptible(reader.read(), connection.signal);
144
+ try {
145
+ text2 += chunk.done ? decoder.decode() : decoder.decode(chunk.value, { stream: true });
146
+ } catch {
147
+ throw new ModelError({
148
+ code: "invalid_response",
149
+ message: "Invalid UTF-8 in model response"
150
+ });
151
+ }
152
+ if (text2.length > 64 * 1024 * 1024)
153
+ throw new ModelError({
154
+ code: "invalid_response",
155
+ message: "Model response exceeds 64 MiB"
156
+ });
157
+ if (chunk.done) break;
158
+ }
159
+ try {
160
+ return JSON.parse(text2);
161
+ } catch {
162
+ throw new ModelError({ code: "invalid_response", message: "Model returned malformed JSON" });
163
+ }
164
+ } catch (cause) {
165
+ throw connection.failure(cause);
166
+ } finally {
167
+ void reader.cancel().catch(() => {
168
+ });
169
+ reader.releaseLock();
170
+ }
171
+ }
172
+
173
+ // src/transport/shared.ts
174
+ function env(names) {
175
+ const processEnv = globalThis.process?.env;
176
+ if (!processEnv) return void 0;
177
+ const list = typeof names === "string" ? [names] : names;
178
+ for (const name of list) {
179
+ const value = processEnv[name]?.trim();
180
+ if (value) return value;
181
+ }
182
+ return void 0;
183
+ }
184
+ function parts(message) {
185
+ return typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
186
+ }
187
+ function object(value) {
188
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
189
+ }
190
+ function array(value) {
191
+ return Array.isArray(value) ? value : [];
192
+ }
193
+ function string(value) {
194
+ return typeof value === "string" ? value : "";
195
+ }
196
+ function count(value) {
197
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
198
+ }
199
+ function json(value) {
200
+ try {
201
+ return JSON.parse(value);
202
+ } catch (cause) {
203
+ throw new ModelError({
204
+ code: "invalid_response",
205
+ message: "Model returned malformed JSON",
206
+ uncertainDelivery: true,
207
+ cause
208
+ });
209
+ }
210
+ }
211
+ function invalid(message) {
212
+ throw new ModelError({ code: "invalid_response", message, uncertainDelivery: true });
213
+ }
214
+ function badRequest(message) {
215
+ throw new ModelError({ code: "invalid_request", message });
216
+ }
217
+ function finish(value) {
218
+ switch (value) {
219
+ case "stop":
220
+ case "end_turn":
221
+ case "stop_sequence":
222
+ case "STOP":
223
+ case "completed":
224
+ return "stop";
225
+ case "length":
226
+ case "max_tokens":
227
+ case "max_output_tokens":
228
+ case "MAX_TOKENS":
229
+ return "length";
230
+ case "tool_calls":
231
+ case "tool_use":
232
+ return "tool_calls";
233
+ case "content_filter":
234
+ case "SAFETY":
235
+ case "RECITATION":
236
+ case "BLOCKLIST":
237
+ case "PROHIBITED_CONTENT":
238
+ return "content_filter";
239
+ default:
240
+ return "unknown";
241
+ }
242
+ }
243
+ function usage(inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens) {
244
+ const counts = [inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens];
245
+ return {
246
+ inputTokens,
247
+ outputTokens,
248
+ cacheReadTokens,
249
+ cacheWriteTokens,
250
+ completeness: counts.every((n) => n !== null) ? "complete" : counts.some((n) => n !== null) ? "partial" : "unknown"
251
+ };
252
+ }
253
+ function emptyUsage() {
254
+ return usage(null, null, null, null);
255
+ }
256
+ function canonical(value) {
257
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
258
+ if (typeof value === "object" && value !== null)
259
+ return `{${Object.entries(value).filter(([, child]) => child !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, child]) => `${JSON.stringify(key)}:${canonical(child)}`).join(",")}}`;
260
+ return JSON.stringify(value) ?? "null";
261
+ }
262
+ function normalizeUsage(protocolId, raw) {
263
+ const u = object(raw);
264
+ if (protocolId.endsWith("/messages")) {
265
+ const input = count(u.input_tokens), read2 = count(u.cache_read_input_tokens), write2 = count(u.cache_creation_input_tokens);
266
+ return usage(
267
+ input !== null && read2 !== null && write2 !== null ? input + read2 + write2 : null,
268
+ count(u.output_tokens),
269
+ read2,
270
+ write2
271
+ );
272
+ }
273
+ if (protocolId === "gemini/generate-content") {
274
+ const candidate = count(u.candidatesTokenCount), thought = count(u.thoughtsTokenCount);
275
+ return usage(
276
+ count(u.promptTokenCount),
277
+ candidate !== null && thought !== null ? candidate + thought : null,
278
+ count(u.cachedContentTokenCount),
279
+ count(u.cacheWriteTokenCount)
280
+ );
281
+ }
282
+ const responses = protocolId.endsWith("/responses");
283
+ const details = object(responses ? u.input_tokens_details : u.prompt_tokens_details);
284
+ const read = count(
285
+ details.cached_tokens ?? (protocolId === "deepseek/chat" ? u.prompt_cache_hit_tokens : void 0)
286
+ );
287
+ const write = protocolId === "kimi/chat" ? count(u.cache_write_tokens) : count(details.cache_write_tokens);
288
+ return usage(
289
+ count(responses ? u.input_tokens : u.prompt_tokens),
290
+ count(responses ? u.output_tokens : u.completion_tokens),
291
+ read,
292
+ write
293
+ );
294
+ }
295
+ var ResponseBuilder = class {
296
+ response;
297
+ calls = /* @__PURE__ */ new Map();
298
+ constructor(protocolId, model) {
299
+ this.response = {
300
+ protocolId,
301
+ model,
302
+ text: "",
303
+ reasoningText: "",
304
+ toolCalls: [],
305
+ usage: emptyUsage(),
306
+ finishReason: "unknown",
307
+ rawResponse: []
308
+ };
309
+ }
310
+ text(delta, reasoning = false) {
311
+ if (!delta) return [];
312
+ if (reasoning) this.response.reasoningText += delta;
313
+ else this.response.text += delta;
314
+ return [{ type: reasoning ? "reasoning.delta" : "text.delta", delta }];
315
+ }
316
+ start(index, id, name, input) {
317
+ if (!id || !name || this.calls.has(index)) invalid("Invalid or duplicate tool call start");
318
+ this.calls.set(index, { id, name, arguments: "", ...input === void 0 ? {} : { input } });
319
+ return { type: "tool_call.start", id, name };
320
+ }
321
+ delta(index, delta) {
322
+ const call = this.calls.get(index);
323
+ if (!call) invalid("Tool delta has no start");
324
+ call.arguments += delta;
325
+ return { type: "tool_call.delta", id: call.id, delta };
326
+ }
327
+ done(index) {
328
+ const call = this.calls.get(index);
329
+ if (!call) invalid("Tool call has no start");
330
+ const toolCall = {
331
+ id: call.id,
332
+ name: call.name,
333
+ input: call.arguments ? json(call.arguments) : call.input ?? {}
334
+ };
335
+ this.response.toolCalls = [...this.response.toolCalls, toolCall];
336
+ this.calls.delete(index);
337
+ return { type: "tool_call.done", toolCall };
338
+ }
339
+ complete() {
340
+ const events = [...this.calls.keys()].map((index) => this.done(index));
341
+ if (this.response.toolCalls.length && this.response.finishReason === "stop")
342
+ this.response.finishReason = "tool_calls";
343
+ return [...events, { type: "response.completed", response: this.response }];
344
+ }
345
+ };
346
+
347
+ // src/transport/spec.ts
348
+ var seven = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
349
+ var three = ["low", "high", "max"];
350
+ var four = ["none", "low", "high", "max"];
351
+ var five = ["low", "medium", "high", "xhigh", "max"];
352
+ function field(wireKey, kind, options = {}) {
353
+ return { wireKey, kind, required: false, ...options };
354
+ }
355
+ var effort = (path, values, defaultValue) => field(path, "enum", { values, ...defaultValue ? { serverDefault: defaultValue } : {} });
356
+ var tokens = (path, minimum = 1, maximum, serverDefault) => field(path, "number", {
357
+ integer: true,
358
+ minimum,
359
+ ...maximum === void 0 ? {} : { maximum },
360
+ ...serverDefault === void 0 ? {} : { serverDefault }
361
+ });
362
+ var bool = (path, serverDefault) => field(path, "boolean", serverDefault === void 0 ? {} : { serverDefault });
363
+ var format = (path, values, serverDefault) => field(path, "format", { values, ...serverDefault ? { serverDefault } : {} });
364
+ var choice = (values, forced = false) => field("tool_choice", "toolChoice", {
365
+ values,
366
+ description: forced ? "Allows an explicit function name." : "String choices only."
367
+ });
368
+ var temp = (maximum, minimum = 0, precision) => field("temperature", "number", {
369
+ minimum,
370
+ maximum,
371
+ serverDefault: 1,
372
+ ...precision === void 0 ? {} : { precision }
373
+ });
374
+ var topP = () => field("top_p", "number", { minimum: 0.01, maximum: 1, precision: 2, serverDefault: 0.95 });
375
+ var thinking = (values, defaultValue) => field("thinking.type", "thinking", {
376
+ values,
377
+ ...defaultValue ? { serverDefault: defaultValue } : {}
378
+ });
379
+ var specs = {
380
+ "openai-compatible/v1/chat": {
381
+ id: "openai-compatible/v1/chat",
382
+ family: "chat",
383
+ base: "",
384
+ path: "/chat/completions",
385
+ apiKeyEnv: [],
386
+ baseUrlEnv: [],
387
+ fields: {
388
+ temperature: field("temperature", "number", { minimum: 0, maximum: 2 }),
389
+ topP: field("top_p", "number", { minimum: 0, maximum: 1 }),
390
+ maxOutputTokens: tokens("max_tokens"),
391
+ maxTokensParam: effort("maxTokensParam", ["max_tokens", "max_completion_tokens"]),
392
+ includeStreamUsage: bool("includeStreamUsage"),
393
+ responseFormat: format("response_format", ["text", "json_object", "json_schema"]),
394
+ reasoningEffort: effort("reasoning_effort", seven),
395
+ thinking: thinking(["enabled", "disabled"]),
396
+ toolChoice: choice(["none", "auto", "required"], true),
397
+ extraBody: field("extraBody", "extraBody")
398
+ },
399
+ notes: [
400
+ "Version 1 explicit gateway profile; baseUrl is required and environment credentials are never inferred.",
401
+ "maxTokensParam defaults to max_tokens; includeStreamUsage defaults to false. These are local encoding controls, not wire fields.",
402
+ "Capabilities belong to the chosen gateway/model; extraBody cannot override typed, transport or continuation fields."
403
+ ]
404
+ },
405
+ "openai/responses": {
406
+ id: "openai/responses",
407
+ family: "responses",
408
+ base: "https://api.openai.com/v1",
409
+ path: "/responses",
410
+ apiKeyEnv: ["OPENAI_RESPONSES_API_KEY", "OPENAI_API_KEY"],
411
+ baseUrlEnv: ["OPENAI_RESPONSES_BASE_URL", "OPENAI_BASE_URL"],
412
+ fields: {
413
+ reasoningEffort: effort("reasoning.effort", seven, "medium"),
414
+ maxOutputTokens: tokens("max_output_tokens", 16),
415
+ verbosity: effort("text.verbosity", ["low", "medium", "high"], "medium"),
416
+ textFormat: format("text.format", ["text", "json_object", "json_schema"], "text"),
417
+ toolChoice: choice(["none", "auto", "required"], true),
418
+ store: bool("store", true)
419
+ },
420
+ notes: [
421
+ "Astra/Sol reject none and minimal; Terra/Luna accept none.",
422
+ "Stateless reasoning replay requires encrypted_content; signatures returned by the service must be preserved."
423
+ ]
424
+ },
425
+ "openai/chat": {
426
+ id: "openai/chat",
427
+ family: "chat",
428
+ base: "https://api.openai.com/v1",
429
+ path: "/chat/completions",
430
+ apiKeyEnv: ["OPENAI_CHAT_API_KEY", "OPENAI_API_KEY"],
431
+ baseUrlEnv: ["OPENAI_CHAT_BASE_URL", "OPENAI_BASE_URL"],
432
+ fields: {
433
+ reasoningEffort: effort("reasoning_effort", seven, "medium"),
434
+ maxOutputTokens: tokens("max_completion_tokens"),
435
+ verbosity: effort("verbosity", ["low", "medium", "high"], "medium"),
436
+ responseFormat: format("response_format", ["text", "json_object", "json_schema"]),
437
+ toolChoice: choice(["none", "auto", "required"], true),
438
+ store: bool("store", false)
439
+ },
440
+ notes: [
441
+ "Current flagship tool calls require Responses; Chat fields do not establish model capability."
442
+ ]
443
+ },
444
+ "anthropic/messages": {
445
+ id: "anthropic/messages",
446
+ family: "messages",
447
+ base: "https://api.anthropic.com",
448
+ path: "/v1/messages",
449
+ apiKeyEnv: ["ANTHROPIC_API_KEY"],
450
+ baseUrlEnv: ["ANTHROPIC_BASE_URL"],
451
+ fields: {
452
+ effort: effort("output_config.effort", five),
453
+ thinking: thinking(["adaptive", "disabled", "between_tools"]),
454
+ maxOutputTokens: { ...tokens("max_tokens"), required: true }
455
+ },
456
+ notes: [
457
+ "Fixed anthropic-version: 2026-10-21.",
458
+ "Opus defaults to medium; Fable/Sonnet to high; Haiku to medium.",
459
+ "display defaults to omitted; only adaptive accepts display summarized or omitted.",
460
+ "No sampling fields or forced tool selection on this surface."
461
+ ]
462
+ },
463
+ "gemini/generate-content": {
464
+ id: "gemini/generate-content",
465
+ family: "gemini",
466
+ base: "https://generativelanguage.googleapis.com/v1beta",
467
+ path: "",
468
+ apiKeyEnv: ["GEMINI_API_KEY"],
469
+ baseUrlEnv: ["GEMINI_BASE_URL"],
470
+ fields: {
471
+ thinkingLevel: effort("generationConfig.thinkingConfig.thinkingLevel", [
472
+ "minimal",
473
+ "low",
474
+ "medium",
475
+ "high",
476
+ "xhigh"
477
+ ]),
478
+ maxOutputTokens: tokens("generationConfig.maxOutputTokens"),
479
+ temperature: field("generationConfig.temperature", "number"),
480
+ topP: field("generationConfig.topP", "number", { minimum: 0, maximum: 1 }),
481
+ responseMimeType: effort("generationConfig.responseMimeType", [
482
+ "text/plain",
483
+ "application/json"
484
+ ])
485
+ },
486
+ notes: [
487
+ "Carbon/Argon default medium and reject xhigh; Neon/Hydrogen default high; Flash-Lite defaults minimal.",
488
+ "Gemini 4 rejects minimal and ignores custom temperature; thinkingBudget is not supported here.",
489
+ "Tool replay preserves thoughtSignature and functionResponse name."
490
+ ]
491
+ },
492
+ "glm/chat": {
493
+ id: "glm/chat",
494
+ family: "chat",
495
+ base: "https://open.bigmodel.cn/api/paas/v4",
496
+ path: "/chat/completions",
497
+ apiKeyEnv: ["GLM_CHAT_API_KEY", "GLM_API_KEY"],
498
+ baseUrlEnv: ["GLM_CHAT_BASE_URL", "GLM_BASE_URL"],
499
+ fields: {
500
+ thinking: thinking(["enabled", "disabled"], "enabled"),
501
+ reasoningEffort: effort("reasoning_effort", seven, "max"),
502
+ maxOutputTokens: tokens("max_tokens", 1, 131072, 65536),
503
+ temperature: temp(1, 0, 2),
504
+ topP: topP(),
505
+ doSample: bool("do_sample", true),
506
+ clearThinking: bool("thinking.clear_thinking", true),
507
+ responseFormat: format("response_format", ["text", "json_object"]),
508
+ toolChoice: choice(["auto"])
509
+ },
510
+ notes: [
511
+ "GLM-5.3/Flash reject disabled and accept low/high/max; GLM-5.2 accepts seven effort tiers.",
512
+ "Flash visual schema does not document response_format.",
513
+ "Explicit clearThinking:false is needed to preserve historical reasoning; doSample:false ignores sampling."
514
+ ]
515
+ },
516
+ "glm/responses": {
517
+ id: "glm/responses",
518
+ family: "responses",
519
+ base: "https://open.bigmodel.cn/api/v1",
520
+ path: "/responses",
521
+ apiKeyEnv: ["GLM_RESPONSES_API_KEY", "GLM_API_KEY"],
522
+ baseUrlEnv: ["GLM_RESPONSES_BASE_URL", "GLM_BASE_URL"],
523
+ fields: {
524
+ reasoningEffort: effort("reasoning.effort", three, "max"),
525
+ maxOutputTokens: tokens("max_output_tokens", 1, 131072, 65536),
526
+ temperature: temp(1, 0, 2),
527
+ topP: topP(),
528
+ textFormat: format("text.format", ["text", "json_object"]),
529
+ store: bool("store", false),
530
+ toolChoice: choice(["none", "auto"])
531
+ },
532
+ notes: [
533
+ "Only GLM-5.3 is documented; 5.2/Flash support remains unknown.",
534
+ "Replay uses client-saved output items without encrypted_content; stored IDs are encoder-owned."
535
+ ]
536
+ },
537
+ "kimi/chat": {
538
+ id: "kimi/chat",
539
+ family: "chat",
540
+ base: "https://api.moonshot.cn/v1",
541
+ path: "/chat/completions",
542
+ apiKeyEnv: ["KIMI_API_KEY", "MOONSHOT_API_KEY"],
543
+ baseUrlEnv: ["KIMI_BASE_URL", "MOONSHOT_BASE_URL"],
544
+ fields: {
545
+ reasoningEffort: effort("reasoning_effort", three, "max"),
546
+ maxOutputTokens: tokens("max_completion_tokens", 1, 1048576, 131072),
547
+ toolChoice: choice(["auto", "none", "required"]),
548
+ cacheTtl: effort("prompt_cache_options.ttl", ["5m", "1h"], "5m")
549
+ },
550
+ notes: [
551
+ "K3 always thinks and requires full reasoning_content replay.",
552
+ "temperature=1, top_p=0.95, n=1 and penalties are fixed; old K2 thinking is unsupported."
553
+ ]
554
+ },
555
+ "deepseek/chat": {
556
+ id: "deepseek/chat",
557
+ family: "chat",
558
+ base: "https://api.deepseek.com",
559
+ path: "/chat/completions",
560
+ apiKeyEnv: ["DEEPSEEK_CHAT_API_KEY", "DEEPSEEK_API_KEY"],
561
+ baseUrlEnv: ["DEEPSEEK_CHAT_BASE_URL", "DEEPSEEK_BASE_URL"],
562
+ fields: {
563
+ reasoningEffort: effort("reasoning_effort", seven, "high"),
564
+ thinking: thinking(["enabled", "disabled"]),
565
+ maxOutputTokens: tokens("max_tokens", 1, 393216),
566
+ temperature: temp(2),
567
+ topP: field("top_p", "number", { minimum: 0, maximum: 1 }),
568
+ responseFormat: format("response_format", ["text", "json_object"]),
569
+ toolChoice: choice(["none", "auto", "required"], true)
570
+ },
571
+ notes: [
572
+ "Thinking defaults on; explicit thinking.type overrides effort.",
573
+ "Thinking ignores temperature and rejects required/forced tools; tool continuation requires reasoning_content.",
574
+ "Output default depends on thinking mode; minimal maps low, medium/xhigh map high server-side."
575
+ ]
576
+ },
577
+ "deepseek/responses": {
578
+ id: "deepseek/responses",
579
+ family: "responses",
580
+ base: "https://api.deepseek.com",
581
+ path: "/responses",
582
+ apiKeyEnv: ["DEEPSEEK_RESPONSES_API_KEY", "DEEPSEEK_API_KEY"],
583
+ baseUrlEnv: ["DEEPSEEK_RESPONSES_BASE_URL", "DEEPSEEK_BASE_URL"],
584
+ fields: {
585
+ reasoningEffort: effort("reasoning.effort", four),
586
+ maxOutputTokens: field("max_output_tokens", "number", { integer: true })
587
+ },
588
+ notes: [
589
+ "Thinking defaults on; the default effort string and output limits are undocumented.",
590
+ "No store, previous_response_id, encrypted_content or non-text format; replay client-saved plaintext items."
591
+ ]
592
+ },
593
+ "deepseek/messages": {
594
+ id: "deepseek/messages",
595
+ family: "messages",
596
+ base: "https://api.deepseek.com/anthropic",
597
+ path: "/v1/messages",
598
+ apiKeyEnv: ["DEEPSEEK_MESSAGES_API_KEY", "DEEPSEEK_API_KEY"],
599
+ baseUrlEnv: ["DEEPSEEK_MESSAGES_BASE_URL", "DEEPSEEK_BASE_URL"],
600
+ fields: {
601
+ effort: effort("output_config.effort", [...seven.slice(0, -1), "ultra", "max"], "high"),
602
+ thinking: thinking(["enabled", "disabled", "adaptive"]),
603
+ maxOutputTokens: tokens("max_tokens")
604
+ },
605
+ notes: [
606
+ "No anthropic-version header. Explicit thinking.type overrides effort; adaptive is sent unchanged.",
607
+ "No redacted_thinking; preserve returned thinking blocks/signature. Explicit cache_creation_input_tokens:0 is retained.",
608
+ "Omitted max_tokens has no documented fixed default."
609
+ ]
610
+ },
611
+ "openrouter/chat": {
612
+ id: "openrouter/chat",
613
+ family: "chat",
614
+ base: "https://openrouter.ai/api/v1",
615
+ path: "/chat/completions",
616
+ apiKeyEnv: ["OPENROUTER_CHAT_API_KEY", "OPENROUTER_API_KEY"],
617
+ baseUrlEnv: ["OPENROUTER_CHAT_BASE_URL", "OPENROUTER_BASE_URL"],
618
+ fields: {
619
+ temperature: field("temperature", "number", { minimum: 0, maximum: 2 }),
620
+ topP: field("top_p", "number", { minimum: 0, maximum: 1 }),
621
+ responseFormat: format("response_format", ["text", "json_object", "json_schema"]),
622
+ toolChoice: choice(["none", "auto", "required"], true),
623
+ reasoningEffort: effort("reasoning.effort", seven),
624
+ maxOutputTokens: tokens("max_tokens"),
625
+ requireParameters: bool("provider.require_parameters", false)
626
+ },
627
+ notes: [
628
+ "Provider/model effort support and defaults vary; seven-tier protocol enum is not a model catalog.",
629
+ "Default require_parameters:false can silently drop unsupported parameters; opt into true for strict routing.",
630
+ "Replay reasoning_details in original order; usage tail choices may be non-empty."
631
+ ]
632
+ },
633
+ "openrouter/responses": {
634
+ id: "openrouter/responses",
635
+ family: "responses",
636
+ base: "https://openrouter.ai/api/v1",
637
+ path: "/responses",
638
+ apiKeyEnv: ["OPENROUTER_RESPONSES_API_KEY", "OPENROUTER_API_KEY"],
639
+ baseUrlEnv: ["OPENROUTER_RESPONSES_BASE_URL", "OPENROUTER_BASE_URL"],
640
+ fields: {
641
+ reasoningEffort: effort("reasoning.effort", seven),
642
+ maxOutputTokens: tokens("max_output_tokens"),
643
+ requireParameters: bool("provider.require_parameters", false),
644
+ store: { ...bool("store", false), values: [false] }
645
+ },
646
+ notes: [
647
+ "Stateless only: store:true and previous_response_id are rejected.",
648
+ "Preserve ordered output items, signatures and encrypted_content. OpenRouter requests encrypted content automatically.",
649
+ "Direct and provider-specific defaults do not apply to OpenRouter; require_parameters defaults false."
650
+ ]
651
+ },
652
+ "openrouter/messages": {
653
+ id: "openrouter/messages",
654
+ family: "messages",
655
+ base: "https://openrouter.ai/api/v1",
656
+ path: "/messages",
657
+ apiKeyEnv: ["OPENROUTER_MESSAGES_API_KEY", "OPENROUTER_API_KEY"],
658
+ baseUrlEnv: ["OPENROUTER_MESSAGES_BASE_URL", "OPENROUTER_BASE_URL"],
659
+ fields: {
660
+ reasoningEffort: effort("reasoning.effort", seven),
661
+ maxOutputTokens: tokens("max_tokens"),
662
+ requireParameters: bool("provider.require_parameters", false)
663
+ },
664
+ notes: [
665
+ "Uses OpenRouter reasoning.effort, never direct thinking configuration.",
666
+ "Preserve ordered content blocks and signatures; gateway model support remains distinct from direct APIs.",
667
+ "require_parameters defaults false and can silently ignore unsupported upstream parameters."
668
+ ]
669
+ }
670
+ };
671
+ function resolveApiKey(spec, explicit) {
672
+ return explicit !== void 0 ? explicit : env(spec.apiKeyEnv);
673
+ }
674
+ function resolveBaseUrl(spec, explicit) {
675
+ return explicit !== void 0 ? explicit : env(spec.baseUrlEnv) ?? spec.base;
676
+ }
677
+ function metadata(spec) {
678
+ const fields = {
679
+ model: { wireKey: "model", required: true },
680
+ ...spec.id === "openai-compatible/v1/chat" ? { baseUrl: { wireKey: "baseUrl", required: true, type: "string" } } : {},
681
+ messages: {
682
+ wireKey: spec.family === "responses" ? "input" : spec.family === "gemini" ? "contents" : "messages",
683
+ required: true
684
+ },
685
+ tools: { wireKey: "tools", required: false }
686
+ };
687
+ for (const [key, { kind, ...meta }] of Object.entries(spec.fields)) {
688
+ const type = kind === "enum" ? "string" : kind === "number" || kind === "boolean" ? kind : "object";
689
+ fields[key] = { ...meta, type };
690
+ if (kind === "thinking")
691
+ fields[key] = {
692
+ ...fields[key],
693
+ properties: {
694
+ type: { wireKey: "thinking.type", required: true, type: "string", values: meta.values },
695
+ ...spec.id === "anthropic/messages" ? {
696
+ display: {
697
+ wireKey: "thinking.display",
698
+ required: false,
699
+ type: "string",
700
+ values: ["summarized", "omitted"],
701
+ serverDefault: "omitted",
702
+ description: "Only valid when thinking.type is adaptive."
703
+ }
704
+ } : {}
705
+ }
706
+ };
707
+ }
708
+ const result = { protocolId: spec.id, defaultBaseUrl: spec.base, fields, modelNotes: spec.notes };
709
+ return freezeJson(result);
710
+ }
711
+ function freezeJson(value) {
712
+ if (value && typeof value === "object") {
713
+ for (const item of Object.values(value)) freezeJson(item);
714
+ Object.freeze(value);
715
+ }
716
+ return value;
717
+ }
718
+ function setPath(body, path, value) {
719
+ const keys2 = path.split(".");
720
+ let target = body;
721
+ for (const key of keys2.slice(0, -1)) target = target[key] ??= {};
722
+ target[keys2.at(-1)] = value;
723
+ }
724
+
725
+ // src/transport/sse.ts
726
+ async function* readSse(connection) {
727
+ const body = connection.response.body;
728
+ if (!body)
729
+ throw new ModelError({ code: "invalid_response", message: "Missing model stream body" });
730
+ const reader = body.getReader();
731
+ const decoder = new TextDecoder("utf-8", { fatal: true });
732
+ let pending = "";
733
+ let event = "";
734
+ let data = [];
735
+ const line = (value) => {
736
+ if (value === "") {
737
+ const frame = data.length ? { event, data: data.join("\n") } : void 0;
738
+ data = [];
739
+ event = "";
740
+ return frame;
741
+ }
742
+ const colon = value.indexOf(":");
743
+ const key = colon < 0 ? value : value.slice(0, colon);
744
+ let field2 = colon < 0 ? "" : value.slice(colon + 1);
745
+ if (field2.startsWith(" ")) field2 = field2.slice(1);
746
+ if (key === "event") event = field2;
747
+ if (key === "data") data.push(field2);
748
+ return void 0;
749
+ };
750
+ try {
751
+ while (true) {
752
+ const chunk = await interruptible(reader.read(), connection.signal);
753
+ try {
754
+ pending += chunk.done ? decoder.decode() : decoder.decode(chunk.value, { stream: true });
755
+ } catch {
756
+ throw new ModelError({
757
+ code: "invalid_response",
758
+ message: "Invalid UTF-8 in model stream"
759
+ });
760
+ }
761
+ while (true) {
762
+ const match = /[\r\n]/.exec(pending);
763
+ if (!match || !chunk.done && match.index === pending.length - 1 && match[0] === "\r")
764
+ break;
765
+ const offset = match.index;
766
+ const width = pending[offset] === "\r" && pending[offset + 1] === "\n" ? 2 : 1;
767
+ const frame = line(pending.slice(0, offset));
768
+ pending = pending.slice(offset + width);
769
+ if (frame) yield frame;
770
+ }
771
+ if (pending.length + data.reduce((size, part) => size + part.length, 0) > 8 * 1024 * 1024) {
772
+ throw new ModelError({
773
+ code: "invalid_response",
774
+ message: "Model SSE frame exceeds 8 MiB"
775
+ });
776
+ }
777
+ if (chunk.done) break;
778
+ }
779
+ } catch (cause) {
780
+ throw connection.failure(cause);
781
+ } finally {
782
+ void reader.cancel().catch(() => {
783
+ });
784
+ reader.releaseLock();
785
+ }
786
+ }
787
+
788
+ // src/transport/extra-body.ts
789
+ var normalized = (key) => key.replace(/[^a-z0-9]/gi, "").toLowerCase();
790
+ var reserved = [
791
+ "model",
792
+ "messages",
793
+ "tools",
794
+ "stream",
795
+ "stream_options",
796
+ "input",
797
+ "contents",
798
+ "headers",
799
+ "authorization",
800
+ "proxy-authorization",
801
+ "apiKey",
802
+ "x-api-key",
803
+ "x-goog-api-key",
804
+ "baseUrl",
805
+ "url",
806
+ "method",
807
+ "body",
808
+ "fetch",
809
+ "signal",
810
+ "timeoutMs",
811
+ "connection",
812
+ "continuation",
813
+ "previous_response_id",
814
+ "conversation",
815
+ "store",
816
+ "include",
817
+ "reasoning",
818
+ "reasoning_content",
819
+ "reasoning_details",
820
+ "encrypted_content",
821
+ "signature",
822
+ "max_tokens",
823
+ "max_completion_tokens",
824
+ "max_output_tokens"
825
+ ];
826
+ function validateExtraBody(value, spec) {
827
+ if (!value || typeof value !== "object" || Array.isArray(value))
828
+ badRequest("extraBody must be a JSON object");
829
+ const forbidden = new Set(
830
+ [
831
+ ...reserved,
832
+ ...Object.keys(spec.fields),
833
+ ...Object.values(spec.fields).map((field2) => field2.wireKey.split(".")[0])
834
+ ].map(normalized)
835
+ );
836
+ const ancestors = /* @__PURE__ */ new Set();
837
+ let nodes = 0;
838
+ const visit = (node, depth) => {
839
+ if (++nodes > 1e4 || depth > 32) badRequest("extraBody exceeds structural limits");
840
+ if (node === null || typeof node === "string" || typeof node === "boolean") return;
841
+ if (typeof node === "number" && Number.isFinite(node)) return;
842
+ if (!node || typeof node !== "object" || ancestors.has(node))
843
+ badRequest("extraBody must contain finite, acyclic JSON");
844
+ if (!Array.isArray(node) && ![Object.prototype, null].includes(Object.getPrototypeOf(node)))
845
+ badRequest("extraBody must contain plain JSON objects");
846
+ ancestors.add(node);
847
+ if (Array.isArray(node) && Object.keys(node).length !== node.length)
848
+ badRequest("extraBody cannot contain sparse or extended arrays");
849
+ for (const key of Reflect.ownKeys(node)) {
850
+ if (Array.isArray(node) && key === "length") continue;
851
+ if (typeof key !== "string" || ["__proto__", "constructor", "prototype"].includes(key))
852
+ badRequest("Invalid extraBody key");
853
+ if (Array.isArray(node) && (!/^(0|[1-9][0-9]*)$/.test(key) || Number(key) >= node.length))
854
+ badRequest("extraBody arrays may only contain indexed elements");
855
+ if (depth === 0 && forbidden.has(normalized(key)))
856
+ badRequest(`Reserved extraBody field: ${key}; use typed options`);
857
+ const property = Object.getOwnPropertyDescriptor(node, key);
858
+ if (!property.enumerable || !("value" in property))
859
+ badRequest("extraBody cannot contain accessors or hidden fields");
860
+ visit(property.value, depth + 1);
861
+ }
862
+ ancestors.delete(node);
863
+ };
864
+ visit(value, 0);
865
+ if (new TextEncoder().encode(JSON.stringify(value)).length > 65536)
866
+ badRequest("extraBody exceeds 64 KiB");
867
+ }
868
+
869
+ // src/transport/validate.ts
870
+ function keys(value, allowed, label) {
871
+ if (!value || typeof value !== "object" || Array.isArray(value))
872
+ badRequest(`${label} must be an object`);
873
+ const row = object(value);
874
+ for (const key of Object.keys(row))
875
+ if (!allowed.includes(key)) badRequest(`Unknown ${label} key: ${key}`);
876
+ return row;
877
+ }
878
+ function nonempty(value, label) {
879
+ if (!string(value).trim()) badRequest(`${label} must be a non-empty string`);
880
+ }
881
+ function jsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
882
+ if (value === null || typeof value === "string" || typeof value === "boolean") return;
883
+ if (typeof value === "number" && Number.isFinite(value)) return;
884
+ if (typeof value !== "object" || !value || ancestors.has(value))
885
+ badRequest("Expected finite, acyclic JSON");
886
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
887
+ badRequest("Expected a JSON object");
888
+ ancestors.add(value);
889
+ for (const child of Object.values(value)) jsonValue(child, ancestors);
890
+ ancestors.delete(value);
891
+ }
892
+ function validateField(value, field2, key, spec) {
893
+ if (field2.kind === "extraBody") {
894
+ validateExtraBody(value, spec);
895
+ return;
896
+ }
897
+ if (field2.kind === "enum") {
898
+ if (!field2.values?.includes(value)) badRequest(`Invalid ${key}`);
899
+ } else if (field2.kind === "boolean") {
900
+ if (typeof value !== "boolean" || field2.values && !field2.values.includes(value))
901
+ badRequest(`Invalid ${key}`);
902
+ } else if (field2.kind === "number") {
903
+ if (typeof value !== "number" || !Number.isFinite(value) || field2.integer && !Number.isInteger(value) || field2.minimum !== void 0 && value < field2.minimum || field2.maximum !== void 0 && value > field2.maximum || field2.precision !== void 0 && Math.abs(value * 10 ** field2.precision - Math.round(value * 10 ** field2.precision)) > 1e-8)
904
+ badRequest(`Invalid ${key}`);
905
+ } else if (field2.kind === "thinking") {
906
+ const row = keys(value, spec.id === "anthropic/messages" ? ["type", "display"] : ["type"], key);
907
+ if (!field2.values?.includes(row.type)) badRequest("Invalid thinking.type");
908
+ if (row.display !== void 0 && (row.type !== "adaptive" || !["summarized", "omitted"].includes(String(row.display))))
909
+ badRequest("display is only allowed with adaptive thinking");
910
+ } else if (field2.kind === "toolChoice") {
911
+ if (typeof value === "string") {
912
+ if (!field2.values?.includes(value)) badRequest("Invalid toolChoice");
913
+ } else {
914
+ if (!field2.description?.startsWith("Allows"))
915
+ badRequest("Forced tool choice is not supported");
916
+ const chat = spec.family === "chat";
917
+ const row = keys(value, chat ? ["type", "function"] : ["type", "name"], key);
918
+ if (row.type !== "function") badRequest("Invalid toolChoice type");
919
+ nonempty(
920
+ chat ? keys(row.function, ["name"], "toolChoice.function").name : row.name,
921
+ "toolChoice name"
922
+ );
923
+ }
924
+ } else if (field2.kind === "format") {
925
+ const row = keys(
926
+ value,
927
+ ["type", "name", "schema", "strict", "description", "json_schema"],
928
+ key
929
+ );
930
+ if (!field2.values?.includes(row.type)) badRequest(`Invalid ${key}.type`);
931
+ if (row.type !== "json_schema") keys(row, ["type"], key);
932
+ else {
933
+ const chat = spec.family === "chat";
934
+ keys(
935
+ row,
936
+ chat ? ["type", "json_schema"] : ["type", "name", "schema", "strict", "description"],
937
+ key
938
+ );
939
+ const schema = chat ? keys(row.json_schema, ["name", "schema", "strict", "description"], "json_schema") : row;
940
+ nonempty(schema.name, "schema name");
941
+ if (!schema.schema || typeof schema.schema !== "object" || Array.isArray(schema.schema))
942
+ badRequest("schema must be an object");
943
+ jsonValue(schema.schema);
944
+ if (schema.strict !== void 0 && typeof schema.strict !== "boolean")
945
+ badRequest("strict must be boolean");
946
+ if (schema.description !== void 0 && typeof schema.description !== "string")
947
+ badRequest("description must be string");
948
+ }
949
+ }
950
+ }
951
+ function validate(request, spec) {
952
+ const row = keys(
953
+ request,
954
+ [
955
+ "model",
956
+ "messages",
957
+ "tools",
958
+ "signal",
959
+ "baseUrl",
960
+ "apiKey",
961
+ "headers",
962
+ "timeoutMs",
963
+ "fetch",
964
+ ...Object.keys(spec.fields)
965
+ ],
966
+ "request"
967
+ );
968
+ nonempty(row.model, "model");
969
+ if (spec.id === "openai-compatible/v1/chat") {
970
+ nonempty(row.baseUrl, "baseUrl");
971
+ if (row.thinking !== void 0 && row.reasoningEffort !== void 0)
972
+ badRequest("Choose thinking or reasoningEffort, not both");
973
+ }
974
+ if (!Array.isArray(request.messages) || request.messages.length === 0)
975
+ badRequest("messages must be a non-empty array");
976
+ const resolvedBaseUrl = request.baseUrl !== void 0 ? request.baseUrl : env(spec.baseUrlEnv);
977
+ if (resolvedBaseUrl !== void 0) {
978
+ nonempty(resolvedBaseUrl, "baseUrl");
979
+ let url;
980
+ try {
981
+ url = new URL(resolvedBaseUrl);
982
+ } catch {
983
+ badRequest("Invalid baseUrl");
984
+ }
985
+ if (!["http:", "https:"].includes(url.protocol)) badRequest("baseUrl must use HTTP(S)");
986
+ }
987
+ if (request.apiKey !== void 0 && typeof request.apiKey !== "string")
988
+ badRequest("Invalid apiKey");
989
+ if (request.fetch !== void 0 && typeof request.fetch !== "function")
990
+ badRequest("Invalid fetch");
991
+ if (request.timeoutMs !== void 0 && (!Number.isFinite(request.timeoutMs) || request.timeoutMs <= 0))
992
+ badRequest("Invalid timeoutMs");
993
+ if (request.signal !== void 0 && !(request.signal instanceof AbortSignal))
994
+ badRequest("Invalid signal");
995
+ try {
996
+ new Headers(request.headers);
997
+ } catch {
998
+ badRequest("Invalid headers");
999
+ }
1000
+ for (const [key, field2] of Object.entries(spec.fields)) {
1001
+ const value = row[key];
1002
+ if (value === void 0) {
1003
+ if (field2.required) badRequest(`Missing ${key}`);
1004
+ } else validateField(value, field2, key, spec);
1005
+ }
1006
+ if (spec.id === "deepseek/chat") {
1007
+ const enabled = object(row.thinking).type ? object(row.thinking).type !== "disabled" : row.reasoningEffort !== "none";
1008
+ if (enabled && (row.toolChoice === "required" || row.toolChoice && typeof row.toolChoice === "object"))
1009
+ badRequest("Thinking rejects required or forced tools");
1010
+ }
1011
+ const callIds = /* @__PURE__ */ new Set();
1012
+ for (const message of request.messages) {
1013
+ keys(message, ["role", "content", "continuation"], "message");
1014
+ if (!["system", "user", "assistant", "tool"].includes(message.role))
1015
+ badRequest("Invalid message role");
1016
+ if (message.continuation !== void 0 && message.role !== "assistant")
1017
+ badRequest("Only assistant messages carry continuation");
1018
+ if (message.continuation !== void 0) {
1019
+ const saved2 = keys(message.continuation, ["protocolId", "model", "payload"], "continuation");
1020
+ nonempty(saved2.model, "continuation model");
1021
+ jsonValue(saved2.payload);
1022
+ }
1023
+ if (typeof message.content !== "string" && !Array.isArray(message.content))
1024
+ badRequest("Invalid message content");
1025
+ for (const part of typeof message.content === "string" ? [] : message.content) {
1026
+ const p = object(part);
1027
+ if (p.type === "text") {
1028
+ keys(p, ["type", "text"], "text part");
1029
+ if (typeof p.text !== "string") badRequest("Invalid text");
1030
+ } else if (p.type === "tool_call") {
1031
+ keys(p, ["type", "id", "name", "input"], "tool call");
1032
+ if (message.role !== "assistant") badRequest("Only assistants emit tool calls");
1033
+ nonempty(p.id, "tool call ID");
1034
+ nonempty(p.name, "tool name");
1035
+ jsonValue(p.input);
1036
+ if (callIds.has(String(p.id))) badRequest("Duplicate tool call ID");
1037
+ callIds.add(String(p.id));
1038
+ } else if (p.type === "tool_result") {
1039
+ keys(p, ["type", "toolCallId", "name", "output", "isError"], "tool result");
1040
+ nonempty(p.toolCallId, "tool result ID");
1041
+ jsonValue(p.output);
1042
+ if (message.role !== "tool" && message.role !== "user")
1043
+ badRequest("Invalid tool result role");
1044
+ if (!callIds.has(String(p.toolCallId)))
1045
+ badRequest("Tool result has no preceding tool call");
1046
+ if (p.name !== void 0) nonempty(p.name, "tool result name");
1047
+ if (p.isError !== void 0 && typeof p.isError !== "boolean")
1048
+ badRequest("Invalid isError");
1049
+ } else badRequest("Unknown dialogue part");
1050
+ }
1051
+ }
1052
+ if (request.tools !== void 0 && !Array.isArray(request.tools))
1053
+ badRequest("tools must be an array");
1054
+ const names = /* @__PURE__ */ new Set();
1055
+ for (const tool of array(request.tools)) {
1056
+ const t = keys(tool, ["name", "description", "inputSchema"], "tool");
1057
+ nonempty(t.name, "tool name");
1058
+ if (names.has(String(t.name))) badRequest("Duplicate tool name");
1059
+ names.add(String(t.name));
1060
+ if (t.description !== void 0 && typeof t.description !== "string")
1061
+ badRequest("Invalid tool description");
1062
+ if (!t.inputSchema || typeof t.inputSchema !== "object" || Array.isArray(t.inputSchema))
1063
+ badRequest("Tool inputSchema must be an object");
1064
+ jsonValue(t.inputSchema);
1065
+ }
1066
+ }
1067
+
1068
+ // src/transport/continuation.ts
1069
+ function requiredPaths(value, path = []) {
1070
+ if (!value || typeof value !== "object") return [];
1071
+ return Object.entries(value).flatMap(([key, child]) => {
1072
+ const next = [...path, key];
1073
+ return [
1074
+ "signature",
1075
+ "encrypted_content",
1076
+ "thoughtSignature",
1077
+ "reasoning_content",
1078
+ "reasoning_details"
1079
+ ].includes(key) ? child === null ? [] : [next] : requiredPaths(child, next);
1080
+ });
1081
+ }
1082
+ function continuation(spec, model, data, extra = {}) {
1083
+ const emptyThinkingSignatures = spec.id === "openrouter/messages" && Array.isArray(data) ? data.flatMap(
1084
+ (item, index) => object(item).type === "thinking" && object(item).signature === "" ? [index] : []
1085
+ ) : [];
1086
+ return {
1087
+ protocolId: spec.id,
1088
+ model,
1089
+ payload: {
1090
+ data: structuredClone(data),
1091
+ requiredPaths: requiredPaths(data),
1092
+ ...emptyThinkingSignatures.length ? { emptyThinkingSignatures } : {},
1093
+ ...extra
1094
+ }
1095
+ };
1096
+ }
1097
+ function replay(spec, saved2, model = saved2.model) {
1098
+ keys(saved2, ["protocolId", "model", "payload"], "continuation");
1099
+ if (saved2.protocolId !== spec.id || saved2.model !== model)
1100
+ badRequest("Continuation protocol/model mismatch; finish the tool chain before switching");
1101
+ nonempty(saved2.model, "continuation model");
1102
+ jsonValue(saved2.payload);
1103
+ const payload = object(saved2.payload);
1104
+ if (!("data" in payload) || !Array.isArray(payload.requiredPaths))
1105
+ badRequest("Incomplete continuation payload");
1106
+ const data = payload.data;
1107
+ const acceptsEmptyThinkingSignature = (index) => spec.id === "openrouter/messages" && array(payload.emptyThinkingSignatures).includes(index);
1108
+ for (const path of payload.requiredPaths) {
1109
+ if (!Array.isArray(path) || !path.length || path.some((p) => typeof p !== "string"))
1110
+ badRequest("Invalid continuation requirements");
1111
+ let current = data;
1112
+ for (const key of path)
1113
+ current = current && typeof current === "object" ? current[key] : void 0;
1114
+ const leaf = String(path.at(-1));
1115
+ if (current === void 0 || current === null || current === "" && leaf !== "reasoning_content" && !(path.length === 2 && leaf === "signature" && acceptsEmptyThinkingSignature(Number(path[0]))))
1116
+ badRequest("Continuation is missing a required signed/reasoning field");
1117
+ }
1118
+ if (spec.family === "responses") {
1119
+ if (!Array.isArray(data))
1120
+ badRequest("Responses continuation must contain ordered output items");
1121
+ for (const item of data) {
1122
+ const row = object(item);
1123
+ if (row.type === "reasoning" && spec.id === "openai/responses" && !string(row.encrypted_content))
1124
+ badRequest("Stateless Responses replay requires encrypted_content");
1125
+ if (row.type === "function_call" && (!string(row.call_id) || !string(row.name) || typeof row.arguments !== "string"))
1126
+ badRequest("Incomplete function call continuation");
1127
+ }
1128
+ } else if (spec.family === "messages") {
1129
+ if (!Array.isArray(data))
1130
+ badRequest("Messages continuation must contain ordered content blocks");
1131
+ for (const [index, item] of data.entries()) {
1132
+ const row = object(item);
1133
+ if (row.type === "thinking" && (!string(row.signature) && !(row.signature === "" && acceptsEmptyThinkingSignature(index)) || typeof row.thinking !== "string"))
1134
+ badRequest("Thinking replay requires signature and original thinking text");
1135
+ if (spec.id === "deepseek/messages" && row.type === "redacted_thinking")
1136
+ badRequest("DeepSeek does not support redacted_thinking");
1137
+ }
1138
+ } else if (spec.family === "gemini") {
1139
+ if (!Array.isArray(data)) badRequest("Gemini continuation must contain ordered parts");
1140
+ const firstCall = array(data).find((item) => object(item).functionCall);
1141
+ if (firstCall && !string(object(firstCall).thoughtSignature))
1142
+ badRequest("Gemini tool replay requires thoughtSignature on its first function call part");
1143
+ } else {
1144
+ if (!data || typeof data !== "object" || Array.isArray(data))
1145
+ badRequest("Chat continuation must contain an assistant message");
1146
+ const row = object(data);
1147
+ if (spec.id === "kimi/chat" && typeof row.reasoning_content !== "string")
1148
+ badRequest("Kimi replay requires reasoning_content");
1149
+ if (spec.id === "deepseek/chat" && array(row.tool_calls).length && typeof row.reasoning_content !== "string" && payload.thinkingDisabled !== true)
1150
+ badRequest("DeepSeek tool replay requires reasoning_content");
1151
+ }
1152
+ return structuredClone(data);
1153
+ }
1154
+
1155
+ // src/transport/encode.ts
1156
+ function output(value) {
1157
+ return typeof value === "string" ? value : JSON.stringify(value);
1158
+ }
1159
+ function text(message) {
1160
+ return parts(message).filter((p) => p.type === "text").map((p) => p.text).join("");
1161
+ }
1162
+ function saved(spec, request, message) {
1163
+ if (message.continuation) {
1164
+ const value = replay(spec, message.continuation, request.model);
1165
+ const calls = parts(message).filter((part) => part.type === "tool_call");
1166
+ const rawCalls = spec.family === "chat" ? array(object(value).tool_calls) : array(value);
1167
+ for (const call of calls) {
1168
+ if (!rawCalls.some((item) => {
1169
+ const row = object(item), fn = object(row.functionCall);
1170
+ const identity = (row.id === call.id || row.call_id === call.id || fn.id === call.id || spec.family === "gemini" && fn.name === call.name) && (row.name === call.name || object(row.function).name === call.name || fn.name === call.name);
1171
+ if (!identity) return false;
1172
+ let input = spec.family === "gemini" ? fn.args ?? {} : row.input;
1173
+ if (spec.family === "responses" || spec.family === "chat") {
1174
+ const args = spec.family === "responses" ? row.arguments : object(row.function).arguments;
1175
+ try {
1176
+ input = JSON.parse(string(args));
1177
+ } catch {
1178
+ badRequest("Continuation has invalid tool arguments");
1179
+ }
1180
+ }
1181
+ return canonical(input) === canonical(call.input);
1182
+ }))
1183
+ badRequest("Continuation does not contain the paired tool call");
1184
+ }
1185
+ return value;
1186
+ }
1187
+ const toolChain = parts(message).some((p) => p.type === "tool_call");
1188
+ if (toolChain) badRequest("Tool-chain replay requires the original continuation");
1189
+ return void 0;
1190
+ }
1191
+ function chatMessages(spec, request) {
1192
+ return request.messages.flatMap((message) => {
1193
+ const restored = saved(spec, request, message);
1194
+ if (restored !== void 0) return [restored];
1195
+ const content = parts(message), calls = content.filter((p) => p.type === "tool_call"), results = content.filter((p) => p.type === "tool_result");
1196
+ const rows = [];
1197
+ if (text(message) || calls.length || !results.length)
1198
+ rows.push({
1199
+ role: message.role,
1200
+ content: text(message) || (calls.length ? null : ""),
1201
+ ...calls.length ? {
1202
+ tool_calls: calls.map((p) => ({
1203
+ id: p.id,
1204
+ type: "function",
1205
+ function: { name: p.name, arguments: JSON.stringify(p.input) }
1206
+ }))
1207
+ } : {}
1208
+ });
1209
+ rows.push(
1210
+ ...results.map((p) => ({
1211
+ role: "tool",
1212
+ tool_call_id: p.toolCallId,
1213
+ content: output(p.output)
1214
+ }))
1215
+ );
1216
+ return rows;
1217
+ });
1218
+ }
1219
+ function messagesBlock(part) {
1220
+ if (part.type === "text") return { type: "text", text: part.text };
1221
+ if (part.type === "tool_call")
1222
+ return { type: "tool_use", id: part.id, name: part.name, input: part.input };
1223
+ return {
1224
+ type: "tool_result",
1225
+ tool_use_id: part.toolCallId,
1226
+ content: output(part.output),
1227
+ ...part.isError === void 0 ? {} : { is_error: part.isError }
1228
+ };
1229
+ }
1230
+ function geminiBlock(part, names) {
1231
+ if (part.type === "text") return { text: part.text };
1232
+ if (part.type === "tool_call") {
1233
+ names.set(part.id, part.name);
1234
+ return { functionCall: { id: part.id, name: part.name, args: part.input } };
1235
+ }
1236
+ const name = part.name ?? names.get(part.toolCallId);
1237
+ if (!name) badRequest("Gemini functionResponse requires its tool name");
1238
+ return {
1239
+ functionResponse: {
1240
+ id: part.toolCallId,
1241
+ name,
1242
+ response: part.output && typeof part.output === "object" && !Array.isArray(part.output) ? part.output : { result: part.output }
1243
+ }
1244
+ };
1245
+ }
1246
+ function encode(spec, request, stream = false) {
1247
+ validate(request, spec);
1248
+ const body = spec.family === "gemini" ? {} : { model: request.model };
1249
+ const row = request;
1250
+ if (spec.family === "chat") body.messages = chatMessages(spec, request);
1251
+ else if (spec.family === "responses") {
1252
+ const input = [];
1253
+ let storedIndex = -1;
1254
+ if (spec.id === "glm/responses" && row.store === true) {
1255
+ for (const [index, message] of request.messages.entries())
1256
+ if (message.continuation && object(message.continuation.payload).stored === true && string(object(message.continuation.payload).responseId))
1257
+ storedIndex = index;
1258
+ }
1259
+ for (const [index, message] of request.messages.entries()) {
1260
+ const restored = saved(spec, request, message);
1261
+ if (storedIndex >= 0 && index <= storedIndex) {
1262
+ if (index === storedIndex)
1263
+ body.previous_response_id = string(object(message.continuation?.payload).responseId);
1264
+ continue;
1265
+ }
1266
+ if (restored !== void 0) input.push(...array(restored));
1267
+ else {
1268
+ for (const p of parts(message)) {
1269
+ if (p.type === "text") input.push({ role: message.role, content: p.text });
1270
+ else if (p.type === "tool_call")
1271
+ input.push({
1272
+ type: "function_call",
1273
+ call_id: p.id,
1274
+ name: p.name,
1275
+ arguments: JSON.stringify(p.input)
1276
+ });
1277
+ else
1278
+ input.push({
1279
+ type: "function_call_output",
1280
+ call_id: p.toolCallId,
1281
+ output: output(p.output)
1282
+ });
1283
+ }
1284
+ }
1285
+ }
1286
+ body.input = input;
1287
+ if (spec.id === "openai/responses" && (row.store === false || request.tools?.length || request.messages.some((m) => m.continuation)))
1288
+ body.include = ["reasoning.encrypted_content"];
1289
+ } else {
1290
+ const gemini = spec.family === "gemini", names = /* @__PURE__ */ new Map();
1291
+ const system = [], messages = [];
1292
+ for (const message of request.messages) {
1293
+ for (const p of parts(message)) if (p.type === "tool_call") names.set(p.id, p.name);
1294
+ const restored = saved(spec, request, message);
1295
+ const content = restored === void 0 ? parts(message).map((p) => gemini ? geminiBlock(p, names) : messagesBlock(p)) : array(restored);
1296
+ if (message.role === "system") system.push(...content);
1297
+ else
1298
+ messages.push(
1299
+ gemini ? { role: message.role === "assistant" ? "model" : "user", parts: content } : { role: message.role === "assistant" ? "assistant" : "user", content }
1300
+ );
1301
+ }
1302
+ body[gemini ? "contents" : "messages"] = messages;
1303
+ if (system.length)
1304
+ body[gemini ? "systemInstruction" : "system"] = gemini ? { parts: system } : system;
1305
+ }
1306
+ if (request.tools !== void 0) {
1307
+ const tools = request.tools.map((tool) => ({
1308
+ name: tool.name,
1309
+ ...tool.description === void 0 ? {} : { description: tool.description },
1310
+ [spec.family === "messages" ? "input_schema" : "parameters"]: tool.inputSchema
1311
+ }));
1312
+ body.tools = spec.family === "chat" ? tools.map((tool) => ({ type: "function", function: tool })) : spec.family === "responses" ? tools.map((tool) => ({ type: "function", ...tool })) : spec.family === "gemini" ? [{ functionDeclarations: tools }] : tools;
1313
+ }
1314
+ for (const [key2, field2] of Object.entries(spec.fields)) {
1315
+ if (row[key2] === void 0) continue;
1316
+ if (spec.id === "openai-compatible/v1/chat") {
1317
+ if (["extraBody", "maxTokensParam", "includeStreamUsage"].includes(key2)) continue;
1318
+ if (key2 === "maxOutputTokens") {
1319
+ body[String(row.maxTokensParam ?? "max_tokens")] = row[key2];
1320
+ continue;
1321
+ }
1322
+ }
1323
+ setPath(body, field2.kind === "thinking" ? "thinking" : field2.wireKey, row[key2]);
1324
+ }
1325
+ if (spec.id === "openai-compatible/v1/chat" && row.extraBody) Object.assign(body, row.extraBody);
1326
+ if (stream) {
1327
+ if (spec.family !== "gemini") body.stream = true;
1328
+ if (spec.family === "chat" && !spec.id.startsWith("openrouter/") && (spec.id !== "openai-compatible/v1/chat" || row.includeStreamUsage === true))
1329
+ body.stream_options = spec.id === "glm/chat" ? { chunk_include_usage: true } : { include_usage: true };
1330
+ }
1331
+ const headers = new Headers(request.headers), key = resolveApiKey(spec, request.apiKey);
1332
+ headers.set("content-type", "application/json");
1333
+ if (key)
1334
+ headers.set(
1335
+ spec.family === "gemini" ? "x-goog-api-key" : spec.family === "messages" && !spec.id.startsWith("openrouter/") ? "x-api-key" : "authorization",
1336
+ spec.family === "gemini" || spec.family === "messages" && !spec.id.startsWith("openrouter/") ? key : `Bearer ${key}`
1337
+ );
1338
+ if (spec.id === "anthropic/messages") headers.set("anthropic-version", "2026-10-21");
1339
+ if (spec.id === "deepseek/messages") headers.delete("anthropic-version");
1340
+ if (spec.id.startsWith("openrouter/")) headers.set("X-OpenRouter-Metadata", "enabled");
1341
+ const base = resolveBaseUrl(spec, request.baseUrl).replace(/\/+$/, "");
1342
+ const path = spec.family === "gemini" ? `/models/${encodeURIComponent(request.model)}:${stream ? "streamGenerateContent?alt=sse" : "generateContent"}` : spec.path;
1343
+ return {
1344
+ url: base + path,
1345
+ method: "POST",
1346
+ headers: Object.fromEntries(headers),
1347
+ body: structuredClone(body)
1348
+ };
1349
+ }
1350
+
1351
+ // src/transport/decode.ts
1352
+ function addCall(builder, id, name, input) {
1353
+ const index = builder.response.toolCalls.length;
1354
+ builder.start(index, string(id), string(name), input);
1355
+ builder.done(index);
1356
+ }
1357
+ function decode(spec, raw, model) {
1358
+ const value = object(raw), builder = new ResponseBuilder(spec.id, model);
1359
+ const result = builder.response;
1360
+ if (value.error || value.status === "failed") invalid("Provider returned a model error");
1361
+ if (spec.family === "chat") {
1362
+ const choice2 = object(array(value.choices)[0]);
1363
+ if (!choice2.message || choice2.finish_reason === "error")
1364
+ invalid("Missing or failed Chat response message");
1365
+ const message = object(choice2.message);
1366
+ builder.text(string(message.content));
1367
+ const reasoning = message.reasoning_content ?? message.reasoning;
1368
+ builder.text(
1369
+ typeof reasoning === "string" ? reasoning : array(message.reasoning_details).map((detail) => string(object(detail).text ?? object(detail).summary)).join(""),
1370
+ true
1371
+ );
1372
+ for (const item of array(message.tool_calls)) {
1373
+ const call = object(item), fn = object(call.function);
1374
+ addCall(builder, call.id, fn.name, json(string(fn.arguments) || "{}"));
1375
+ }
1376
+ result.usage = normalizeUsage(spec.id, value.usage);
1377
+ result.finishReason = finish(choice2.finish_reason);
1378
+ result.continuation = continuation(spec, model, message);
1379
+ } else if (spec.family === "responses") {
1380
+ if (!Array.isArray(value.output)) invalid("Missing Responses output items");
1381
+ for (const item of value.output) {
1382
+ const block = object(item);
1383
+ if (block.type === "function_call")
1384
+ addCall(builder, block.call_id, block.name, json(string(block.arguments) || "{}"));
1385
+ if (block.type === "message" || block.type === "reasoning") {
1386
+ const content = Array.isArray(block.content) ? block.content : block.content ? [block.content] : array(block.summary);
1387
+ for (const part of content)
1388
+ builder.text(string(object(part).text), block.type === "reasoning");
1389
+ }
1390
+ }
1391
+ result.usage = normalizeUsage(spec.id, value.usage);
1392
+ result.finishReason = value.status === "incomplete" ? finish(object(value.incomplete_details).reason) : finish(value.status);
1393
+ result.continuation = continuation(
1394
+ spec,
1395
+ model,
1396
+ value.output,
1397
+ spec.id === "glm/responses" && string(value.id) ? { stored: value.store === true, responseId: string(value.id) } : {}
1398
+ );
1399
+ } else if (spec.family === "messages") {
1400
+ if (!Array.isArray(value.content)) invalid("Missing Messages content blocks");
1401
+ for (const item of value.content) {
1402
+ const block = object(item);
1403
+ if (block.type === "text") builder.text(string(block.text));
1404
+ if (block.type === "thinking") builder.text(string(block.thinking), true);
1405
+ if (block.type === "redacted_thinking" && spec.id === "deepseek/messages")
1406
+ invalid("DeepSeek returned unsupported redacted_thinking");
1407
+ if (block.type === "tool_use")
1408
+ addCall(builder, block.id, block.name, block.input);
1409
+ }
1410
+ result.usage = normalizeUsage(spec.id, value.usage);
1411
+ result.finishReason = finish(value.stop_reason);
1412
+ result.continuation = continuation(spec, model, value.content);
1413
+ } else {
1414
+ const candidate = object(array(value.candidates)[0]), content = object(candidate.content);
1415
+ if (!Array.isArray(content.parts)) {
1416
+ if (!object(value.promptFeedback).blockReason && !candidate.finishReason)
1417
+ invalid("Missing Gemini candidate content");
1418
+ }
1419
+ const blocks = array(content.parts);
1420
+ for (const item of blocks) {
1421
+ const part = object(item);
1422
+ builder.text(string(part.text), part.thought === true);
1423
+ if (part.functionCall) {
1424
+ const call = object(part.functionCall);
1425
+ addCall(
1426
+ builder,
1427
+ string(call.id) || `gemini-call-${result.toolCalls.length}`,
1428
+ call.name,
1429
+ call.args ?? {}
1430
+ );
1431
+ }
1432
+ }
1433
+ result.usage = normalizeUsage(spec.id, value.usageMetadata);
1434
+ result.finishReason = finish(
1435
+ candidate.finishReason ?? object(value.promptFeedback).blockReason
1436
+ );
1437
+ result.continuation = continuation(spec, model, blocks);
1438
+ }
1439
+ if (result.toolCalls.length && result.finishReason === "stop") result.finishReason = "tool_calls";
1440
+ result.rawResponse = raw;
1441
+ return result;
1442
+ }
1443
+
1444
+ // src/transport/stream.ts
1445
+ function accumulator(spec, model) {
1446
+ const builder = new ResponseBuilder(spec.id, model), frames = [];
1447
+ const blocks = /* @__PURE__ */ new Map(), argumentsByIndex = /* @__PURE__ */ new Map();
1448
+ const openBlocks = /* @__PURE__ */ new Set();
1449
+ const details = [], detailKeys = /* @__PURE__ */ new Map();
1450
+ let rawUsage = {}, started = false, finished = false, final;
1451
+ const deltaText = (value, reasoning = false) => builder.text(string(value), reasoning);
1452
+ const accept = (raw, event) => {
1453
+ frames.push(raw);
1454
+ const value = object(raw), type = string(value.type) || event;
1455
+ if (value.error || type === "error" || type === "response.failed" || value.status === "failed")
1456
+ invalid("Provider reported a stream error");
1457
+ const events = [];
1458
+ if (spec.family === "chat") {
1459
+ if (raw === "[DONE]") {
1460
+ if (!finished) invalid("Chat stream omitted finish_reason");
1461
+ return { events, complete: true };
1462
+ }
1463
+ if (value.usage) builder.response.usage = normalizeUsage(spec.id, value.usage);
1464
+ const choice2 = object(array(value.choices)[0]), delta = object(choice2.delta);
1465
+ events.push(
1466
+ ...deltaText(delta.content),
1467
+ ...deltaText(delta.reasoning_content ?? delta.reasoning, true)
1468
+ );
1469
+ const message = blocks.get(0) ?? { role: "assistant", content: "" };
1470
+ blocks.set(0, message);
1471
+ if (typeof delta.reasoning_content === "string")
1472
+ message.reasoning_content = string(message.reasoning_content) + delta.reasoning_content;
1473
+ if (typeof delta.reasoning === "string")
1474
+ message.reasoning = string(message.reasoning) + delta.reasoning;
1475
+ for (const item of array(delta.reasoning_details)) {
1476
+ const detail = object(item);
1477
+ if (typeof delta.reasoning !== "string" && typeof delta.reasoning_content !== "string")
1478
+ events.push(...deltaText(detail.text ?? detail.summary, true));
1479
+ const identity = detail.index !== void 0 ? `index:${String(detail.index)}` : string(detail.id) ? `id:${string(detail.id)}` : "";
1480
+ const position = identity ? detailKeys.get(identity) : void 0;
1481
+ if (position === void 0) {
1482
+ if (identity) detailKeys.set(identity, details.length);
1483
+ details.push(structuredClone(detail));
1484
+ } else {
1485
+ const target = details[position];
1486
+ for (const [key, child] of Object.entries(detail))
1487
+ target[key] = ["text", "summary", "data", "signature"].includes(key) && typeof child === "string" ? string(target[key]) + child : child;
1488
+ }
1489
+ }
1490
+ for (const item of array(delta.tool_calls)) {
1491
+ const call = object(item), fn = object(call.function), index = Number(call.index);
1492
+ if (!Number.isInteger(index) || index < 0) invalid("Invalid Chat tool index");
1493
+ if (!builder.calls.has(index))
1494
+ events.push(builder.start(index, string(call.id), string(fn.name)));
1495
+ if (typeof fn.arguments === "string") events.push(builder.delta(index, fn.arguments));
1496
+ }
1497
+ if (choice2.finish_reason != null) {
1498
+ if (choice2.finish_reason === "error") invalid("Chat stream finished with error");
1499
+ builder.response.finishReason = finish(choice2.finish_reason);
1500
+ finished = true;
1501
+ }
1502
+ } else if (spec.family === "messages") {
1503
+ const index = Number(value.index);
1504
+ if (type === "message_start") {
1505
+ if (started) invalid("Duplicate message_start");
1506
+ started = true;
1507
+ rawUsage = { ...object(object(value.message).usage) };
1508
+ } else if (type === "content_block_start") {
1509
+ if (!started || !Number.isInteger(index) || index < 0 || blocks.has(index))
1510
+ invalid("Invalid content block index");
1511
+ const block = structuredClone(object(value.content_block));
1512
+ blocks.set(index, block);
1513
+ openBlocks.add(index);
1514
+ if (block.type === "tool_use")
1515
+ events.push(
1516
+ builder.start(index, string(block.id), string(block.name), block.input)
1517
+ );
1518
+ if (block.type === "text") events.push(...deltaText(block.text));
1519
+ if (block.type === "thinking") events.push(...deltaText(block.thinking, true));
1520
+ } else if (type === "content_block_delta") {
1521
+ const block = blocks.get(index);
1522
+ if (!block || !openBlocks.has(index)) invalid("Delta has no open content block");
1523
+ const delta = object(value.delta);
1524
+ if (delta.type === "text_delta") {
1525
+ block.text = string(block.text) + string(delta.text);
1526
+ events.push(...deltaText(delta.text));
1527
+ }
1528
+ if (delta.type === "thinking_delta") {
1529
+ block.thinking = string(block.thinking) + string(delta.thinking);
1530
+ events.push(...deltaText(delta.thinking, true));
1531
+ }
1532
+ if (delta.type === "signature_delta")
1533
+ block.signature = string(block.signature) + string(delta.signature);
1534
+ if (delta.type === "input_json_delta") {
1535
+ const fragment = string(delta.partial_json);
1536
+ argumentsByIndex.set(index, (argumentsByIndex.get(index) ?? "") + fragment);
1537
+ events.push(builder.delta(index, fragment));
1538
+ }
1539
+ } else if (type === "content_block_stop") {
1540
+ if (!openBlocks.delete(index)) invalid("Stop has no open content block");
1541
+ if (builder.calls.has(index)) {
1542
+ const args = argumentsByIndex.get(index);
1543
+ if (args) blocks.get(index).input = json(args);
1544
+ events.push(builder.done(index));
1545
+ }
1546
+ } else if (type === "message_delta") {
1547
+ rawUsage = { ...rawUsage, ...object(value.usage) };
1548
+ const reason = object(value.delta).stop_reason;
1549
+ if (reason != null) {
1550
+ builder.response.finishReason = finish(reason);
1551
+ finished = true;
1552
+ }
1553
+ } else if (type === "message_stop") {
1554
+ if (!started || !finished || builder.calls.size || openBlocks.size)
1555
+ invalid("Incomplete Messages stream");
1556
+ builder.response.usage = normalizeUsage(spec.id, rawUsage);
1557
+ builder.response.continuation = continuation(
1558
+ spec,
1559
+ model,
1560
+ [...blocks.entries()].sort(([a], [b]) => a - b).map(([, block]) => block)
1561
+ );
1562
+ return { events, complete: true };
1563
+ }
1564
+ } else if (spec.family === "responses") {
1565
+ if (type === "response.output_text.delta") events.push(...deltaText(value.delta));
1566
+ else if (type === "response.reasoning_text.delta" || type === "response.reasoning_summary_text.delta")
1567
+ events.push(...deltaText(value.delta, true));
1568
+ else if (type === "response.output_item.added") {
1569
+ const index = Number(value.output_index), block = structuredClone(object(value.item));
1570
+ if (!Number.isInteger(index) || blocks.has(index)) invalid("Invalid output item index");
1571
+ blocks.set(index, block);
1572
+ if (block.type === "function_call")
1573
+ events.push(builder.start(index, string(block.call_id), string(block.name)));
1574
+ } else if (type === "response.function_call_arguments.delta") {
1575
+ const index = Number(value.output_index), fragment = string(value.delta);
1576
+ argumentsByIndex.set(index, (argumentsByIndex.get(index) ?? "") + fragment);
1577
+ events.push(builder.delta(index, fragment));
1578
+ } else if (type === "response.function_call_arguments.done") {
1579
+ const index = Number(value.output_index), block = blocks.get(index);
1580
+ if (!block) invalid("Arguments done has no output item");
1581
+ block.arguments = typeof value.arguments === "string" ? value.arguments : argumentsByIndex.get(index) ?? "";
1582
+ const call = builder.calls.get(index);
1583
+ if (call) {
1584
+ call.arguments = string(block.arguments);
1585
+ events.push(builder.done(index));
1586
+ }
1587
+ } else if (type === "response.output_item.done") {
1588
+ const index = Number(value.output_index), block = structuredClone(object(value.item));
1589
+ blocks.set(index, block);
1590
+ const call = builder.calls.get(index);
1591
+ if (call) {
1592
+ call.arguments = string(block.arguments);
1593
+ events.push(builder.done(index));
1594
+ }
1595
+ } else if (type === "response.completed" || type === "response.incomplete") {
1596
+ const response = object(value.response);
1597
+ const output2 = response.output ?? [...blocks.entries()].sort(([a], [b]) => a - b).map(([, block]) => block);
1598
+ final = decode(
1599
+ spec,
1600
+ {
1601
+ ...response,
1602
+ output: output2,
1603
+ status: response.status ?? (type === "response.incomplete" ? "incomplete" : "completed")
1604
+ },
1605
+ model
1606
+ );
1607
+ for (const call of final.toolCalls)
1608
+ if (!builder.response.toolCalls.some((done) => done.id === call.id)) {
1609
+ const pending = [...builder.calls.entries()].find(([, item]) => item.id === call.id);
1610
+ if (pending) {
1611
+ pending[1].arguments = JSON.stringify(call.input);
1612
+ events.push(builder.done(pending[0]));
1613
+ } else {
1614
+ events.push(
1615
+ { type: "tool_call.start", id: call.id, name: call.name },
1616
+ { type: "tool_call.done", toolCall: call }
1617
+ );
1618
+ }
1619
+ }
1620
+ if (builder.calls.size) invalid("Responses stream left unfinished tool calls");
1621
+ return { events, complete: true };
1622
+ }
1623
+ } else {
1624
+ const candidate = object(array(value.candidates)[0]), incoming = array(object(candidate.content).parts);
1625
+ for (const item of incoming) {
1626
+ const part = structuredClone(object(item));
1627
+ if (part.functionCall && !string(object(part.functionCall).id))
1628
+ object(part.functionCall).id = `gemini-call-${builder.response.toolCalls.length}`;
1629
+ blocks.set(blocks.size, part);
1630
+ events.push(...deltaText(part.text, part.thought === true));
1631
+ if (part.functionCall) {
1632
+ const call = object(part.functionCall), index = builder.response.toolCalls.length;
1633
+ events.push(
1634
+ builder.start(
1635
+ index,
1636
+ string(call.id),
1637
+ string(call.name),
1638
+ call.args ?? {}
1639
+ ),
1640
+ builder.done(index)
1641
+ );
1642
+ }
1643
+ }
1644
+ if (value.usageMetadata)
1645
+ builder.response.usage = normalizeUsage(spec.id, value.usageMetadata);
1646
+ if (candidate.finishReason != null) {
1647
+ builder.response.finishReason = finish(candidate.finishReason);
1648
+ finished = true;
1649
+ }
1650
+ if (object(value.promptFeedback).blockReason) {
1651
+ builder.response.finishReason = finish(object(value.promptFeedback).blockReason);
1652
+ finished = true;
1653
+ }
1654
+ }
1655
+ return { events, complete: false };
1656
+ };
1657
+ return {
1658
+ accept,
1659
+ result() {
1660
+ if (spec.family === "gemini") {
1661
+ if (!finished) invalid("Gemini stream omitted finishReason");
1662
+ builder.response.continuation = continuation(spec, model, [
1663
+ ...blocks.values()
1664
+ ]);
1665
+ } else if (spec.family === "chat") {
1666
+ const message = blocks.get(0) ?? { role: "assistant" };
1667
+ message.content = builder.response.text;
1668
+ if (details.length) message.reasoning_details = details;
1669
+ builder.complete();
1670
+ if (builder.response.toolCalls.length)
1671
+ message.tool_calls = builder.response.toolCalls.map((call) => ({
1672
+ id: call.id,
1673
+ type: "function",
1674
+ function: { name: call.name, arguments: JSON.stringify(call.input) }
1675
+ }));
1676
+ builder.response.continuation = continuation(spec, model, message);
1677
+ }
1678
+ const result = final ?? builder.response;
1679
+ if (result.toolCalls.length && result.finishReason === "stop")
1680
+ result.finishReason = "tool_calls";
1681
+ result.rawResponse = frames;
1682
+ return result;
1683
+ }
1684
+ };
1685
+ }
1686
+
1687
+ // src/transport/protocol.ts
1688
+ function contextualize(spec, request, result) {
1689
+ const row = request;
1690
+ if (result.continuation) {
1691
+ const payload = object(result.continuation.payload);
1692
+ if (spec.id === "glm/responses") {
1693
+ if (row.store !== true) {
1694
+ delete payload.stored;
1695
+ delete payload.responseId;
1696
+ } else if (typeof payload.responseId === "string" && payload.responseId)
1697
+ payload.stored = true;
1698
+ }
1699
+ if (spec.id === "deepseek/chat" && (object(row.thinking).type === "disabled" || !row.thinking && row.reasoningEffort === "none"))
1700
+ payload.thinkingDisabled = true;
1701
+ }
1702
+ return result;
1703
+ }
1704
+ function createProtocol(spec) {
1705
+ const meta = metadata(spec);
1706
+ const protocol = {
1707
+ meta,
1708
+ encode(request) {
1709
+ return encode(spec, request);
1710
+ },
1711
+ decode(raw, model) {
1712
+ if (!model.trim()) badRequest("decode requires a non-empty model");
1713
+ return decode(spec, raw, model);
1714
+ },
1715
+ replay(saved2, model) {
1716
+ return replay(spec, saved2, model);
1717
+ },
1718
+ async generateText(request) {
1719
+ const wire = encode(spec, request);
1720
+ const connection = await connect(
1721
+ wire.url,
1722
+ wire.body,
1723
+ wire.headers,
1724
+ { ...request, headers: wire.headers },
1725
+ request
1726
+ );
1727
+ try {
1728
+ return contextualize(
1729
+ spec,
1730
+ request,
1731
+ decode(spec, await readJson(connection), request.model)
1732
+ );
1733
+ } catch (cause) {
1734
+ throw connection.failure(cause);
1735
+ } finally {
1736
+ connection.close();
1737
+ }
1738
+ },
1739
+ async *streamText(request) {
1740
+ const wire = encode(spec, request, true);
1741
+ const connection = await connect(
1742
+ wire.url,
1743
+ wire.body,
1744
+ wire.headers,
1745
+ { ...request, headers: wire.headers },
1746
+ request
1747
+ );
1748
+ const state = accumulator(spec, request.model), doneCalls = /* @__PURE__ */ new Set();
1749
+ let completed = false;
1750
+ try {
1751
+ for await (const frame of readSse(connection)) {
1752
+ const accepted = state.accept(
1753
+ frame.data === "[DONE]" ? "[DONE]" : json(frame.data),
1754
+ frame.event
1755
+ );
1756
+ for (const event of accepted.events) {
1757
+ if (event.type === "tool_call.done") doneCalls.add(event.toolCall.id);
1758
+ yield event;
1759
+ }
1760
+ if (accepted.complete) {
1761
+ completed = true;
1762
+ break;
1763
+ }
1764
+ }
1765
+ if (!completed && spec.family !== "gemini")
1766
+ throw new ModelError({
1767
+ code: "invalid_response",
1768
+ message: "Model stream ended before completion",
1769
+ uncertainDelivery: true
1770
+ });
1771
+ const response = contextualize(spec, request, state.result());
1772
+ for (const toolCall of response.toolCalls)
1773
+ if (!doneCalls.has(toolCall.id)) yield { type: "tool_call.done", toolCall };
1774
+ yield { type: "response.completed", response };
1775
+ } catch (cause) {
1776
+ throw connection.failure(cause);
1777
+ } finally {
1778
+ connection.close();
1779
+ }
1780
+ },
1781
+ bind(config) {
1782
+ keys(
1783
+ config,
1784
+ [
1785
+ "model",
1786
+ "baseUrl",
1787
+ "apiKey",
1788
+ "headers",
1789
+ "timeoutMs",
1790
+ "fetch",
1791
+ ...Object.keys(spec.fields)
1792
+ ],
1793
+ "bind config"
1794
+ );
1795
+ validate({ ...config, messages: [{ role: "user", content: "" }] }, spec);
1796
+ const boundBaseUrl = resolveBaseUrl(spec, config.baseUrl);
1797
+ const { fetch: customFetch, headers, ...serializable } = config;
1798
+ const frozen = {
1799
+ ...structuredClone(serializable),
1800
+ baseUrl: boundBaseUrl,
1801
+ ...customFetch ? { fetch: customFetch } : {},
1802
+ ...headers ? { headers: Object.fromEntries(new Headers(headers)) } : {}
1803
+ };
1804
+ const requestFor = (input) => {
1805
+ keys(input, ["messages", "tools", "maxOutputTokens", "signal"], "bound input");
1806
+ return {
1807
+ ...frozen,
1808
+ ...Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0))
1809
+ };
1810
+ };
1811
+ return Object.freeze({
1812
+ protocolId: spec.id,
1813
+ model: config.model,
1814
+ baseUrl: boundBaseUrl,
1815
+ meta,
1816
+ generate: (input) => protocol.generateText(requestFor(input)),
1817
+ stream: (input) => protocol.streamText(requestFor(input)),
1818
+ encode: (input) => protocol.encode(requestFor(input)),
1819
+ replay: (saved2) => replay(spec, saved2, frozen.model)
1820
+ });
1821
+ }
1822
+ };
1823
+ return Object.freeze(protocol);
1824
+ }
1825
+
1826
+ export { ModelError, abortError, canonical, createProtocol, emptyUsage, object, specs };
1827
+ //# sourceMappingURL=chunk-EFJFQCXF.js.map
1828
+ //# sourceMappingURL=chunk-EFJFQCXF.js.map