@machina.ai/ch-llm-reboot 0.1.5-alpha.1.c1
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/LICENSE +21 -0
- package/README.i18n.yaml +6 -0
- package/README.md +113 -0
- package/README.zh.md +113 -0
- package/lib/index.js +1936 -0
- package/lib/types/adapter.d.ts +23 -0
- package/lib/types/catalog.d.ts +95 -0
- package/lib/types/dispatcher.d.ts +30 -0
- package/lib/types/errors.d.ts +31 -0
- package/lib/types/formatters/anthropic.d.ts +120 -0
- package/lib/types/formatters/bedrock.d.ts +127 -0
- package/lib/types/formatters/gemini.d.ts +147 -0
- package/lib/types/formatters/index.d.ts +10 -0
- package/lib/types/formatters/openai.d.ts +136 -0
- package/lib/types/index.d.ts +49 -0
- package/lib/types/sse-parser.d.ts +18 -0
- package/lib/types/types.d.ts +103 -0
- package/package.json +47 -0
package/lib/index.js
ADDED
|
@@ -0,0 +1,1936 @@
|
|
|
1
|
+
import z from "@deepseek-ai/schemastery";
|
|
2
|
+
import { CONTEXT_WINDOW_EXCEEDED_CODE, LlmAdapter, LlmError, ProviderRequestId, QUOTA_EXCEEDED_CODE, RetryPolicySchema, isContextWindowExceededError, isQuotaExceededError, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
|
|
3
|
+
import { loadCellHarnessConfigSync, resolveExperimentalFeaturesEnabled } from "@machina.ai/ch-auth-reboot-sso";
|
|
4
|
+
//#region lib/types/catalog.js
|
|
5
|
+
/**
|
|
6
|
+
* Canonical Model Catalog, Capabilities & Dynamic Alias Resolution Engine.
|
|
7
|
+
*
|
|
8
|
+
* @module @machina.ai/ch-llm-reboot/catalog
|
|
9
|
+
*/
|
|
10
|
+
/**
|
|
11
|
+
* Built-in canonical model definitions across the 5 provider families.
|
|
12
|
+
*/
|
|
13
|
+
const CANONICAL_MODELS = [
|
|
14
|
+
{
|
|
15
|
+
id: "gemini-3.8-flash",
|
|
16
|
+
canonicalId: "gemini-3.8-flash",
|
|
17
|
+
name: "Gemini 3.8 Flash",
|
|
18
|
+
family: "gemini",
|
|
19
|
+
contextWindow: 1048576,
|
|
20
|
+
maxTokens: 65536,
|
|
21
|
+
modalities: ["text", "image"],
|
|
22
|
+
supportsThinking: true,
|
|
23
|
+
defaultThinkingLevel: "MEDIUM",
|
|
24
|
+
supportedThinkingLevels: [
|
|
25
|
+
"MINIMAL",
|
|
26
|
+
"LOW",
|
|
27
|
+
"MEDIUM",
|
|
28
|
+
"HIGH"
|
|
29
|
+
],
|
|
30
|
+
aliases: ["auto", "auto-gemini-3.8"]
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
id: "gemini-3.7-flash",
|
|
34
|
+
canonicalId: "gemini-3.7-flash",
|
|
35
|
+
name: "Gemini 3.7 Flash",
|
|
36
|
+
family: "gemini",
|
|
37
|
+
contextWindow: 1048576,
|
|
38
|
+
maxTokens: 65536,
|
|
39
|
+
modalities: ["text", "image"],
|
|
40
|
+
supportsThinking: true,
|
|
41
|
+
defaultThinkingLevel: "MEDIUM",
|
|
42
|
+
supportedThinkingLevels: [
|
|
43
|
+
"MINIMAL",
|
|
44
|
+
"LOW",
|
|
45
|
+
"MEDIUM",
|
|
46
|
+
"HIGH"
|
|
47
|
+
],
|
|
48
|
+
aliases: ["flash"]
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
id: "gemini-3.6-flash",
|
|
52
|
+
canonicalId: "gemini-3.6-flash",
|
|
53
|
+
name: "Gemini 3.6 Flash",
|
|
54
|
+
family: "gemini",
|
|
55
|
+
contextWindow: 1048576,
|
|
56
|
+
maxTokens: 65536,
|
|
57
|
+
modalities: ["text", "image"],
|
|
58
|
+
supportsThinking: false
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
id: "gemini-3.1-pro-preview",
|
|
62
|
+
canonicalId: "gemini-3.1-pro-preview",
|
|
63
|
+
name: "Gemini 3.1 Pro Preview",
|
|
64
|
+
family: "gemini",
|
|
65
|
+
contextWindow: 1048576,
|
|
66
|
+
maxTokens: 65536,
|
|
67
|
+
modalities: ["text", "image"],
|
|
68
|
+
supportsThinking: true,
|
|
69
|
+
defaultThinkingLevel: "HIGH",
|
|
70
|
+
supportedThinkingLevels: [
|
|
71
|
+
"LOW",
|
|
72
|
+
"MEDIUM",
|
|
73
|
+
"HIGH",
|
|
74
|
+
"MAX"
|
|
75
|
+
],
|
|
76
|
+
aliases: ["pro"]
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
id: "gemini-3.1-pro-preview-customtools",
|
|
80
|
+
canonicalId: "gemini-3.1-pro-preview-customtools",
|
|
81
|
+
name: "Gemini 3.1 Pro Preview (Custom Tools)",
|
|
82
|
+
family: "gemini",
|
|
83
|
+
contextWindow: 1048576,
|
|
84
|
+
maxTokens: 65536,
|
|
85
|
+
modalities: ["text", "image"],
|
|
86
|
+
supportsThinking: true,
|
|
87
|
+
defaultThinkingLevel: "HIGH"
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
id: "gemini-3.1-flash-lite",
|
|
91
|
+
canonicalId: "gemini-3.1-flash-lite",
|
|
92
|
+
name: "Gemini 3.1 Flash Lite",
|
|
93
|
+
family: "gemini",
|
|
94
|
+
contextWindow: 1048576,
|
|
95
|
+
maxTokens: 65536,
|
|
96
|
+
modalities: ["text", "image"],
|
|
97
|
+
supportsThinking: false,
|
|
98
|
+
aliases: ["flash-lite"]
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
id: "gemini-3.1-flash-lite-preview",
|
|
102
|
+
canonicalId: "gemini-3.1-flash-lite-preview",
|
|
103
|
+
name: "Gemini 3.1 Flash Lite Preview",
|
|
104
|
+
family: "gemini",
|
|
105
|
+
contextWindow: 1048576,
|
|
106
|
+
maxTokens: 65536,
|
|
107
|
+
modalities: ["text", "image"],
|
|
108
|
+
supportsThinking: false
|
|
109
|
+
},
|
|
110
|
+
{
|
|
111
|
+
id: "gemini-3-pro-preview",
|
|
112
|
+
canonicalId: "gemini-3-pro-preview",
|
|
113
|
+
name: "Gemini 3 Pro Preview",
|
|
114
|
+
family: "gemini",
|
|
115
|
+
contextWindow: 1048576,
|
|
116
|
+
maxTokens: 65536,
|
|
117
|
+
modalities: ["text", "image"],
|
|
118
|
+
supportsThinking: true
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
id: "gemini-3-flash-preview",
|
|
122
|
+
canonicalId: "gemini-3-flash-preview",
|
|
123
|
+
name: "Gemini 3 Flash Preview",
|
|
124
|
+
family: "gemini",
|
|
125
|
+
contextWindow: 1048576,
|
|
126
|
+
maxTokens: 65536,
|
|
127
|
+
modalities: ["text", "image"],
|
|
128
|
+
supportsThinking: true
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
id: "gemini-2.5-flash",
|
|
132
|
+
canonicalId: "gemini-2.5-flash",
|
|
133
|
+
name: "Gemini 2.5 Flash",
|
|
134
|
+
family: "gemini",
|
|
135
|
+
contextWindow: 1048576,
|
|
136
|
+
maxTokens: 65536,
|
|
137
|
+
modalities: ["text", "image"],
|
|
138
|
+
supportsThinking: true
|
|
139
|
+
},
|
|
140
|
+
{
|
|
141
|
+
id: "gemini-2.5-flash-lite",
|
|
142
|
+
canonicalId: "gemini-2.5-flash-lite",
|
|
143
|
+
name: "Gemini 2.5 Flash Lite",
|
|
144
|
+
family: "gemini",
|
|
145
|
+
contextWindow: 1048576,
|
|
146
|
+
maxTokens: 65536,
|
|
147
|
+
modalities: ["text", "image"],
|
|
148
|
+
supportsThinking: false
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
id: "gemini-2.5-computer-use-preview-10-2025",
|
|
152
|
+
canonicalId: "gemini-2.5-computer-use-preview-10-2025",
|
|
153
|
+
name: "Gemini 2.5 Computer Use Preview",
|
|
154
|
+
family: "gemini",
|
|
155
|
+
contextWindow: 1048576,
|
|
156
|
+
maxTokens: 65536,
|
|
157
|
+
modalities: ["text", "image"],
|
|
158
|
+
supportsThinking: false
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
id: "gemini-embedding-001",
|
|
162
|
+
canonicalId: "gemini-embedding-001",
|
|
163
|
+
name: "Gemini Embedding 001",
|
|
164
|
+
family: "gemini",
|
|
165
|
+
contextWindow: 2048,
|
|
166
|
+
maxTokens: 0,
|
|
167
|
+
modalities: ["text"],
|
|
168
|
+
supportsThinking: false
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
id: "openai/gpt-5.6-terra",
|
|
172
|
+
canonicalId: "openai/gpt-5.6-terra",
|
|
173
|
+
name: "GPT-5.6 Terra",
|
|
174
|
+
family: "openai",
|
|
175
|
+
contextWindow: 11e5,
|
|
176
|
+
maxTokens: 32768,
|
|
177
|
+
modalities: ["text", "image"],
|
|
178
|
+
supportsThinking: true,
|
|
179
|
+
defaultThinkingLevel: "HIGH",
|
|
180
|
+
aliases: ["gpt-5.6-terra", "auto-gpt-5.6-frontier"]
|
|
181
|
+
},
|
|
182
|
+
{
|
|
183
|
+
id: "openai/gpt-5.6-luna",
|
|
184
|
+
canonicalId: "openai/gpt-5.6-luna",
|
|
185
|
+
name: "GPT-5.6 Luna",
|
|
186
|
+
family: "openai",
|
|
187
|
+
contextWindow: 11e5,
|
|
188
|
+
maxTokens: 32768,
|
|
189
|
+
modalities: ["text", "image"],
|
|
190
|
+
supportsThinking: true,
|
|
191
|
+
defaultThinkingLevel: "MEDIUM",
|
|
192
|
+
aliases: ["gpt-5.6-luna"]
|
|
193
|
+
},
|
|
194
|
+
{
|
|
195
|
+
id: "openai/gpt-5.4",
|
|
196
|
+
canonicalId: "openai/gpt-5.4",
|
|
197
|
+
name: "GPT-5.4",
|
|
198
|
+
family: "openai",
|
|
199
|
+
contextWindow: 2e5,
|
|
200
|
+
maxTokens: 16384,
|
|
201
|
+
modalities: ["text", "image"],
|
|
202
|
+
supportsThinking: true,
|
|
203
|
+
aliases: ["gpt-5.4", "auto-gpt-5.4"]
|
|
204
|
+
},
|
|
205
|
+
{
|
|
206
|
+
id: "openai/gpt-5.4-mini",
|
|
207
|
+
canonicalId: "openai/gpt-5.4-mini",
|
|
208
|
+
name: "GPT-5.4 Mini",
|
|
209
|
+
family: "openai",
|
|
210
|
+
contextWindow: 128e3,
|
|
211
|
+
maxTokens: 16384,
|
|
212
|
+
modalities: ["text", "image"],
|
|
213
|
+
supportsThinking: false,
|
|
214
|
+
aliases: ["gpt-5.4-mini"]
|
|
215
|
+
},
|
|
216
|
+
{
|
|
217
|
+
id: "openai/gpt-4o",
|
|
218
|
+
canonicalId: "openai/gpt-4o",
|
|
219
|
+
name: "GPT-4o",
|
|
220
|
+
family: "openai",
|
|
221
|
+
contextWindow: 128e3,
|
|
222
|
+
maxTokens: 16384,
|
|
223
|
+
modalities: ["text", "image"],
|
|
224
|
+
supportsThinking: false,
|
|
225
|
+
aliases: ["gpt-4o"]
|
|
226
|
+
},
|
|
227
|
+
{
|
|
228
|
+
id: "openai/gpt-4o-mini",
|
|
229
|
+
canonicalId: "openai/gpt-4o-mini",
|
|
230
|
+
name: "GPT-4o Mini",
|
|
231
|
+
family: "openai",
|
|
232
|
+
contextWindow: 128e3,
|
|
233
|
+
maxTokens: 16384,
|
|
234
|
+
modalities: ["text", "image"],
|
|
235
|
+
supportsThinking: false,
|
|
236
|
+
aliases: ["gpt-4o-mini"]
|
|
237
|
+
},
|
|
238
|
+
{
|
|
239
|
+
id: "xai/grok-4.6",
|
|
240
|
+
canonicalId: "xai/grok-4.6",
|
|
241
|
+
name: "Grok 4.6",
|
|
242
|
+
family: "xai",
|
|
243
|
+
contextWindow: 5e5,
|
|
244
|
+
maxTokens: 32768,
|
|
245
|
+
modalities: ["text", "image"],
|
|
246
|
+
supportsThinking: true,
|
|
247
|
+
defaultThinkingLevel: "HIGH",
|
|
248
|
+
aliases: ["grok-4.6", "auto-grok-4.6"]
|
|
249
|
+
},
|
|
250
|
+
{
|
|
251
|
+
id: "xai/grok-4-1-fast-reasoning",
|
|
252
|
+
canonicalId: "xai/grok-4-1-fast-reasoning",
|
|
253
|
+
name: "Grok 4.1 Fast Reasoning",
|
|
254
|
+
family: "xai",
|
|
255
|
+
contextWindow: 256e3,
|
|
256
|
+
maxTokens: 16384,
|
|
257
|
+
modalities: ["text", "image"],
|
|
258
|
+
supportsThinking: true,
|
|
259
|
+
aliases: ["grok-4.1-fast", "grok-4-1-fast-reasoning"]
|
|
260
|
+
},
|
|
261
|
+
{
|
|
262
|
+
id: "anthropic/claude-3-7-sonnet",
|
|
263
|
+
canonicalId: "anthropic/claude-3-7-sonnet",
|
|
264
|
+
name: "Claude 3.7 Sonnet",
|
|
265
|
+
family: "anthropic",
|
|
266
|
+
contextWindow: 2e5,
|
|
267
|
+
maxTokens: 64e3,
|
|
268
|
+
modalities: ["text", "image"],
|
|
269
|
+
supportsThinking: true,
|
|
270
|
+
defaultThinkingLevel: "HIGH",
|
|
271
|
+
aliases: ["claude-3-7-sonnet", "claude-3.7-sonnet"]
|
|
272
|
+
},
|
|
273
|
+
{
|
|
274
|
+
id: "anthropic/fable-5",
|
|
275
|
+
canonicalId: "anthropic/fable-5",
|
|
276
|
+
name: "Fable 5",
|
|
277
|
+
family: "anthropic",
|
|
278
|
+
contextWindow: 2e5,
|
|
279
|
+
maxTokens: 16384,
|
|
280
|
+
modalities: ["text"],
|
|
281
|
+
supportsThinking: false,
|
|
282
|
+
aliases: ["fable-5"]
|
|
283
|
+
},
|
|
284
|
+
{
|
|
285
|
+
id: "anthropic/opus-4.8",
|
|
286
|
+
canonicalId: "anthropic/opus-4.8",
|
|
287
|
+
name: "Claude Opus 4.8",
|
|
288
|
+
family: "anthropic",
|
|
289
|
+
contextWindow: 2e5,
|
|
290
|
+
maxTokens: 32768,
|
|
291
|
+
modalities: ["text", "image"],
|
|
292
|
+
supportsThinking: true,
|
|
293
|
+
aliases: [
|
|
294
|
+
"opus-4.8",
|
|
295
|
+
"claude-opus-4-7",
|
|
296
|
+
"claude-opus-5",
|
|
297
|
+
"claude-sonnet-5"
|
|
298
|
+
]
|
|
299
|
+
},
|
|
300
|
+
{
|
|
301
|
+
id: "bedrock/anthropic.claude-3-7-sonnet-20250219-v1:0",
|
|
302
|
+
canonicalId: "bedrock/anthropic.claude-3-7-sonnet-20250219-v1:0",
|
|
303
|
+
name: "Bedrock Claude 3.7 Sonnet",
|
|
304
|
+
family: "bedrock",
|
|
305
|
+
contextWindow: 2e5,
|
|
306
|
+
maxTokens: 64e3,
|
|
307
|
+
modalities: ["text", "image"],
|
|
308
|
+
supportsThinking: true,
|
|
309
|
+
enabled: false
|
|
310
|
+
},
|
|
311
|
+
{
|
|
312
|
+
id: "bedrock/amazon.nova-pro-v1:0",
|
|
313
|
+
canonicalId: "bedrock/amazon.nova-pro-v1:0",
|
|
314
|
+
name: "Amazon Nova Pro",
|
|
315
|
+
family: "bedrock",
|
|
316
|
+
contextWindow: 3e5,
|
|
317
|
+
maxTokens: 8192,
|
|
318
|
+
modalities: ["text", "image"],
|
|
319
|
+
supportsThinking: false,
|
|
320
|
+
enabled: false
|
|
321
|
+
},
|
|
322
|
+
{
|
|
323
|
+
id: "bedrock/amazon.nova-lite-v1:0",
|
|
324
|
+
canonicalId: "bedrock/amazon.nova-lite-v1:0",
|
|
325
|
+
name: "Amazon Nova Lite",
|
|
326
|
+
family: "bedrock",
|
|
327
|
+
contextWindow: 3e5,
|
|
328
|
+
maxTokens: 8192,
|
|
329
|
+
modalities: ["text", "image"],
|
|
330
|
+
supportsThinking: false,
|
|
331
|
+
enabled: false
|
|
332
|
+
}
|
|
333
|
+
];
|
|
334
|
+
let bedrockEnabled = false;
|
|
335
|
+
/**
|
|
336
|
+
* Returns whether Amazon Bedrock models are currently enabled.
|
|
337
|
+
*
|
|
338
|
+
* @returns true if enabled, false if disabled.
|
|
339
|
+
*/
|
|
340
|
+
function isBedrockEnabled() {
|
|
341
|
+
return bedrockEnabled;
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Enables or disables Amazon Bedrock family models.
|
|
345
|
+
*
|
|
346
|
+
* @param enabled Whether to enable Bedrock models.
|
|
347
|
+
*/
|
|
348
|
+
function setBedrockEnabled(enabled) {
|
|
349
|
+
bedrockEnabled = enabled;
|
|
350
|
+
}
|
|
351
|
+
const MODEL_MAP = /* @__PURE__ */ new Map();
|
|
352
|
+
const ALIAS_MAP = /* @__PURE__ */ new Map();
|
|
353
|
+
for (const model of CANONICAL_MODELS) {
|
|
354
|
+
MODEL_MAP.set(model.id, model);
|
|
355
|
+
MODEL_MAP.set(model.canonicalId, model);
|
|
356
|
+
if (model.aliases) for (const alias of model.aliases) ALIAS_MAP.set(alias.toLowerCase(), model.id);
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Returns all active catalog model definitions.
|
|
360
|
+
* Filters out temporarily disabled model families (e.g. Bedrock).
|
|
361
|
+
*
|
|
362
|
+
* @returns Array of canonical model definitions.
|
|
363
|
+
*/
|
|
364
|
+
function listCatalogModels() {
|
|
365
|
+
return CANONICAL_MODELS.filter((m) => {
|
|
366
|
+
if (m.family === "bedrock") return bedrockEnabled;
|
|
367
|
+
return m.enabled !== false;
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Resolves an alias, shorthand, or full ID to the canonical model ID.
|
|
372
|
+
*
|
|
373
|
+
* @param aliasOrId Input alias or model ID.
|
|
374
|
+
* @returns Resolved canonical model ID.
|
|
375
|
+
*/
|
|
376
|
+
function resolveModelId(aliasOrId) {
|
|
377
|
+
const normalized = aliasOrId.trim();
|
|
378
|
+
const lower = normalized.toLowerCase();
|
|
379
|
+
const hit = ALIAS_MAP.get(lower);
|
|
380
|
+
if (hit !== void 0) return hit;
|
|
381
|
+
return normalized;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Returns the model definition for a given model ID or alias.
|
|
385
|
+
*
|
|
386
|
+
* @param modelId Model ID or alias.
|
|
387
|
+
* @returns Definition if found, undefined otherwise.
|
|
388
|
+
*/
|
|
389
|
+
function getModelDefinition(modelId) {
|
|
390
|
+
const resolved = resolveModelId(modelId);
|
|
391
|
+
return MODEL_MAP.get(resolved);
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Infers the provider family from the model ID and definition.
|
|
395
|
+
*
|
|
396
|
+
* @param modelId Model identifier.
|
|
397
|
+
* @returns Inferred ProviderFamily.
|
|
398
|
+
*/
|
|
399
|
+
function inferProviderFamily(modelId) {
|
|
400
|
+
const def = getModelDefinition(modelId);
|
|
401
|
+
if (def !== void 0) return def.family;
|
|
402
|
+
const lower = modelId.toLowerCase();
|
|
403
|
+
if (lower.startsWith("anthropic/") || lower.startsWith("claude")) return "anthropic";
|
|
404
|
+
if (lower.startsWith("bedrock/")) return "bedrock";
|
|
405
|
+
if (lower.startsWith("openai/") || lower.startsWith("gpt-") || lower.startsWith("o1") || lower.startsWith("o3")) return "openai";
|
|
406
|
+
if (lower.startsWith("xai/") || lower.startsWith("grok")) return "xai";
|
|
407
|
+
if (lower.startsWith("gemini/") || lower.startsWith("gemma/") || lower.startsWith("gemini") || lower.startsWith("gemma")) return "gemini";
|
|
408
|
+
return "gemini";
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Provider families exposed as their own Cordis adapter route, so the Host's
|
|
412
|
+
* per-provider model catalog groups the chat composer's selector by family
|
|
413
|
+
* (Gemini, Anthropic, OpenAI, X.AI) without any change to the composer itself.
|
|
414
|
+
* Bedrock is deliberately excluded from routing until enabled deployment-wide.
|
|
415
|
+
*/
|
|
416
|
+
const ROUTABLE_FAMILIES = [
|
|
417
|
+
"gemini",
|
|
418
|
+
"anthropic",
|
|
419
|
+
"openai",
|
|
420
|
+
"xai"
|
|
421
|
+
];
|
|
422
|
+
/** Family-route display name shown as the provider name in selectors and directories. */
|
|
423
|
+
const FAMILY_DISPLAY_NAME = {
|
|
424
|
+
gemini: "Gemini",
|
|
425
|
+
anthropic: "Anthropic",
|
|
426
|
+
openai: "OpenAI",
|
|
427
|
+
xai: "X.AI",
|
|
428
|
+
bedrock: "Amazon Bedrock"
|
|
429
|
+
};
|
|
430
|
+
/**
|
|
431
|
+
* Builds the family-scoped Cordis route id for a configured provider name prefix.
|
|
432
|
+
*
|
|
433
|
+
* @param providerName Configured provider name prefix (default `'reboot'`).
|
|
434
|
+
* @param family Provider family.
|
|
435
|
+
* @returns the route id, e.g. `'reboot-gemini'`.
|
|
436
|
+
*/
|
|
437
|
+
function familyRoute(providerName, family) {
|
|
438
|
+
return `${providerName}-${family}`;
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Recovers the provider family a family-scoped route id was built for.
|
|
442
|
+
*
|
|
443
|
+
* @param providerName Configured provider name prefix.
|
|
444
|
+
* @param route Route id to inspect.
|
|
445
|
+
* @returns the family, or undefined when `route` does not match this prefix's family-route pattern.
|
|
446
|
+
*/
|
|
447
|
+
function familyOfRoute(providerName, route) {
|
|
448
|
+
const prefix = `${providerName}-`;
|
|
449
|
+
if (!route.startsWith(prefix)) return void 0;
|
|
450
|
+
const family = route.slice(prefix.length);
|
|
451
|
+
return ROUTABLE_FAMILIES.includes(family) ? family : void 0;
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Lists the models a single family's route currently serves, honoring the
|
|
455
|
+
* `CELL_EXPERIMENTAL_FEATURES` gate (only Gemini is visible while disabled)
|
|
456
|
+
* and the Bedrock kill switch.
|
|
457
|
+
*
|
|
458
|
+
* @param family Provider family the route was built for.
|
|
459
|
+
* @param experimentalEnabled Whether experimental (non-Gemini) families are enabled.
|
|
460
|
+
* @returns models for that family, or an empty list while gated off (an empty
|
|
461
|
+
* route is excluded from the Host's provider catalog, hiding the family entirely).
|
|
462
|
+
*/
|
|
463
|
+
function modelsForFamilyRoute(family, experimentalEnabled) {
|
|
464
|
+
if (family === "bedrock") return bedrockEnabled ? CANONICAL_MODELS.filter((m) => m.family === "bedrock") : [];
|
|
465
|
+
if (family !== "gemini" && !experimentalEnabled) return [];
|
|
466
|
+
return CANONICAL_MODELS.filter((m) => m.family === family);
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Resolves the upstream endpoint route and target URL for a given model request.
|
|
470
|
+
*
|
|
471
|
+
* @param baseUrl Base agent API URL (e.g. 'https://api.machina.ai').
|
|
472
|
+
* @param modelId Model ID or alias.
|
|
473
|
+
* @returns Resolved endpoint route with target URL and provider family.
|
|
474
|
+
*/
|
|
475
|
+
function resolveEndpointRoute(baseUrl, modelId) {
|
|
476
|
+
const resolvedId = resolveModelId(modelId);
|
|
477
|
+
const family = inferProviderFamily(resolvedId);
|
|
478
|
+
const cleanBase = baseUrl.replace(/\/+$/u, "");
|
|
479
|
+
let targetUrl;
|
|
480
|
+
let unprefixedModelId = resolvedId;
|
|
481
|
+
switch (family) {
|
|
482
|
+
case "anthropic":
|
|
483
|
+
targetUrl = `${cleanBase}/cell/v1.1/anthropic/v1/messages`;
|
|
484
|
+
break;
|
|
485
|
+
case "bedrock":
|
|
486
|
+
if (!bedrockEnabled) throw new Error("llm-reboot: Bedrock family models are temporarily disabled");
|
|
487
|
+
unprefixedModelId = resolvedId.replace(/^bedrock\//u, "");
|
|
488
|
+
targetUrl = `${cleanBase}/cell/v1.1/bedrock/model/${unprefixedModelId}/invoke`;
|
|
489
|
+
break;
|
|
490
|
+
case "gemini":
|
|
491
|
+
unprefixedModelId = resolvedId.replace(/^gemini\//u, "");
|
|
492
|
+
targetUrl = `${cleanBase}/cell/v1.1/gemini/v1beta/models/${unprefixedModelId}:generateContent`;
|
|
493
|
+
break;
|
|
494
|
+
case "openai":
|
|
495
|
+
targetUrl = `${cleanBase}/cell/v1.1/openai/v1/chat/completions`;
|
|
496
|
+
break;
|
|
497
|
+
case "xai":
|
|
498
|
+
targetUrl = `${cleanBase}/cell/v1.1/xai/v1/chat/completions`;
|
|
499
|
+
break;
|
|
500
|
+
}
|
|
501
|
+
return {
|
|
502
|
+
family,
|
|
503
|
+
modelId: resolvedId,
|
|
504
|
+
targetUrl
|
|
505
|
+
};
|
|
506
|
+
}
|
|
507
|
+
//#endregion
|
|
508
|
+
//#region lib/types/errors.js
|
|
509
|
+
/**
|
|
510
|
+
* Unified Error Mapping for Upstream Reboot LLM Provider Responses.
|
|
511
|
+
*
|
|
512
|
+
* @module @machina.ai/ch-llm-reboot/errors
|
|
513
|
+
*/
|
|
514
|
+
/**
|
|
515
|
+
* Maps an HTTP response status and raw body into a normalized LlmError.
|
|
516
|
+
*
|
|
517
|
+
* @param status HTTP response status code.
|
|
518
|
+
* @param statusText HTTP status text.
|
|
519
|
+
* @param rawBody Response body text or parsed JSON.
|
|
520
|
+
* @param requestId Optional upstream request id header.
|
|
521
|
+
* @returns Normalized LlmError.
|
|
522
|
+
*/
|
|
523
|
+
function mapHttpErrorToLlmError(status, statusText, rawBody, requestId) {
|
|
524
|
+
let parsedMessage = "";
|
|
525
|
+
let errorDetail = "";
|
|
526
|
+
if (rawBody && rawBody.length > 0) try {
|
|
527
|
+
const parsed = JSON.parse(rawBody);
|
|
528
|
+
if (typeof parsed.error === "object") {
|
|
529
|
+
parsedMessage = typeof parsed.error.message === "string" ? parsed.error.message : "";
|
|
530
|
+
errorDetail = [
|
|
531
|
+
parsed.error.code,
|
|
532
|
+
parsed.error.type,
|
|
533
|
+
parsed.error.message
|
|
534
|
+
].filter(Boolean).join(" ");
|
|
535
|
+
} else if (typeof parsed.error === "string") {
|
|
536
|
+
parsedMessage = parsed.error;
|
|
537
|
+
errorDetail = parsed.error;
|
|
538
|
+
} else if (typeof parsed.message === "string") {
|
|
539
|
+
parsedMessage = parsed.message;
|
|
540
|
+
errorDetail = parsed.message;
|
|
541
|
+
}
|
|
542
|
+
} catch {
|
|
543
|
+
parsedMessage = rawBody.slice(0, 200);
|
|
544
|
+
errorDetail = parsedMessage;
|
|
545
|
+
}
|
|
546
|
+
const message = parsedMessage.length > 0 ? `Reboot API error (${status} ${statusText}): ${parsedMessage}` : `Reboot API error: ${status} ${statusText}`;
|
|
547
|
+
let code;
|
|
548
|
+
if (status === 401 || status === 403) code = isQuotaExceededError(errorDetail) ? QUOTA_EXCEEDED_CODE : "AUTH";
|
|
549
|
+
else if (status === 429) code = isQuotaExceededError(errorDetail) ? QUOTA_EXCEEDED_CODE : "RATE_LIMIT";
|
|
550
|
+
else if (status === 400) code = isContextWindowExceededError(errorDetail) ? CONTEXT_WINDOW_EXCEEDED_CODE : "INVALID_REQUEST";
|
|
551
|
+
else if (status === 404) code = "NOT_FOUND";
|
|
552
|
+
else if (status === 503 || status === 504) code = "SERVICE_UNAVAILABLE";
|
|
553
|
+
else if (status >= 500) code = "SERVER";
|
|
554
|
+
else code = `HTTP_${status}`;
|
|
555
|
+
return new LlmError(message, code, {
|
|
556
|
+
status,
|
|
557
|
+
...requestId && requestId.length > 0 ? { requestId: ProviderRequestId(requestId) } : {}
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
//#endregion
|
|
561
|
+
//#region lib/types/formatters/gemini.js
|
|
562
|
+
/**
|
|
563
|
+
* Google Gemini & Gemma Request Serializer and Response/SSE Normalizer.
|
|
564
|
+
*
|
|
565
|
+
* @module @machina.ai/ch-llm-reboot/formatters/gemini
|
|
566
|
+
*/
|
|
567
|
+
/**
|
|
568
|
+
* Recursively sanitizes JSON schemas into strict Google Gemini schema protobuf structures.
|
|
569
|
+
* Strips unsupported keywords (e.g. additionalProperties, $schema, default, title) that cause
|
|
570
|
+
* Protobuf decoding 400 Bad Request errors in Google Generative Language API.
|
|
571
|
+
*
|
|
572
|
+
* @param schema Input schema object.
|
|
573
|
+
* @returns Cleaned Gemini-compatible schema object.
|
|
574
|
+
*/
|
|
575
|
+
function sanitizeGeminiSchema(schema) {
|
|
576
|
+
if (typeof schema !== "object" || schema === null || Array.isArray(schema)) return;
|
|
577
|
+
const record = schema;
|
|
578
|
+
const result = {};
|
|
579
|
+
if (typeof record.type === "string") result.type = record.type;
|
|
580
|
+
else if (Array.isArray(record.type) && record.type.length > 0) {
|
|
581
|
+
const nonNull = record.type.find((t) => t !== "null");
|
|
582
|
+
result.type = typeof nonNull === "string" ? nonNull : "string";
|
|
583
|
+
if (record.type.includes("null")) result.nullable = true;
|
|
584
|
+
}
|
|
585
|
+
if (typeof record.description === "string") result.description = record.description;
|
|
586
|
+
if (typeof record.format === "string") result.format = record.format;
|
|
587
|
+
if (typeof record.nullable === "boolean") result.nullable = record.nullable;
|
|
588
|
+
if (Array.isArray(record.enum)) result.enum = record.enum.filter((item) => typeof item === "string");
|
|
589
|
+
if (Array.isArray(record.required)) result.required = record.required.filter((item) => typeof item === "string");
|
|
590
|
+
if (typeof record.properties === "object" && record.properties !== null && !Array.isArray(record.properties)) {
|
|
591
|
+
const propertiesRecord = record.properties;
|
|
592
|
+
const sanitizedProps = {};
|
|
593
|
+
for (const [propName, propSchema] of Object.entries(propertiesRecord)) {
|
|
594
|
+
const sanitized = sanitizeGeminiSchema(propSchema);
|
|
595
|
+
if (sanitized !== void 0) sanitizedProps[propName] = sanitized;
|
|
596
|
+
}
|
|
597
|
+
result.properties = sanitizedProps;
|
|
598
|
+
}
|
|
599
|
+
if (record.items !== void 0) {
|
|
600
|
+
const sanitizedItems = sanitizeGeminiSchema(record.items);
|
|
601
|
+
if (sanitizedItems !== void 0) result.items = sanitizedItems;
|
|
602
|
+
}
|
|
603
|
+
if (typeof record.minItems === "number") result.minItems = record.minItems;
|
|
604
|
+
if (typeof record.maxItems === "number") result.maxItems = record.maxItems;
|
|
605
|
+
if (result.properties !== void 0 && !result.type) result.type = "object";
|
|
606
|
+
if (result.items !== void 0 && !result.type) result.type = "array";
|
|
607
|
+
return result;
|
|
608
|
+
}
|
|
609
|
+
/**
|
|
610
|
+
* Serializes standard GenerateOptions into Gemini REST/SSE JSON request payload.
|
|
611
|
+
*
|
|
612
|
+
* @param options Fully assembled model request.
|
|
613
|
+
* @returns Gemini wire request payload.
|
|
614
|
+
*/
|
|
615
|
+
function formatGeminiRequest(options) {
|
|
616
|
+
let systemPrompt = options.system;
|
|
617
|
+
const contents = [];
|
|
618
|
+
for (const message of options.messages) {
|
|
619
|
+
if (message.role === "system") {
|
|
620
|
+
const textParts = [];
|
|
621
|
+
for (const block of message.content) if (block.type === "text") textParts.push(block.text);
|
|
622
|
+
if (textParts.length > 0) systemPrompt = textParts.join("\n");
|
|
623
|
+
continue;
|
|
624
|
+
}
|
|
625
|
+
if (message.role === "user" || message.role === "tool") {
|
|
626
|
+
const parts = [];
|
|
627
|
+
for (const block of message.content) switch (block.type) {
|
|
628
|
+
case "text":
|
|
629
|
+
parts.push({ text: block.text });
|
|
630
|
+
break;
|
|
631
|
+
case "image": {
|
|
632
|
+
const rawAttachment = block.attachment;
|
|
633
|
+
if (typeof rawAttachment.data === "string" && typeof rawAttachment.mimeType === "string") parts.push({ inlineData: {
|
|
634
|
+
mimeType: rawAttachment.mimeType,
|
|
635
|
+
data: rawAttachment.data
|
|
636
|
+
} });
|
|
637
|
+
break;
|
|
638
|
+
}
|
|
639
|
+
case "tool-result": {
|
|
640
|
+
const textParts = [];
|
|
641
|
+
for (const subBlock of block.content) if (subBlock.type === "text") textParts.push(subBlock.text);
|
|
642
|
+
const text = textParts.join("\n");
|
|
643
|
+
let resultData = {};
|
|
644
|
+
try {
|
|
645
|
+
const parsed = JSON.parse(text);
|
|
646
|
+
resultData = typeof parsed === "object" && parsed !== null ? parsed : { result: parsed };
|
|
647
|
+
} catch {
|
|
648
|
+
resultData = { output: text };
|
|
649
|
+
}
|
|
650
|
+
const toolName = message.source?.toolName ?? "tool";
|
|
651
|
+
parts.push({ functionResponse: {
|
|
652
|
+
name: toolName,
|
|
653
|
+
response: resultData
|
|
654
|
+
} });
|
|
655
|
+
break;
|
|
656
|
+
}
|
|
657
|
+
default: break;
|
|
658
|
+
}
|
|
659
|
+
if (parts.length > 0) contents.push({
|
|
660
|
+
role: "user",
|
|
661
|
+
parts
|
|
662
|
+
});
|
|
663
|
+
} else {
|
|
664
|
+
const parts = [];
|
|
665
|
+
for (const block of message.content) switch (block.type) {
|
|
666
|
+
case "text":
|
|
667
|
+
parts.push({ text: block.text });
|
|
668
|
+
break;
|
|
669
|
+
case "reasoning":
|
|
670
|
+
parts.push({
|
|
671
|
+
text: block.text,
|
|
672
|
+
thought: true
|
|
673
|
+
});
|
|
674
|
+
break;
|
|
675
|
+
case "tool-call": {
|
|
676
|
+
let parsedArgs = {};
|
|
677
|
+
try {
|
|
678
|
+
parsedArgs = JSON.parse(block.arguments);
|
|
679
|
+
} catch {
|
|
680
|
+
parsedArgs = { raw: block.arguments };
|
|
681
|
+
}
|
|
682
|
+
const blockRecord = block;
|
|
683
|
+
const signature = typeof blockRecord.thoughtSignature === "string" && blockRecord.thoughtSignature.length > 0 ? blockRecord.thoughtSignature : typeof blockRecord.thought_signature === "string" && blockRecord.thought_signature.length > 0 ? blockRecord.thought_signature : "skip_thought_signature_validator";
|
|
684
|
+
parts.push({
|
|
685
|
+
functionCall: {
|
|
686
|
+
name: block.name,
|
|
687
|
+
args: parsedArgs
|
|
688
|
+
},
|
|
689
|
+
thought_signature: signature
|
|
690
|
+
});
|
|
691
|
+
break;
|
|
692
|
+
}
|
|
693
|
+
default: break;
|
|
694
|
+
}
|
|
695
|
+
if (parts.length > 0) contents.push({
|
|
696
|
+
role: "model",
|
|
697
|
+
parts
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
const payload = { contents };
|
|
702
|
+
if (systemPrompt && systemPrompt.length > 0) payload.systemInstruction = {
|
|
703
|
+
role: "user",
|
|
704
|
+
parts: [{ text: systemPrompt }]
|
|
705
|
+
};
|
|
706
|
+
if (options.tools && options.tools.length > 0) payload.tools = [{ functionDeclarations: options.tools.map((t) => ({
|
|
707
|
+
name: t.name,
|
|
708
|
+
description: t.description,
|
|
709
|
+
parameters: sanitizeGeminiSchema(t.parameters) ?? {
|
|
710
|
+
type: "object",
|
|
711
|
+
properties: {}
|
|
712
|
+
}
|
|
713
|
+
})) }];
|
|
714
|
+
const generationConfig = {};
|
|
715
|
+
if (options.temperature !== void 0) generationConfig.temperature = options.temperature;
|
|
716
|
+
if (options.maxTokens !== void 0) generationConfig.maxOutputTokens = options.maxTokens;
|
|
717
|
+
if (options.stop && options.stop.length > 0) generationConfig.stopSequences = options.stop;
|
|
718
|
+
if (Object.keys(generationConfig).length > 0) payload.generationConfig = generationConfig;
|
|
719
|
+
return payload;
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* Parses raw Gemini response JSON or SSE chunk into normalized components.
|
|
723
|
+
*
|
|
724
|
+
* @param chunk Raw parsed Gemini chunk object.
|
|
725
|
+
* @param _blockOffset Block index offset.
|
|
726
|
+
* @returns Normalized chunk items.
|
|
727
|
+
*/
|
|
728
|
+
function parseGeminiChunk(chunk, _blockOffset = 0) {
|
|
729
|
+
const typedChunk = typeof chunk === "object" && chunk !== null ? chunk : {};
|
|
730
|
+
const textDeltas = [];
|
|
731
|
+
const reasoningDeltas = [];
|
|
732
|
+
const toolCalls = [];
|
|
733
|
+
const candidate = typedChunk.candidates?.[0];
|
|
734
|
+
if (candidate?.content?.parts) for (const part of candidate.content.parts) {
|
|
735
|
+
if (part.thought === true && typeof part.text === "string") reasoningDeltas.push(part.text);
|
|
736
|
+
else if (typeof part.text === "string") textDeltas.push(part.text);
|
|
737
|
+
if (part.functionCall) {
|
|
738
|
+
const rawPart = part;
|
|
739
|
+
const sig = typeof rawPart.thought_signature === "string" ? rawPart.thought_signature : typeof rawPart.thoughtSignature === "string" ? rawPart.thoughtSignature : void 0;
|
|
740
|
+
toolCalls.push({
|
|
741
|
+
name: part.functionCall.name,
|
|
742
|
+
arguments: JSON.stringify(part.functionCall.args ?? {}),
|
|
743
|
+
...sig !== void 0 ? { thoughtSignature: sig } : {}
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
let finishReason;
|
|
748
|
+
if (candidate?.finishReason) switch (candidate.finishReason) {
|
|
749
|
+
case "STOP":
|
|
750
|
+
finishReason = { kind: "stop" };
|
|
751
|
+
break;
|
|
752
|
+
case "MAX_TOKENS":
|
|
753
|
+
finishReason = { kind: "max-tokens" };
|
|
754
|
+
break;
|
|
755
|
+
default:
|
|
756
|
+
finishReason = { kind: "stop" };
|
|
757
|
+
break;
|
|
758
|
+
}
|
|
759
|
+
let usage;
|
|
760
|
+
if (typedChunk.usageMetadata) {
|
|
761
|
+
const prompt = typedChunk.usageMetadata.promptTokenCount ?? 0;
|
|
762
|
+
const candidates = typedChunk.usageMetadata.candidatesTokenCount ?? 0;
|
|
763
|
+
const total = typedChunk.usageMetadata.totalTokenCount ?? prompt + candidates;
|
|
764
|
+
const cached = typedChunk.usageMetadata.cachedContentTokenCount ?? 0;
|
|
765
|
+
usage = {
|
|
766
|
+
inputTokens: Math.max(0, prompt - cached),
|
|
767
|
+
outputTokens: candidates,
|
|
768
|
+
totalTokens: total,
|
|
769
|
+
...cached > 0 ? { cacheReadTokens: cached } : {}
|
|
770
|
+
};
|
|
771
|
+
}
|
|
772
|
+
return {
|
|
773
|
+
textDeltas,
|
|
774
|
+
reasoningDeltas,
|
|
775
|
+
toolCalls,
|
|
776
|
+
usage,
|
|
777
|
+
finishReason
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
//#endregion
|
|
781
|
+
//#region lib/types/formatters/anthropic.js
|
|
782
|
+
/**
|
|
783
|
+
* Anthropic Messages API Request Serializer and SSE Event Normalizer.
|
|
784
|
+
*
|
|
785
|
+
* @module @machina.ai/ch-llm-reboot/formatters/anthropic
|
|
786
|
+
*/
|
|
787
|
+
/**
|
|
788
|
+
* Formats GenerateOptions into Anthropic Messages API request payload.
|
|
789
|
+
*
|
|
790
|
+
* @param options Fully assembled model request.
|
|
791
|
+
* @returns Anthropic wire request payload.
|
|
792
|
+
*/
|
|
793
|
+
function formatAnthropicRequest(options) {
|
|
794
|
+
const cleanModel = resolveModelId(options.model).replace(/^anthropic\//u, "");
|
|
795
|
+
let systemPrompt = options.system;
|
|
796
|
+
const messages = [];
|
|
797
|
+
for (const message of options.messages) {
|
|
798
|
+
if (message.role === "system") {
|
|
799
|
+
const textParts = [];
|
|
800
|
+
for (const block of message.content) if (block.type === "text") textParts.push(block.text);
|
|
801
|
+
if (textParts.length > 0) systemPrompt = textParts.join("\n");
|
|
802
|
+
continue;
|
|
803
|
+
}
|
|
804
|
+
if (message.role === "user" || message.role === "tool") {
|
|
805
|
+
const blocks = [];
|
|
806
|
+
for (const block of message.content) switch (block.type) {
|
|
807
|
+
case "text":
|
|
808
|
+
blocks.push({
|
|
809
|
+
type: "text",
|
|
810
|
+
text: block.text
|
|
811
|
+
});
|
|
812
|
+
break;
|
|
813
|
+
case "image": {
|
|
814
|
+
const rawAttachment = block.attachment;
|
|
815
|
+
if (typeof rawAttachment.data === "string" && typeof rawAttachment.mimeType === "string") blocks.push({
|
|
816
|
+
type: "image",
|
|
817
|
+
source: {
|
|
818
|
+
type: "base64",
|
|
819
|
+
media_type: rawAttachment.mimeType,
|
|
820
|
+
data: rawAttachment.data
|
|
821
|
+
}
|
|
822
|
+
});
|
|
823
|
+
break;
|
|
824
|
+
}
|
|
825
|
+
case "tool-result": {
|
|
826
|
+
const textParts = [];
|
|
827
|
+
for (const subBlock of block.content) if (subBlock.type === "text") textParts.push(subBlock.text);
|
|
828
|
+
blocks.push({
|
|
829
|
+
type: "tool_result",
|
|
830
|
+
tool_use_id: block.toolCallId,
|
|
831
|
+
content: textParts.join("\n"),
|
|
832
|
+
is_error: block.isError
|
|
833
|
+
});
|
|
834
|
+
break;
|
|
835
|
+
}
|
|
836
|
+
default: break;
|
|
837
|
+
}
|
|
838
|
+
const firstBlock = blocks[0];
|
|
839
|
+
if (blocks.length === 1 && firstBlock?.type === "text" && firstBlock.text !== void 0) messages.push({
|
|
840
|
+
role: "user",
|
|
841
|
+
content: firstBlock.text
|
|
842
|
+
});
|
|
843
|
+
else if (blocks.length > 0) messages.push({
|
|
844
|
+
role: "user",
|
|
845
|
+
content: blocks
|
|
846
|
+
});
|
|
847
|
+
} else {
|
|
848
|
+
const blocks = [];
|
|
849
|
+
for (const block of message.content) switch (block.type) {
|
|
850
|
+
case "text":
|
|
851
|
+
blocks.push({
|
|
852
|
+
type: "text",
|
|
853
|
+
text: block.text
|
|
854
|
+
});
|
|
855
|
+
break;
|
|
856
|
+
case "reasoning":
|
|
857
|
+
blocks.push({
|
|
858
|
+
type: "thinking",
|
|
859
|
+
thinking: block.text
|
|
860
|
+
});
|
|
861
|
+
break;
|
|
862
|
+
case "tool-call": {
|
|
863
|
+
let parsedArgs = {};
|
|
864
|
+
try {
|
|
865
|
+
parsedArgs = JSON.parse(block.arguments);
|
|
866
|
+
} catch {
|
|
867
|
+
parsedArgs = { raw: block.arguments };
|
|
868
|
+
}
|
|
869
|
+
blocks.push({
|
|
870
|
+
type: "tool_use",
|
|
871
|
+
id: block.id,
|
|
872
|
+
name: block.name,
|
|
873
|
+
input: parsedArgs
|
|
874
|
+
});
|
|
875
|
+
break;
|
|
876
|
+
}
|
|
877
|
+
default: break;
|
|
878
|
+
}
|
|
879
|
+
const firstBlock = blocks[0];
|
|
880
|
+
if (blocks.length === 1 && firstBlock?.type === "text" && firstBlock.text !== void 0) messages.push({
|
|
881
|
+
role: "assistant",
|
|
882
|
+
content: firstBlock.text
|
|
883
|
+
});
|
|
884
|
+
else if (blocks.length > 0) messages.push({
|
|
885
|
+
role: "assistant",
|
|
886
|
+
content: blocks
|
|
887
|
+
});
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
const payload = {
|
|
891
|
+
model: cleanModel,
|
|
892
|
+
messages,
|
|
893
|
+
max_tokens: options.maxTokens ?? 4096
|
|
894
|
+
};
|
|
895
|
+
if (systemPrompt && systemPrompt.length > 0) payload.system = systemPrompt;
|
|
896
|
+
if (options.temperature !== void 0) payload.temperature = options.temperature;
|
|
897
|
+
if (options.stop && options.stop.length > 0) payload.stop_sequences = options.stop;
|
|
898
|
+
if (options.tools && options.tools.length > 0) payload.tools = options.tools.map((t) => ({
|
|
899
|
+
name: t.name,
|
|
900
|
+
description: t.description,
|
|
901
|
+
input_schema: t.parameters
|
|
902
|
+
}));
|
|
903
|
+
return payload;
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* Parses raw Anthropic SSE event into normalized components.
|
|
907
|
+
*
|
|
908
|
+
* @param event Raw parsed Anthropic SSE event.
|
|
909
|
+
* @returns Normalized event items.
|
|
910
|
+
*/
|
|
911
|
+
function parseAnthropicSseEvent(event) {
|
|
912
|
+
const typedEvent = typeof event === "object" && event !== null ? event : {};
|
|
913
|
+
const type = typedEvent.type;
|
|
914
|
+
if (type === "message_start" && typedEvent.message?.usage) {
|
|
915
|
+
const rawUsage = typedEvent.message.usage;
|
|
916
|
+
const input = rawUsage.input_tokens ?? 0;
|
|
917
|
+
const output = rawUsage.output_tokens ?? 0;
|
|
918
|
+
const cached = rawUsage.cache_read_input_tokens ?? 0;
|
|
919
|
+
return {
|
|
920
|
+
eventType: type,
|
|
921
|
+
usage: {
|
|
922
|
+
inputTokens: Math.max(0, input - cached),
|
|
923
|
+
outputTokens: output,
|
|
924
|
+
totalTokens: input + output,
|
|
925
|
+
...cached > 0 ? { cacheReadTokens: cached } : {}
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
if (type === "content_block_start") {
|
|
930
|
+
const cb = typedEvent.content_block;
|
|
931
|
+
if (cb?.type === "tool_use") return {
|
|
932
|
+
eventType: type,
|
|
933
|
+
toolCallId: cb.id,
|
|
934
|
+
toolName: cb.name
|
|
935
|
+
};
|
|
936
|
+
}
|
|
937
|
+
if (type === "content_block_delta") {
|
|
938
|
+
const delta = typedEvent.delta;
|
|
939
|
+
if (delta?.type === "text_delta") return {
|
|
940
|
+
eventType: type,
|
|
941
|
+
textDelta: delta.text
|
|
942
|
+
};
|
|
943
|
+
if (delta?.type === "thinking_delta") return {
|
|
944
|
+
eventType: type,
|
|
945
|
+
reasoningDelta: delta.thinking
|
|
946
|
+
};
|
|
947
|
+
if (delta?.type === "input_json_delta") return {
|
|
948
|
+
eventType: type,
|
|
949
|
+
toolArgumentsDelta: delta.partial_json
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
if (type === "message_delta") {
|
|
953
|
+
let finishReason;
|
|
954
|
+
if (typedEvent.delta?.stop_reason) switch (typedEvent.delta.stop_reason) {
|
|
955
|
+
case "end_turn":
|
|
956
|
+
case "stop_sequence":
|
|
957
|
+
finishReason = { kind: "stop" };
|
|
958
|
+
break;
|
|
959
|
+
case "tool_use":
|
|
960
|
+
finishReason = { kind: "tool-calls" };
|
|
961
|
+
break;
|
|
962
|
+
case "max_tokens":
|
|
963
|
+
finishReason = { kind: "max-tokens" };
|
|
964
|
+
break;
|
|
965
|
+
default:
|
|
966
|
+
finishReason = { kind: "stop" };
|
|
967
|
+
break;
|
|
968
|
+
}
|
|
969
|
+
let usage;
|
|
970
|
+
if (typedEvent.usage) {
|
|
971
|
+
const inTokens = typedEvent.usage.input_tokens ?? 0;
|
|
972
|
+
const outTokens = typedEvent.usage.output_tokens ?? 0;
|
|
973
|
+
usage = {
|
|
974
|
+
inputTokens: inTokens,
|
|
975
|
+
outputTokens: outTokens,
|
|
976
|
+
totalTokens: inTokens + outTokens
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
return {
|
|
980
|
+
eventType: type,
|
|
981
|
+
finishReason,
|
|
982
|
+
usage
|
|
983
|
+
};
|
|
984
|
+
}
|
|
985
|
+
return { eventType: type };
|
|
986
|
+
}
|
|
987
|
+
//#endregion
|
|
988
|
+
//#region lib/types/formatters/openai.js
|
|
989
|
+
/**
|
|
990
|
+
* OpenAI & xAI (Grok) Chat Completions Request Serializer and Stream Normalizer.
|
|
991
|
+
*
|
|
992
|
+
* @module @machina.ai/ch-llm-reboot/formatters/openai
|
|
993
|
+
*/
|
|
994
|
+
/**
|
|
995
|
+
* Formats GenerateOptions into OpenAI Chat Completions JSON request payload.
|
|
996
|
+
*
|
|
997
|
+
* @param options Fully assembled model request.
|
|
998
|
+
* @returns OpenAI wire request payload.
|
|
999
|
+
*/
|
|
1000
|
+
function formatOpenAiRequest(options) {
|
|
1001
|
+
const cleanModel = resolveModelId(options.model).replace(/^(?:openai|xai)\//u, "");
|
|
1002
|
+
const messages = [];
|
|
1003
|
+
if (options.system) messages.push({
|
|
1004
|
+
role: "system",
|
|
1005
|
+
content: options.system
|
|
1006
|
+
});
|
|
1007
|
+
for (const message of options.messages) {
|
|
1008
|
+
if (message.role === "system") {
|
|
1009
|
+
const textParts = [];
|
|
1010
|
+
for (const block of message.content) if (block.type === "text") textParts.push(block.text);
|
|
1011
|
+
if (textParts.length > 0) messages.push({
|
|
1012
|
+
role: "system",
|
|
1013
|
+
content: textParts.join("\n")
|
|
1014
|
+
});
|
|
1015
|
+
continue;
|
|
1016
|
+
}
|
|
1017
|
+
if (message.role === "user" || message.role === "tool") {
|
|
1018
|
+
const blocks = [];
|
|
1019
|
+
for (const block of message.content) switch (block.type) {
|
|
1020
|
+
case "text":
|
|
1021
|
+
blocks.push({
|
|
1022
|
+
type: "text",
|
|
1023
|
+
text: block.text
|
|
1024
|
+
});
|
|
1025
|
+
break;
|
|
1026
|
+
case "image": {
|
|
1027
|
+
const rawAttachment = block.attachment;
|
|
1028
|
+
if (typeof rawAttachment.data === "string") {
|
|
1029
|
+
const mime = typeof rawAttachment.mimeType === "string" ? rawAttachment.mimeType : "image/jpeg";
|
|
1030
|
+
blocks.push({
|
|
1031
|
+
type: "image_url",
|
|
1032
|
+
image_url: { url: `data:${mime};base64,${rawAttachment.data}` }
|
|
1033
|
+
});
|
|
1034
|
+
}
|
|
1035
|
+
break;
|
|
1036
|
+
}
|
|
1037
|
+
case "tool-result": {
|
|
1038
|
+
const textParts = [];
|
|
1039
|
+
for (const subBlock of block.content) if (subBlock.type === "text") textParts.push(subBlock.text);
|
|
1040
|
+
messages.push({
|
|
1041
|
+
role: "tool",
|
|
1042
|
+
tool_call_id: block.toolCallId,
|
|
1043
|
+
content: textParts.join("\n")
|
|
1044
|
+
});
|
|
1045
|
+
break;
|
|
1046
|
+
}
|
|
1047
|
+
default: break;
|
|
1048
|
+
}
|
|
1049
|
+
const firstBlock = blocks[0];
|
|
1050
|
+
if (blocks.length === 1 && firstBlock?.type === "text" && firstBlock.text !== void 0) messages.push({
|
|
1051
|
+
role: "user",
|
|
1052
|
+
content: firstBlock.text
|
|
1053
|
+
});
|
|
1054
|
+
else if (blocks.length > 0) messages.push({
|
|
1055
|
+
role: "user",
|
|
1056
|
+
content: blocks
|
|
1057
|
+
});
|
|
1058
|
+
} else {
|
|
1059
|
+
let textContent = "";
|
|
1060
|
+
let reasoningContent = "";
|
|
1061
|
+
const toolCalls = [];
|
|
1062
|
+
for (const block of message.content) switch (block.type) {
|
|
1063
|
+
case "text":
|
|
1064
|
+
textContent += block.text;
|
|
1065
|
+
break;
|
|
1066
|
+
case "reasoning":
|
|
1067
|
+
reasoningContent += block.text;
|
|
1068
|
+
break;
|
|
1069
|
+
case "tool-call":
|
|
1070
|
+
toolCalls.push({
|
|
1071
|
+
id: block.id,
|
|
1072
|
+
type: "function",
|
|
1073
|
+
function: {
|
|
1074
|
+
name: block.name,
|
|
1075
|
+
arguments: block.arguments
|
|
1076
|
+
}
|
|
1077
|
+
});
|
|
1078
|
+
break;
|
|
1079
|
+
default: break;
|
|
1080
|
+
}
|
|
1081
|
+
const assistantMsg = {
|
|
1082
|
+
role: "assistant",
|
|
1083
|
+
content: textContent.length > 0 ? textContent : null
|
|
1084
|
+
};
|
|
1085
|
+
if (reasoningContent.length > 0) assistantMsg.reasoning_content = reasoningContent;
|
|
1086
|
+
if (toolCalls.length > 0) assistantMsg.tool_calls = toolCalls;
|
|
1087
|
+
messages.push(assistantMsg);
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
const payload = {
|
|
1091
|
+
model: cleanModel,
|
|
1092
|
+
messages,
|
|
1093
|
+
stream: true,
|
|
1094
|
+
stream_options: { include_usage: true }
|
|
1095
|
+
};
|
|
1096
|
+
if (options.temperature !== void 0) payload.temperature = options.temperature;
|
|
1097
|
+
if (options.maxTokens !== void 0) payload.max_tokens = options.maxTokens;
|
|
1098
|
+
if (options.stop && options.stop.length > 0) payload.stop = options.stop;
|
|
1099
|
+
if (options.reasoningEffort) payload.reasoning_effort = options.reasoningEffort;
|
|
1100
|
+
if (options.tools && options.tools.length > 0) payload.tools = options.tools.map((t) => ({
|
|
1101
|
+
type: "function",
|
|
1102
|
+
function: {
|
|
1103
|
+
name: t.name,
|
|
1104
|
+
description: t.description,
|
|
1105
|
+
parameters: t.parameters
|
|
1106
|
+
}
|
|
1107
|
+
}));
|
|
1108
|
+
return payload;
|
|
1109
|
+
}
|
|
1110
|
+
/**
|
|
1111
|
+
* Parses raw OpenAI / xAI SSE chunk into normalized components.
|
|
1112
|
+
*
|
|
1113
|
+
* @param chunk Raw parsed OpenAI JSON chunk.
|
|
1114
|
+
* @returns Normalized chunk items.
|
|
1115
|
+
*/
|
|
1116
|
+
function parseOpenAiChunk(chunk) {
|
|
1117
|
+
const typedChunk = typeof chunk === "object" && chunk !== null ? chunk : {};
|
|
1118
|
+
let textDelta;
|
|
1119
|
+
let reasoningDelta;
|
|
1120
|
+
const toolCalls = [];
|
|
1121
|
+
const choice = typedChunk.choices?.[0];
|
|
1122
|
+
if (choice?.delta) {
|
|
1123
|
+
const delta = choice.delta;
|
|
1124
|
+
if (typeof delta.content === "string") textDelta = delta.content;
|
|
1125
|
+
if (typeof delta.reasoning_content === "string") reasoningDelta = delta.reasoning_content;
|
|
1126
|
+
else if (typeof delta.thought === "string") reasoningDelta = delta.thought;
|
|
1127
|
+
if (Array.isArray(delta.tool_calls)) for (const tc of delta.tool_calls) toolCalls.push({
|
|
1128
|
+
index: tc.index ?? 0,
|
|
1129
|
+
id: tc.id,
|
|
1130
|
+
name: tc.function?.name,
|
|
1131
|
+
argumentsDelta: tc.function?.arguments
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
let finishReason;
|
|
1135
|
+
if (choice?.finish_reason) switch (choice.finish_reason) {
|
|
1136
|
+
case "stop":
|
|
1137
|
+
finishReason = { kind: "stop" };
|
|
1138
|
+
break;
|
|
1139
|
+
case "tool_calls":
|
|
1140
|
+
finishReason = { kind: "tool-calls" };
|
|
1141
|
+
break;
|
|
1142
|
+
case "length":
|
|
1143
|
+
finishReason = { kind: "max-tokens" };
|
|
1144
|
+
break;
|
|
1145
|
+
default:
|
|
1146
|
+
finishReason = { kind: "stop" };
|
|
1147
|
+
break;
|
|
1148
|
+
}
|
|
1149
|
+
let usage;
|
|
1150
|
+
if (typedChunk.usage) {
|
|
1151
|
+
const prompt = typedChunk.usage.prompt_tokens ?? 0;
|
|
1152
|
+
const completion = typedChunk.usage.completion_tokens ?? 0;
|
|
1153
|
+
const total = typedChunk.usage.total_tokens ?? prompt + completion;
|
|
1154
|
+
const cached = typedChunk.usage.prompt_tokens_details?.cached_tokens ?? 0;
|
|
1155
|
+
const reasoning = typedChunk.usage.completion_tokens_details?.reasoning_tokens ?? void 0;
|
|
1156
|
+
usage = {
|
|
1157
|
+
inputTokens: Math.max(0, prompt - cached),
|
|
1158
|
+
outputTokens: completion,
|
|
1159
|
+
totalTokens: total,
|
|
1160
|
+
...cached > 0 ? { cacheReadTokens: cached } : {},
|
|
1161
|
+
...reasoning !== void 0 ? { reasoningTokens: reasoning } : {}
|
|
1162
|
+
};
|
|
1163
|
+
}
|
|
1164
|
+
return {
|
|
1165
|
+
textDelta,
|
|
1166
|
+
reasoningDelta,
|
|
1167
|
+
toolCalls,
|
|
1168
|
+
usage,
|
|
1169
|
+
finishReason
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
//#endregion
|
|
1173
|
+
//#region lib/types/formatters/bedrock.js
|
|
1174
|
+
/**
|
|
1175
|
+
* Amazon Bedrock Converse/Invoke Request Serializer and Stream Normalizer.
|
|
1176
|
+
*
|
|
1177
|
+
* @module @machina.ai/ch-llm-reboot/formatters/bedrock
|
|
1178
|
+
*/
|
|
1179
|
+
/**
|
|
1180
|
+
* Formats GenerateOptions into Amazon Bedrock Converse request payload.
|
|
1181
|
+
*
|
|
1182
|
+
* @param options Fully assembled model request.
|
|
1183
|
+
* @returns Bedrock wire request payload.
|
|
1184
|
+
*/
|
|
1185
|
+
function formatBedrockRequest(options) {
|
|
1186
|
+
let systemPrompt = options.system;
|
|
1187
|
+
const messages = [];
|
|
1188
|
+
for (const message of options.messages) {
|
|
1189
|
+
if (message.role === "system") {
|
|
1190
|
+
const textParts = [];
|
|
1191
|
+
for (const block of message.content) if (block.type === "text") textParts.push(block.text);
|
|
1192
|
+
if (textParts.length > 0) systemPrompt = textParts.join("\n");
|
|
1193
|
+
continue;
|
|
1194
|
+
}
|
|
1195
|
+
if (message.role === "user" || message.role === "tool") {
|
|
1196
|
+
const blocks = [];
|
|
1197
|
+
for (const block of message.content) switch (block.type) {
|
|
1198
|
+
case "text":
|
|
1199
|
+
blocks.push({ text: block.text });
|
|
1200
|
+
break;
|
|
1201
|
+
case "image": {
|
|
1202
|
+
const rawAttachment = block.attachment;
|
|
1203
|
+
if (typeof rawAttachment.data === "string") {
|
|
1204
|
+
const mime = (typeof rawAttachment.mimeType === "string" ? rawAttachment.mimeType : "image/jpeg").replace("image/", "");
|
|
1205
|
+
blocks.push({ image: {
|
|
1206
|
+
format: mime,
|
|
1207
|
+
source: { bytes: rawAttachment.data }
|
|
1208
|
+
} });
|
|
1209
|
+
}
|
|
1210
|
+
break;
|
|
1211
|
+
}
|
|
1212
|
+
case "tool-result": {
|
|
1213
|
+
const textParts = [];
|
|
1214
|
+
for (const subBlock of block.content) if (subBlock.type === "text") textParts.push(subBlock.text);
|
|
1215
|
+
blocks.push({ toolResult: {
|
|
1216
|
+
toolUseId: block.toolCallId,
|
|
1217
|
+
content: [{ text: textParts.join("\n") }],
|
|
1218
|
+
status: block.isError ? "error" : "success"
|
|
1219
|
+
} });
|
|
1220
|
+
break;
|
|
1221
|
+
}
|
|
1222
|
+
default: break;
|
|
1223
|
+
}
|
|
1224
|
+
if (blocks.length > 0) messages.push({
|
|
1225
|
+
role: "user",
|
|
1226
|
+
content: blocks
|
|
1227
|
+
});
|
|
1228
|
+
} else {
|
|
1229
|
+
const blocks = [];
|
|
1230
|
+
for (const block of message.content) switch (block.type) {
|
|
1231
|
+
case "text":
|
|
1232
|
+
blocks.push({ text: block.text });
|
|
1233
|
+
break;
|
|
1234
|
+
case "reasoning":
|
|
1235
|
+
blocks.push({ text: block.text });
|
|
1236
|
+
break;
|
|
1237
|
+
case "tool-call": {
|
|
1238
|
+
let parsedArgs = {};
|
|
1239
|
+
try {
|
|
1240
|
+
parsedArgs = JSON.parse(block.arguments);
|
|
1241
|
+
} catch {
|
|
1242
|
+
parsedArgs = { raw: block.arguments };
|
|
1243
|
+
}
|
|
1244
|
+
blocks.push({ toolUse: {
|
|
1245
|
+
toolUseId: block.id,
|
|
1246
|
+
name: block.name,
|
|
1247
|
+
input: parsedArgs
|
|
1248
|
+
} });
|
|
1249
|
+
break;
|
|
1250
|
+
}
|
|
1251
|
+
default: break;
|
|
1252
|
+
}
|
|
1253
|
+
if (blocks.length > 0) messages.push({
|
|
1254
|
+
role: "assistant",
|
|
1255
|
+
content: blocks
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
const payload = { messages };
|
|
1260
|
+
if (systemPrompt && systemPrompt.length > 0) payload.system = [{ text: systemPrompt }];
|
|
1261
|
+
const inferenceConfig = {};
|
|
1262
|
+
if (options.maxTokens !== void 0) inferenceConfig.maxTokens = options.maxTokens;
|
|
1263
|
+
if (options.temperature !== void 0) inferenceConfig.temperature = options.temperature;
|
|
1264
|
+
if (options.stop && options.stop.length > 0) inferenceConfig.stopSequences = options.stop;
|
|
1265
|
+
if (Object.keys(inferenceConfig).length > 0) payload.inferenceConfig = inferenceConfig;
|
|
1266
|
+
if (options.tools && options.tools.length > 0) payload.toolConfig = { tools: options.tools.map((t) => ({ toolSpec: {
|
|
1267
|
+
name: t.name,
|
|
1268
|
+
description: t.description,
|
|
1269
|
+
inputSchema: { json: t.parameters }
|
|
1270
|
+
} })) };
|
|
1271
|
+
return payload;
|
|
1272
|
+
}
|
|
1273
|
+
/**
|
|
1274
|
+
* Parses raw Bedrock Converse chunk into normalized components.
|
|
1275
|
+
*
|
|
1276
|
+
* @param chunk Raw parsed Bedrock chunk.
|
|
1277
|
+
* @returns Normalized chunk items.
|
|
1278
|
+
*/
|
|
1279
|
+
function parseBedrockChunk(chunk) {
|
|
1280
|
+
const typedChunk = typeof chunk === "object" && chunk !== null ? chunk : {};
|
|
1281
|
+
let textDelta;
|
|
1282
|
+
let toolCallId;
|
|
1283
|
+
let toolName;
|
|
1284
|
+
let toolArgumentsDelta;
|
|
1285
|
+
let finishReason;
|
|
1286
|
+
let usage;
|
|
1287
|
+
if (typedChunk.contentBlockStart?.start?.toolUse) {
|
|
1288
|
+
toolCallId = typedChunk.contentBlockStart.start.toolUse.toolUseId;
|
|
1289
|
+
toolName = typedChunk.contentBlockStart.start.toolUse.name;
|
|
1290
|
+
}
|
|
1291
|
+
if (typedChunk.contentBlockDelta?.delta) {
|
|
1292
|
+
const delta = typedChunk.contentBlockDelta.delta;
|
|
1293
|
+
if (typeof delta.text === "string") textDelta = delta.text;
|
|
1294
|
+
if (delta.toolUse?.input !== void 0) toolArgumentsDelta = typeof delta.toolUse.input === "string" ? delta.toolUse.input : JSON.stringify(delta.toolUse.input);
|
|
1295
|
+
}
|
|
1296
|
+
if (typedChunk.messageStop?.stopReason) switch (typedChunk.messageStop.stopReason) {
|
|
1297
|
+
case "end_turn":
|
|
1298
|
+
case "stop_sequence":
|
|
1299
|
+
finishReason = { kind: "stop" };
|
|
1300
|
+
break;
|
|
1301
|
+
case "tool_use":
|
|
1302
|
+
finishReason = { kind: "tool-calls" };
|
|
1303
|
+
break;
|
|
1304
|
+
case "max_tokens":
|
|
1305
|
+
finishReason = { kind: "max-tokens" };
|
|
1306
|
+
break;
|
|
1307
|
+
default:
|
|
1308
|
+
finishReason = { kind: "stop" };
|
|
1309
|
+
break;
|
|
1310
|
+
}
|
|
1311
|
+
if (typedChunk.metadata?.usage) {
|
|
1312
|
+
const u = typedChunk.metadata.usage;
|
|
1313
|
+
const inTokens = u.inputTokens ?? 0;
|
|
1314
|
+
const outTokens = u.outputTokens ?? 0;
|
|
1315
|
+
usage = {
|
|
1316
|
+
inputTokens: inTokens,
|
|
1317
|
+
outputTokens: outTokens,
|
|
1318
|
+
totalTokens: u.totalTokens ?? inTokens + outTokens
|
|
1319
|
+
};
|
|
1320
|
+
}
|
|
1321
|
+
return {
|
|
1322
|
+
textDelta,
|
|
1323
|
+
toolCallId,
|
|
1324
|
+
toolName,
|
|
1325
|
+
toolArgumentsDelta,
|
|
1326
|
+
usage,
|
|
1327
|
+
finishReason
|
|
1328
|
+
};
|
|
1329
|
+
}
|
|
1330
|
+
//#endregion
|
|
1331
|
+
//#region lib/types/sse-parser.js
|
|
1332
|
+
/**
|
|
1333
|
+
* Server-Sent Events (SSE) Stream Parser.
|
|
1334
|
+
*
|
|
1335
|
+
* @module @machina.ai/ch-llm-reboot/sse-parser
|
|
1336
|
+
*/
|
|
1337
|
+
/**
|
|
1338
|
+
* Parses a byte ReadableStream into an async iterable of parsed SSE events.
|
|
1339
|
+
* Handles boundary splitting, CRLF / LF line endings, and multiline data payloads.
|
|
1340
|
+
*
|
|
1341
|
+
* @param stream Raw Uint8Array stream from response body.
|
|
1342
|
+
* @returns Async iterable yielding individual parsed SseEvent objects.
|
|
1343
|
+
*/
|
|
1344
|
+
async function* parseSseStream(stream) {
|
|
1345
|
+
const reader = stream.getReader();
|
|
1346
|
+
const decoder = new TextDecoder("utf-8");
|
|
1347
|
+
let buffer = "";
|
|
1348
|
+
let totalRawText = "";
|
|
1349
|
+
let yieldedCount = 0;
|
|
1350
|
+
let currentEvent;
|
|
1351
|
+
let currentDataLines = [];
|
|
1352
|
+
try {
|
|
1353
|
+
while (true) {
|
|
1354
|
+
const { done, value } = await reader.read();
|
|
1355
|
+
if (done) break;
|
|
1356
|
+
const chunk = decoder.decode(value, { stream: true });
|
|
1357
|
+
totalRawText += chunk;
|
|
1358
|
+
buffer += chunk;
|
|
1359
|
+
const lines = buffer.split(/\r\n|\r|\n/u);
|
|
1360
|
+
buffer = lines.pop() ?? "";
|
|
1361
|
+
for (const line of lines) {
|
|
1362
|
+
if (line.trim() === "") {
|
|
1363
|
+
if (currentDataLines.length > 0) {
|
|
1364
|
+
yieldedCount++;
|
|
1365
|
+
yield {
|
|
1366
|
+
event: currentEvent,
|
|
1367
|
+
data: currentDataLines.join("\n")
|
|
1368
|
+
};
|
|
1369
|
+
currentEvent = void 0;
|
|
1370
|
+
currentDataLines = [];
|
|
1371
|
+
}
|
|
1372
|
+
continue;
|
|
1373
|
+
}
|
|
1374
|
+
if (line.startsWith(":")) continue;
|
|
1375
|
+
if (line.startsWith("event:")) currentEvent = line.slice(6).trim();
|
|
1376
|
+
else if (line.startsWith("data:")) currentDataLines.push(line.slice(5).trim());
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
if (currentDataLines.length > 0) {
|
|
1380
|
+
yieldedCount++;
|
|
1381
|
+
yield {
|
|
1382
|
+
event: currentEvent,
|
|
1383
|
+
data: currentDataLines.join("\n")
|
|
1384
|
+
};
|
|
1385
|
+
} else if (buffer.trim().length > 0) {
|
|
1386
|
+
const line = buffer.trim();
|
|
1387
|
+
if (line.startsWith("data:")) {
|
|
1388
|
+
yieldedCount++;
|
|
1389
|
+
yield {
|
|
1390
|
+
event: currentEvent,
|
|
1391
|
+
data: line.slice(5).trim()
|
|
1392
|
+
};
|
|
1393
|
+
}
|
|
1394
|
+
}
|
|
1395
|
+
if (yieldedCount === 0 && totalRawText.trim().length > 0) {
|
|
1396
|
+
const candidate = totalRawText.trim();
|
|
1397
|
+
if (candidate.startsWith("{") || candidate.startsWith("[")) yield { data: candidate };
|
|
1398
|
+
}
|
|
1399
|
+
} finally {
|
|
1400
|
+
reader.releaseLock();
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
//#endregion
|
|
1404
|
+
//#region lib/types/dispatcher.js
|
|
1405
|
+
/**
|
|
1406
|
+
* Zero-API-Key Upstream Streaming Dispatcher for Reboot LLM Provider.
|
|
1407
|
+
*
|
|
1408
|
+
* @module @machina.ai/ch-llm-reboot/dispatcher
|
|
1409
|
+
*/
|
|
1410
|
+
/**
|
|
1411
|
+
* Dispatches one generation request to the upstream Reboot gateway through `ctx.rebootAuth.fetch` and normalizes the
|
|
1412
|
+
* provider's HTTP stream into the Cordis StreamChunk protocol. The upstream response body is read lazily, so a caller
|
|
1413
|
+
* must consume the returned iterable to completion.
|
|
1414
|
+
* The resolved configuration is re-read on each dispatch, and a missing `ctx.rebootAuth` fails the dispatch rather
|
|
1415
|
+
* than the mount.
|
|
1416
|
+
*/
|
|
1417
|
+
var RebootDispatcher = class {
|
|
1418
|
+
ctx;
|
|
1419
|
+
getConfig;
|
|
1420
|
+
constructor(ctx, getConfig) {
|
|
1421
|
+
this.ctx = ctx;
|
|
1422
|
+
this.getConfig = getConfig;
|
|
1423
|
+
}
|
|
1424
|
+
/**
|
|
1425
|
+
* Dispatches an LLM generation request to the upstream target endpoint
|
|
1426
|
+
* using authenticated ctx.rebootAuth.fetch with Zero API Keys.
|
|
1427
|
+
*
|
|
1428
|
+
* @param options Assembled generation options.
|
|
1429
|
+
* @param signal Optional caller abort signal.
|
|
1430
|
+
* @returns Async stream of standardized Cordis StreamChunks.
|
|
1431
|
+
*/
|
|
1432
|
+
async *dispatchStream(options, signal) {
|
|
1433
|
+
const route = resolveEndpointRoute(this.getConfig().agent.agent_api_url, options.model);
|
|
1434
|
+
let bodyPayload;
|
|
1435
|
+
const headers = {
|
|
1436
|
+
"Content-Type": "application/json",
|
|
1437
|
+
"Accept": "text/event-stream, application/json"
|
|
1438
|
+
};
|
|
1439
|
+
switch (route.family) {
|
|
1440
|
+
case "gemini":
|
|
1441
|
+
bodyPayload = JSON.stringify(formatGeminiRequest(options));
|
|
1442
|
+
break;
|
|
1443
|
+
case "anthropic":
|
|
1444
|
+
headers["anthropic-version"] = "2023-06-01";
|
|
1445
|
+
bodyPayload = JSON.stringify(formatAnthropicRequest(options));
|
|
1446
|
+
break;
|
|
1447
|
+
case "openai":
|
|
1448
|
+
case "xai":
|
|
1449
|
+
bodyPayload = JSON.stringify(formatOpenAiRequest(options));
|
|
1450
|
+
break;
|
|
1451
|
+
case "bedrock":
|
|
1452
|
+
headers.Accept = "application/json, text/event-stream";
|
|
1453
|
+
bodyPayload = JSON.stringify(formatBedrockRequest(options));
|
|
1454
|
+
break;
|
|
1455
|
+
}
|
|
1456
|
+
const authService = this.ctx.rebootAuth;
|
|
1457
|
+
if (!authService || typeof authService.fetch !== "function") throw new Error("Reboot LLM Provider requires RebootAuthService (ctx.rebootAuth.fetch). Please ensure @machina.ai/ch-auth-reboot-sso is registered.");
|
|
1458
|
+
const response = await authService.fetch(route.targetUrl, {
|
|
1459
|
+
method: "POST",
|
|
1460
|
+
headers,
|
|
1461
|
+
body: bodyPayload,
|
|
1462
|
+
signal: signal ?? options.signal,
|
|
1463
|
+
sessionId: options.sessionId
|
|
1464
|
+
});
|
|
1465
|
+
if (!response.ok) {
|
|
1466
|
+
let errorDetails = "";
|
|
1467
|
+
try {
|
|
1468
|
+
errorDetails = await response.text();
|
|
1469
|
+
} catch {
|
|
1470
|
+
errorDetails = response.statusText;
|
|
1471
|
+
}
|
|
1472
|
+
throw mapHttpErrorToLlmError(response.status, response.statusText, errorDetails);
|
|
1473
|
+
}
|
|
1474
|
+
if (!response.body) throw new LlmError("Reboot LLM Provider received empty response body from upstream.", "EMPTY_RESPONSE", { status: response.status });
|
|
1475
|
+
let blockIndex = 0;
|
|
1476
|
+
let activeBlockType = null;
|
|
1477
|
+
let currentBlockText = "";
|
|
1478
|
+
let currentToolId = "";
|
|
1479
|
+
let currentToolName = "";
|
|
1480
|
+
let currentToolArgs = "";
|
|
1481
|
+
let currentToolThoughtSignature;
|
|
1482
|
+
let latestUsage;
|
|
1483
|
+
let finishReason;
|
|
1484
|
+
const closeCurrentBlock = () => {
|
|
1485
|
+
const closedChunks = [];
|
|
1486
|
+
if (activeBlockType === "text") {
|
|
1487
|
+
closedChunks.push({
|
|
1488
|
+
type: "block-end",
|
|
1489
|
+
index: blockIndex,
|
|
1490
|
+
block: {
|
|
1491
|
+
type: "text",
|
|
1492
|
+
text: currentBlockText
|
|
1493
|
+
}
|
|
1494
|
+
});
|
|
1495
|
+
blockIndex++;
|
|
1496
|
+
activeBlockType = null;
|
|
1497
|
+
currentBlockText = "";
|
|
1498
|
+
} else if (activeBlockType === "reasoning") {
|
|
1499
|
+
closedChunks.push({
|
|
1500
|
+
type: "block-end",
|
|
1501
|
+
index: blockIndex,
|
|
1502
|
+
block: {
|
|
1503
|
+
type: "reasoning",
|
|
1504
|
+
text: currentBlockText
|
|
1505
|
+
}
|
|
1506
|
+
});
|
|
1507
|
+
blockIndex++;
|
|
1508
|
+
activeBlockType = null;
|
|
1509
|
+
currentBlockText = "";
|
|
1510
|
+
} else if (activeBlockType === "tool-call") {
|
|
1511
|
+
closedChunks.push({
|
|
1512
|
+
type: "block-end",
|
|
1513
|
+
index: blockIndex,
|
|
1514
|
+
block: {
|
|
1515
|
+
type: "tool-call",
|
|
1516
|
+
id: currentToolId,
|
|
1517
|
+
name: currentToolName,
|
|
1518
|
+
arguments: currentToolArgs,
|
|
1519
|
+
...currentToolThoughtSignature !== void 0 ? { thoughtSignature: currentToolThoughtSignature } : {}
|
|
1520
|
+
}
|
|
1521
|
+
});
|
|
1522
|
+
blockIndex++;
|
|
1523
|
+
activeBlockType = null;
|
|
1524
|
+
currentToolId = "";
|
|
1525
|
+
currentToolName = "";
|
|
1526
|
+
currentToolArgs = "";
|
|
1527
|
+
currentToolThoughtSignature = void 0;
|
|
1528
|
+
}
|
|
1529
|
+
return closedChunks;
|
|
1530
|
+
};
|
|
1531
|
+
for await (const sseEvent of parseSseStream(response.body)) {
|
|
1532
|
+
if (sseEvent.data === "[DONE]") break;
|
|
1533
|
+
let parsedJson;
|
|
1534
|
+
try {
|
|
1535
|
+
parsedJson = JSON.parse(sseEvent.data);
|
|
1536
|
+
} catch {
|
|
1537
|
+
continue;
|
|
1538
|
+
}
|
|
1539
|
+
switch (route.family) {
|
|
1540
|
+
case "gemini": {
|
|
1541
|
+
const parsed = parseGeminiChunk(parsedJson, blockIndex);
|
|
1542
|
+
if (parsed.usage) latestUsage = parsed.usage;
|
|
1543
|
+
if (parsed.finishReason) finishReason = parsed.finishReason;
|
|
1544
|
+
for (const reasoning of parsed.reasoningDeltas) {
|
|
1545
|
+
if (activeBlockType !== "reasoning") {
|
|
1546
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1547
|
+
activeBlockType = "reasoning";
|
|
1548
|
+
currentBlockText = "";
|
|
1549
|
+
yield {
|
|
1550
|
+
type: "block-start",
|
|
1551
|
+
index: blockIndex,
|
|
1552
|
+
blockType: "reasoning"
|
|
1553
|
+
};
|
|
1554
|
+
}
|
|
1555
|
+
currentBlockText += reasoning;
|
|
1556
|
+
yield {
|
|
1557
|
+
type: "reasoning-delta",
|
|
1558
|
+
index: blockIndex,
|
|
1559
|
+
text: reasoning
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
for (const text of parsed.textDeltas) {
|
|
1563
|
+
if (activeBlockType !== "text") {
|
|
1564
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1565
|
+
activeBlockType = "text";
|
|
1566
|
+
currentBlockText = "";
|
|
1567
|
+
yield {
|
|
1568
|
+
type: "block-start",
|
|
1569
|
+
index: blockIndex,
|
|
1570
|
+
blockType: "text"
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
currentBlockText += text;
|
|
1574
|
+
yield {
|
|
1575
|
+
type: "text-delta",
|
|
1576
|
+
index: blockIndex,
|
|
1577
|
+
text
|
|
1578
|
+
};
|
|
1579
|
+
}
|
|
1580
|
+
for (const tc of parsed.toolCalls) {
|
|
1581
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1582
|
+
activeBlockType = "tool-call";
|
|
1583
|
+
currentToolId = `call_${Date.now()}_${blockIndex}`;
|
|
1584
|
+
currentToolName = tc.name;
|
|
1585
|
+
currentToolArgs = tc.arguments;
|
|
1586
|
+
currentToolThoughtSignature = tc.thoughtSignature;
|
|
1587
|
+
yield {
|
|
1588
|
+
type: "block-start",
|
|
1589
|
+
index: blockIndex,
|
|
1590
|
+
blockType: "tool-call"
|
|
1591
|
+
};
|
|
1592
|
+
yield {
|
|
1593
|
+
type: "tool-call-delta",
|
|
1594
|
+
index: blockIndex,
|
|
1595
|
+
id: currentToolId,
|
|
1596
|
+
name: currentToolName,
|
|
1597
|
+
argumentsDelta: currentToolArgs
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
break;
|
|
1601
|
+
}
|
|
1602
|
+
case "anthropic": {
|
|
1603
|
+
const parsed = parseAnthropicSseEvent(parsedJson);
|
|
1604
|
+
if (parsed.usage) latestUsage = {
|
|
1605
|
+
...latestUsage,
|
|
1606
|
+
...parsed.usage
|
|
1607
|
+
};
|
|
1608
|
+
if (parsed.finishReason) finishReason = parsed.finishReason;
|
|
1609
|
+
if (parsed.reasoningDelta) {
|
|
1610
|
+
if (activeBlockType !== "reasoning") {
|
|
1611
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1612
|
+
activeBlockType = "reasoning";
|
|
1613
|
+
currentBlockText = "";
|
|
1614
|
+
yield {
|
|
1615
|
+
type: "block-start",
|
|
1616
|
+
index: blockIndex,
|
|
1617
|
+
blockType: "reasoning"
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
currentBlockText += parsed.reasoningDelta;
|
|
1621
|
+
yield {
|
|
1622
|
+
type: "reasoning-delta",
|
|
1623
|
+
index: blockIndex,
|
|
1624
|
+
text: parsed.reasoningDelta
|
|
1625
|
+
};
|
|
1626
|
+
}
|
|
1627
|
+
if (parsed.textDelta) {
|
|
1628
|
+
if (activeBlockType !== "text") {
|
|
1629
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1630
|
+
activeBlockType = "text";
|
|
1631
|
+
currentBlockText = "";
|
|
1632
|
+
yield {
|
|
1633
|
+
type: "block-start",
|
|
1634
|
+
index: blockIndex,
|
|
1635
|
+
blockType: "text"
|
|
1636
|
+
};
|
|
1637
|
+
}
|
|
1638
|
+
currentBlockText += parsed.textDelta;
|
|
1639
|
+
yield {
|
|
1640
|
+
type: "text-delta",
|
|
1641
|
+
index: blockIndex,
|
|
1642
|
+
text: parsed.textDelta
|
|
1643
|
+
};
|
|
1644
|
+
}
|
|
1645
|
+
if (parsed.toolCallId && parsed.toolName) {
|
|
1646
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1647
|
+
activeBlockType = "tool-call";
|
|
1648
|
+
currentToolId = parsed.toolCallId;
|
|
1649
|
+
currentToolName = parsed.toolName;
|
|
1650
|
+
currentToolArgs = "";
|
|
1651
|
+
yield {
|
|
1652
|
+
type: "block-start",
|
|
1653
|
+
index: blockIndex,
|
|
1654
|
+
blockType: "tool-call"
|
|
1655
|
+
};
|
|
1656
|
+
}
|
|
1657
|
+
if (parsed.toolArgumentsDelta) {
|
|
1658
|
+
currentToolArgs += parsed.toolArgumentsDelta;
|
|
1659
|
+
yield {
|
|
1660
|
+
type: "tool-call-delta",
|
|
1661
|
+
index: blockIndex,
|
|
1662
|
+
id: currentToolId,
|
|
1663
|
+
argumentsDelta: parsed.toolArgumentsDelta
|
|
1664
|
+
};
|
|
1665
|
+
}
|
|
1666
|
+
break;
|
|
1667
|
+
}
|
|
1668
|
+
case "openai":
|
|
1669
|
+
case "xai": {
|
|
1670
|
+
const parsed = parseOpenAiChunk(parsedJson);
|
|
1671
|
+
if (parsed.usage) latestUsage = parsed.usage;
|
|
1672
|
+
if (parsed.finishReason) finishReason = parsed.finishReason;
|
|
1673
|
+
if (parsed.reasoningDelta) {
|
|
1674
|
+
if (activeBlockType !== "reasoning") {
|
|
1675
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1676
|
+
activeBlockType = "reasoning";
|
|
1677
|
+
currentBlockText = "";
|
|
1678
|
+
yield {
|
|
1679
|
+
type: "block-start",
|
|
1680
|
+
index: blockIndex,
|
|
1681
|
+
blockType: "reasoning"
|
|
1682
|
+
};
|
|
1683
|
+
}
|
|
1684
|
+
currentBlockText += parsed.reasoningDelta;
|
|
1685
|
+
yield {
|
|
1686
|
+
type: "reasoning-delta",
|
|
1687
|
+
index: blockIndex,
|
|
1688
|
+
text: parsed.reasoningDelta
|
|
1689
|
+
};
|
|
1690
|
+
}
|
|
1691
|
+
if (parsed.textDelta) {
|
|
1692
|
+
if (activeBlockType !== "text") {
|
|
1693
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1694
|
+
activeBlockType = "text";
|
|
1695
|
+
currentBlockText = "";
|
|
1696
|
+
yield {
|
|
1697
|
+
type: "block-start",
|
|
1698
|
+
index: blockIndex,
|
|
1699
|
+
blockType: "text"
|
|
1700
|
+
};
|
|
1701
|
+
}
|
|
1702
|
+
currentBlockText += parsed.textDelta;
|
|
1703
|
+
yield {
|
|
1704
|
+
type: "text-delta",
|
|
1705
|
+
index: blockIndex,
|
|
1706
|
+
text: parsed.textDelta
|
|
1707
|
+
};
|
|
1708
|
+
}
|
|
1709
|
+
for (const tc of parsed.toolCalls) if (tc.name || tc.id) {
|
|
1710
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1711
|
+
activeBlockType = "tool-call";
|
|
1712
|
+
currentToolId = tc.id ?? `call_${blockIndex}`;
|
|
1713
|
+
currentToolName = tc.name ?? "";
|
|
1714
|
+
currentToolArgs = tc.argumentsDelta ?? "";
|
|
1715
|
+
yield {
|
|
1716
|
+
type: "block-start",
|
|
1717
|
+
index: blockIndex,
|
|
1718
|
+
blockType: "tool-call"
|
|
1719
|
+
};
|
|
1720
|
+
yield {
|
|
1721
|
+
type: "tool-call-delta",
|
|
1722
|
+
index: blockIndex,
|
|
1723
|
+
id: currentToolId,
|
|
1724
|
+
name: currentToolName,
|
|
1725
|
+
argumentsDelta: currentToolArgs
|
|
1726
|
+
};
|
|
1727
|
+
} else if (tc.argumentsDelta) {
|
|
1728
|
+
currentToolArgs += tc.argumentsDelta;
|
|
1729
|
+
yield {
|
|
1730
|
+
type: "tool-call-delta",
|
|
1731
|
+
index: blockIndex,
|
|
1732
|
+
id: currentToolId,
|
|
1733
|
+
argumentsDelta: tc.argumentsDelta
|
|
1734
|
+
};
|
|
1735
|
+
}
|
|
1736
|
+
break;
|
|
1737
|
+
}
|
|
1738
|
+
case "bedrock": {
|
|
1739
|
+
const parsed = parseBedrockChunk(parsedJson);
|
|
1740
|
+
if (parsed.usage) latestUsage = parsed.usage;
|
|
1741
|
+
if (parsed.finishReason) finishReason = parsed.finishReason;
|
|
1742
|
+
if (parsed.textDelta) {
|
|
1743
|
+
if (activeBlockType !== "text") {
|
|
1744
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1745
|
+
activeBlockType = "text";
|
|
1746
|
+
currentBlockText = "";
|
|
1747
|
+
yield {
|
|
1748
|
+
type: "block-start",
|
|
1749
|
+
index: blockIndex,
|
|
1750
|
+
blockType: "text"
|
|
1751
|
+
};
|
|
1752
|
+
}
|
|
1753
|
+
currentBlockText += parsed.textDelta;
|
|
1754
|
+
yield {
|
|
1755
|
+
type: "text-delta",
|
|
1756
|
+
index: blockIndex,
|
|
1757
|
+
text: parsed.textDelta
|
|
1758
|
+
};
|
|
1759
|
+
}
|
|
1760
|
+
if (parsed.toolCallId && parsed.toolName) {
|
|
1761
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1762
|
+
activeBlockType = "tool-call";
|
|
1763
|
+
currentToolId = parsed.toolCallId;
|
|
1764
|
+
currentToolName = parsed.toolName;
|
|
1765
|
+
currentToolArgs = "";
|
|
1766
|
+
yield {
|
|
1767
|
+
type: "block-start",
|
|
1768
|
+
index: blockIndex,
|
|
1769
|
+
blockType: "tool-call"
|
|
1770
|
+
};
|
|
1771
|
+
}
|
|
1772
|
+
if (parsed.toolArgumentsDelta) {
|
|
1773
|
+
currentToolArgs += parsed.toolArgumentsDelta;
|
|
1774
|
+
yield {
|
|
1775
|
+
type: "tool-call-delta",
|
|
1776
|
+
index: blockIndex,
|
|
1777
|
+
id: currentToolId,
|
|
1778
|
+
argumentsDelta: parsed.toolArgumentsDelta
|
|
1779
|
+
};
|
|
1780
|
+
}
|
|
1781
|
+
break;
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
for (const c of closeCurrentBlock()) yield c;
|
|
1786
|
+
if (latestUsage) yield {
|
|
1787
|
+
type: "usage",
|
|
1788
|
+
usage: latestUsage
|
|
1789
|
+
};
|
|
1790
|
+
yield {
|
|
1791
|
+
type: "finish",
|
|
1792
|
+
reason: finishReason ?? { kind: "stop" }
|
|
1793
|
+
};
|
|
1794
|
+
}
|
|
1795
|
+
};
|
|
1796
|
+
//#endregion
|
|
1797
|
+
//#region lib/types/adapter.js
|
|
1798
|
+
/**
|
|
1799
|
+
* Cordis LlmAdapter implementation for Reboot Multi-Model Gateway.
|
|
1800
|
+
*
|
|
1801
|
+
* @module @machina.ai/ch-llm-reboot/adapter
|
|
1802
|
+
*/
|
|
1803
|
+
/**
|
|
1804
|
+
* Concrete LlmAdapter translating harness requests through Reboot AI Gateway.
|
|
1805
|
+
*/
|
|
1806
|
+
var RebootLlmAdapter = class extends LlmAdapter {
|
|
1807
|
+
ctx;
|
|
1808
|
+
getConfig;
|
|
1809
|
+
dispatcher;
|
|
1810
|
+
constructor(ctx, getConfig) {
|
|
1811
|
+
super();
|
|
1812
|
+
this.ctx = ctx;
|
|
1813
|
+
this.getConfig = getConfig;
|
|
1814
|
+
this.dispatcher = new RebootDispatcher(ctx, getConfig);
|
|
1815
|
+
}
|
|
1816
|
+
providerInfo(provider) {
|
|
1817
|
+
const family = familyOfRoute(this.getConfig().provider_name, provider);
|
|
1818
|
+
return {
|
|
1819
|
+
id: provider,
|
|
1820
|
+
name: family === void 0 ? "Reboot AI Gateway" : FAMILY_DISPLAY_NAME[family]
|
|
1821
|
+
};
|
|
1822
|
+
}
|
|
1823
|
+
listModels(provider) {
|
|
1824
|
+
const family = familyOfRoute(this.getConfig().provider_name, provider);
|
|
1825
|
+
if (family === void 0) return Promise.resolve([]);
|
|
1826
|
+
const visibleModels = modelsForFamilyRoute(family, resolveExperimentalFeaturesEnabled());
|
|
1827
|
+
return Promise.resolve(visibleModels.map((m) => ({
|
|
1828
|
+
provider,
|
|
1829
|
+
id: m.id,
|
|
1830
|
+
name: m.name,
|
|
1831
|
+
inputModalities: ["text", "image"]
|
|
1832
|
+
})));
|
|
1833
|
+
}
|
|
1834
|
+
resolveModel(provider, model, _signal) {
|
|
1835
|
+
const def = getModelDefinition(resolveModelId(model));
|
|
1836
|
+
if (def === void 0) return Promise.resolve({
|
|
1837
|
+
provider,
|
|
1838
|
+
id: model,
|
|
1839
|
+
name: model,
|
|
1840
|
+
inputModalities: ["text", "image"]
|
|
1841
|
+
});
|
|
1842
|
+
return Promise.resolve({
|
|
1843
|
+
provider,
|
|
1844
|
+
id: model,
|
|
1845
|
+
name: def.name,
|
|
1846
|
+
inputModalities: ["text", "image"],
|
|
1847
|
+
context: { contextWindow: def.contextWindow },
|
|
1848
|
+
...def.maxTokens > 0 ? { defaultMaxTokens: def.maxTokens } : {}
|
|
1849
|
+
});
|
|
1850
|
+
}
|
|
1851
|
+
providerRetryPolicy(_provider) {
|
|
1852
|
+
return this.getConfig().retryPolicy;
|
|
1853
|
+
}
|
|
1854
|
+
async *stream(options) {
|
|
1855
|
+
yield* this.dispatcher.dispatchStream(options, options.signal);
|
|
1856
|
+
}
|
|
1857
|
+
};
|
|
1858
|
+
//#endregion
|
|
1859
|
+
//#region lib/types/index.js
|
|
1860
|
+
/**
|
|
1861
|
+
* Reboot Multi-Model LLM Provider plugin for DeepSeek Harness.
|
|
1862
|
+
*
|
|
1863
|
+
* @module @machina.ai/ch-llm-reboot
|
|
1864
|
+
*/
|
|
1865
|
+
/** Upstream Reboot AI Gateway base URL applied when `agent.agent_api_url` is absent from plugin config and ~/.cell-harness/config.yaml. */
|
|
1866
|
+
const DEFAULT_AGENT_API_URL = "https://api.machina.ai";
|
|
1867
|
+
/**
|
|
1868
|
+
* Upstream request timeout in seconds applied when `agent.timeout_seconds` is absent; resolved configs reject
|
|
1869
|
+
* non-positive or fractional values.
|
|
1870
|
+
*/
|
|
1871
|
+
const DEFAULT_TIMEOUT_SECONDS = 1200;
|
|
1872
|
+
/** Startup model or routing alias applied when `default_model` is absent, before the catalog resolves it to a provider model. */
|
|
1873
|
+
const DEFAULT_MODEL = "auto-gemini-3.8";
|
|
1874
|
+
/** Provider name prefix applied when `provider_name` is absent; it builds the per-family route keys registered with `ctx.llm`. */
|
|
1875
|
+
const DEFAULT_PROVIDER_NAME = "reboot";
|
|
1876
|
+
const Config = z.object({
|
|
1877
|
+
agent: z.object({
|
|
1878
|
+
agent_api_url: z.string().default(DEFAULT_AGENT_API_URL),
|
|
1879
|
+
timeout_seconds: z.number().default(DEFAULT_TIMEOUT_SECONDS)
|
|
1880
|
+
}),
|
|
1881
|
+
default_model: z.string().default(DEFAULT_MODEL),
|
|
1882
|
+
provider_name: z.string().default(DEFAULT_PROVIDER_NAME),
|
|
1883
|
+
enable_dynamic_routing: z.boolean().default(true),
|
|
1884
|
+
retryPolicy: RetryPolicySchema
|
|
1885
|
+
});
|
|
1886
|
+
/**
|
|
1887
|
+
* Validates and normalizes raw configuration.
|
|
1888
|
+
*
|
|
1889
|
+
* @param raw Raw input configuration.
|
|
1890
|
+
* @returns Resolved configuration.
|
|
1891
|
+
*/
|
|
1892
|
+
function resolveRebootLlmConfig(raw) {
|
|
1893
|
+
const external = loadCellHarnessConfigSync();
|
|
1894
|
+
const agentUrl = raw.agent?.agent_api_url ?? external.agent.agent_api_url;
|
|
1895
|
+
let parsedUrl;
|
|
1896
|
+
try {
|
|
1897
|
+
parsedUrl = new URL(agentUrl);
|
|
1898
|
+
} catch {
|
|
1899
|
+
throw new Error(`llm-reboot: agent.agent_api_url is not a valid URL: ${JSON.stringify(agentUrl)}`);
|
|
1900
|
+
}
|
|
1901
|
+
if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") throw new Error(`llm-reboot: agent.agent_api_url must be http(s), got ${parsedUrl.protocol}`);
|
|
1902
|
+
const timeoutSeconds = raw.agent?.timeout_seconds ?? external.agent.timeout_seconds;
|
|
1903
|
+
if (!Number.isInteger(timeoutSeconds) || timeoutSeconds <= 0) throw new Error("llm-reboot: agent.timeout_seconds must be a positive integer");
|
|
1904
|
+
return {
|
|
1905
|
+
agent: {
|
|
1906
|
+
agent_api_url: agentUrl,
|
|
1907
|
+
timeout_seconds: timeoutSeconds
|
|
1908
|
+
},
|
|
1909
|
+
default_model: raw.default_model ?? external.llm.default_model,
|
|
1910
|
+
provider_name: raw.provider_name ?? external.llm.provider_name,
|
|
1911
|
+
enable_dynamic_routing: raw.enable_dynamic_routing ?? external.llm.enable_dynamic_routing,
|
|
1912
|
+
retryPolicy: resolveRetryPolicy(raw.retryPolicy, "llm-reboot")
|
|
1913
|
+
};
|
|
1914
|
+
}
|
|
1915
|
+
const name = "llm-reboot";
|
|
1916
|
+
const inject = ["rebootAuth", "llm"];
|
|
1917
|
+
/**
|
|
1918
|
+
* Mounts the Reboot LLM provider adapter into the Cordis context.
|
|
1919
|
+
*
|
|
1920
|
+
* @param ctx The Cordis context.
|
|
1921
|
+
* @param config Plugin configuration.
|
|
1922
|
+
*/
|
|
1923
|
+
function apply(ctx, config = {}) {
|
|
1924
|
+
const resolved = resolveRebootLlmConfig(config);
|
|
1925
|
+
const adapter = new RebootLlmAdapter(ctx, () => resolved);
|
|
1926
|
+
const routes = ROUTABLE_FAMILIES.map((family) => familyRoute(resolved.provider_name, family));
|
|
1927
|
+
ctx.llm.registerConfigurableProviders(ROUTABLE_FAMILIES.map((family) => ({
|
|
1928
|
+
provider: familyRoute(resolved.provider_name, family),
|
|
1929
|
+
displayName: FAMILY_DISPLAY_NAME[family],
|
|
1930
|
+
settingsNs: "llm-reboot",
|
|
1931
|
+
settingsPath: []
|
|
1932
|
+
})));
|
|
1933
|
+
ctx.llm.registerAdapter(routes, adapter);
|
|
1934
|
+
}
|
|
1935
|
+
//#endregion
|
|
1936
|
+
export { CANONICAL_MODELS, Config, DEFAULT_AGENT_API_URL, DEFAULT_MODEL, DEFAULT_PROVIDER_NAME, DEFAULT_TIMEOUT_SECONDS, FAMILY_DISPLAY_NAME, ROUTABLE_FAMILIES, RebootDispatcher, RebootLlmAdapter, apply, familyOfRoute, familyRoute, formatAnthropicRequest, formatBedrockRequest, formatGeminiRequest, formatOpenAiRequest, getModelDefinition, inferProviderFamily, inject, isBedrockEnabled, listCatalogModels, modelsForFamilyRoute, name, parseAnthropicSseEvent, parseBedrockChunk, parseGeminiChunk, parseOpenAiChunk, parseSseStream, resolveEndpointRoute, resolveModelId, resolveRebootLlmConfig, sanitizeGeminiSchema, setBedrockEnabled };
|