@bike4mind/cli 4.8.0 → 4.10.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 (39) hide show
  1. package/README.md +21 -0
  2. package/bin/bike4mind-cli.mjs +342 -239
  3. package/dist/{AgentHistoryStore-Bvmcy2kf.mjs → AgentHistoryStore-CjGVgxLR.mjs} +305 -644
  4. package/dist/{ApiClient-Yp2LPlX3.mjs → ApiClient-SVXSI3HI.mjs} +3 -3
  5. package/dist/{BubblewrapRuntime-OI4qFPNB.mjs → BubblewrapRuntime-CTc_KPnd.mjs} +2 -2
  6. package/dist/{ConfigStore-CP1W86Ui.mjs → ConfigStore-B2Dy-PT9.mjs} +7 -8
  7. package/dist/ConfigStore-zlY0PikB.mjs +2 -0
  8. package/dist/{Logger-3RbeTZ9o.mjs → Logger-7MmrU5w6.mjs} +4845 -1126
  9. package/dist/{SandboxOrchestrator-lpxVEFO7.mjs → SandboxOrchestrator-CeDwd6Fj.mjs} +1 -1
  10. package/dist/{SandboxRuntimeAdapter-u6c_IrjP.mjs → SandboxRuntimeAdapter-CFEIywKt.mjs} +1 -1
  11. package/dist/{SandboxRuntimeAdapter-C3xICJtQ.mjs → SandboxRuntimeAdapter-CjNDzYSf.mjs} +2 -2
  12. package/dist/{SeatbeltRuntime-Ccd_QbjX.mjs → SeatbeltRuntime-CQItj-F1.mjs} +2 -2
  13. package/dist/{WorkItemsClient-D4sFGL9X.mjs → WorkItemsClient-C9_pjHCo.mjs} +3 -4
  14. package/dist/{buildToolSearch-CqHKSLtG.mjs → buildToolSearch-8xyBwXRx.mjs} +2 -2
  15. package/dist/commands/acpCommand.mjs +6 -7
  16. package/dist/commands/apiCommand.mjs +1 -1
  17. package/dist/commands/doctorCommand.mjs +2 -2
  18. package/dist/commands/envCommand.mjs +1 -1
  19. package/dist/commands/headlessCommand.mjs +10 -11
  20. package/dist/commands/hostCommand.mjs +1 -1
  21. package/dist/commands/mcpCommand.mjs +3 -3
  22. package/dist/commands/mirrorCommand.mjs +2 -2
  23. package/dist/commands/modelsCommand.mjs +4 -4
  24. package/dist/commands/pluginCommand.mjs +1 -1
  25. package/dist/commands/skillsCommand.mjs +3 -3
  26. package/dist/commands/updateCommand.mjs +2 -2
  27. package/dist/dist-DHgMhdzV.mjs +10138 -0
  28. package/dist/{fit-BOnDsgbk.mjs → fit-D8Quui6j.mjs} +3 -3
  29. package/dist/index.mjs +732 -69
  30. package/dist/{modelServers-B7zI5XnO.mjs → modelServers-JsKBm7Wn.mjs} +1 -1
  31. package/dist/{package-WlxLVpUb.mjs → package-r_xumsGY.mjs} +1 -1
  32. package/dist/{serve-DpsV0mag.mjs → serve-BM9PKMLH.mjs} +873 -60
  33. package/dist/{store-xeJRhBtO.mjs → store-CmOg7JIt.mjs} +2 -0
  34. package/dist/store-OGMXhD4A.mjs +2 -0
  35. package/dist/{updateChecker-Boq0RruU.mjs → updateChecker-BOqaLeZU.mjs} +1 -1
  36. package/package.json +12 -44
  37. package/dist/ConfigStore-Bo4od3Eu.mjs +0 -2
  38. package/dist/dist-BPhZ0dCz.mjs +0 -4776
  39. package/dist/store-Bpdo9Syo.mjs +0 -2
@@ -1,4776 +0,0 @@
1
- #!/usr/bin/env node
2
- import { $ as SupportedFabFileMimeTypes, Ct as isSupportedEmbeddingModel, E as CompletionReasoningEffortSchema, G as OllamaEmbeddingModel, It as stripDeliveredArtifactBlocks, J as PermissionDeniedError, K as OpenAIEmbeddingModel, Lt as stripToolArtifactMarkup, M as EMBEDDING_MODEL_CATALOG, N as EMBEDDING_MODEL_IDS, Nt as servableEmbeddingDimensions, S as CONTEXT_WINDOW_SAFETY_BUFFER_TOKENS, T as ChatModels, Tt as isUserInitiatedAbort, U as ModelBackend, Ut as visibleReplyText, V as MODEL_INFO_FIELD_GROUP_OF, _ as AudioMimeType, ct as createThinkMarkerEscaper, d as ARTIFACT_REMOVED_PLACEHOLDER, f as AdminAiStoredConfigSchema, ft as getEmbeddingModelCapabilities, gt as hasDeliverablePinnedArtifact, jt as resolveSettingDefinition, lt as escapeThinkMarkers, mt as getQuestErrorCode, nn as APP_NAME, nt as VoyageAIEmbeddingModel, p as AiAccessRefusedError, rn as WEBSITE_URL, u as ARTIFACT_DELIVERED_PLACEHOLDER, ut as filterToolArtifactMarkup, vt as isEnforceCreditsLocked, wt as isSupportedFabFileMimeType, y as BedrockEmbeddingModel, yt as isExpectedToolError } from "./Logger-3RbeTZ9o.mjs";
3
- import { b as ollamaNumCtx } from "./modelHub-BSB6qRFP.mjs";
4
- import "crypto";
5
- import path from "path";
6
- import { v4 } from "uuid";
7
- import { z as z$1 } from "zod";
8
- import "axios";
9
- import "node:crypto";
10
- import { promisify as promisify$1 } from "util";
11
- import dns from "dns";
12
- import http from "http";
13
- import https from "https";
14
- import "mammoth";
15
- import "jszip";
16
- import "unpdf";
17
- import "mime-types";
18
- import "@aws-sdk/client-s3";
19
- import "@aws-sdk/s3-request-presigner";
20
- import "file-type";
21
- import "@smithy/node-http-handler";
22
- import "@opensearch-project/opensearch";
23
- import "@aws-sdk/credential-provider-node";
24
- import "@opensearch-project/opensearch/aws-v3";
25
- import "@aws-sdk/client-bedrock-runtime";
26
- import OpenAI from "openai";
27
- import "@anthropic-ai/sdk";
28
- import { Agent } from "undici";
29
- import "@aws-sdk/client-cloudwatch";
30
- import "@anthropic-ai/sdk/lib/credentials/oidc-federation";
31
- import "@anthropic-ai/sdk/core/streaming";
32
- import "@google/genai";
33
- import "lodash/pick.js";
34
- import "openai/streaming";
35
- import { Ollama } from "ollama";
36
- import "@aws-sdk/client-sqs";
37
- import "@aws-sdk/client-apigatewaymanagementapi";
38
- import { createParser } from "eventsource-parser";
39
- //#region ../../b4m-core/observability/dist/index.mjs
40
- const REDACTED = "[REDACTED]";
41
- const TRUNCATED = "[Truncated]";
42
- /** Deep or wide enough that a log line would be unreadable anyway; bounds cost as well as output. */
43
- const MAX_DEPTH = 8;
44
- const MAX_NODES = 2e3;
45
- const sensitiveSuffix = /(?:secret|token|password|apikey|body|bodypreview|prompt|promptpreview|parameterspreview|toolresult|preview|snippet)$/i;
46
- const sensitiveField = /^(authorization|proxyAuthorization|cookie|setCookie|headers|config|request|response|body|requestBody|responseBody|data|message|messages|conversation|conversationHistory|prompt|systemPrompt|content|text|toolResult|toolResults|arguments|parameters|parametersPreview|fullChunk|result|password|securityQuestions|userNotes|apiKey|xiApiKey|xKey|token|accessToken|refreshToken|clientSecret|signingSecret|secret|previousKey|otc|otp|oneTimeCode|verificationCode|magicLink|samlResponse|userToken|tokenPrefix|username|firstName|lastName|fullName|displayName|subject|query|searchQuery|params|commandText)$/i;
47
- /**
48
- * Value patterns scrubbed from every string, including message text and stack traces, so a value
49
- * interpolated into a template literal is caught even though no field name points at it. Every
50
- * quantifier is bounded or runs over a class that excludes the following delimiter, so each pass
51
- * stays linear in the input.
52
- */
53
- const stringScrubbers = [
54
- [/\bBearer\s+[^\s"'\\,;]+/gi, `Bearer ${REDACTED}`],
55
- [/([?&#](?:code|token|access_token|refresh_token|id_token|client_secret|otc|otp|key|api_key|apikey|password|signature|sig|x-amz-signature|x-amz-credential|x-amz-security-token)=)[^&\s"'\\#]+/gi, `$1${REDACTED}`],
56
- [/\beyJ[\w-]{5,}\.[\w-]{5,}\.[\w-]*/g, "[REDACTED_JWT]"],
57
- [/\b(?:sk-[\w-]{20,}|(?:b4m_live|whsec|github_pat|gh[pousr])_\w{12,}|xox[abposr]-[\w-]{12,}|xapp-[\w-]{12,}|(?:sk|rk)_(?:live|test)_\w{12,}|AIza[\w-]{30,}|(?:AKIA|ASIA)[0-9A-Z]{16})/g, REDACTED],
58
- [/\b[\w.%+-]{1,64}@((?:[A-Za-z0-9-]{1,63}\.){1,8}[A-Za-z]{2,24})\b/g, "***@$1"]
59
- ];
60
- function redactString(value) {
61
- let result = value;
62
- for (const [pattern, replacement] of stringScrubbers) result = result.replace(pattern, replacement);
63
- return result;
64
- }
65
- /**
66
- * The request id that ties a provider failure to the provider's own logs. Kept because it is the
67
- * one field an operator needs to ask the provider what went wrong, and it carries no secret.
68
- */
69
- function requestIdOf(value) {
70
- const record = value;
71
- for (const field of [
72
- "request_id",
73
- "requestID",
74
- "requestId"
75
- ]) {
76
- const id = record[field];
77
- if (typeof id === "string" && id) return id;
78
- }
79
- const metadata = record.$metadata;
80
- if (typeof metadata?.requestId === "string" && metadata.requestId) return metadata.requestId;
81
- for (const container of [record.response, record]) {
82
- const header = (container?.headers)?.["x-request-id"];
83
- if (typeof header === "string" && header) return header;
84
- }
85
- }
86
- /**
87
- * Errors thrown by the model and cloud SDKs (axios config/response, AWS `$metadata`) put the
88
- * request and response bodies on the error object. Keeping only the safe fields means an incident
89
- * log still says WHAT failed ("context length exceeded") without serializing the payload.
90
- */
91
- function redactProviderError(value, state, depth) {
92
- const record = value;
93
- const status = typeof record.status === "number" ? record.status : typeof record.$metadata?.httpStatusCode === "number" ? record.$metadata.httpStatusCode : void 0;
94
- return {
95
- name: value.name,
96
- message: redactString(value.message),
97
- code: typeof record.code === "string" ? record.code : void 0,
98
- status,
99
- requestId: requestIdOf(value),
100
- ...causeField(value, state, depth)
101
- };
102
- }
103
- /**
104
- * `cause` is non-enumerable when set through the Error constructor, so spreading an Error drops it -
105
- * and with undici the cause is the only place the real network reason (ECONNRESET, ENOTFOUND, ...)
106
- * lives. Walked like any nested value, so MAX_DEPTH and the circular guard bound a cause chain.
107
- */
108
- function causeField(value, state, depth) {
109
- const { cause } = value;
110
- return cause === void 0 ? {} : { cause: walk(cause, state, depth + 1) };
111
- }
112
- function isProviderError(value) {
113
- return "status" in value && typeof value.status === "number" || [
114
- "isAxiosError",
115
- "headers",
116
- "request_id",
117
- "requestID",
118
- "response",
119
- "config",
120
- "$metadata",
121
- "$response"
122
- ].some((field) => field in value);
123
- }
124
- /** Normalize the key once so `api_key`, `apiKey` and `api-key` all reach the same tests. */
125
- function isSensitiveKey(key) {
126
- const normalized = key.replace(/[-_]/g, "");
127
- return sensitiveField.test(normalized) || sensitiveSuffix.test(normalized);
128
- }
129
- function redactEntry(key, value, state, depth) {
130
- return isSensitiveKey(key) ? REDACTED : walk(value, state, depth + 1);
131
- }
132
- function walk(value, state, depth) {
133
- if (++state.nodes > MAX_NODES) return TRUNCATED;
134
- if (typeof value === "string") return redactString(value);
135
- if (typeof value !== "object" || value === null) return value;
136
- if (state.seen.has(value)) return "[Circular]";
137
- if (depth >= MAX_DEPTH) return TRUNCATED;
138
- state.seen.add(value);
139
- try {
140
- if (value instanceof Date) return value.toISOString();
141
- if (typeof Buffer !== "undefined" && value instanceof Buffer) return `<Buffer ${value.length} bytes>`;
142
- if (value instanceof Map) {
143
- const entries = {};
144
- for (const [key, entry] of value) entries[String(key)] = redactEntry(String(key), entry, state, depth);
145
- return entries;
146
- }
147
- if (value instanceof Set) return [...value].map((entry) => walk(entry, state, depth + 1));
148
- if (Array.isArray(value)) return value.map((entry) => walk(entry, state, depth + 1));
149
- if (value instanceof Error) {
150
- if (isProviderError(value)) return redactProviderError(value, state, depth);
151
- const own = { ...value };
152
- delete own.cause;
153
- return {
154
- ...walk(own, state, depth + 1),
155
- ...causeField(value, state, depth),
156
- name: value.name,
157
- message: redactString(value.message),
158
- stack: redactString(value.stack ?? "")
159
- };
160
- }
161
- const toJSON = value.toJSON;
162
- if (typeof toJSON === "function") {
163
- const json = toJSON.call(value);
164
- if (json !== value) return walk(json, state, depth + 1);
165
- }
166
- const sanitized = {};
167
- for (const [key, field] of Object.entries(value)) {
168
- if (typeof field === "function") continue;
169
- sanitized[key] = redactEntry(key, field, state, depth);
170
- }
171
- return sanitized;
172
- } catch {
173
- return "[Unserializable]";
174
- } finally {
175
- state.seen.delete(value);
176
- }
177
- }
178
- /** Sanitize before formatting so JSON, pretty and plain output share the same boundary. */
179
- function redactLogValue(value, seen = /* @__PURE__ */ new WeakSet()) {
180
- return walk(value, {
181
- seen,
182
- nodes: 0
183
- }, 0);
184
- }
185
- var Logger = class Logger {
186
- static _globalInstance;
187
- static contextProvider;
188
- static setContextProvider(provider) {
189
- Logger.contextProvider = provider;
190
- }
191
- static get globalInstance() {
192
- return Logger.contextProvider?.() ?? (Logger._globalInstance ??= new Logger());
193
- }
194
- metadata = {};
195
- logInJson;
196
- prettyPrint;
197
- minLevel;
198
- static LOG_LEVELS = {
199
- debug: 0,
200
- info: 1,
201
- warn: 2,
202
- error: 3
203
- };
204
- static MAX_CAUSE_DEPTH = 5;
205
- static COLORS = {
206
- debug: "\x1B[36m",
207
- info: "\x1B[32m",
208
- warn: "\x1B[33m",
209
- error: "\x1B[31m",
210
- reset: "\x1B[0m",
211
- dim: "\x1B[2m"
212
- };
213
- static LEVEL_LABELS = {
214
- debug: "DEBUG",
215
- info: " INFO",
216
- warn: " WARN",
217
- error: "ERROR"
218
- };
219
- static INDENT = " ";
220
- static NESTED_INDENT = " ";
221
- constructor(options = {}) {
222
- const isLocalDev = process.env.IS_LOCAL === "true" || process.env.NODE_ENV === "development" || process.env.SST_LIVE === "true";
223
- const { metadata = {}, logInJson = process.env.LOG_JSON === "true" || !isLocalDev, prettyPrint = isLocalDev && process.env.LOG_PRETTY !== "false", minLevel = process.env.LOG_LEVEL || "info" } = options;
224
- this.metadata = redactLogValue(metadata);
225
- this.logInJson = logInJson;
226
- this.prettyPrint = prettyPrint;
227
- this.minLevel = minLevel;
228
- }
229
- shouldLog(level) {
230
- return Logger.LOG_LEVELS[level] >= Logger.LOG_LEVELS[this.minLevel];
231
- }
232
- static errorReplacer(_key, value) {
233
- return value instanceof Error ? Logger.serializeError(value, 0, /* @__PURE__ */ new Set()) : value;
234
- }
235
- static serializeError(error, depth, seen) {
236
- seen.add(error);
237
- const serialized = {
238
- ...error,
239
- name: error.name,
240
- message: error.message,
241
- stack: error.stack
242
- };
243
- const { cause } = error;
244
- if (cause !== void 0) serialized.cause = cause instanceof Error ? depth + 1 >= Logger.MAX_CAUSE_DEPTH || seen.has(cause) ? "[Truncated]" : Logger.serializeError(cause, depth + 1, seen) : cause;
245
- return serialized;
246
- }
247
- /**
248
- * Safely stringify a value, handling circular references
249
- */
250
- safeStringify(value, indent) {
251
- try {
252
- return JSON.stringify(value, Logger.errorReplacer, indent);
253
- } catch {
254
- return "[Circular]";
255
- }
256
- }
257
- /**
258
- * An object carrying structured fields, as opposed to a message part
259
- * (Errors and arrays stay in the message so their shape survives).
260
- */
261
- isMetadataArg(value) {
262
- if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
263
- try {
264
- return !(value instanceof Error);
265
- } catch {
266
- return false;
267
- }
268
- }
269
- /**
270
- * Leading-position metadata is held to a stricter bar than trailing: a class
271
- * instance (Date, Map, ...) spreads to `{}` in output(), so lifting one out of
272
- * the message would erase it rather than structure it.
273
- */
274
- isPlainObject(value) {
275
- if (!this.isMetadataArg(value)) return false;
276
- try {
277
- const proto = Object.getPrototypeOf(value);
278
- return proto === Object.prototype || proto === null;
279
- } catch {
280
- return false;
281
- }
282
- }
283
- /**
284
- * Parse log arguments to extract message and optional metadata.
285
- * Metadata may be the last argument (`msg, meta`) or, pino-style, the first
286
- * (`meta, msg`); a trailing object wins when a call supplies both.
287
- */
288
- parseArgs(args, errorAware = false) {
289
- if (args.length === 0) return { message: "" };
290
- let metadata;
291
- let messageArgs = args;
292
- const lastArg = args[args.length - 1];
293
- const firstArg = args[0];
294
- if (args.length > 1 && this.isMetadataArg(lastArg)) {
295
- metadata = lastArg;
296
- messageArgs = args.slice(0, -1);
297
- } else if (args.length > 1 && this.isPlainObject(firstArg) && args.slice(1).every((a) => a === null || typeof a !== "object")) {
298
- metadata = firstArg;
299
- messageArgs = args.slice(1);
300
- }
301
- return {
302
- message: messageArgs.map((a) => {
303
- if (errorAware && a instanceof Error) return this.safeStringify(redactLogValue(a));
304
- return typeof a === "string" ? String(redactLogValue(a)) : this.safeStringify(redactLogValue(a));
305
- }).join(" "),
306
- metadata: metadata ? redactLogValue(metadata) : void 0
307
- };
308
- }
309
- /**
310
- * Output a log message using the appropriate format
311
- */
312
- output(level, consoleFn, message, metadata) {
313
- const allMetadata = {
314
- ...this.metadata,
315
- ...metadata
316
- };
317
- if (this.logInJson) consoleFn(this.safeStringify({
318
- ...allMetadata,
319
- severity: level,
320
- message
321
- }));
322
- else if (this.prettyPrint) consoleFn(this.formatPretty(level, message, metadata));
323
- else if (Object.keys(allMetadata).length > 0) consoleFn(message, allMetadata);
324
- else consoleFn(message);
325
- }
326
- /**
327
- * Format a log message with pino-pretty-like output for local development
328
- */
329
- formatPretty(level, message, metadata) {
330
- const { reset, dim } = Logger.COLORS;
331
- const color = Logger.COLORS[level];
332
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
333
- const parts = [];
334
- parts.push(`${dim}[${timestamp}]${reset} ${color}${Logger.LEVEL_LABELS[level]}${reset} ${message}`);
335
- const allMetadata = {
336
- ...this.metadata,
337
- ...metadata
338
- };
339
- const metadataKeys = Object.keys(allMetadata);
340
- if (metadataKeys.length > 0) for (const key of metadataKeys) {
341
- const value = allMetadata[key];
342
- if (typeof value === "object" && value !== null) {
343
- const indentedJson = this.safeStringify(value, 2).split("\n").map((line, idx) => idx === 0 ? line : Logger.NESTED_INDENT + line).join("\n");
344
- parts.push(`${Logger.INDENT}${dim}${key}:${reset} ${indentedJson}`);
345
- } else parts.push(`${Logger.INDENT}${dim}${key}:${reset} ${value}`);
346
- }
347
- return parts.join("\n");
348
- }
349
- resetMetadata() {
350
- this.metadata = {};
351
- return this;
352
- }
353
- withMetadata(metadata) {
354
- return new Logger({
355
- metadata: {
356
- ...this.metadata,
357
- ...metadata
358
- },
359
- logInJson: this.logInJson,
360
- prettyPrint: this.prettyPrint,
361
- minLevel: this.minLevel
362
- });
363
- }
364
- updateMetadata(metadata) {
365
- this.metadata = {
366
- ...this.metadata,
367
- ...redactLogValue(metadata)
368
- };
369
- return this;
370
- }
371
- log(...args) {
372
- return this.info(...args);
373
- }
374
- debug(...args) {
375
- if (!this.shouldLog("debug")) return;
376
- const { message, metadata } = this.parseArgs(args);
377
- this.output("debug", console.debug, message, metadata);
378
- }
379
- info(...args) {
380
- if (!this.shouldLog("info")) return;
381
- const { message, metadata } = this.parseArgs(args);
382
- this.output("info", console.info, message, metadata);
383
- }
384
- warn(...args) {
385
- if (!this.shouldLog("warn")) return;
386
- const { message, metadata } = this.parseArgs(args);
387
- this.output("warn", console.warn, message, metadata);
388
- }
389
- error(...args) {
390
- if (!this.shouldLog("error")) return;
391
- const { message, metadata } = this.parseArgs(args, true);
392
- this.output("error", console.error, message, metadata);
393
- }
394
- /** @deprecated: use Logger.log instance method instead */
395
- static log(...args) {
396
- return Logger.globalInstance.log(...args);
397
- }
398
- /** @deprecated: use Logger.debug instance method instead */
399
- static debug(...args) {
400
- return Logger.globalInstance.debug(...args);
401
- }
402
- /** @deprecated: use Logger.info instance method instead */
403
- static info(...args) {
404
- return Logger.globalInstance.info(...args);
405
- }
406
- /** @deprecated: use Logger.warn instance method instead */
407
- static warn(...args) {
408
- return Logger.globalInstance.warn(...args);
409
- }
410
- /** @deprecated: use Logger.error instance method instead */
411
- static error(...args) {
412
- return Logger.globalInstance.error(...args);
413
- }
414
- /**
415
- * Update tags for all log following log messages (until resetMetadata()):
416
- * @deprecated: Use Logger.withMetadata() instead
417
- */
418
- static updateMetadata(metadata) {
419
- return Logger.globalInstance.updateMetadata(metadata);
420
- }
421
- /**
422
- * Temporarily add tags for log messages descended from the returned handle:
423
- * @deprecated: Use Logger.withMetadata() instead
424
- */
425
- static withMetadata(metadata) {
426
- return Logger.globalInstance.withMetadata(metadata);
427
- }
428
- /**
429
- * Reset tags associated with the global logger instance:
430
- * @deprecated: Don't use the global logger instance; use Logger injected from caller instead
431
- */
432
- static resetMetadata() {
433
- return Logger.globalInstance.resetMetadata();
434
- }
435
- setLevel(level) {
436
- this.minLevel = level;
437
- return this;
438
- }
439
- static colorize = (...args) => ({
440
- black: `\x1b[30m${args.join(" ")}\x1b[0m`,
441
- red: `\x1b[31m${args.join(" ")}\x1b[0m`,
442
- green: `\x1b[32m${args.join(" ")}\x1b[0m`,
443
- yellow: `\x1b[33m${args.join(" ")}\x1b[0m`,
444
- blue: `\x1b[34m${args.join(" ")}\x1b[0m`
445
- });
446
- };
447
- promisify$1(dns.resolve4);
448
- promisify$1(dns.resolve6);
449
- /**
450
- * Check if an IPv4 address is in a private/internal range.
451
- */
452
- function isPrivateIPv4(ip) {
453
- const nonCanonical = ip.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
454
- if (nonCanonical && nonCanonical.slice(1).some((octet) => octet.length > 1 && octet.startsWith("0"))) return true;
455
- const ipv4Match = ip.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
456
- if (!ipv4Match) return false;
457
- const [, a, b, c] = ipv4Match.map(Number);
458
- if (a === 10) return true;
459
- if (a === 172 && b >= 16 && b <= 31) return true;
460
- if (a === 192 && b === 168) return true;
461
- if (a === 127) return true;
462
- if (a === 169 && b === 254) return true;
463
- if (a === 0) return true;
464
- if (a === 100 && b >= 64 && b <= 127) return true;
465
- if (a === 192 && b === 0 && c === 0) return true;
466
- if (a === 192 && b === 0 && c === 2 || a === 198 && b === 51 && c === 100 || a === 203 && b === 0 && c === 113) return true;
467
- if (a === 198 && (b === 18 || b === 19)) return true;
468
- if (a >= 224 && a <= 239) return true;
469
- if (a >= 240) return true;
470
- return false;
471
- }
472
- /**
473
- * Check if an IPv6 address is in a private/internal range.
474
- */
475
- /**
476
- * Strip the brackets WHATWG URL keeps on an IPv6 hostname: `new URL('http://[::1]/').hostname` is
477
- * `'[::1]'`, not `'::1'`. Every literal check below compares against unbracketed forms, so without
478
- * this a bracketed address matched nothing and fell through as safe.
479
- *
480
- * Same treatment as the sibling guards in this repo - `ssrfGuard.ts` and `external-image.ts` both
481
- * strip brackets before their literal checks.
482
- */
483
- function stripIpv6Brackets(hostname) {
484
- const h = hostname.toLowerCase();
485
- return h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h;
486
- }
487
- /**
488
- * Canonicalize an IPv6 literal to the RFC 5952 form - leading zeros dropped per hextet, longest run of
489
- * two or more zero hextets compressed to `::`. That is the shape both feeders already hand this module
490
- * (WHATWG `URL.hostname` at the `validateUrlForFetch` call site, and getaddrinfo answers via
491
- * `ssrfSafeLookup`), so it is the shape every prefix arm in `isPrivateIPv6` was written against.
492
- * Canonicalizing once here is what lets those arms cover a family instead of enumerating its legal
493
- * spellings: `0:0:0:0:0:ffff:127.0.0.1` arrives as `::ffff:127.0.0.1` instead of matching nothing.
494
- *
495
- * A dotted IPv4 tail is deliberately kept dotted, unlike WHATWG which hexifies it. The mapped branch
496
- * below decodes a dotted tail exactly through `isPrivateIPv4` and only blanket-refuses when the tail is
497
- * hex, so hexifying here would turn `::ffff:8.8.8.8` into an over-block.
498
- *
499
- * This cannot over-block: dropping leading zeros only shortens hextets below 0x1000, and every
500
- * globally routable address is inside 2000::/3 (first hextet 0x2000-0x3fff), which never carries one.
501
- * Input that does not parse as IPv6 is returned untouched, so it keeps whatever verdict it has today -
502
- * which is also why the redundant zero-padded arms further down (`2001:0db8:`, `2001:0000:`,
503
- * `0064:ff9b:`, `0100::`) are left in place rather than deleted.
504
- */
505
- function normalizeIpv6(ip) {
506
- const ported = ip.match(/^(\[[^\]]*\]):\d+$/);
507
- const bare = stripIpv6Brackets(ported ? ported[1] : ip).replace(/%.*$/, "");
508
- const halves = bare.split("::");
509
- if (halves.length > 2) return bare;
510
- if (halves.length === 2 && halves[0].includes(".")) return bare;
511
- const tokens = halves.flatMap((half) => half === "" ? [] : half.split(":"));
512
- const dotted = tokens.length > 0 && tokens[tokens.length - 1].includes(".") ? tokens.pop() : void 0;
513
- if (!tokens.every((token) => /^[0-9a-f]{1,4}$/.test(token))) return bare;
514
- const compressed = halves.length === 2;
515
- const width = tokens.length + (dotted ? 2 : 0);
516
- if (compressed ? width > 8 : width !== 8) return bare;
517
- const hextets = tokens.map((token) => token.replace(/^0+(?=.)/, ""));
518
- if (compressed) {
519
- const headWidth = halves[0] === "" ? 0 : halves[0].split(":").length;
520
- hextets.splice(headWidth, 0, ...new Array(8 - width).fill("0"));
521
- }
522
- const run = {
523
- start: -1,
524
- length: 0
525
- };
526
- for (let i = 0; i < hextets.length; i++) {
527
- if (hextets[i] !== "0") continue;
528
- let end = i;
529
- while (end < hextets.length && hextets[end] === "0") end++;
530
- if (end - i > run.length) {
531
- run.start = i;
532
- run.length = end - i;
533
- }
534
- i = end;
535
- }
536
- const body = run.length >= 2 ? `${hextets.slice(0, run.start).join(":")}::${hextets.slice(run.start + run.length).join(":")}` : hextets.join(":");
537
- if (dotted === void 0) return body;
538
- return body.endsWith(":") ? `${body}${dotted}` : `${body}:${dotted}`;
539
- }
540
- function isPrivateIPv6(ip) {
541
- const normalized = normalizeIpv6(ip);
542
- if (!normalized.includes(":")) return false;
543
- if (/[[\]]/.test(normalized)) return true;
544
- if (!/^[0-9a-f:.]+$/.test(normalized)) return false;
545
- if (normalized.includes(".") && !/^::(ffff:)?\d+\.\d+\.\d+\.\d+$/.test(normalized)) return true;
546
- if (normalized === "::1" || normalized === "0:0:0:0:0:0:0:1") return true;
547
- if (normalized === "::" || normalized === "0:0:0:0:0:0:0:0") return true;
548
- if (normalized.startsWith("fe")) return true;
549
- if (normalized.startsWith("fc") || normalized.startsWith("fd")) return true;
550
- if (normalized.startsWith("ff")) return true;
551
- if (normalized.startsWith("::ffff:")) {
552
- const tail = normalized.slice(7);
553
- return /^\d+\.\d+\.\d+\.\d+$/.test(tail) ? isPrivateIPv4(tail) : true;
554
- }
555
- if (normalized.startsWith("::")) {
556
- const tail = normalized.slice(2);
557
- return /^\d+\.\d+\.\d+\.\d+$/.test(tail) ? isPrivateIPv4(tail) : true;
558
- }
559
- if (normalized.startsWith("0:")) return true;
560
- if (normalized.startsWith("5f00:")) return true;
561
- if (normalized.startsWith("3fff:")) {
562
- const rest = normalized.slice(5);
563
- if ((rest.startsWith(":") ? 0 : parseInt(rest.split(":")[0], 16)) <= 4095) return true;
564
- }
565
- if (normalized.startsWith("2001:db8:") || normalized.startsWith("2001:0db8:")) return true;
566
- if (normalized.startsWith("2002:")) return true;
567
- if (normalized.startsWith("2001:0:") || normalized.startsWith("2001:0000:") || normalized.startsWith("2001::")) return true;
568
- if (normalized.startsWith("100::") || normalized.startsWith("0100::")) return true;
569
- if (normalized.startsWith("64:ff9b:") || normalized.startsWith("0064:ff9b:")) return true;
570
- return false;
571
- }
572
- /**
573
- * Strip what belongs to the interface or the transport rather than to the address: a zone index
574
- * (`fe80::1%eth0`) and, for an IPv4 literal, a trailing port (`8.8.8.8:443`).
575
- *
576
- * MUST be shared by every exported entry point. `isPrivateIP` and `isPrivateOrInternalHostname` each carry
577
- * their own family gate, and the comment on those gates says why they are kept identical: three gates
578
- * disagreeing about what counts as IPv4 is how the bracketed-IPv6 hole happened. Stripping in one of them
579
- * only reproduced exactly that - `8.8.8.8:443` came back public from one export and private from the other,
580
- * because the second missed its IPv4 branch and was then caught by the misplaced-quad arm.
581
- *
582
- * Only a DOTTED port is stripped. An unbracketed `ipv6:port` is genuinely ambiguous - a bare IPv6 address is
583
- * mostly colons - so it stays refused, and the bracketed spelling is what `normalizeIpv6` handles.
584
- */
585
- function stripZoneAndIpv4Port(host) {
586
- const head = host.split("%")[0];
587
- const zoneless = head.includes(":") || /^(\d+\.){3}\d+$/.test(head) ? head : host;
588
- return zoneless.match(/^((?:\d+\.){3}\d+):\d+$/)?.[1] ?? zoneless;
589
- }
590
- /**
591
- * Check if an IP address (IPv4 or IPv6) is in a private/internal range.
592
- */
593
- function isPrivateIP(ip) {
594
- const address = stripZoneAndIpv4Port(ip);
595
- if (/^(\d+\.){3}\d+$/.test(address)) return isPrivateIPv4(address);
596
- return isPrivateIPv6(address);
597
- }
598
- /** Marks a refusal that came from the connect-time hook, so callers can tell it from a DNS failure. */
599
- const SSRF_BLOCKED_CODE = "ERR_SSRF_BLOCKED_ADDRESS";
600
- /**
601
- * DNS lookup that re-validates at CONNECT time. THIS is the check that stops DNS rebinding.
602
- *
603
- * The pre-flight in `validateUrlForFetch` resolves the hostname and then hands the NAME to the HTTP
604
- * client, which resolves it a second time before opening the socket. Those are two different
605
- * resolutions, so an attacker who controls the authoritative server can answer the first with a
606
- * public address and the second with `169.254.169.254` - a textbook TOCTOU, and the reason the old
607
- * "this prevents DNS rebinding attacks" comment on that function was false.
608
- *
609
- * Installing this as the agent's `lookup` removes the gap rather than narrowing it: Node passes the
610
- * address this function returns straight to `net.connect`, so the IP that gets validated is by
611
- * construction the IP the socket dials. There is no third resolution in between for a rebind to win.
612
- *
613
- * Refuses if ANY resolved address is private, matching `validateUrlForFetch` - a dual-stack host must
614
- * not become reachable just because Node happened to prefer the healthy family this time.
615
- *
616
- * The two match in POLICY but deliberately differ in RESOLVER: `validateUrlForFetch` uses
617
- * `dns.resolve4`/`resolve6` (c-ares, straight to DNS) while this uses `dns.lookup` (getaddrinfo, which
618
- * also reads `/etc/hosts` and the OS cache). They can therefore legitimately disagree - an
619
- * `/etc/hosts` entry passes the pre-flight and is refused here. That is fail-closed and the right way
620
- * round, but it means "the URL validated and then the connection was blocked" is reachable in normal
621
- * operation and is NOT evidence that the pin is broken.
622
- */
623
- const ssrfSafeLookup = createSsrfSafeLookup();
624
- /**
625
- * Builds a connect-time lookup with the `ssrfSafeLookup` policy. `isAllowedPrivate` lets a caller admit
626
- * specific private addresses (the self-host CIDR opt-in in `pinnedFetch.ts`); every address it does not
627
- * admit is judged exactly as `ssrfSafeLookup` judges it.
628
- */
629
- function createSsrfSafeLookup(options = {}) {
630
- const { isAllowedPrivate } = options;
631
- return (hostname, lookupOptions, callback) => ssrfSafeLookupImpl(hostname, lookupOptions, callback, isAllowedPrivate);
632
- }
633
- function ssrfSafeLookupImpl(hostname, options, callback, isAllowedPrivate) {
634
- const resolveOptions = {
635
- ...options,
636
- all: true
637
- };
638
- dns.lookup(hostname, resolveOptions, (err, addresses) => {
639
- if (err) {
640
- callback(err, "", 0);
641
- return;
642
- }
643
- if (!addresses || addresses.length === 0) {
644
- const empty = /* @__PURE__ */ new Error(`No addresses resolved for hostname ${hostname}`);
645
- empty.code = "ENOTFOUND";
646
- callback(empty, "", 0);
647
- return;
648
- }
649
- const privateHit = addresses.find((entry) => isPrivateIP(entry.address) && !isAllowedPrivate?.(entry.address, entry.family));
650
- if (privateHit) {
651
- const blocked = /* @__PURE__ */ new Error(`Blocked connection to private IP address (${privateHit.address}) for hostname ${hostname}`);
652
- blocked.code = SSRF_BLOCKED_CODE;
653
- callback(blocked, "", 0);
654
- return;
655
- }
656
- if (options.all) {
657
- callback(null, addresses);
658
- return;
659
- }
660
- callback(null, addresses[0].address, addresses[0].family);
661
- });
662
- }
663
- new http.Agent({
664
- lookup: ssrfSafeLookup,
665
- keepAlive: false
666
- });
667
- new https.Agent({
668
- lookup: ssrfSafeLookup,
669
- keepAlive: false
670
- });
671
- SupportedFabFileMimeTypes.TXT_MARKDOWN, SupportedFabFileMimeTypes.TXT_MD_LEGACY, SupportedFabFileMimeTypes.TXT_PLAIN;
672
- z$1.object({
673
- text: z$1.string(),
674
- tokenCount: z$1.number()
675
- });
676
- const PROVIDER_LABEL = {
677
- openai: "OpenAI",
678
- voyage: "Voyage AI",
679
- bedrock: "Amazon Bedrock",
680
- ollama: "Ollama",
681
- gemini: "Gemini"
682
- };
683
- /** Per-provider model info, derived from EMBEDDING_MODEL_CATALOG so widths and input ceilings have one owner. */
684
- const embeddingModelInfoMap = (models) => Object.fromEntries(models.map((model) => {
685
- const capabilities = EMBEDDING_MODEL_CATALOG[model];
686
- return [model, {
687
- provider: PROVIDER_LABEL[capabilities.provider],
688
- model,
689
- contextWindow: capabilities.maxInputTokens,
690
- dimensions: servableEmbeddingDimensions(capabilities)
691
- }];
692
- }));
693
- embeddingModelInfoMap(Object.values(OpenAIEmbeddingModel));
694
- embeddingModelInfoMap(Object.values(VoyageAIEmbeddingModel));
695
- embeddingModelInfoMap(Object.values(BedrockEmbeddingModel));
696
- embeddingModelInfoMap(Object.values(OllamaEmbeddingModel));
697
- `${APP_NAME || "App"}`, WEBSITE_URL && `${WEBSITE_URL}`;
698
- `${"a, span, em, strong, b, i, u, code, kbd, samp, var, sub, sup, small, abbr, cite, q, time, mark, s, del, ins, bdi, bdo, wbr, ruby, rt, rp".split(", ").join("):not(")}`;
699
- [
700
- "[aria-hidden=\"true\"]",
701
- "[hidden]",
702
- "button",
703
- "input",
704
- "select",
705
- "textarea",
706
- "option",
707
- "optgroup",
708
- "datalist",
709
- "label",
710
- "dialog",
711
- "template",
712
- "svg",
713
- "[role=\"button\"]",
714
- "[role=\"search\"]",
715
- "[role=\"searchbox\"]",
716
- "[role=\"combobox\"]",
717
- "[role=\"listbox\"]",
718
- "[role=\"menu\"]",
719
- "[role=\"menubar\"]",
720
- "[role=\"tablist\"]",
721
- "[role=\"toolbar\"]",
722
- "[role=\"dialog\"]",
723
- "[role=\"alertdialog\"]",
724
- "[role=\"tooltip\"]",
725
- "[role=\"radiogroup\"]"
726
- ].join(", ");
727
- var BaseStorage = class {
728
- /**
729
- * Origin a browser fetches this storage's signed GET links from, or '' when signed links
730
- * are not usable by a browser here. Storages that cannot presign for browsers keep the
731
- * default.
732
- */
733
- async browserSigningOrigin() {
734
- return "";
735
- }
736
- };
737
- new Map(EMBEDDING_MODEL_IDS.filter(isSupportedEmbeddingModel).map((model) => [model, getEmbeddingModelCapabilities(model).dimensions.native]));
738
- ChatModels.KIMI_K3;
739
- ChatModels.KIMI_K2_7_CODE, ChatModels.KIMI_K2_7_CODE_HIGHSPEED, ChatModels.KIMI_K2_6, ChatModels.KIMI_K2_5;
740
- ChatModels.KIMI_K2_7_CODE, ChatModels.KIMI_K2_7_CODE_HIGHSPEED;
741
- ChatModels.KIMI_K2_7_CODE, ChatModels.KIMI_K2_7_CODE_HIGHSPEED, ChatModels.KIMI_K2_6;
742
- ChatModels.KIMI_K3, ChatModels.KIMI_K2_7_CODE, ChatModels.KIMI_K2_7_CODE_HIGHSPEED, ChatModels.KIMI_K2_6, ChatModels.KIMI_K2_5;
743
- ChatModels.KIMI_K2_THINKING_BEDROCK, ChatModels.KIMI_K2_5_BEDROCK, ChatModels.DEEPSEEK_R1_BEDROCK, ChatModels.DEEPSEEK_FLASH, ChatModels.DEEPSEEK_V4_PRO, ChatModels.KIMI_K3, ChatModels.KIMI_K2_7_CODE, ChatModels.KIMI_K2_7_CODE_HIGHSPEED, ChatModels.KIMI_K2_6, ChatModels.KIMI_K2_5;
744
- ChatModels.CLAUDE_4_7_OPUS, ChatModels.CLAUDE_4_7_OPUS_BEDROCK, ChatModels.CLAUDE_4_8_OPUS, ChatModels.CLAUDE_4_8_OPUS_BEDROCK, ChatModels.CLAUDE_5_SONNET, ChatModels.CLAUDE_5_SONNET_BEDROCK, ChatModels.CLAUDE_5_OPUS, ChatModels.CLAUDE_5_OPUS_BEDROCK, ChatModels.CLAUDE_5_5_HAIKU, ChatModels.CLAUDE_5_5_HAIKU_BEDROCK, ChatModels.CLAUDE_5_5_SONNET, ChatModels.CLAUDE_5_5_SONNET_BEDROCK;
745
- ChatModels.CLAUDE_5_SONNET, ChatModels.CLAUDE_5_SONNET_BEDROCK, ChatModels.CLAUDE_5_5_SONNET, ChatModels.CLAUDE_5_5_SONNET_BEDROCK, ChatModels.CLAUDE_FABLE_5, ChatModels.CLAUDE_FABLE_5_BEDROCK, ChatModels.CLAUDE_FABLE_5_1_BEDROCK, ChatModels.CLAUDE_5_OPUS, ChatModels.CLAUDE_5_OPUS_BEDROCK, ChatModels.CLAUDE_5_5_OPUS, ChatModels.CLAUDE_5_5_OPUS_BEDROCK, ChatModels.CLAUDE_5_5_HAIKU, ChatModels.CLAUDE_5_5_HAIKU_BEDROCK;
746
- ChatModels.DEEPSEEK_FLASH, ChatModels.DEEPSEEK_V4_PRO;
747
- ModelBackend.Anthropic, ModelBackend.Gemini, ModelBackend.XAI, ModelBackend.Ollama, ModelBackend.BFL, ModelBackend.LocalImage, ModelBackend.AWS;
748
- CompletionReasoningEffortSchema.options;
749
- //#endregion
750
- //#region ../../b4m-core/llm-adapters/dist/index.mjs
751
- /**
752
- * A tool failure that must end the turn rather than be fed back to the model as a
753
- * recoverable observation: a declined tool (PermissionDeniedError), an out-of-credits
754
- * error (tagged via `getQuestErrorCode`) or an account that lost AI access mid-turn
755
- * (AiAccessRefusedError), none of which any retry can satisfy.
756
- * Also exempts these from the services tool failure guard (toolFailureGuard.ts).
757
- */
758
- function isTerminalToolError(error) {
759
- return error instanceof PermissionDeniedError || error instanceof AiAccessRefusedError || getQuestErrorCode(error) !== void 0;
760
- }
761
- /**
762
- * Thrown by the services tool failure guard (toolFailureGuard.ts) in place of running a tool that
763
- * already failed repeatedly this turn. An expected refusal, not a new failure: the failures that
764
- * tripped it were logged when they happened.
765
- */
766
- var ToolBlockedError = class extends Error {
767
- constructor(message) {
768
- super(message);
769
- this.name = "ToolBlockedError";
770
- }
771
- };
772
- /**
773
- * Log level for a tool failure fed back to the model. Adapters that log a failed tool
774
- * (Bedrock, Anthropic, Gemini) pick the level through this.
775
- */
776
- function toolFailureLogLevel(error) {
777
- return error instanceof ToolBlockedError || isExpectedToolError(error) ? "warn" : "error";
778
- }
779
- /** Whether the named tool is flagged `endsTurnAfterText` in the offered tool list. */
780
- function isTurnEndingTool(name, tools) {
781
- return tools?.find((tool) => tool.toolSchema.name === name)?.endsTurnAfterText === true;
782
- }
783
- /**
784
- * Whether the tool loop should end the turn after this round's tool batch instead of making
785
- * the follow-up model call. True only when the round already streamed non-empty answer text
786
- * AND every tool it called is flagged `endsTurnAfterText`: the follow-up round would only
787
- * repeat the answer. A tool-only round still recurses so the model gets to answer.
788
- *
789
- * The single decision point for every adapter's tool loop - keep them from drifting.
790
- */
791
- function shouldEndTurnAfterTools(calledToolNames, tools, roundText) {
792
- const names = calledToolNames.filter((name) => Boolean(name));
793
- if (names.length === 0 || !visibleReplyText(roundText).trim()) return false;
794
- return names.every((name) => isTurnEndingTool(name, tools));
795
- }
796
- /**
797
- * Execute an array of async tasks either in parallel (with concurrency limiting)
798
- * or sequentially, returning outcomes in the original order.
799
- *
800
- * Terminal errors (see isTerminalToolError) are always re-thrown immediately: sequential
801
- * breaks the loop on the first one; parallel runs every task to completion (inherent to
802
- * Promise.allSettled) then pre-scans outcomes before returning - accepted because these
803
- * errors are rare in multi-tool batches.
804
- *
805
- * Fault isolation: uses Promise.allSettled so a single failure doesn't abort the batch.
806
- * Order preservation: results are indexed back to the original task array.
807
- */
808
- async function executeToolsBatch(tasks, options) {
809
- const { parallel, maxConcurrency = 8 } = options;
810
- if (parallel && tasks.length > 1) {
811
- const outcomes = (await runWithConcurrency(tasks, maxConcurrency)).map((s) => s.status === "fulfilled" ? {
812
- ok: true,
813
- result: s.value
814
- } : {
815
- ok: false,
816
- error: s.reason
817
- });
818
- for (const outcome of outcomes) if (!outcome.ok && isTerminalToolError(outcome.error)) throw outcome.error;
819
- return outcomes;
820
- }
821
- const outcomes = [];
822
- for (const task of tasks) try {
823
- const result = await task();
824
- outcomes.push({
825
- ok: true,
826
- result
827
- });
828
- } catch (error) {
829
- if (isTerminalToolError(error)) throw error;
830
- outcomes.push({
831
- ok: false,
832
- error
833
- });
834
- }
835
- return outcomes;
836
- }
837
- /**
838
- * Run tasks with bounded concurrency using a worker-pool pattern.
839
- * Spawns up to `limit` workers that pull from a shared task queue.
840
- * Results are stored by index to preserve original ordering.
841
- */
842
- async function runWithConcurrency(tasks, limit) {
843
- if (limit >= tasks.length) return Promise.allSettled(tasks.map((fn) => fn()));
844
- const results = new Array(tasks.length);
845
- let nextIndex = 0;
846
- async function worker() {
847
- while (nextIndex < tasks.length) {
848
- const index = nextIndex++;
849
- try {
850
- results[index] = {
851
- status: "fulfilled",
852
- value: await tasks[index]()
853
- };
854
- } catch (reason) {
855
- results[index] = {
856
- status: "rejected",
857
- reason
858
- };
859
- }
860
- }
861
- }
862
- const workerCount = Math.min(limit, tasks.length);
863
- await Promise.all(Array.from({ length: workerCount }, () => worker()));
864
- return results;
865
- }
866
- /**
867
- * Attaches a tool call's outcome onto its `toolsUsed` entry so it survives into
868
- * `promptMeta.functionCalls.returnValue`/`.success` (see ChatCompletionProcess.ts's mapper
869
- * and utils.ts's `replayableToolCalls`, which gates a whole replay path on at least one
870
- * recorded `returnValue`). Every backend pushes a `toolsUsed` entry before executing the
871
- * tool and only learns the real outcome a few lines later - this is the merge-back.
872
- */
873
- /**
874
- * Cap applied to a persisted `returnValue` before it reaches Mongo (chars, not bytes). Also the
875
- * cap on what a later turn replays back to the model for this call (utils.ts's Priority 2
876
- * reconstruction reads the same persisted, already-truncated value) - this is not a
877
- * persistence-only limit, it is what a continued conversation sees of an older tool result too.
878
- */
879
- const MAX_RECORDED_TOOL_RESULT_CHARS = 8e3;
880
- const TOOL_RESULT_TRUNCATION_NOTICE = "\n[tool result truncated]";
881
- /** Cap on the in-memory full result (chars). */
882
- const MAX_FULL_TOOL_RESULT_CHARS = 2e5;
883
- const FULL_TOOL_RESULT_KEY = "__b4mFullToolResult";
884
- function truncateToolResult(observation) {
885
- if (observation.length <= 8e3) return observation;
886
- return observation.slice(0, MAX_RECORDED_TOOL_RESULT_CHARS) + TOOL_RESULT_TRUNCATION_NOTICE;
887
- }
888
- /**
889
- * Keeps the untruncated result on the entry for the reply parser's echo check (see
890
- * buildToolEchoSources in services). It is non-enumerable so JSON.stringify and spreads skip it:
891
- * `toolsUsed` also leaves the process whole (Research Mode streams each callback's completionInfo
892
- * over the websocket, where API Gateway caps a post at 128 KB), and it must never be persisted.
893
- */
894
- function attachFullToolResult(entry, observation) {
895
- const text = String(observation);
896
- const value = {
897
- text: text.slice(0, MAX_FULL_TOOL_RESULT_CHARS),
898
- truncated: text.length > MAX_FULL_TOOL_RESULT_CHARS
899
- };
900
- Object.defineProperty(entry, FULL_TOOL_RESULT_KEY, {
901
- value,
902
- enumerable: false,
903
- configurable: true,
904
- writable: true
905
- });
906
- }
907
- /**
908
- * Finds the NOT-YET-STAMPED `toolsUsed` entry for this call (id-first, falling back to the
909
- * first unstamped entry with the same name when a provider omitted an id) and attaches the
910
- * truncated result. The "not yet stamped" filter (`success === undefined`) is what keeps this
911
- * safe across recursive tool-call turns: `toolsUsed` accumulates across rounds, so a later
912
- * turn's call to the same tool must not overwrite an earlier turn's already-recorded entry.
913
- * Never throws - a call with no matching entry (e.g. one filtered out before execution) is a
914
- * silent no-op, matching the tolerance the existing normalize-by-id sites already have.
915
- */
916
- function recordToolResult(toolsUsed, call, observation, success, executionTimeMs) {
917
- const wantId = call.id || void 0;
918
- const entry = toolsUsed.find((t) => t.success === void 0 && t.name === call.name && (wantId === void 0 || t.id === wantId));
919
- if (!entry) {
920
- Logger.globalInstance.debug(`[recordToolResult] no unstamped toolsUsed entry matched name=${call.name} id=${call.id ?? "(none)"} - result not recorded`);
921
- return;
922
- }
923
- entry.returnValue = truncateToolResult(String(observation));
924
- attachFullToolResult(entry, observation);
925
- entry.success = success;
926
- if (executionTimeMs !== void 0) entry.executionTime = executionTimeMs;
927
- }
928
- /** The `artifactType` the named tool declared at registration, for the helpers below. */
929
- function declaredArtifactType(tools, toolName) {
930
- return tools?.find((t) => t.toolSchema.name === toolName)?.artifactType;
931
- }
932
- /**
933
- * Helper function to handle tool result streaming for artifact-generating tools
934
- * This ensures tools like recharts that generate artifacts are streamed immediately
935
- * rather than waiting for recursive completion calls.
936
- *
937
- * Only the emitters in TOOL_ARTIFACT_EMITTERS (or a tool that declared `artifactType`, see
938
- * declaredArtifactType) stream, and only their pinned artifact type: streamed text is parsed
939
- * into reply artifacts, so any other tool's markup would render.
940
- *
941
- * What does stream is still a raw tool artifact rather than reply prose, so `streamCallback`
942
- * receives the channel tag and a public surface drops the text on that tag alone.
943
- */
944
- async function handleToolResultStreaming(toolName, toolResult, streamCallback, artifactType) {
945
- const filtered = filterToolArtifactMarkup(toolName, String(toolResult), artifactType);
946
- if (filtered !== null) await streamCallback([filtered], { channel: "tool-artifact" });
947
- }
948
- /**
949
- * Strips artifact markup from a tool result before it re-enters history, so the model cannot echo
950
- * it into a second card. Live-emitting backends pass `delivered` = whether their tool-artifact
951
- * emit fired. The `hasDeliverablePinnedArtifact` fallback is for the OpenAI Responses path, whose
952
- * artifact reaches the client through sharedToolBuilder extraction instead.
953
- *
954
- * The delivered/removed choice is made once per result and stamped on every block it contains.
955
- * That holds because each emitter emits one pinned block; a result mixing a foreign-type block
956
- * with a pinned one would label both DELIVERED.
957
- */
958
- function stripUnstreamedToolResult(toolName, result, delivered) {
959
- return stripToolArtifactMarkup(result, delivered ?? hasDeliverablePinnedArtifact(toolName, result) ? ARTIFACT_DELIVERED_PLACEHOLDER : ARTIFACT_REMOVED_PLACEHOLDER);
960
- }
961
- /**
962
- * Buffers a recursive completion's text instead of streaming it live, so an <artifact> tag the
963
- * model echoes back (after seeing its own tool result, even sanitized) can be stripped before the
964
- * client ever renders a second, empty card for it. Only removes blocks whose `identifier` matches
965
- * one already delivered this turn (stripDeliveredArtifactBlocks) - a stray "<artifact" the model's
966
- * prose merely mentions, or a genuinely NEW artifact the model composes with a different
967
- * identifier, must not cost the rest of a legitimate reply, unlike the tool-output-facing
968
- * stripToolArtifactMarkup.
969
- *
970
- * One instance is created lazily by whichever level first streams an artifact in a recursive
971
- * chain, and reused UNCHANGED by every deeper level (never recreated per level) - see each
972
- * backend's `_internal.artifactGuard`. A chained tool call's artifact goes through `emitArtifact`
973
- * on this same shared instance, which flushes any text already buffered ahead of it before
974
- * sending the artifact through - so ordering survives even when the chained call happens several
975
- * recursion levels below where the guard was created.
976
- */
977
- function createRecursiveArtifactGuard(cb) {
978
- let buffer = "";
979
- let deliveredMarkup = "";
980
- let meta = {};
981
- const callback = (async (text, info) => {
982
- for (const chunk of text) if (chunk != null) buffer += chunk;
983
- if (info?.inputTokens || info?.outputTokens) meta = { ...info };
984
- });
985
- const emitArtifact = async (results, info) => {
986
- if (buffer) {
987
- const pending = buffer;
988
- buffer = "";
989
- const stripped = stripDeliveredArtifactBlocks(pending, deliveredMarkup);
990
- if (stripped.trim()) await cb([stripped], {});
991
- }
992
- deliveredMarkup += results.join("");
993
- await cb(results, info);
994
- };
995
- const markDelivered = (markup) => {
996
- deliveredMarkup += markup;
997
- };
998
- let flushPromise = null;
999
- const flush = () => {
1000
- if (flushPromise) return flushPromise;
1001
- const cleaned = stripDeliveredArtifactBlocks(buffer, deliveredMarkup).trim();
1002
- let resolve;
1003
- let reject;
1004
- flushPromise = new Promise((res, rej) => {
1005
- resolve = res;
1006
- reject = rej;
1007
- });
1008
- (async () => cb(cleaned ? [cleaned] : [], meta))().then(() => resolve(), reject);
1009
- return flushPromise;
1010
- };
1011
- return {
1012
- callback,
1013
- emitArtifact,
1014
- markDelivered,
1015
- flush
1016
- };
1017
- }
1018
- /**
1019
- * Drops the messages whose instructions assume a tool is attached (see `IMessage.requiresTool`).
1020
- *
1021
- * Call this wherever a turn continues with tools removed. Re-sending "you MUST use the X tool" on a
1022
- * call that carries no tools leaves the model no valid move, and it answers by emitting the tool call
1023
- * as text in the reply - which is exactly what the callers that inject those prompts gate against
1024
- * when they decide whether to add them in the first place.
1025
- *
1026
- * Drops on the presence of the marker, not on which tool it names, because every call site today
1027
- * removes the whole tool set at once. A site that ever drops only SOME tools would need to compare
1028
- * `requiresTool` against the survivors instead.
1029
- */
1030
- const stripToolDependentMessages = (messages) => messages.filter((message) => !message.requiresTool);
1031
- /**
1032
- * Anthropic's hard ceiling on `cache_control` markers per request. Exceeding it fails the
1033
- * WHOLE request with `ValidationException: A maximum of 4 blocks with cache_control may be
1034
- * provided`, which is non-retryable - so an over-budget request loses the turn outright,
1035
- * after the user has already waited for it.
1036
- * See https://docs.claude.com/en/docs/build-with-claude/prompt-caching (tools, system and messages
1037
- * all count toward the same four).
1038
- */
1039
- const MAX_CACHE_CONTROL_BLOCKS = 4;
1040
- /**
1041
- * Does this block already carry a marker? Re-marking one costs no budget.
1042
- *
1043
- * Tests the VALUE, not just key presence: a block carrying an explicit
1044
- * `cache_control: undefined` is not a marker as far as the provider is concerned, and counting
1045
- * it would spend budget on nothing and drop a breakpoint we could have kept.
1046
- */
1047
- function hasMarker(block) {
1048
- return !!block && typeof block === "object" && !!block.cache_control;
1049
- }
1050
- /**
1051
- * Markers already on the request. Callers upstream attach their own before this runs -
1052
- * `bedrockBackend/anthropic.ts` marks each system block flagged `cache: true` (the mid-stack
1053
- * shareable-prefix breakpoint) - so this adapter's budget is whatever they left, not the full four.
1054
- */
1055
- function censusMarkers(params) {
1056
- const { tools, system, messages } = markerSites(params);
1057
- return {
1058
- tools: tools.length,
1059
- system: system.length,
1060
- messages: messages.length,
1061
- total: tools.length + system.length + messages.length
1062
- };
1063
- }
1064
- function markerSites(params) {
1065
- const sitesIn = (region, value) => Array.isArray(value) ? value.flatMap((block, index) => hasMarker(block) ? [{
1066
- region,
1067
- index
1068
- }] : []) : [];
1069
- const messages = [];
1070
- if (Array.isArray(params.messages)) params.messages.forEach((message, messageIndex) => {
1071
- const content = message?.content;
1072
- if (!Array.isArray(content)) return;
1073
- content.forEach((block, index) => {
1074
- const inner = block?.content;
1075
- if (Array.isArray(inner)) inner.forEach((innerBlock, nested) => {
1076
- if (hasMarker(innerBlock)) messages.push({
1077
- region: "messages",
1078
- index,
1079
- message: messageIndex,
1080
- nested
1081
- });
1082
- });
1083
- if (hasMarker(block)) messages.push({
1084
- region: "messages",
1085
- index,
1086
- message: messageIndex
1087
- });
1088
- });
1089
- });
1090
- return {
1091
- tools: sitesIn("tools", params.tools),
1092
- system: sitesIn("system", params.system),
1093
- messages
1094
- };
1095
- }
1096
- /**
1097
- * Anthropic-specific caching adapter
1098
- * Adds explicit cache_control markers to content blocks
1099
- */
1100
- var AnthropicCachingAdapter = class {
1101
- applyCaching(apiParams, strategy, logger) {
1102
- if (!strategy.enableCaching) return apiParams;
1103
- const ttl = strategy.cacheTTL ?? "5m";
1104
- const modifiedParams = { ...apiParams };
1105
- const cacheControl = {
1106
- type: "ephemeral",
1107
- ...ttl === "1h" ? { ttl } : {}
1108
- };
1109
- const inbound = censusMarkers(modifiedParams);
1110
- let budget = MAX_CACHE_CONTROL_BLOCKS - inbound.total;
1111
- const dropped = [];
1112
- /** Claim one marker slot, or record the miss. Re-marking a marked block is free. */
1113
- const claim = (name, alreadyMarked) => {
1114
- if (alreadyMarked) return true;
1115
- if (budget <= 0) {
1116
- dropped.push(name);
1117
- return false;
1118
- }
1119
- budget -= 1;
1120
- return true;
1121
- };
1122
- const systemParam = modifiedParams.system;
1123
- if (strategy.cacheSystemPrompt && systemParam) {
1124
- const systemArray = Array.isArray(systemParam) ? [...systemParam] : [{
1125
- type: "text",
1126
- text: systemParam
1127
- }];
1128
- if (systemArray.length > 0) {
1129
- const lastBlock = systemArray[systemArray.length - 1];
1130
- if (claim("system", hasMarker(lastBlock))) {
1131
- systemArray[systemArray.length - 1] = {
1132
- ...lastBlock,
1133
- cache_control: cacheControl
1134
- };
1135
- modifiedParams.system = systemArray;
1136
- }
1137
- }
1138
- }
1139
- const messagesParam = modifiedParams.messages;
1140
- if (strategy.cacheConversationHistory && Array.isArray(messagesParam) && messagesParam.length > 0) {
1141
- const messages = [...messagesParam];
1142
- let anchorIndex = messages.length - 1 - (strategy.historyCacheExcludeTrailingCount ?? 0);
1143
- while (anchorIndex >= 0 && messages[anchorIndex].role === "system") anchorIndex--;
1144
- if (anchorIndex >= 0) {
1145
- const anchorMsg = messages[anchorIndex];
1146
- const msgContent = anchorMsg.content;
1147
- let contentArray;
1148
- if (typeof msgContent === "string") contentArray = [{
1149
- type: "text",
1150
- text: msgContent
1151
- }];
1152
- else if (Array.isArray(msgContent)) contentArray = [...msgContent];
1153
- if (contentArray && contentArray.length > 0) {
1154
- const lastBlock = contentArray[contentArray.length - 1];
1155
- if (claim("history", hasMarker(lastBlock))) {
1156
- contentArray[contentArray.length - 1] = {
1157
- ...lastBlock,
1158
- cache_control: cacheControl
1159
- };
1160
- messages[anchorIndex] = {
1161
- ...anchorMsg,
1162
- content: contentArray
1163
- };
1164
- modifiedParams.messages = messages;
1165
- }
1166
- }
1167
- }
1168
- }
1169
- const tools = modifiedParams.tools;
1170
- const markIndex = Array.isArray(tools) ? tools.findLastIndex((t) => {
1171
- const tool = t;
1172
- const isServerTool = typeof tool.type === "string" && !("input_schema" in tool);
1173
- return tool.defer_loading !== true && !isServerTool;
1174
- }) : -1;
1175
- if (strategy.cacheTools && Array.isArray(tools) && markIndex >= 0) {
1176
- const toolsCopy = [...tools];
1177
- const markTool = toolsCopy[markIndex];
1178
- if (claim("tools", hasMarker(markTool))) {
1179
- toolsCopy[markIndex] = {
1180
- ...markTool,
1181
- cache_control: cacheControl
1182
- };
1183
- modifiedParams.tools = toolsCopy;
1184
- }
1185
- }
1186
- const outbound = censusMarkers(modifiedParams);
1187
- const census = {
1188
- inbound,
1189
- outbound,
1190
- limit: MAX_CACHE_CONTROL_BLOCKS
1191
- };
1192
- if (outbound.total >= MAX_CACHE_CONTROL_BLOCKS) {
1193
- const message = "[PromptCache] cache_control census at the ceiling";
1194
- if (logger) logger.info(message, census);
1195
- else console.info(message, JSON.stringify(census));
1196
- } else if (logger) logger.debug("[PromptCache] cache_control census", census);
1197
- if (outbound.total > MAX_CACHE_CONTROL_BLOCKS) {
1198
- const message = `[PromptCache] request exceeds the ${MAX_CACHE_CONTROL_BLOCKS}-block cache_control limit on arrival (${outbound.total}); capCacheControlMarkers will strip the excess before send`;
1199
- const detail = {
1200
- inbound,
1201
- outbound,
1202
- limit: MAX_CACHE_CONTROL_BLOCKS
1203
- };
1204
- if (logger) logger.warn(message, detail);
1205
- else console.warn(message, JSON.stringify(detail));
1206
- } else if (dropped.length > 0) {
1207
- const message = `[PromptCache] cache_control budget exhausted (limit ${MAX_CACHE_CONTROL_BLOCKS}); skipped breakpoints: ${dropped.join(", ")}`;
1208
- const detail = {
1209
- dropped,
1210
- inbound,
1211
- outbound,
1212
- limit: MAX_CACHE_CONTROL_BLOCKS
1213
- };
1214
- if (logger) logger.warn(message, detail);
1215
- else console.warn(message, JSON.stringify(detail));
1216
- }
1217
- return modifiedParams;
1218
- }
1219
- extractCacheStats(response, model) {
1220
- const usage = response.usage;
1221
- if (!usage) return void 0;
1222
- const cacheReadTokens = usage.cache_read_input_tokens || 0;
1223
- const cacheWriteTokens = usage.cache_creation_input_tokens || 0;
1224
- const uncachedTokens = usage.input_tokens || 0;
1225
- const totalInputTokens = cacheReadTokens + cacheWriteTokens + uncachedTokens;
1226
- const cacheHitRate = totalInputTokens > 0 ? cacheReadTokens / totalInputTokens * 100 : 0;
1227
- const costSavingsPercent = cacheHitRate * .9;
1228
- const estimatedLatencyReduction = cacheHitRate * .85;
1229
- return {
1230
- provider: ModelBackend.Anthropic,
1231
- model,
1232
- totalInputTokens,
1233
- cacheReadTokens,
1234
- cacheWriteTokens,
1235
- uncachedTokens,
1236
- cacheHitRate,
1237
- costSavingsPercent,
1238
- estimatedLatencyReduction,
1239
- providerMetadata: { hadCacheWrite: cacheWriteTokens > 0 }
1240
- };
1241
- }
1242
- };
1243
- /**
1244
- * OpenAI-specific caching adapter
1245
- * OpenAI caching is AUTOMATIC - no explicit markers needed
1246
- * Just ensure static content is at the beginning of prompts
1247
- */
1248
- var OpenAICachingAdapter = class {
1249
- applyCaching(apiParams, strategy) {
1250
- return apiParams;
1251
- }
1252
- extractCacheStats(response, model) {
1253
- const usage = response.usage;
1254
- if (!usage) return void 0;
1255
- const totalInputTokens = usage.prompt_tokens || 0;
1256
- const cachedTokens = usage.prompt_tokens_details?.cached_tokens || 0;
1257
- const cacheHitRate = totalInputTokens > 0 ? cachedTokens / totalInputTokens * 100 : 0;
1258
- const costSavingsPercent = cacheHitRate * .9;
1259
- const estimatedLatencyReduction = cacheHitRate * .8;
1260
- return {
1261
- provider: ModelBackend.OpenAI,
1262
- model,
1263
- totalInputTokens,
1264
- cacheReadTokens: cachedTokens,
1265
- cacheWriteTokens: 0,
1266
- uncachedTokens: totalInputTokens - cachedTokens,
1267
- cacheHitRate,
1268
- costSavingsPercent,
1269
- estimatedLatencyReduction,
1270
- providerMetadata: { automatic: true }
1271
- };
1272
- }
1273
- };
1274
- /**
1275
- * Gemini-specific caching adapter
1276
- * Gemini 2.5+ supports IMPLICIT (automatic) caching by default
1277
- * Explicit caching via Vertex AI API is optional (not implemented yet)
1278
- */
1279
- var GeminiCachingAdapter = class {
1280
- applyCaching(apiParams, strategy) {
1281
- return apiParams;
1282
- }
1283
- extractCacheStats(response, model) {
1284
- const usage = response.usageMetadata;
1285
- if (!usage) return void 0;
1286
- const totalInputTokens = usage.promptTokenCount || 0;
1287
- const cachedTokens = usage.cachedContentTokenCount || 0;
1288
- const cacheHitRate = totalInputTokens > 0 ? cachedTokens / totalInputTokens * 100 : 0;
1289
- const costSavingsPercent = cacheHitRate * (model.includes("2.5") ? .9 : .75);
1290
- const estimatedLatencyReduction = cacheHitRate * .75;
1291
- return {
1292
- provider: ModelBackend.Gemini,
1293
- model,
1294
- totalInputTokens,
1295
- cacheReadTokens: cachedTokens,
1296
- cacheWriteTokens: 0,
1297
- uncachedTokens: totalInputTokens - cachedTokens,
1298
- cacheHitRate,
1299
- costSavingsPercent,
1300
- estimatedLatencyReduction,
1301
- providerMetadata: { implicit: true }
1302
- };
1303
- }
1304
- };
1305
- /**
1306
- * Split a cache-INCLUSIVE prompt total into the disjoint pair CompletionInfo carries.
1307
- *
1308
- * Forwarding the cached count without subtracting double-bills it; forwarding nothing
1309
- * charges the full input rate on tokens the provider billed at a fraction of it.
1310
- * Subtracting is the only split that bills what the provider actually charged.
1311
- *
1312
- * Clamped at zero: if a feed ever reports more cached than prompt tokens, a negative
1313
- * input count would silently credit the user.
1314
- */
1315
- function splitCacheInclusiveInput(totalPromptTokens, cacheReadTokens) {
1316
- if (cacheReadTokens <= 0) return { inputTokens: totalPromptTokens };
1317
- const cached = Math.min(cacheReadTokens, totalPromptTokens);
1318
- return {
1319
- inputTokens: Math.max(0, totalPromptTokens - cached),
1320
- cacheReadInputTokens: cached
1321
- };
1322
- }
1323
- /**
1324
- * `prior` plus one provider request's usage, split like splitCacheInclusiveInput. Takes the
1325
- * request's OWN prompt/cached/output counts, never the running totals: each entry is priced on its
1326
- * own long-context tier (getTurnsCost), so an accumulated value here would re-tier the whole chain.
1327
- */
1328
- function appendCacheInclusiveTurn(prior, turnPromptTokens, turnCacheReadTokens, turnOutputTokens) {
1329
- return [...prior ?? [], {
1330
- ...splitCacheInclusiveInput(turnPromptTokens, turnCacheReadTokens),
1331
- outputTokens: turnOutputTokens
1332
- }];
1333
- }
1334
- /**
1335
- * Cached prompt tokens from a raw provider usage object, across every spelling in use:
1336
- * OpenAI Chat Completions nests them under `prompt_tokens_details`, the OpenAI
1337
- * Responses API under `input_tokens_details`, Moonshot publishes a flat
1338
- * `cached_tokens` alongside the OpenAI-shaped nesting, and DeepSeek its own flat
1339
- * `prompt_cache_hit_tokens`. Reading only one spelling silently bills every cache
1340
- * hit on the other transports at the full input rate.
1341
- *
1342
- * DeepSeek's own spelling leads, because it is the number its invoice is computed
1343
- * from; the OpenAI-shaped ones it also sends are the fallback for a proxy that
1344
- * forwards only those.
1345
- */
1346
- function cachedTokensFromUsage(usage) {
1347
- if (!usage) return 0;
1348
- const candidates = [
1349
- usage.prompt_cache_hit_tokens,
1350
- usage.cached_tokens,
1351
- usage.prompt_tokens_details?.cached_tokens,
1352
- usage.input_tokens_details?.cached_tokens
1353
- ];
1354
- for (const value of candidates) if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
1355
- return 0;
1356
- }
1357
- /**
1358
- * xAI Grok-specific caching adapter
1359
- * Caching is automatic with optional conversation ID for cache affinity
1360
- */
1361
- var XAICachingAdapter = class {
1362
- applyCaching(apiParams, strategy) {
1363
- return apiParams;
1364
- }
1365
- getHeaders(strategy) {
1366
- const headers = {};
1367
- if (strategy.conversationId) headers["x-grok-conv-id"] = strategy.conversationId;
1368
- return headers;
1369
- }
1370
- extractCacheStats(response, model) {
1371
- const usage = response.usage;
1372
- if (!usage) return void 0;
1373
- const totalInputTokens = usage.prompt_tokens || 0;
1374
- const cachedTokens = cachedTokensFromUsage(usage);
1375
- const cacheHitRate = totalInputTokens > 0 ? cachedTokens / totalInputTokens * 100 : 0;
1376
- const costSavingsPercent = cacheHitRate * .65;
1377
- const estimatedLatencyReduction = cacheHitRate * .7;
1378
- return {
1379
- provider: ModelBackend.XAI,
1380
- model,
1381
- totalInputTokens,
1382
- cacheReadTokens: cachedTokens,
1383
- cacheWriteTokens: 0,
1384
- uncachedTokens: totalInputTokens - cachedTokens,
1385
- cacheHitRate,
1386
- costSavingsPercent,
1387
- estimatedLatencyReduction,
1388
- providerMetadata: {
1389
- automatic: true,
1390
- conversationId: usage.x_grok_conv_id
1391
- }
1392
- };
1393
- }
1394
- };
1395
- /**
1396
- * Moonshot (Kimi) context caching. Automatic, like xAI's: there is no parameter,
1397
- * no header, and no explicit cache-creation call. A prompt only becomes cacheable
1398
- * once it exceeds 256 tokens, so short turns legitimately report a 0% hit rate.
1399
- * @see https://platform.kimi.ai/docs/guide/use-context-caching-feature-of-kimi-api
1400
- */
1401
- var KimiCachingAdapter = class {
1402
- applyCaching(apiParams, _strategy) {
1403
- return apiParams;
1404
- }
1405
- extractCacheStats(response, model) {
1406
- const usage = response.usage;
1407
- if (!usage) return void 0;
1408
- const totalInputTokens = usage.prompt_tokens || 0;
1409
- const details = usage.prompt_tokens_details;
1410
- const cachedTokens = usage.cached_tokens || details?.cached_tokens || 0;
1411
- const cacheHitRate = totalInputTokens > 0 ? cachedTokens / totalInputTokens * 100 : 0;
1412
- const costSavingsPercent = cacheHitRate * .9;
1413
- const estimatedLatencyReduction = cacheHitRate * .7;
1414
- return {
1415
- provider: ModelBackend.Kimi,
1416
- model,
1417
- totalInputTokens,
1418
- cacheReadTokens: cachedTokens,
1419
- cacheWriteTokens: 0,
1420
- uncachedTokens: Math.max(0, totalInputTokens - cachedTokens),
1421
- cacheHitRate,
1422
- costSavingsPercent,
1423
- estimatedLatencyReduction,
1424
- providerMetadata: {
1425
- automatic: true,
1426
- minimumCacheablePromptTokens: 256
1427
- }
1428
- };
1429
- }
1430
- };
1431
- /**
1432
- * DeepSeek context caching. Automatic, like Moonshot's and xAI's: no parameter,
1433
- * no header, no explicit cache-creation call. The adapter exists only to read
1434
- * the counters back out.
1435
- * @see https://api-docs.deepseek.com/guides/kv_cache
1436
- */
1437
- var DeepSeekCachingAdapter = class {
1438
- applyCaching(apiParams, _strategy) {
1439
- return apiParams;
1440
- }
1441
- extractCacheStats(response, model) {
1442
- const usage = response.usage;
1443
- if (!usage) return void 0;
1444
- const totalInputTokens = usage.prompt_tokens || 0;
1445
- const cachedTokens = cachedTokensFromUsage(usage);
1446
- const cacheHitRate = totalInputTokens > 0 ? cachedTokens / totalInputTokens * 100 : 0;
1447
- const costSavingsPercent = cacheHitRate * .98;
1448
- const estimatedLatencyReduction = cacheHitRate * .7;
1449
- return {
1450
- provider: ModelBackend.DeepSeek,
1451
- model,
1452
- totalInputTokens,
1453
- cacheReadTokens: cachedTokens,
1454
- cacheWriteTokens: 0,
1455
- uncachedTokens: Math.max(0, totalInputTokens - cachedTokens),
1456
- cacheHitRate,
1457
- costSavingsPercent,
1458
- estimatedLatencyReduction,
1459
- providerMetadata: { automatic: true }
1460
- };
1461
- }
1462
- };
1463
- /**
1464
- * No-op adapter for providers without caching support
1465
- */
1466
- var NoOpCachingAdapter = class {
1467
- applyCaching(apiParams) {
1468
- return apiParams;
1469
- }
1470
- extractCacheStats() {}
1471
- };
1472
- ModelBackend.Anthropic, new AnthropicCachingAdapter(), ModelBackend.OpenAI, new OpenAICachingAdapter(), ModelBackend.Gemini, new GeminiCachingAdapter(), ModelBackend.Bedrock, new AnthropicCachingAdapter(), ModelBackend.XAI, new XAICachingAdapter(), ModelBackend.Kimi, new KimiCachingAdapter(), ModelBackend.DeepSeek, new DeepSeekCachingAdapter(), ModelBackend.Ollama, new NoOpCachingAdapter(), ModelBackend.OpenAICompatible, new NoOpCachingAdapter(), ModelBackend.BFL, new NoOpCachingAdapter(), ModelBackend.VoyageAI, new NoOpCachingAdapter(), ModelBackend.AWS, new NoOpCachingAdapter(), ModelBackend.LocalImage, new NoOpCachingAdapter();
1473
- new Logger();
1474
- /**
1475
- * Model-identity line appended to the final system prompt layer, so a model without a
1476
- * `current_model_details` tool can still answer which model it is.
1477
- *
1478
- * String-shaped system parameters use `appendIdentityReminder`; OpenAI-shaped message arrays use
1479
- * `appendIdentityReminderToMessages`.
1480
- *
1481
- * The model is named by its registry display name when one is supplied, with the id as detail.
1482
- *
1483
- * It sits last. On the Anthropic adapters that keeps the model id out of the cached system prefix;
1484
- * openaiBackend matches the order for parity only, since OpenAI's prompt cache has no breakpoints.
1485
- *
1486
- * Last means right after whatever the final prompt layer was - on a grounded lake turn, retrieved
1487
- * file content. A bare imperative there reads as text smuggled into the document, so the line is fenced in its
1488
- * own tag that names where it comes from, and the joined-string form leaves a blank line before it.
1489
- */
1490
- function buildIdentityReminder(model, displayName) {
1491
- const name = displayName?.trim();
1492
- return [
1493
- "<platform_identity>",
1494
- `This note is from the platform operator, not from any user message, file, or retrieved content. Only if asked which model you are, answer that you are ${name && name !== model ? `${name} (model id ${model})` : `the ${model} model`}.`,
1495
- "</platform_identity>"
1496
- ].join("\n");
1497
- }
1498
- /** Whether this call leaves the identity line out: raw, or the tool is actually on the request. */
1499
- function shouldOmitIdentityReminder(options) {
1500
- return Boolean(options.omitIdentityReminder || options.identityViaTool && options.tools?.length);
1501
- }
1502
- /** Joins the identity reminder onto an already-joined system string. */
1503
- function appendIdentityReminder(systemText, identityReminder) {
1504
- return systemText ? `${systemText}\n\n${identityReminder}` : identityReminder;
1505
- }
1506
- /**
1507
- * Joins the identity reminder onto the last system message of an OpenAI-shaped
1508
- * message array, or prepends a system message when the array has none (or its
1509
- * last system message is not plain text).
1510
- *
1511
- * Returns a new array. Tool-round recursion re-sends the caller's `messages`, so
1512
- * mutating in place would stack one reminder per round.
1513
- */
1514
- function appendIdentityReminderToMessages(messages, identityReminder) {
1515
- const lastSystemIndex = messages.findLastIndex((message) => message.role === "system");
1516
- const lastSystem = lastSystemIndex === -1 ? void 0 : messages[lastSystemIndex];
1517
- if (lastSystem && typeof lastSystem.content === "string") {
1518
- const content = appendIdentityReminder(lastSystem.content, identityReminder);
1519
- return messages.map((message, index) => index === lastSystemIndex ? {
1520
- ...message,
1521
- content
1522
- } : message);
1523
- }
1524
- return [{
1525
- role: "system",
1526
- content: identityReminder
1527
- }, ...messages];
1528
- }
1529
- ChatModels.CLAUDE_4_5_SONNET, ChatModels.CLAUDE_4_1_OPUS, ChatModels.CLAUDE_4_5_HAIKU, ChatModels.CLAUDE_4_5_OPUS, ChatModels.CLAUDE_4_6_SONNET, ChatModels.CLAUDE_4_6_OPUS;
1530
- ChatModels.CLAUDE_4_5_SONNET_BEDROCK, ChatModels.CLAUDE_4_5_HAIKU_BEDROCK, ChatModels.CLAUDE_4_5_OPUS_BEDROCK, ChatModels.CLAUDE_4_6_SONNET_BEDROCK, ChatModels.CLAUDE_4_6_OPUS_BEDROCK;
1531
- /**
1532
- * Models served by ConverseBedrockBackend. Adding a Converse-compatible Bedrock model is a
1533
- * `ChatModels` entry plus a record here: routing (getLlmByModel's Bedrock branch), the
1534
- * Bedrock listing (UndifferentiatedBedrockBackend) and request shaping all read this table.
1535
- */
1536
- const CONVERSE_BEDROCK_MODELS = [{
1537
- id: ChatModels.NOVA_PRO_BEDROCK,
1538
- type: "text",
1539
- name: "Amazon Nova Pro",
1540
- backend: ModelBackend.Bedrock,
1541
- contextWindow: 3e5,
1542
- max_tokens: 1e4,
1543
- can_stream: true,
1544
- pricing: { 3e5: {
1545
- input: 8e-7,
1546
- output: 32e-7
1547
- } },
1548
- inlineReasoningTag: "thinking",
1549
- supportsVision: true,
1550
- supportsTools: true,
1551
- supportsImageVariation: false,
1552
- releaseDate: "2024-12-03",
1553
- rank: 5,
1554
- description: "Amazon's Nova Pro via AWS Bedrock - multimodal (text and images), tool use, and a 300K-token context window."
1555
- }];
1556
- new Set(CONVERSE_BEDROCK_MODELS.map((m) => String(m.id)));
1557
- ChatModels.DEEPSEEK_R1_BEDROCK, ModelBackend.Bedrock, ChatModels.DEEPSEEK_V3_1, ModelBackend.Bedrock;
1558
- /** OpenAI Chat Completions `finish_reason` (also covers xAI, which shares the same API shape). */
1559
- function normalizeOpenAIFinishReason(reason) {
1560
- if (!reason) return void 0;
1561
- switch (reason) {
1562
- case "length": return "max_tokens";
1563
- case "tool_calls":
1564
- case "function_call": return "tool_use";
1565
- default: return reason;
1566
- }
1567
- }
1568
- /** Ollama `done_reason` (chat/generate responses). */
1569
- function normalizeOllamaDoneReason(reason) {
1570
- if (!reason) return void 0;
1571
- switch (reason) {
1572
- case "length": return "max_tokens";
1573
- default: return reason;
1574
- }
1575
- }
1576
- /**
1577
- * A reasoning model spent its whole output budget thinking and produced no answer
1578
- * (finish_reason: length). The same budget fails the same way, so callers must not retry it.
1579
- * The message keeps the "output budget was exhausted" phrase that log searches and tests match.
1580
- */
1581
- var OutputBudgetExhaustedError = class extends Error {
1582
- provider;
1583
- model;
1584
- constructor(provider, model) {
1585
- super(`${provider} returned no content for ${model}: the output budget was exhausted before any answer was produced (finish_reason: length). Raise maxTokens or lower the reasoning effort.`);
1586
- this.provider = provider;
1587
- this.model = model;
1588
- this.name = "OutputBudgetExhaustedError";
1589
- }
1590
- };
1591
- /**
1592
- * The stream closed with no finish reason and nothing usable. Transient, so worth one retry.
1593
- * The message must not say "aborted", "overloaded" or "timeout": the fallback predicates match those.
1594
- */
1595
- var StreamEndedWithoutFinishError = class extends Error {
1596
- provider;
1597
- model;
1598
- constructor(provider, model) {
1599
- super(`${provider} returned no content for ${model} (finish_reason: unknown).`);
1600
- this.provider = provider;
1601
- this.model = model;
1602
- this.name = "StreamEndedWithoutFinishError";
1603
- }
1604
- };
1605
- /** Type guard: does this message already carry OpenAI-style `tool_calls`? */
1606
- function hasToolCalls(msg) {
1607
- return msg.role === "assistant" && "tool_calls" in msg;
1608
- }
1609
- function isToolUseBlock(block) {
1610
- return block.type === "tool_use";
1611
- }
1612
- function isToolResultBlock(block) {
1613
- return block.type === "tool_result";
1614
- }
1615
- function isTextBlock(block) {
1616
- return block.type === "text";
1617
- }
1618
- /**
1619
- * Convert a single IMessage from B4M standard format to OpenAI-compatible format.
1620
- * Returns an array because a single user message with multiple tool_result blocks
1621
- * expands into multiple OpenAI 'tool' role messages.
1622
- *
1623
- * Messages already in OpenAI format (with `tool_calls` property) pass through unchanged.
1624
- * Messages without tool_use/tool_result content blocks pass through unchanged.
1625
- */
1626
- function convertMessageToOpenAIFormat(msg, options = {}) {
1627
- if (hasToolCalls(msg)) {
1628
- const reasoningContent = msg.reasoning_content;
1629
- return [{
1630
- role: "assistant",
1631
- content: null,
1632
- tool_calls: msg.tool_calls,
1633
- ...options.preserveReasoningContent && typeof reasoningContent === "string" ? { reasoning_content: reasoningContent } : {}
1634
- }];
1635
- }
1636
- if (msg.role === "assistant" && Array.isArray(msg.content)) {
1637
- const contentBlocks = msg.content;
1638
- const toolUseBlocks = contentBlocks.filter(isToolUseBlock);
1639
- if (toolUseBlocks.length > 0) {
1640
- const textParts = contentBlocks.filter(isTextBlock).map((block) => block.text).filter(Boolean);
1641
- return [{
1642
- role: "assistant",
1643
- content: textParts.length > 0 ? textParts.join("\n") : null,
1644
- tool_calls: toolUseBlocks.map((block) => ({
1645
- id: block.id,
1646
- type: "function",
1647
- function: {
1648
- name: block.name,
1649
- arguments: JSON.stringify(block.input)
1650
- }
1651
- }))
1652
- }];
1653
- }
1654
- }
1655
- if (msg.role === "user" && Array.isArray(msg.content)) {
1656
- const toolResultBlocks = msg.content.filter(isToolResultBlock);
1657
- if (toolResultBlocks.length > 0) return toolResultBlocks.map((block) => ({
1658
- role: "tool",
1659
- content: block.content,
1660
- tool_call_id: block.tool_use_id
1661
- }));
1662
- }
1663
- if (msg.requiresTool !== void 0 || msg.cache !== void 0 || msg.perTurn !== void 0) {
1664
- const { requiresTool: _requiresTool, cache: _cache, perTurn: _perTurn, ...providerSafe } = msg;
1665
- return [providerSafe];
1666
- }
1667
- return [msg];
1668
- }
1669
- /**
1670
- * Convert an array of IMessages from B4M standard format to OpenAI-compatible format.
1671
- * Returns OpenAIFormattedMessage[] - callers targeting OpenAI SDK types should cast at the boundary.
1672
- */
1673
- function convertMessagesToOpenAIFormat(messages, options = {}) {
1674
- return messages.flatMap((msg) => convertMessageToOpenAIFormat(msg, options));
1675
- }
1676
- /**
1677
- * Ollama's native /api/chat requires tool-call arguments as an object and rejects a JSON string
1678
- * with a 400. Unparseable or non-object input is kept under `_raw` rather than dropped.
1679
- */
1680
- function toOllamaToolArguments(args) {
1681
- if (args !== null && typeof args === "object" && !Array.isArray(args)) return args;
1682
- if (typeof args !== "string" || args.trim() === "") return {};
1683
- try {
1684
- const parsed = JSON.parse(args);
1685
- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1686
- } catch {}
1687
- return { _raw: args };
1688
- }
1689
- var OllamaBackend = class OllamaBackend {
1690
- _host;
1691
- _api;
1692
- _logger;
1693
- _clientHost;
1694
- _clientHeaders;
1695
- _agent;
1696
- _fetch;
1697
- _requestSettings;
1698
- _settingsWarning;
1699
- currentModel = "";
1700
- /**
1701
- * `options.fetch` replaces the default transport, for servers that need credentials the host URL cannot carry.
1702
- * `options.requestSettings` supplies per-model fields, such as the CLI's reading of Desktop's model settings.
1703
- * `options.settingsWarning` takes a mid-turn warning about those settings in place of `logger.warn`.
1704
- */
1705
- constructor(host, logger, options = {}) {
1706
- this._fetch = options.fetch;
1707
- this._requestSettings = options.requestSettings;
1708
- this._logger = logger ?? new Logger();
1709
- this._settingsWarning = options.settingsWarning ?? ((message) => this._logger.warn(message));
1710
- this._host = host ?? "http://localhost:11434";
1711
- const url = new URL(this._host);
1712
- const headers = {};
1713
- if (url.username && url.password) {
1714
- headers.Authorization = `Basic ${Buffer.from(`${url.username}:${url.password}`).toString("base64")}`;
1715
- url.username = "";
1716
- url.password = "";
1717
- }
1718
- this._agent = new Agent({
1719
- headersTimeout: 18e5,
1720
- bodyTimeout: 36e5
1721
- });
1722
- this._clientHost = url.toString();
1723
- this._clientHeaders = headers;
1724
- this._api = this.createClient();
1725
- }
1726
- /**
1727
- * Build an Ollama client. The `ollama` package takes no per-request
1728
- * AbortSignal (it only attaches an internal controller to streaming requests
1729
- * and exposes a client-wide abort()), so cancellation has to be bound into
1730
- * the fetch of a client made for that one request - hence the optional
1731
- * `signal`. The undici Agent is shared across clients so connection pooling
1732
- * and the raised timeouts survive.
1733
- */
1734
- createClient(signal) {
1735
- const custom = this._fetch;
1736
- const fetchWithTimeout = (input, init) => (custom ?? globalThis.fetch)(input, {
1737
- ...init,
1738
- ...!custom && { dispatcher: this._agent },
1739
- ...signal && { signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal }
1740
- });
1741
- return new Ollama({
1742
- host: this._clientHost,
1743
- headers: this._clientHeaders,
1744
- fetch: fetchWithTimeout
1745
- });
1746
- }
1747
- /** Rejects when Ollama is unreachable; getAvailableModels needs a down host to differ from an empty one. */
1748
- async getModelInfo() {
1749
- const models = await this._api.list();
1750
- this._listedNumCtx.clear();
1751
- this._numCtxChangeWarned.clear();
1752
- const isSelfHost = process.env.B4M_SELF_HOST === "true";
1753
- return await Promise.all(models.models.map(async (model) => {
1754
- const details = await this.getModelDetailsCached(model.name);
1755
- const { capabilities } = details;
1756
- const contextWindow = await this.listedNumCtx(model.name, details);
1757
- return {
1758
- id: model.name,
1759
- type: "text",
1760
- name: model.name,
1761
- backend: ModelBackend.Ollama,
1762
- contextWindow,
1763
- max_tokens: OllamaBackend.advertisedOutputCap(contextWindow),
1764
- supportsImageVariation: false,
1765
- pricing: { [contextWindow]: {
1766
- input: 0,
1767
- output: 0
1768
- } },
1769
- freeToRun: true,
1770
- supportsVision: capabilities.includes("vision"),
1771
- supportsTools: capabilities.includes("tools"),
1772
- can_think: capabilities.includes("thinking"),
1773
- can_stream: true,
1774
- logoFile: "Ollama_Logo.svg",
1775
- rank: 1,
1776
- description: isSelfHost ? "Runs locally on your own hardware via Ollama. No API key required, and nothing leaves your machine. Performance and capabilities vary by model." : `This model is served from ${process.env.APP_NAME ? `${process.env.APP_NAME}'s` : "the platform"} Ollama servers using publicly available open-source models. Performance and capabilities vary by model.`
1777
- };
1778
- }));
1779
- }
1780
- /** Ollama's default when a model doesn't report a context length. */
1781
- static DEFAULT_CONTEXT_WINDOW = 8192;
1782
- /**
1783
- * Output ceiling we advertise for a local model. Half of what we allocate, because advertising
1784
- * the whole window made the server's context - output - buffer negative and emptied the prompt.
1785
- *
1786
- * Halving alone is not enough at the bottom of the range: OLLAMA_MAX_NUM_CTX accepts any positive
1787
- * value, so an operator setting 2000 would leave exactly zero input budget for every local model
1788
- * at once. The second bound keeps input room for any window ABOVE the safety buffer.
1789
- *
1790
- * At or below the buffer nothing here can: a 500-token window yields a cap of 1 and still leaves
1791
- * 500 - 1 - 1000 negative. Clamping the window up to hide that would advertise more context than
1792
- * the model has, which is the misreporting this whole change removes, so the honest answer is
1793
- * that such a model cannot serve a chat prompt at all.
1794
- */
1795
- static advertisedOutputCap(contextWindow) {
1796
- const halved = Math.floor(contextWindow / 2);
1797
- return Math.max(1, Math.min(halved, contextWindow - CONTEXT_WINDOW_SAFETY_BUFFER_TOKENS - 1));
1798
- }
1799
- /** Per-model /api/show results, so the tool-call recursion shows once, not per round. */
1800
- _modelDetails = /* @__PURE__ */ new Map();
1801
- getModelDetailsCached(model) {
1802
- let details = this._modelDetails.get(model);
1803
- if (!details) {
1804
- details = this.getModelDetails(model);
1805
- this._modelDetails.set(model, details);
1806
- }
1807
- return details;
1808
- }
1809
- /**
1810
- * Fetch a model's capabilities and context window from Ollama (/api/show).
1811
- * capabilities is e.g. ['completion', 'tools', 'vision']; the context length
1812
- * lives in model_info under "<architecture>.context_length" (e.g.
1813
- * "qwen2.context_length"). Returns safe defaults on any error so a transient
1814
- * show() failure degrades gracefully instead of dropping the whole list.
1815
- */
1816
- async getModelDetails(model) {
1817
- try {
1818
- const info = await this._api.show({ model });
1819
- const capabilities = info.capabilities ?? [];
1820
- const raw = info.model_info;
1821
- const entries = raw instanceof Map ? Array.from(raw.entries()) : Object.entries(raw ?? {});
1822
- const ctx = entries.find(([k]) => k.endsWith(".context_length"))?.[1];
1823
- const trainedContext = typeof ctx === "number" && Number.isSafeInteger(ctx) && ctx > 0 ? ctx : void 0;
1824
- const contextWindow = trainedContext ?? OllamaBackend.DEFAULT_CONTEXT_WINDOW;
1825
- const thinking = info.thinking;
1826
- return {
1827
- capabilities,
1828
- contextWindow,
1829
- facts: {
1830
- capabilities,
1831
- modelInfo: Object.fromEntries(entries),
1832
- ...typeof info.parameters === "string" && { parameters: info.parameters },
1833
- ...typeof info.modelfile === "string" && { modelfile: info.modelfile },
1834
- ...Array.isArray(thinking?.values) && { thinkingValues: thinking.values },
1835
- ...trainedContext !== void 0 && { trainedContext }
1836
- }
1837
- };
1838
- } catch (error) {
1839
- this._logger.debug(`[OllamaBackend] Could not fetch details for ${model}:`, error);
1840
- this._detailsFailed.add(model);
1841
- return {
1842
- capabilities: [],
1843
- contextWindow: OllamaBackend.DEFAULT_CONTEXT_WINDOW,
1844
- facts: {
1845
- capabilities: [],
1846
- modelInfo: {}
1847
- }
1848
- };
1849
- }
1850
- }
1851
- requestSettings(model, details) {
1852
- if (!this._requestSettings) return Promise.resolve({});
1853
- return this._requestSettings(model, {
1854
- ...details.facts,
1855
- defaultNumCtx: ollamaNumCtx(details.contextWindow)
1856
- });
1857
- }
1858
- _listedNumCtx = /* @__PURE__ */ new Map();
1859
- _numCtxChangeWarned = /* @__PURE__ */ new Set();
1860
- /** The num_ctx a listing advertises: the model's own setting, or the default when it has none or it cannot be read. */
1861
- async listedNumCtx(model, details) {
1862
- const numCtx = (await this.requestSettings(model, details).catch((error) => {
1863
- this._logger.debug(`[OllamaBackend] Settings for ${model} not read while listing:`, error);
1864
- }))?.numCtx ?? ollamaNumCtx(details.contextWindow);
1865
- this._listedNumCtx.set(model, numCtx);
1866
- return numCtx;
1867
- }
1868
- sentNumCtx(model, wanted) {
1869
- const listed = this._listedNumCtx.get(model);
1870
- if (listed === void 0) return wanted;
1871
- if (wanted !== listed && !this._numCtxChangeWarned.has(model)) {
1872
- this._numCtxChangeWarned.add(model);
1873
- this._settingsWarning(`[OllamaBackend] ${model}: context size changed from ${listed} to ${wanted}; the context change applies after the model list is refreshed or the CLI restarts.`);
1874
- }
1875
- return listed;
1876
- }
1877
- _detailsFailed = /* @__PURE__ */ new Set();
1878
- /** True when /api/show failed for `model`, so its `supportsTools: false` is a fallback, not what Ollama said. */
1879
- toolSupportUnchecked(model) {
1880
- return this._detailsFailed.has(model);
1881
- }
1882
- /**
1883
- * Ollama model parameters for a request. Everything here is silently dropped
1884
- * if the `options` object is omitted, which is why num_ctx matters most:
1885
- * without it the server falls back to its own 4096 default and truncates the
1886
- * prompt from the front, taking the tool block with it - so a large turn
1887
- * makes a tool-capable model answer that it has no tools. Sizing from the
1888
- * model's own reported window keeps that consistent with the context length
1889
- * the picker advertises.
1890
- */
1891
- async buildRequestFields(model, options) {
1892
- const details = await this.getModelDetailsCached(model);
1893
- const settings = await this.requestSettings(model, details);
1894
- const numCtx = this.sentNumCtx(model, settings.numCtx ?? ollamaNumCtx(details.contextWindow));
1895
- const maxTokens = options.maxTokens ?? settings.maxOutputTokens;
1896
- const think = typeof options.thinking?.enabled === "boolean" ? options.thinking.enabled : settings.think;
1897
- return {
1898
- options: {
1899
- num_ctx: numCtx,
1900
- ...typeof options.temperature === "number" && { temperature: options.temperature },
1901
- ...settings.options,
1902
- ...typeof maxTokens === "number" && { num_predict: Math.min(maxTokens, numCtx) }
1903
- },
1904
- ...settings.keepAlive !== void 0 && { keep_alive: settings.keepAlive },
1905
- ...think !== void 0 && { think }
1906
- };
1907
- }
1908
- async complete(model, messages, options, callback) {
1909
- this.currentModel = model;
1910
- const toolCallCount = options._internal?.toolCallCount ?? 0;
1911
- const maxToolCalls = options._internal?.maxToolCalls ?? 10;
1912
- const priorToolsUsed = options._internal?.accumToolsUsed ?? [];
1913
- const priorInputTokens = options._internal?.accumInputTokens ?? 0;
1914
- const priorOutputTokens = options._internal?.accumOutputTokens ?? 0;
1915
- const toolsAvailable = (options.tools?.length ?? 0) > 0;
1916
- const offerTools = toolsAvailable && toolCallCount < maxToolCalls;
1917
- if (toolsAvailable && !offerTools) this._logger.warn(`[OllamaBackend] Max tool calls (${maxToolCalls}) reached; answering without tools.`);
1918
- const formattedTools = offerTools ? this.formatTools(options.tools ?? []) : [];
1919
- const conversationMessages = offerTools ? messages : stripToolDependentMessages(messages);
1920
- const requestMessages = shouldOmitIdentityReminder({
1921
- ...options,
1922
- tools: offerTools ? options.tools : void 0
1923
- }) ? conversationMessages : appendIdentityReminderToMessages(conversationMessages, buildIdentityReminder(options.modelIdentityId ?? model, options.modelDisplayName));
1924
- const baseRequest = {
1925
- model,
1926
- messages: this.buildMessages(requestMessages),
1927
- ...await this.buildRequestFields(model, options),
1928
- ...formattedTools.length > 0 && { tools: formattedTools }
1929
- };
1930
- try {
1931
- const round = await this.runChatRound(baseRequest, options, callback, { buffer: offerTools });
1932
- const inputTokens = priorInputTokens + (round.completionInfo.inputTokens ?? 0);
1933
- const outputTokens = priorOutputTokens + (round.completionInfo.outputTokens ?? 0);
1934
- let toolCalls = this.normalizeToolCalls(round.toolCalls);
1935
- if (toolCalls.length === 0 && offerTools) toolCalls = this.parseContentToolCall(round.content, options.tools ?? []);
1936
- const toolsUsed = [...priorToolsUsed, ...toolCalls.map((tc) => ({
1937
- name: tc.name,
1938
- arguments: tc.arguments,
1939
- id: tc.id
1940
- }))];
1941
- if (toolCalls.length === 0) {
1942
- await callback([offerTools ? round.content : ""], {
1943
- inputTokens,
1944
- outputTokens,
1945
- ...toolsUsed.length > 0 && { toolsUsed },
1946
- ...round.completionInfo.stopReason ? { stopReason: round.completionInfo.stopReason } : {}
1947
- });
1948
- return;
1949
- }
1950
- if (options.executeTools === false) {
1951
- await callback([""], {
1952
- inputTokens,
1953
- outputTokens,
1954
- toolsUsed
1955
- });
1956
- return;
1957
- }
1958
- const resolved = toolCalls.map((tc) => ({
1959
- tc,
1960
- toolFn: options.tools?.find((t) => t.toolSchema.name === tc.name)?.toolFn
1961
- })).filter((r) => !!r.toolFn);
1962
- const unknownCalls = toolCalls.filter((tc) => !options.tools?.some((t) => t.toolSchema.name === tc.name));
1963
- for (const tc of unknownCalls) this.pushToolMessages(messages, {
1964
- id: tc.id,
1965
- name: tc.name,
1966
- parameters: tc.arguments || "{}"
1967
- }, `Error: tool "${tc.name}" is not available. Do not call it again; answer directly or use a listed tool.`);
1968
- const outcomes = await executeToolsBatch(resolved.map(({ tc, toolFn }) => async () => {
1969
- let params = {};
1970
- try {
1971
- params = JSON.parse(tc.arguments || "{}");
1972
- } catch {}
1973
- this._logger.debug(`[OllamaBackend] Executing tool ${tc.name}`);
1974
- return String(await toolFn(params));
1975
- }), {
1976
- parallel: options.parallelToolExecution !== false,
1977
- maxConcurrency: options.maxParallelTools
1978
- });
1979
- const inheritedArtifactGuard = options._internal?.artifactGuard;
1980
- let artifactGuard = inheritedArtifactGuard;
1981
- const observations = [];
1982
- for (let i = 0; i < outcomes.length; i++) {
1983
- const outcome = outcomes[i];
1984
- const { tc } = resolved[i];
1985
- const params = tc.arguments || "{}";
1986
- if (outcome.ok) {
1987
- let emitted = false;
1988
- await handleToolResultStreaming(tc.name, outcome.result, async (results, artifactInfo) => {
1989
- emitted = true;
1990
- if (!artifactGuard) artifactGuard = createRecursiveArtifactGuard(callback);
1991
- await artifactGuard.emitArtifact(results, {
1992
- toolsUsed,
1993
- ...artifactInfo
1994
- });
1995
- }, declaredArtifactType(options.tools, tc.name));
1996
- observations[i] = stripUnstreamedToolResult(tc.name, outcome.result, emitted);
1997
- this.pushToolMessages(messages, {
1998
- id: tc.id,
1999
- name: tc.name,
2000
- parameters: params
2001
- }, observations[i]);
2002
- } else {
2003
- if (outcome.error instanceof PermissionDeniedError) throw outcome.error;
2004
- const errorMessage = outcome.error instanceof Error ? outcome.error.message : "Unknown error";
2005
- this._logger[toolFailureLogLevel(outcome.error)]("[Tool Execution] Tool failed", {
2006
- toolName: tc.name,
2007
- error: errorMessage
2008
- });
2009
- const errorMsg = stripToolArtifactMarkup(`Error running ${tc.name}: ${errorMessage}`, ARTIFACT_REMOVED_PLACEHOLDER);
2010
- observations[i] = errorMsg;
2011
- this.pushToolMessages(messages, {
2012
- id: tc.id,
2013
- name: tc.name,
2014
- parameters: params
2015
- }, errorMsg);
2016
- }
2017
- }
2018
- const executedToolsUsed = [...priorToolsUsed, ...resolved.map(({ tc }, i) => {
2019
- const entry = {
2020
- name: tc.name,
2021
- arguments: tc.arguments,
2022
- id: tc.id,
2023
- returnValue: truncateToolResult(String(observations[i])),
2024
- success: outcomes[i].ok
2025
- };
2026
- attachFullToolResult(entry, observations[i]);
2027
- return entry;
2028
- })];
2029
- if (options.abortSignal?.aborted) {
2030
- await (artifactGuard?.callback ?? callback)([""], {
2031
- inputTokens,
2032
- outputTokens,
2033
- toolsUsed: executedToolsUsed
2034
- });
2035
- if (!inheritedArtifactGuard && artifactGuard) await artifactGuard.flush();
2036
- return;
2037
- }
2038
- if (round.toolCalls.length > 0 && shouldEndTurnAfterTools(toolCalls.map((tc) => tc.name), options.tools, round.content)) {
2039
- this._logger.info("[Tool Execution] Ending turn: answer already produced, only end-of-turn tools ran", {
2040
- model,
2041
- toolsExecuted: toolCalls.map((tc) => tc.name)
2042
- });
2043
- await (artifactGuard?.callback ?? callback)([round.content], {
2044
- inputTokens,
2045
- outputTokens,
2046
- toolsUsed: executedToolsUsed,
2047
- stopReason: "tool_use"
2048
- });
2049
- if (!inheritedArtifactGuard && artifactGuard) await artifactGuard.flush();
2050
- return;
2051
- }
2052
- await this.complete(model, messages, {
2053
- ...options,
2054
- _internal: {
2055
- ...options._internal,
2056
- toolCallCount: toolCallCount + 1,
2057
- accumToolsUsed: executedToolsUsed,
2058
- accumInputTokens: inputTokens,
2059
- accumOutputTokens: outputTokens,
2060
- artifactGuard
2061
- }
2062
- }, artifactGuard?.callback ?? callback);
2063
- if (!inheritedArtifactGuard && artifactGuard) await artifactGuard.flush();
2064
- } catch (error) {
2065
- if (error instanceof Error && isUserInitiatedAbort(error, options.abortSignal)) this._logger.debug("[OllamaBackend] Ollama request cancelled by the caller");
2066
- else this._logger.error("[OllamaBackend] Error during Ollama API call:", error);
2067
- throw error;
2068
- }
2069
- }
2070
- /**
2071
- * Run a single Ollama chat turn. Streams text chunks to `callback` unless
2072
- * `buffer` is set (used for tool-eligible rounds, where the content is
2073
- * withheld until we know whether it is a tool call or the final answer).
2074
- * Returns the full text, any native tool calls, and token usage.
2075
- */
2076
- async runChatRound(baseRequest, options, callback, { buffer }) {
2077
- const toolCalls = [];
2078
- let content = "";
2079
- let inputTokens = 0;
2080
- let outputTokens = 0;
2081
- let doneReason;
2082
- const api = options.abortSignal ? this.createClient(options.abortSignal) : this._api;
2083
- if (options.stream) {
2084
- const response = await api.chat({
2085
- ...baseRequest,
2086
- stream: true
2087
- });
2088
- let startedThinking = false;
2089
- let stoppedThinking = false;
2090
- let thinkingFieldOpen = false;
2091
- const thinkEscaper = createThinkMarkerEscaper();
2092
- for await (const chunk of response) {
2093
- if (chunk.message.tool_calls?.length) toolCalls.push(...chunk.message.tool_calls);
2094
- let piece = "";
2095
- const thinkPiece = chunk.message.thinking || "";
2096
- if (thinkPiece) {
2097
- if (!thinkingFieldOpen) {
2098
- piece += "<think>";
2099
- thinkingFieldOpen = true;
2100
- }
2101
- piece += thinkEscaper.push(thinkPiece);
2102
- }
2103
- const contentPiece = chunk.message.content || "";
2104
- if (contentPiece) {
2105
- if (thinkingFieldOpen) {
2106
- piece += thinkEscaper.flush();
2107
- piece += "</think>";
2108
- thinkingFieldOpen = false;
2109
- }
2110
- startedThinking = startedThinking || contentPiece.includes("<think>");
2111
- stoppedThinking = stoppedThinking || contentPiece.includes("</think>");
2112
- piece += contentPiece;
2113
- }
2114
- if (chunk.done && (thinkingFieldOpen || startedThinking && !stoppedThinking)) {
2115
- if (thinkingFieldOpen) piece += thinkEscaper.flush();
2116
- piece = `${piece}</think>`;
2117
- thinkingFieldOpen = false;
2118
- }
2119
- content += piece;
2120
- inputTokens = Math.max(inputTokens, chunk.prompt_eval_count || 0);
2121
- outputTokens += chunk.eval_count || 0;
2122
- if (chunk.done_reason) doneReason = chunk.done_reason;
2123
- if (!buffer && piece) await callback([piece], {
2124
- inputTokens,
2125
- outputTokens
2126
- });
2127
- }
2128
- } else {
2129
- const response = await api.chat({
2130
- ...baseRequest,
2131
- stream: false
2132
- });
2133
- if (response.message.tool_calls?.length) toolCalls.push(...response.message.tool_calls);
2134
- const think = response.message.thinking || "";
2135
- content = (think ? `<think>${escapeThinkMarkers(think)}</think>` : "") + (response.message.content || "");
2136
- inputTokens = response.prompt_eval_count || 0;
2137
- outputTokens = response.eval_count || 0;
2138
- doneReason = response.done_reason;
2139
- if (!buffer) await callback([content], {
2140
- inputTokens,
2141
- outputTokens
2142
- });
2143
- }
2144
- const stopReason = normalizeOllamaDoneReason(doneReason);
2145
- return {
2146
- content,
2147
- toolCalls,
2148
- completionInfo: {
2149
- inputTokens,
2150
- outputTokens,
2151
- ...stopReason ? { stopReason } : {}
2152
- }
2153
- };
2154
- }
2155
- /**
2156
- * Normalize Ollama's native tool_calls into the shared NormalizedToolCall shape.
2157
- *
2158
- * Ids are real uuids, not a position-derived string. A prior version keyed ids off
2159
- * `accumulated-count + round-local-index`, but the accumulated count is measured AFTER
2160
- * hallucinated calls are filtered out while the round-local index is assigned BEFORE that
2161
- * filter runs, so the two can drift and mint the same id for two different real calls across
2162
- * rounds - replayableToolCalls dedupes by id and silently drops the later one. A uuid makes
2163
- * the whole collision class unrepresentable, matching how the other backends already mint ids.
2164
- */
2165
- normalizeToolCalls(toolCalls) {
2166
- return toolCalls.map((tc) => ({
2167
- name: tc.function.name,
2168
- arguments: JSON.stringify(tc.function.arguments ?? {}),
2169
- id: `ollama-tool-${v4()}`
2170
- }));
2171
- }
2172
- /**
2173
- * Some smaller models emit tool calls as plain message content instead of
2174
- * using the native tool_calls field: a bare {"name":...,"arguments":{...}},
2175
- * the same wrapped in a ```json fence, or several such objects run together
2176
- * ({...} {...}). Recover every such object that names an available tool; if
2177
- * none match, the content is a normal answer.
2178
- *
2179
- * Guards against false positives: reasoning traces (<think>...</think>) are
2180
- * stripped first. The search source is a leading bare object (only when the
2181
- * reply STARTS with one) plus every fenced body - so a call wrapped in a fence
2182
- * after preamble prose is recovered, a bare call is not lost just because the
2183
- * reply also contains an unrelated fence, and JSON merely quoted mid-prose
2184
- * ("the math_evaluate tool takes {...}") is ignored. The seen-set dedupes any
2185
- * overlap between the two sources.
2186
- *
2187
- * Because any fenced block is a search source, a fenced EXAMPLE of a real
2188
- * (authorized) tool is also recovered and executed. This stays bounded to
2189
- * authorized tools (tryParseToolCallJson requires a name present in `tools`),
2190
- * so there is no privilege escalation - only a wider trigger surface.
2191
- */
2192
- parseContentToolCall(content, tools) {
2193
- const withoutThink = content.replace(/<think>[\s\S]*?<\/think>/gi, "").trim();
2194
- const fenced = this.extractFencedBlocks(withoutThink);
2195
- const source = [withoutThink.startsWith("{") ? withoutThink : "", ...fenced].join("\n");
2196
- if (!source.trim()) return [];
2197
- const calls = [];
2198
- const seen = /* @__PURE__ */ new Set();
2199
- for (const candidate of this.extractJsonObjects(source)) {
2200
- const call = this.tryParseToolCallJson(candidate, tools);
2201
- if (!call) continue;
2202
- const key = `${call.name}:${call.arguments}`;
2203
- if (seen.has(key)) continue;
2204
- seen.add(key);
2205
- calls.push({
2206
- ...call,
2207
- id: `ollama-content-tool-${v4()}`
2208
- });
2209
- }
2210
- return calls;
2211
- }
2212
- /**
2213
- * Return the body of every ```-fenced block, so a tool call the model wrapped
2214
- * in a fence after preamble prose can be isolated from the surrounding text.
2215
- */
2216
- extractFencedBlocks(content) {
2217
- const blocks = [];
2218
- const fenceRegex = /```[^\n]*\n?([\s\S]*?)```/g;
2219
- let match;
2220
- while ((match = fenceRegex.exec(content)) !== null) blocks.push(match[1]);
2221
- return blocks;
2222
- }
2223
- /**
2224
- * Extract every balanced top-level {...} substring from arbitrary text. String
2225
- * contents are respected so braces inside JSON strings don't throw off nesting,
2226
- * and code fences / prose around the objects are ignored. Handles multiple
2227
- * objects run together, which is how some models emit parallel tool calls.
2228
- */
2229
- extractJsonObjects(content) {
2230
- const objects = [];
2231
- let depth = 0;
2232
- let start = -1;
2233
- let inString = false;
2234
- let escaped = false;
2235
- for (let i = 0; i < content.length; i++) {
2236
- const ch = content[i];
2237
- if (inString) {
2238
- if (escaped) escaped = false;
2239
- else if (ch === "\\") escaped = true;
2240
- else if (ch === "\"") inString = false;
2241
- continue;
2242
- }
2243
- if (ch === "\"") inString = true;
2244
- else if (ch === "{") {
2245
- if (depth === 0) start = i;
2246
- depth++;
2247
- } else if (ch === "}" && depth > 0) {
2248
- depth--;
2249
- if (depth === 0 && start !== -1) {
2250
- objects.push(content.slice(start, i + 1));
2251
- start = -1;
2252
- }
2253
- }
2254
- }
2255
- return objects;
2256
- }
2257
- /**
2258
- * Parse one candidate string as a tool call naming a known tool. Models
2259
- * improvise the shape, so accept the common ones:
2260
- * {"name":"t","arguments":{...}} (Ollama/most)
2261
- * {"function":"t","arguments":{...}} (function-as-name)
2262
- * {"function":{"name":"t","arguments":{}}} (OpenAI-style nested)
2263
- * plus "parameters"/"args" aliases for the arguments.
2264
- */
2265
- tryParseToolCallJson(text, tools) {
2266
- const trimmed = text.trim();
2267
- if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return null;
2268
- let parsed;
2269
- try {
2270
- parsed = JSON.parse(trimmed);
2271
- } catch {
2272
- return null;
2273
- }
2274
- if (!parsed || typeof parsed !== "object") return null;
2275
- const obj = parsed;
2276
- let name;
2277
- let args;
2278
- const fn = obj.function;
2279
- if (fn && typeof fn === "object") {
2280
- name = fn.name;
2281
- args = fn.arguments;
2282
- } else name = obj.name ?? obj.function ?? obj.tool ?? obj.tool_name;
2283
- if (args === void 0) args = obj.arguments ?? obj.parameters ?? obj.args ?? {};
2284
- if (typeof name !== "string" || !tools.some((t) => t.toolSchema.name === name)) return null;
2285
- return {
2286
- name,
2287
- arguments: typeof args === "string" ? args : JSON.stringify(args ?? {})
2288
- };
2289
- }
2290
- pushToolMessages(messages, tool, result, _thinkingBlocks) {
2291
- messages.push({
2292
- content: "",
2293
- role: "assistant",
2294
- tool_calls: [{ function: {
2295
- name: tool.name,
2296
- arguments: toOllamaToolArguments(tool.parameters)
2297
- } }]
2298
- });
2299
- messages.push({
2300
- role: "tool",
2301
- tool_name: tool.name,
2302
- content: result
2303
- });
2304
- }
2305
- /**
2306
- * Convert ICompletionOptionTools into Ollama's Tool schema format.
2307
- */
2308
- formatTools(tools) {
2309
- return tools.map((tool) => ({
2310
- type: "function",
2311
- function: {
2312
- ...tool.toolSchema,
2313
- parameters: {
2314
- ...tool.toolSchema.parameters,
2315
- required: tool.toolSchema.parameters.required ?? []
2316
- }
2317
- }
2318
- }));
2319
- }
2320
- /**
2321
- * Map IMessage[] to Ollama's Message[], preserving tool_calls for multi-turn
2322
- * tool conversations (added by pushToolMessages).
2323
- * First converts B4M standard format (tool_use/tool_result) to OpenAI-compatible
2324
- * format since Ollama uses the same tool_calls/role:tool convention.
2325
- */
2326
- buildMessages(messages) {
2327
- return convertMessagesToOpenAIFormat(messages).map((msg) => {
2328
- const raw = msg;
2329
- const mapped = {
2330
- role: msg.role,
2331
- content: ""
2332
- };
2333
- if (Array.isArray(msg.content)) {
2334
- const texts = [];
2335
- const images = [];
2336
- for (const block of msg.content) if (block.type === "text" && typeof block.text === "string") texts.push(block.text);
2337
- else if (block.type === "image") {
2338
- if (block.source.type === "base64") images.push(block.source.data);
2339
- else this._logger.debug("[OllamaBackend] Dropping non-base64 image block; Ollama requires inline base64.");
2340
- } else if (block.type === "image_url") {
2341
- const dataUrl = block.image_url.url.match(/^data:[^,]*;base64,(.+)$/s);
2342
- if (dataUrl) images.push(dataUrl[1]);
2343
- else this._logger.debug("[OllamaBackend] Dropping non-data image_url; Ollama requires inline base64.");
2344
- }
2345
- mapped.content = texts.join("\n");
2346
- if (images.length > 0) mapped.images = images;
2347
- } else mapped.content = msg.content != null ? String(msg.content) : "";
2348
- if (Array.isArray(raw.tool_calls)) mapped.tool_calls = raw.tool_calls.map((call) => ({
2349
- ...call,
2350
- function: {
2351
- ...call.function,
2352
- arguments: toOllamaToolArguments(call.function?.arguments)
2353
- }
2354
- }));
2355
- if (typeof raw.tool_name === "string") mapped.tool_name = raw.tool_name;
2356
- return mapped;
2357
- });
2358
- }
2359
- async listModels() {
2360
- try {
2361
- this._logger.debug("[OllamaBackend] Listing models from Ollama");
2362
- const response = await this._api.list();
2363
- this._logger.debug("[OllamaBackend] Models listed from Ollama:", response.models);
2364
- return response.models;
2365
- } catch (error) {
2366
- this._logger.error("[OllamaBackend] Error listing models from Ollama:", error);
2367
- if (error.message?.includes("ECONNREFUSED") || error.message?.includes("Failed to fetch")) throw new Error(`Could not connect to Ollama. Please make sure it is running at ${this._host}`);
2368
- throw error;
2369
- }
2370
- }
2371
- };
2372
- ChatModels.O1_PREVIEW, ChatModels.O1_MINI, ChatModels.O1, ChatModels.O3_MINI, ChatModels.O3, ChatModels.O4_MINI;
2373
- ChatModels.GPT5, ChatModels.GPT5_2025_08_07, ChatModels.GPT5_MINI, ChatModels.GPT5_NANO, ChatModels.GPT5_CHAT_LATEST;
2374
- ChatModels.GPT5_1, ChatModels.GPT5_1_CHAT_LATEST;
2375
- ChatModels.GPT5_2, ChatModels.GPT5_2_CHAT_LATEST;
2376
- ChatModels.GPT5_4, ChatModels.GPT5_4_MINI, ChatModels.GPT5_4_MINI_2026_03_17, ChatModels.GPT5_4_NANO;
2377
- ChatModels.GPT5_5;
2378
- ChatModels.GPT5_6_SOL, ChatModels.GPT5_6_LUNA, ChatModels.GPT5_6_TERRA;
2379
- ModelBackend.Bedrock, ModelBackend.AWS, ModelBackend.OpenAI, ModelBackend.Anthropic, ModelBackend.Gemini, ModelBackend.Ollama, ModelBackend.OpenAICompatible, ModelBackend.BFL, ModelBackend.XAI, ModelBackend.Kimi, ModelBackend.DeepSeek, ModelBackend.LocalImage, ModelBackend.VoyageAI;
2380
- Object.values(ModelBackend);
2381
- Object.entries(MODEL_INFO_FIELD_GROUP_OF);
2382
- var LocalRuntimeError = class extends Error {
2383
- runtimeId;
2384
- constructor(message, runtimeId, options) {
2385
- super(message, options);
2386
- this.runtimeId = runtimeId;
2387
- this.name = "LocalRuntimeError";
2388
- }
2389
- };
2390
- var RuntimeUnsupportedError = class extends LocalRuntimeError {
2391
- operation;
2392
- constructor(runtimeId, operation) {
2393
- super(`${runtimeId} does not support ${operation}`, runtimeId);
2394
- this.operation = operation;
2395
- this.name = "RuntimeUnsupportedError";
2396
- }
2397
- };
2398
- var RuntimeHttpError = class extends LocalRuntimeError {
2399
- status;
2400
- detail;
2401
- constructor(message, runtimeId, status, detail = null) {
2402
- super(message, runtimeId);
2403
- this.status = status;
2404
- this.detail = detail;
2405
- this.name = "RuntimeHttpError";
2406
- }
2407
- };
2408
- /** No HTTP answer: refused, reset, unresolvable host, or timed out. The underlying error is `cause`. */
2409
- var RuntimeConnectionError = class extends LocalRuntimeError {
2410
- constructor(message, runtimeId, options) {
2411
- super(message, runtimeId, options);
2412
- this.name = "RuntimeConnectionError";
2413
- }
2414
- };
2415
- /** The runtime answered, but not in the shape its API documents. */
2416
- var RuntimeProtocolError = class extends LocalRuntimeError {
2417
- constructor(message, runtimeId, options) {
2418
- super(message, runtimeId, options);
2419
- this.name = "RuntimeProtocolError";
2420
- }
2421
- };
2422
- /** A pull whose stream stayed open but sent nothing for `idleTimeoutMs`, as when the network drops quietly. */
2423
- var PullIdleTimeoutError = class extends LocalRuntimeError {
2424
- ref;
2425
- idleTimeoutMs;
2426
- constructor(runtimeId, ref, idleTimeoutMs) {
2427
- super(`${runtimeId} sent nothing for ${idleTimeoutMs}ms while pulling ${ref}`, runtimeId);
2428
- this.ref = ref;
2429
- this.idleTimeoutMs = idleTimeoutMs;
2430
- this.name = "PullIdleTimeoutError";
2431
- }
2432
- };
2433
- var ModelNotFoundError = class extends LocalRuntimeError {
2434
- model;
2435
- constructor(runtimeId, model, options) {
2436
- super(`${runtimeId} has no model named ${model}`, runtimeId, options);
2437
- this.model = model;
2438
- this.name = "ModelNotFoundError";
2439
- }
2440
- };
2441
- const errorBodySchema = z$1.union([z$1.object({ error: z$1.union([z$1.string(), z$1.object({ message: z$1.string() }).transform((error) => error.message)]) }).transform((body) => body.error), z$1.object({ detail: z$1.string() }).transform((body) => body.detail)]);
2442
- /**
2443
- * Accepts `host:port`, `http://host:port` or an OpenAI-style base ending in `/v1`; null when unusable or when
2444
- * it embeds `user:pass@` credentials.
2445
- * `localhost` becomes `127.0.0.1` so both spellings dedupe to one runtime.
2446
- */
2447
- function parseBaseUrl(hostOrUrl) {
2448
- const url = toUrl(hostOrUrl);
2449
- if (!url || url.username || url.password) return null;
2450
- if (url.hostname === "localhost") url.hostname = "127.0.0.1";
2451
- const path = url.pathname.replace(/\/+$/, "").replace(/\/v1$/, "");
2452
- return `${url.origin}${path}`;
2453
- }
2454
- function toUrl(hostOrUrl) {
2455
- const trimmed = hostOrUrl.trim();
2456
- const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `http://${trimmed}`;
2457
- if (!URL.canParse(withScheme)) return null;
2458
- const url = new URL(withScheme);
2459
- return (url.protocol === "http:" || url.protocol === "https:") && url.hostname ? url : null;
2460
- }
2461
- /** `parseBaseUrl` for constructors: throws `LocalRuntimeError` instead of returning null. */
2462
- function requireBaseUrl(hostOrUrl, runtimeKind) {
2463
- const url = toUrl(hostOrUrl);
2464
- if (url && (url.username || url.password)) throw new LocalRuntimeError(`${runtimeKind} base URL must not contain credentials; pass apiKey instead`, runtimeKind);
2465
- const baseUrl = parseBaseUrl(hostOrUrl);
2466
- if (!baseUrl) throw new LocalRuntimeError(`Invalid ${runtimeKind} base URL`, runtimeKind);
2467
- return baseUrl;
2468
- }
2469
- const RUNTIME_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
2470
- /** The caller's `id` option, or the address-derived default; throws `LocalRuntimeError` for an unusable id. */
2471
- function chooseRuntimeId(id, fallback, runtimeKind) {
2472
- if (id === void 0) return fallback;
2473
- if (!RUNTIME_ID.test(id)) throw new LocalRuntimeError(`Invalid ${runtimeKind} runtime id`, runtimeKind);
2474
- return id;
2475
- }
2476
- function hostPort(baseUrl) {
2477
- const url = new URL(baseUrl);
2478
- const port = url.port || (url.protocol === "https:" ? "443" : "80");
2479
- return `${url.hostname}:${port}`;
2480
- }
2481
- /** Preserve the familiar HTTP root identity while distinguishing TLS and reverse-proxy roots. */
2482
- function runtimeEndpointId(baseUrl) {
2483
- const url = new URL(baseUrl);
2484
- return url.protocol === "http:" && url.pathname === "/" ? hostPort(baseUrl) : baseUrl;
2485
- }
2486
- function combinedSignal(signal, timeoutMs) {
2487
- const timeout = timeoutMs === void 0 ? void 0 : AbortSignal.timeout(timeoutMs);
2488
- if (signal && timeout) return AbortSignal.any([signal, timeout]);
2489
- return signal ?? timeout;
2490
- }
2491
- /**
2492
- * Wraps a failure below HTTP in `RuntimeConnectionError`. Errors of ours and anything thrown after the
2493
- * caller's `signal` aborted (fetch's `AbortError`, or the abort reason) pass through unchanged.
2494
- */
2495
- function connectionError(client, path, error, options = {}) {
2496
- if (error instanceof LocalRuntimeError || options.signal?.aborted) return error;
2497
- return new RuntimeConnectionError(`${client.runtimeId} ${path} failed: ${describeError(error, options.timeoutMs)}`, client.runtimeId, { cause: error });
2498
- }
2499
- const INVALID_HEADER_VALUE = /[\0\r\n]|[^\0-\xff]/;
2500
- /** Throws `LocalRuntimeError` naming the header, never its value, when fetch would reject that value. */
2501
- function assertHeaderValues(headers, runtimeId) {
2502
- for (const [name, value] of Object.entries(headers ?? {})) if (INVALID_HEADER_VALUE.test(value)) throw new LocalRuntimeError(`${runtimeId} ${name} header contains a character HTTP does not allow`, runtimeId);
2503
- }
2504
- /** Throws `RuntimeHttpError` on a non-2xx status and `RuntimeConnectionError` when there is no response. */
2505
- async function send(client, path, options = {}) {
2506
- assertHeaderValues(client.headers, client.runtimeId);
2507
- const hasBody = options.body !== void 0;
2508
- const contentType = options.stream ? "application/octet-stream" : hasBody ? "application/json" : null;
2509
- let response;
2510
- try {
2511
- response = await client.fetch(`${client.baseUrl}${path}`, {
2512
- method: options.method ?? "GET",
2513
- headers: {
2514
- ...client.headers,
2515
- ...contentType ? { "content-type": contentType } : {}
2516
- },
2517
- body: options.stream ?? (hasBody ? JSON.stringify(options.body) : void 0),
2518
- ...options.stream ? { duplex: "half" } : {},
2519
- signal: combinedSignal(options.signal, options.timeoutMs),
2520
- redirect: "error"
2521
- });
2522
- } catch (error) {
2523
- throw connectionError(client, path, error, options);
2524
- }
2525
- if (!response.ok) {
2526
- const text = await response.text().catch(() => "");
2527
- const parsed = errorBodySchema.safeParse(safeJsonParse(text));
2528
- const detail = parsed.success ? parsed.data : null;
2529
- throw new RuntimeHttpError(`${client.runtimeId} ${path} returned HTTP ${response.status}${detail === null ? "" : `: ${detail}`}`, client.runtimeId, response.status, detail);
2530
- }
2531
- return response;
2532
- }
2533
- function safeJsonParse(text) {
2534
- try {
2535
- return JSON.parse(text);
2536
- } catch {
2537
- return;
2538
- }
2539
- }
2540
- function isAuthError(error) {
2541
- return error instanceof RuntimeHttpError && (error.status === 401 || error.status === 403);
2542
- }
2543
- async function requestJson(client, path, schema, options = {}) {
2544
- const response = await send(client, path, options);
2545
- let text;
2546
- try {
2547
- text = await response.text();
2548
- } catch (error) {
2549
- throw connectionError(client, path, error, options);
2550
- }
2551
- return parseJson(client, path, text, schema);
2552
- }
2553
- function parseJson(client, path, text, schema) {
2554
- let raw;
2555
- try {
2556
- raw = JSON.parse(text);
2557
- } catch (cause) {
2558
- throw new RuntimeProtocolError(`${client.runtimeId} ${path} returned invalid JSON`, client.runtimeId, { cause });
2559
- }
2560
- const parsed = schema.safeParse(raw);
2561
- if (!parsed.success) throw new RuntimeProtocolError(`${client.runtimeId} ${path} returned an unexpected shape`, client.runtimeId, { cause: parsed.error });
2562
- return parsed.data;
2563
- }
2564
- /** One-line reason for a failed request, suitable for `RuntimeHealth.error`. */
2565
- function describeError(error, timeoutMs) {
2566
- if (error instanceof RuntimeConnectionError) return describeError(error.cause, timeoutMs);
2567
- if (error instanceof LocalRuntimeError) return error.message;
2568
- if (error instanceof Error) {
2569
- if (error.name === "TimeoutError") return `timed out${timeoutMs === void 0 ? "" : ` after ${timeoutMs}ms`}`;
2570
- if (error.name === "AbortError") return "aborted";
2571
- const code = causeCode(error);
2572
- if (code === "ECONNREFUSED") return "connection refused";
2573
- if (code) return `${error.message} (${code})`;
2574
- return error.message;
2575
- }
2576
- return String(error);
2577
- }
2578
- function causeCode(error) {
2579
- const cause = error.cause;
2580
- if (cause && typeof cause === "object" && "code" in cause && typeof cause.code === "string") return cause.code;
2581
- }
2582
- const openAIModelsSchema = z$1.object({ data: z$1.array(z$1.unknown()) });
2583
- const openAIModelEntrySchema = z$1.object({
2584
- id: z$1.string().min(1),
2585
- owned_by: z$1.string().optional(),
2586
- meta: z$1.object({ size: z$1.number().optional() }).nullable().optional(),
2587
- status: z$1.unknown().optional(),
2588
- root: z$1.unknown().optional(),
2589
- parent: z$1.unknown().optional(),
2590
- max_model_len: z$1.unknown().optional()
2591
- });
2592
- const lmStudioModelsSchema = z$1.object({
2593
- object: z$1.literal("list"),
2594
- data: z$1.array(z$1.unknown())
2595
- });
2596
- const lmStudioEntrySchema = z$1.object({
2597
- id: z$1.string().min(1),
2598
- type: z$1.string(),
2599
- arch: z$1.string().optional(),
2600
- quantization: z$1.string().optional()
2601
- });
2602
- /** Health text for a 401/403, so a UI can ask for (or re-ask for) a key. */
2603
- function authErrorMessage(hasApiKey) {
2604
- return hasApiKey ? "API key was rejected" : "Requires an API key";
2605
- }
2606
- const NO_CAPABILITIES = {
2607
- tools: false,
2608
- vision: false,
2609
- thinking: false,
2610
- embeddings: false,
2611
- completion: false
2612
- };
2613
- function bareModel(name, sizeBytes = null) {
2614
- return {
2615
- name,
2616
- sizeBytes,
2617
- quantization: null,
2618
- family: null,
2619
- parameterSize: null,
2620
- modifiedAt: null,
2621
- capabilities: { ...NO_CAPABILITIES }
2622
- };
2623
- }
2624
- const text = (value) => typeof value === "string" && value ? value : void 0;
2625
- const loadStateOf = (status) => status && typeof status === "object" && !Array.isArray(status) ? text(status.value) : void 0;
2626
- const positiveInt = (value) => typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
2627
- /**
2628
- * One model per set of weights: names sharing a `root` collapse into the first listed, which keeps the
2629
- * rest as aliases. An adapter names its base by that first name and inherits the base's context.
2630
- */
2631
- function listedModels(entries) {
2632
- const models = [];
2633
- const byRoot = /* @__PURE__ */ new Map();
2634
- const byName = /* @__PURE__ */ new Map();
2635
- for (const entry of entries) {
2636
- const root = text(entry.root);
2637
- const parent = text(entry.parent);
2638
- const shared = !parent && root ? byRoot.get(root) : void 0;
2639
- if (shared) {
2640
- if (shared.name !== entry.id && !shared.aliases?.includes(entry.id)) shared.aliases = [...shared.aliases ?? [], entry.id];
2641
- byName.set(entry.id, shared);
2642
- continue;
2643
- }
2644
- const base = parent ? byName.get(parent) : void 0;
2645
- const contextLength = positiveInt(entry.max_model_len) ?? base?.contextLength;
2646
- const loadState = loadStateOf(entry.status);
2647
- const model = {
2648
- ...bareModel(entry.id, entry.meta?.size ?? null),
2649
- ...contextLength ? { contextLength } : {},
2650
- ...loadState ? { loadState } : {},
2651
- ...parent ? { baseModel: base?.name ?? parent } : {}
2652
- };
2653
- if (root && !parent) byRoot.set(root, model);
2654
- byName.set(entry.id, model);
2655
- models.push(model);
2656
- }
2657
- return models;
2658
- }
2659
- /** LM Studio, llama-server, vLLM and anything else serving the OpenAI `/v1/models` endpoint. */
2660
- var OpenAICompatibleRuntime = class {
2661
- kind = "openai-compatible";
2662
- id;
2663
- baseUrl;
2664
- product;
2665
- capabilities = {
2666
- canPull: false,
2667
- canRemove: false,
2668
- canInspect: false,
2669
- reportsLoaded: false
2670
- };
2671
- client;
2672
- requestTimeoutMs;
2673
- healthTimeoutMs;
2674
- hasApiKey;
2675
- constructor(options) {
2676
- this.baseUrl = requireBaseUrl(options.baseUrl, "openai-compatible");
2677
- this.id = chooseRuntimeId(options.id, `openai-compatible:${runtimeEndpointId(this.baseUrl)}`, "openai-compatible");
2678
- this.product = options.product ?? null;
2679
- this.requestTimeoutMs = options.requestTimeoutMs ?? 1e4;
2680
- this.healthTimeoutMs = options.healthTimeoutMs ?? 1500;
2681
- this.hasApiKey = !!options.apiKey;
2682
- this.client = {
2683
- runtimeId: this.id,
2684
- baseUrl: this.baseUrl,
2685
- fetch: options.fetch ?? fetch,
2686
- headers: options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : void 0
2687
- };
2688
- }
2689
- async health() {
2690
- try {
2691
- await requestJson(this.client, "/v1/models", openAIModelsSchema, { timeoutMs: this.healthTimeoutMs });
2692
- return {
2693
- ok: true,
2694
- version: null,
2695
- error: null
2696
- };
2697
- } catch (error) {
2698
- return {
2699
- ok: false,
2700
- version: null,
2701
- error: isAuthError(error) ? authErrorMessage(this.hasApiKey) : describeError(error, this.healthTimeoutMs)
2702
- };
2703
- }
2704
- }
2705
- async list() {
2706
- if (this.product === "lmstudio") {
2707
- const rich = await this.listLmStudio().catch(() => null);
2708
- if (rich) return rich;
2709
- }
2710
- const { data } = await requestJson(this.client, "/v1/models", openAIModelsSchema, { timeoutMs: this.requestTimeoutMs });
2711
- return listedModels(data.flatMap((raw) => {
2712
- const entry = openAIModelEntrySchema.safeParse(raw);
2713
- return entry.success ? [entry.data] : [];
2714
- }));
2715
- }
2716
- async inspect(model) {
2717
- const found = (await this.list()).find((entry) => entry.name === model || entry.aliases?.includes(model));
2718
- if (!found) throw new ModelNotFoundError(this.id, model);
2719
- return {
2720
- model: found,
2721
- arch: null,
2722
- tensorStats: null
2723
- };
2724
- }
2725
- async pull(_ref, _opts) {
2726
- throw new RuntimeUnsupportedError(this.id, "pull");
2727
- }
2728
- async remove(_model) {
2729
- throw new RuntimeUnsupportedError(this.id, "remove");
2730
- }
2731
- async loaded() {
2732
- throw new RuntimeUnsupportedError(this.id, "loaded");
2733
- }
2734
- async listLmStudio() {
2735
- const { data } = await requestJson(this.client, "/api/v0/models", lmStudioModelsSchema, { timeoutMs: this.requestTimeoutMs });
2736
- return data.flatMap((raw) => {
2737
- const entry = lmStudioEntrySchema.safeParse(raw);
2738
- if (!entry.success) return [];
2739
- const { id, type, arch, quantization } = entry.data;
2740
- return [{
2741
- ...bareModel(id),
2742
- quantization: quantization || null,
2743
- family: arch || null,
2744
- capabilities: {
2745
- ...NO_CAPABILITIES,
2746
- completion: type === "llm" || type === "vlm",
2747
- vision: type === "vlm",
2748
- embeddings: type === "embeddings"
2749
- }
2750
- }];
2751
- });
2752
- }
2753
- };
2754
- /** Refused before anything was sent: wrong origin, or a transport rule (see addressPolicy). */
2755
- var ServerTransportError = class extends Error {
2756
- constructor(message) {
2757
- super(message);
2758
- this.name = "ServerTransportError";
2759
- }
2760
- };
2761
- /** The server answered with a redirect. Never followed, so a credential cannot be carried anywhere else. */
2762
- var ServerRedirectError = class extends Error {
2763
- crossOrigin;
2764
- constructor(message, crossOrigin) {
2765
- super(message);
2766
- this.crossOrigin = crossOrigin;
2767
- this.name = "ServerRedirectError";
2768
- }
2769
- };
2770
- sshServerUrl(11434);
2771
- /** The URL requests use for the server on the far end's loopback port `port`. */
2772
- function sshServerUrl(port) {
2773
- return `http://127.0.0.1:${port}`;
2774
- }
2775
- /** The connection did not come up or dropped; a later check may succeed. Shown as Unreachable. */
2776
- var SshConnectionError = class extends Error {
2777
- constructor(message) {
2778
- super(message);
2779
- this.name = "SshConnectionError";
2780
- }
2781
- };
2782
- /** The system error code on the error itself (Node http mid-body drops) or on its cause (fetch). */
2783
- function errorCode(err) {
2784
- if (!(err instanceof Error)) return void 0;
2785
- const own = err.code;
2786
- if (typeof own === "string") return own;
2787
- const cause = err.cause?.code;
2788
- return typeof cause === "string" ? cause : void 0;
2789
- }
2790
- const DROP_CODES = /* @__PURE__ */ new Set([
2791
- "ECONNRESET",
2792
- "UND_ERR_SOCKET",
2793
- "ERR_STREAM_PREMATURE_CLOSE"
2794
- ]);
2795
- /** One line for a failed request; never includes a header or credential. */
2796
- function describeFailure(err) {
2797
- if (err instanceof ServerTransportError || err instanceof ServerRedirectError) return err.message;
2798
- if (err instanceof SshConnectionError) return err.message;
2799
- if (err instanceof Error && err.cause instanceof SshConnectionError) return err.cause.message;
2800
- if (err instanceof DOMException && err.name === "TimeoutError") return "it did not answer in time";
2801
- if (err instanceof Error && err.name === "TimeoutError") return "it did not answer in time";
2802
- if (err instanceof PullIdleTimeoutError) return "it stopped sending data";
2803
- const code = errorCode(err);
2804
- if (code === "ECONNREFUSED") return "connection refused";
2805
- if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "host not found";
2806
- if (code === "EHOSTUNREACH" || code === "ENETUNREACH") return "no route to the host";
2807
- if (code === "ETIMEDOUT") return "the connection timed out";
2808
- if (code && DROP_CODES.has(code)) return "the connection dropped";
2809
- if (err instanceof TypeError && /terminated|aborted/i.test(err.message)) return "the connection dropped";
2810
- if (err instanceof Error && /ended (the reply )?before/i.test(err.message)) return "the connection dropped";
2811
- return code ?? (err instanceof Error ? err.message : String(err));
2812
- }
2813
- /** Tokens a `numCtx` context keeps free for the reply. */
2814
- function replyRoom(numCtx, maxTokens) {
2815
- return Math.min(maxTokens ?? 2048, Math.floor(numCtx / 4));
2816
- }
2817
- /** Whether a context the server fixes holds a prompt of `promptTokens` plus room for the reply. */
2818
- function holdsPrompt(numCtx, promptTokens, maxTokens) {
2819
- return promptTokens + replyRoom(numCtx, maxTokens) <= numCtx;
2820
- }
2821
- const PROPS_TIMEOUT_MS = 5e3;
2822
- /** Long enough for a busy server to produce the probe's one token. */
2823
- const TOOLS_PROBE_TIMEOUT_MS = 2e4;
2824
- const PROBE_TOOL = {
2825
- type: "function",
2826
- function: {
2827
- name: "ping",
2828
- description: "Replies pong.",
2829
- parameters: {
2830
- type: "object",
2831
- properties: {}
2832
- }
2833
- }
2834
- };
2835
- /**
2836
- * llama-server without --jinja (500), vLLM without --enable-auto-tool-choice (400, `"auto" tool choice requires
2837
- * --enable-auto-tool-choice and --tool-call-parser to be set`), and some proxies refuse a request that declares tools.
2838
- */
2839
- function isToolRefusal(status, body) {
2840
- if (status !== 400 && status !== 500) return false;
2841
- return /\btools?\b/i.test(body);
2842
- }
2843
- /** isToolRefusal on a response, reading the body only for a status a refusal can have. */
2844
- async function refusesTools(response) {
2845
- if (response.status !== 400 && response.status !== 500) return false;
2846
- return isToolRefusal(response.status, await response.clone().text());
2847
- }
2848
- /**
2849
- * Asks with a one-token request that declares a tool; null when the answer says nothing about tool support,
2850
- * including when `signal` aborts it.
2851
- */
2852
- async function probeToolSupport(fetch, baseUrl, model, timeoutMs = TOOLS_PROBE_TIMEOUT_MS, signal) {
2853
- try {
2854
- const timeout = AbortSignal.timeout(timeoutMs);
2855
- const response = await fetch(`${baseUrl}/v1/chat/completions`, {
2856
- method: "POST",
2857
- headers: { "content-type": "application/json" },
2858
- signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
2859
- body: JSON.stringify({
2860
- model,
2861
- messages: [{
2862
- role: "user",
2863
- content: "ping"
2864
- }],
2865
- max_tokens: 1,
2866
- tools: [PROBE_TOOL]
2867
- })
2868
- });
2869
- if (response.ok) {
2870
- await response.body?.cancel();
2871
- return "accepted";
2872
- }
2873
- if (await refusesTools(response)) return "refused";
2874
- await response.body?.cancel();
2875
- return null;
2876
- } catch {
2877
- return null;
2878
- }
2879
- }
2880
- /** llama-server's context from `/props`; undefined for other products or when it cannot be read. */
2881
- async function serverContextTokens(fetch, baseUrl, product, signal) {
2882
- if (product !== "llama-server") return void 0;
2883
- try {
2884
- const timeout = AbortSignal.timeout(PROPS_TIMEOUT_MS);
2885
- const response = await fetch(`${baseUrl}/props`, { signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
2886
- if (!response.ok) return void 0;
2887
- const body = await response.json();
2888
- return tokenCount(body.default_generation_settings?.n_ctx) || tokenCount(body.n_ctx) || void 0;
2889
- } catch {
2890
- return;
2891
- }
2892
- }
2893
- function tokenCount(value) {
2894
- return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
2895
- }
2896
- /** Why tools are off and how to turn them on, for the server's settings row and the chat it happened in. */
2897
- function toolsOffHint(label, product, app) {
2898
- if (product === "vllm") return `${label} was started without tool calling, so its chats run without tools. Restart vLLM with --enable-auto-tool-choice and a --tool-call-parser for the model, ${app.recheck}`;
2899
- if (product === "llama-server") return `${label} refuses tool calls, so its chats run without tools. Restart llama-server with --jinja, ${app.recheck}`;
2900
- return `${label} refuses tool calls, so its chats run without tools. Turn tool calling on there, ${app.recheck}`;
2901
- }
2902
- /** Why tools are off when the server's context is too small for the app's prompt and tools. */
2903
- function contextTooSmallHint(label, product, small, toolPromptTokens, app) {
2904
- const smallest = Math.min(...small.map((model) => model.context));
2905
- return `${label} runs ${small.map((model) => model.name).join(", ")} with ${new Set(small.map((model) => model.context)).size === 1 ? `a ${smallest}-token context` : `contexts as small as ${smallest} tokens`}, too small for ${app.name}'s instructions and tools (about ${toolPromptTokens} tokens), so its chats run without tools. ${restartWithContext(product, toolPromptTokens)}, ${app.recheck}`;
2906
- }
2907
- /** Why a turn cannot be sent at all: the context is too small for the prompt even without tools. */
2908
- function promptTooLargeHint(label, product, model, promptTokens, app) {
2909
- return `${label} runs ${model.name} with a ${model.context}-token context, too small for ${app.name}'s instructions even without tools (about ${promptTokens} tokens). ${restartWithContext(product, promptTokens)}, ${app.recheck}`;
2910
- }
2911
- /** Why a turn cannot be sent: the user's message, not the app's instructions, overflows the context. */
2912
- function messageTooLongHint(label, model, messageTokens) {
2913
- return `This message (about ${messageTokens} tokens) is too long for ${model.name}'s ${model.context}-token context on ${label}. Send a shorter message, or use a model with a larger context.`;
2914
- }
2915
- /**
2916
- * Why a turn cannot be sent: the conversation so far leaves no room in the context for a reply.
2917
- * The phrase "context window" must stay: the agents package matches it (isContextLimitError) to compact and retry.
2918
- */
2919
- function conversationFullHint(label, model) {
2920
- return `This conversation no longer fits ${model.name}'s ${model.context}-token context window on ${label} with room for a reply. Start a new conversation, or use a model with a larger context.`;
2921
- }
2922
- function restartWithContext(product, promptTokens) {
2923
- const target = Math.max(16384, 2 ** Math.ceil(Math.log2(promptTokens + replyRoom(16384))));
2924
- if (product === "vllm") return `Restart vLLM with --max-model-len ${target}`;
2925
- if (product === "llama-server") return `Restart llama-server with --ctx-size ${target}`;
2926
- return `Give it a context of ${target} tokens or more`;
2927
- }
2928
- const DEFAULT_CONTEXT_WINDOW = 16384;
2929
- const CHARS_PER_TOKEN = 4;
2930
- const REQUEST_TIMEOUT_MS = 36e5;
2931
- const DEFAULT_APP = {
2932
- name: "the CLI",
2933
- recheck: "then start a new b4m session."
2934
- };
2935
- /** vLLM, llama-server, LM Studio and any other server that speaks OpenAI's `/v1/chat/completions`. */
2936
- var OpenAICompatibleBackend = class {
2937
- options;
2938
- currentModel = "";
2939
- api;
2940
- runtime;
2941
- logger;
2942
- app;
2943
- toolsOff = false;
2944
- smallNoticed = /* @__PURE__ */ new Set();
2945
- canonical = /* @__PURE__ */ new Map();
2946
- contexts = /* @__PURE__ */ new Map();
2947
- listed = false;
2948
- constructor(options) {
2949
- this.options = options;
2950
- this.logger = options.logger ?? new Logger();
2951
- this.app = options.app ?? DEFAULT_APP;
2952
- this.runtime = new OpenAICompatibleRuntime({
2953
- baseUrl: options.baseUrl,
2954
- fetch: options.fetch,
2955
- product: options.product,
2956
- requestTimeoutMs: options.listingTimeoutMs
2957
- });
2958
- this.api = new OpenAI({
2959
- apiKey: "none",
2960
- baseURL: `${this.runtime.baseUrl}/v1`,
2961
- fetch: this.guardedFetch(),
2962
- maxRetries: 0,
2963
- timeout: REQUEST_TIMEOUT_MS
2964
- });
2965
- }
2966
- /** Drops the SDK's own `authorization`, and runs `redact` over error bodies before the SDK reads them. */
2967
- guardedFetch() {
2968
- return async (input, init) => {
2969
- const headers = new Headers(init?.headers);
2970
- headers.delete("authorization");
2971
- const response = await this.options.fetch(String(input), {
2972
- ...init,
2973
- headers: Object.fromEntries(headers.entries())
2974
- });
2975
- if (response.ok) return response;
2976
- const responseHeaders = new Headers(response.headers);
2977
- responseHeaders.delete("content-length");
2978
- return new Response(withErrorKey(this.redact(await response.text())), {
2979
- status: response.status,
2980
- statusText: response.statusText,
2981
- headers: responseHeaders
2982
- });
2983
- };
2984
- }
2985
- async getModelInfo() {
2986
- const models = await this.runtime.list();
2987
- this.listed = true;
2988
- return Promise.all(models.map(async (model) => {
2989
- this.canonical.set(model.name, model.name);
2990
- for (const alias of model.aliases ?? []) this.canonical.set(alias, model.name);
2991
- const reported = model.contextLength ?? await serverContextTokens(this.options.fetch, this.runtime.baseUrl, this.options.product);
2992
- if (reported) this.contexts.set(model.name, reported);
2993
- const contextWindow = reported ?? DEFAULT_CONTEXT_WINDOW;
2994
- return {
2995
- id: model.name,
2996
- type: "text",
2997
- name: model.baseModel ? `${model.name} (LoRA on ${model.baseModel})` : model.name,
2998
- backend: ModelBackend.OpenAICompatible,
2999
- contextWindow,
3000
- max_tokens: Math.max(1, Math.floor(contextWindow / 2)),
3001
- supportsImageVariation: false,
3002
- pricing: { [contextWindow]: {
3003
- input: 0,
3004
- output: 0
3005
- } },
3006
- freeToRun: true,
3007
- supportsVision: model.capabilities.vision,
3008
- supportsTools: !this.toolsOff,
3009
- can_think: model.capabilities.thinking,
3010
- can_stream: true,
3011
- description: `Served by ${this.options.label}. Capabilities depend on the model.`
3012
- };
3013
- }));
3014
- }
3015
- async contextOf(name) {
3016
- if (!this.listed) try {
3017
- await this.getModelInfo();
3018
- } catch (error) {
3019
- this.logger.warn(`Could not list ${this.options.label}'s models: ${this.redact(describeFailure(error))}`);
3020
- }
3021
- return this.contexts.get(name);
3022
- }
3023
- /**
3024
- * `isToolRefusal` matches any 400/500 that mentions tools, including a bad tool history, so a sticky
3025
- * tools-off waits for a one-token probe. An inconclusive probe keeps the refusal reading.
3026
- */
3027
- async probeConfirmsRefusal(name, signal) {
3028
- const verdict = await probeToolSupport(this.options.fetch, this.runtime.baseUrl, name, void 0, signal);
3029
- if (signal?.aborted) return false;
3030
- if (verdict === "accepted") {
3031
- this.logger.warn(`${this.options.label} rejected a request with tools but accepts tools, so they stay on.`);
3032
- return false;
3033
- }
3034
- if (verdict === null) this.logger.warn(`Could not confirm that ${this.options.label} refuses tools.`);
3035
- return true;
3036
- }
3037
- /**
3038
- * Fits this turn into a context the server fixes: whether its tools fit, and `maxTokens` capped by the room the
3039
- * whole prompt leaves. Throws with the restart hint when the instructions alone do not fit, and with the matching
3040
- * fix when the last message or the whole conversation leaves no room for a reply. Unknown contexts are assumed
3041
- * to fit.
3042
- */
3043
- async fitContext(name, messages, tools, maxTokens) {
3044
- const context = await this.contextOf(name);
3045
- if (!context) return {
3046
- toolsFit: true,
3047
- maxTokens
3048
- };
3049
- const tokens = (chars) => Math.ceil(chars / CHARS_PER_TOKEN);
3050
- const toolChars = tools.length ? JSON.stringify(tools.map((tool) => tool.toolSchema)).length : 0;
3051
- const systemChars = messages.filter((message) => message.role === "system").map(textOf).join("").length;
3052
- const lastUser = messages.findLast((message) => message.role === "user");
3053
- const lastUserChars = lastUser ? textOf(lastUser).length : 0;
3054
- const baseChars = systemChars + lastUserChars;
3055
- if (!holdsPrompt(context, tokens(systemChars), maxTokens)) throw new Error(promptTooLargeHint(this.options.label, this.options.product, {
3056
- name,
3057
- context
3058
- }, tokens(systemChars), this.app));
3059
- if (!holdsPrompt(context, tokens(baseChars), maxTokens)) throw new Error(messageTooLongHint(this.options.label, {
3060
- name,
3061
- context
3062
- }, tokens(lastUserChars)));
3063
- let toolsFit = true;
3064
- if (tools.length && !holdsPrompt(context, tokens(baseChars + toolChars), maxTokens)) {
3065
- toolsFit = false;
3066
- if (!this.smallNoticed.has(name)) {
3067
- this.smallNoticed.add(name);
3068
- this.options.onNotice?.(contextTooSmallHint(this.options.label, this.options.product, [{
3069
- name,
3070
- context
3071
- }], tokens(baseChars + toolChars), this.app));
3072
- }
3073
- }
3074
- if (maxTokens === void 0) return {
3075
- toolsFit,
3076
- maxTokens
3077
- };
3078
- const room = context - tokens(messages.reduce((sum, message) => sum + textOf(message).length, 0) + (toolsFit ? toolChars : 0));
3079
- if (room < replyRoom(context, maxTokens)) throw new Error(conversationFullHint(this.options.label, {
3080
- name,
3081
- context
3082
- }));
3083
- return {
3084
- toolsFit,
3085
- maxTokens: Math.min(maxTokens, room)
3086
- };
3087
- }
3088
- async complete(model, messages, options, callback, toolsUsed = []) {
3089
- this.currentModel = model;
3090
- const name = this.canonical.get(model) ?? model;
3091
- const toolCallCount = options._internal?.toolCallCount ?? 0;
3092
- const accumInputTokens = options._internal?.accumInputTokens ?? 0;
3093
- const accumOutputTokens = options._internal?.accumOutputTokens ?? 0;
3094
- const accumTurnUsage = options._internal?.accumTurnUsage;
3095
- const maxToolCalls = options._internal?.maxToolCalls ?? 10;
3096
- const rawTools = options.tools;
3097
- const requested = Array.isArray(rawTools) ? rawTools : rawTools ? [rawTools] : [];
3098
- if (requested.length && toolCallCount >= maxToolCalls) {
3099
- this.logger.warn(`Max tool calls limit (${maxToolCalls}) reached. Disabling tools to prevent infinite loops.`);
3100
- await this.complete(model, stripToolDependentMessages(messages), {
3101
- ...options,
3102
- tools: void 0,
3103
- _internal: options._internal
3104
- }, callback, toolsUsed);
3105
- return;
3106
- }
3107
- const wanted = requested.length > 0 && !this.toolsOff ? requested : [];
3108
- const fit = await this.fitContext(name, messages, wanted, options.maxTokens);
3109
- const sendTools = wanted.length > 0 && fit.toolsFit;
3110
- if (requested.length && !sendTools) {
3111
- await this.complete(model, stripToolDependentMessages(messages), {
3112
- ...options,
3113
- tools: void 0,
3114
- _internal: options._internal
3115
- }, callback, toolsUsed);
3116
- return;
3117
- }
3118
- const parameters = {
3119
- model: name,
3120
- messages: this.formatMessages(messages, name, options),
3121
- stream: true,
3122
- stream_options: { include_usage: true },
3123
- ...fit.maxTokens ? { max_tokens: fit.maxTokens } : {},
3124
- ...options.temperature !== void 0 ? { temperature: options.temperature } : {},
3125
- ...options.topP !== void 0 ? { top_p: options.topP } : {},
3126
- ...options.stop ? { stop: options.stop } : {},
3127
- ...sendTools ? { tools: this.formatTools(requested) } : {}
3128
- };
3129
- let stream;
3130
- try {
3131
- stream = await this.api.chat.completions.create(parameters, { signal: options.abortSignal });
3132
- } catch (error) {
3133
- if (sendTools && error instanceof OpenAI.APIError && error.status !== void 0) {
3134
- const detail = typeof error.error === "string" ? error.error : JSON.stringify(error.error ?? error.message);
3135
- if (isToolRefusal(error.status, `${error.message} ${detail}`) && await this.probeConfirmsRefusal(name, options.abortSignal)) {
3136
- if (!this.toolsOff) {
3137
- this.toolsOff = true;
3138
- this.options.onNotice?.(toolsOffHint(this.options.label, this.options.product, this.app));
3139
- }
3140
- await this.complete(model, stripToolDependentMessages(messages), {
3141
- ...options,
3142
- tools: void 0,
3143
- _internal: options._internal
3144
- }, callback, toolsUsed);
3145
- return;
3146
- }
3147
- if (options.abortSignal?.aborted) throw new OpenAI.APIUserAbortError();
3148
- }
3149
- throw this.describeError(error);
3150
- }
3151
- const func = [];
3152
- let inputTokens = 0;
3153
- let outputTokens = 0;
3154
- let finishReason;
3155
- let inThinking = false;
3156
- const reasoningEscaper = createThinkMarkerEscaper();
3157
- let sawProse = false;
3158
- let roundText = "";
3159
- let reasoning = "";
3160
- const info = () => ({
3161
- ...splitCacheInclusiveInput(accumInputTokens + inputTokens, 0),
3162
- outputTokens: accumOutputTokens + outputTokens,
3163
- turnUsage: appendCacheInclusiveTurn(accumTurnUsage, inputTokens, 0, outputTokens),
3164
- toolsUsed: toolsUsed.length > 0 ? toolsUsed : void 0
3165
- });
3166
- try {
3167
- for await (const chunk of stream) {
3168
- const out = [];
3169
- if (chunk.usage) {
3170
- inputTokens = Math.max(inputTokens, chunk.usage.prompt_tokens || 0);
3171
- outputTokens = chunk.usage.completion_tokens || outputTokens;
3172
- }
3173
- for (const choice of chunk.choices ?? []) {
3174
- if (choice.finish_reason) finishReason = choice.finish_reason;
3175
- const delta = choice.delta;
3176
- const thinking = delta.reasoning_content || delta.reasoning;
3177
- if (thinking) {
3178
- reasoning += thinking;
3179
- out[choice.index] = (inThinking ? "" : "<think>") + reasoningEscaper.push(thinking);
3180
- inThinking = true;
3181
- if (!delta.content) continue;
3182
- }
3183
- if (inThinking && delta.content) {
3184
- inThinking = false;
3185
- sawProse = true;
3186
- roundText += delta.content;
3187
- out[choice.index] = (out[choice.index] ?? "") + reasoningEscaper.flush() + "</think>" + delta.content;
3188
- continue;
3189
- }
3190
- for (const call of delta.tool_calls ?? []) {
3191
- func[call.index] ||= {};
3192
- func[call.index].name ||= call.function?.name;
3193
- func[call.index].id ||= call.id;
3194
- func[call.index].parameters = (func[call.index].parameters ?? "") + (call.function?.arguments || "");
3195
- }
3196
- if (func.length > 0) continue;
3197
- if (delta.content) sawProse = true;
3198
- roundText += delta.content || "";
3199
- out[choice.index] = delta.content || "";
3200
- }
3201
- await callback(out, {
3202
- ...info(),
3203
- ...normalizeOpenAIFinishReason(finishReason) ? { stopReason: normalizeOpenAIFinishReason(finishReason) } : {}
3204
- });
3205
- }
3206
- } catch (error) {
3207
- throw this.describeError(error);
3208
- }
3209
- if (inThinking) {
3210
- await callback([reasoningEscaper.flush() + "</think>"], info());
3211
- inThinking = false;
3212
- }
3213
- const calls = func.filter((call) => call?.name).map((call, index) => ({
3214
- name: call.name,
3215
- parameters: call.parameters || "{}",
3216
- id: call.id || `call_${toolCallCount}_${index}`
3217
- }));
3218
- if (!sawProse && calls.length === 0) {
3219
- if (finishReason === "length") throw new OutputBudgetExhaustedError(this.options.label, name);
3220
- if (finishReason === void 0 && !options.abortSignal?.aborted) throw new StreamEndedWithoutFinishError(this.options.label, name);
3221
- throw new Error(`${this.options.label} returned no content for ${name} (finish_reason: ${finishReason ?? "unknown"}).`);
3222
- }
3223
- if (calls.length === 0) return;
3224
- for (const call of calls) toolsUsed.push({
3225
- name: call.name,
3226
- arguments: call.parameters,
3227
- id: call.id
3228
- });
3229
- if (options.executeTools === false) {
3230
- await callback([null], {
3231
- ...info(),
3232
- ...reasoning ? { thinking: [reasoning] } : {}
3233
- });
3234
- return;
3235
- }
3236
- const resolved = [];
3237
- const round = [];
3238
- const reject = (tool, observation) => {
3239
- recordToolResult(toolsUsed, tool, observation, false);
3240
- round.push({
3241
- tool,
3242
- result: observation
3243
- });
3244
- };
3245
- for (const { id, name: toolName, parameters } of calls) {
3246
- const toolFn = requested.find((tool) => tool.toolSchema.name === toolName)?.toolFn;
3247
- if (!toolFn) {
3248
- reject({
3249
- id,
3250
- name: toolName,
3251
- parameters
3252
- }, `Error: tool "${toolName}" is not available. Do not call it again; answer directly or use a listed tool.`);
3253
- continue;
3254
- }
3255
- try {
3256
- resolved.push({
3257
- id,
3258
- name: toolName,
3259
- parameters,
3260
- parsed: JSON.parse(parameters),
3261
- toolFn
3262
- });
3263
- } catch {
3264
- this.logger.warn(`JSON parse error for ${toolName} arguments`);
3265
- const entry = toolsUsed.find((tool) => tool.name === toolName && tool.id === id);
3266
- if (entry) entry.arguments = "{}";
3267
- reject({
3268
- id,
3269
- name: toolName,
3270
- parameters: "{}"
3271
- }, "Error: Tool arguments were malformed and could not be parsed.");
3272
- }
3273
- }
3274
- const batch = await executeToolsBatch(resolved.map(({ id, name: toolName, parameters, parsed, toolFn }) => async () => ({
3275
- id,
3276
- name: toolName,
3277
- parameters,
3278
- result: await toolFn(parsed)
3279
- })), {
3280
- parallel: options.parallelToolExecution !== false,
3281
- maxConcurrency: options.maxParallelTools
3282
- });
3283
- const inheritedGuard = options._internal?.artifactGuard;
3284
- let guard = inheritedGuard;
3285
- for (const [i, outcome] of batch.entries()) {
3286
- const target = resolved[i];
3287
- if (outcome.ok) {
3288
- const { id, name: toolName, parameters, result } = outcome.result;
3289
- let emitted = false;
3290
- await handleToolResultStreaming(toolName, result, async (results, artifactInfo) => {
3291
- emitted = true;
3292
- if (!guard) guard = createRecursiveArtifactGuard(callback);
3293
- await guard.emitArtifact(results, {
3294
- toolsUsed,
3295
- ...artifactInfo
3296
- });
3297
- }, declaredArtifactType(requested, toolName));
3298
- const resultStr = stripUnstreamedToolResult(toolName, result.toString(), emitted);
3299
- recordToolResult(toolsUsed, {
3300
- id,
3301
- name: toolName
3302
- }, resultStr, true);
3303
- round.push({
3304
- tool: {
3305
- id,
3306
- name: toolName,
3307
- parameters
3308
- },
3309
- result: resultStr
3310
- });
3311
- } else {
3312
- if (outcome.error instanceof PermissionDeniedError) throw outcome.error;
3313
- const message = outcome.error instanceof Error ? outcome.error.message : "Unknown error";
3314
- this.logger[toolFailureLogLevel(outcome.error)]("[Tool Execution] Tool failed", {
3315
- backend: this.options.label,
3316
- toolName: target.name,
3317
- error: message
3318
- });
3319
- const observation = stripToolArtifactMarkup(`Error processing ${target.name} tool: ${message}`, ARTIFACT_REMOVED_PLACEHOLDER);
3320
- recordToolResult(toolsUsed, {
3321
- id: target.id,
3322
- name: target.name
3323
- }, observation, false);
3324
- round.push({
3325
- tool: {
3326
- id: target.id,
3327
- name: target.name,
3328
- parameters: target.parameters
3329
- },
3330
- result: observation
3331
- });
3332
- }
3333
- }
3334
- this.pushToolRound(messages, round, reasoning || void 0);
3335
- if (shouldEndTurnAfterTools(calls.map((call) => call.name), requested, roundText)) {
3336
- await (guard?.callback ?? callback)([], {
3337
- ...info(),
3338
- stopReason: "tool_use"
3339
- });
3340
- if (!inheritedGuard && guard) await guard.flush();
3341
- return;
3342
- }
3343
- await this.complete(model, messages, {
3344
- ...options,
3345
- _internal: {
3346
- ...options._internal,
3347
- toolCallCount: toolCallCount + 1,
3348
- accumInputTokens: accumInputTokens + inputTokens,
3349
- accumOutputTokens: accumOutputTokens + outputTokens,
3350
- accumTurnUsage: appendCacheInclusiveTurn(accumTurnUsage, inputTokens, 0, outputTokens),
3351
- artifactGuard: guard
3352
- }
3353
- }, guard?.callback ?? callback, toolsUsed);
3354
- if (!inheritedGuard && guard) await guard.flush();
3355
- }
3356
- redact(text) {
3357
- return this.options.redact?.(text) ?? text;
3358
- }
3359
- /**
3360
- * Credentials never reach a message: 401/403 drop the body, `guardedFetch` scrubs other error bodies, and an
3361
- * error event inside a 200 stream (an `APIError` without a status) is scrubbed here.
3362
- */
3363
- describeError(error) {
3364
- const { label } = this.options;
3365
- if (error instanceof OpenAI.APIUserAbortError) return error;
3366
- if (error instanceof OpenAI.APIConnectionError) return /* @__PURE__ */ new Error(`${label} could not be reached: ${describeFailure(error.cause ?? error)}`);
3367
- if (!(error instanceof OpenAI.APIError)) return error;
3368
- if (error.status === void 0) return /* @__PURE__ */ new Error(`${label}: ${this.redact(error.message)}`);
3369
- if (error.status === 401 || error.status === 403) return /* @__PURE__ */ new Error(`${label} needs credentials.`);
3370
- const body = typeof error.error === "object" && error.error ? error.error : void 0;
3371
- const detail = typeof body?.message === "string" ? body.message : error.message;
3372
- return /* @__PURE__ */ new Error(`${label} returned HTTP ${error.status}: ${detail}`);
3373
- }
3374
- formatMessages(messages, model, options) {
3375
- return convertMessagesToOpenAIFormat(shouldOmitIdentityReminder(options) ? messages : appendIdentityReminderToMessages(messages, buildIdentityReminder(model, options.modelDisplayName)), { preserveReasoningContent: true });
3376
- }
3377
- formatTools(tools = []) {
3378
- return tools.map((tool) => ({
3379
- type: "function",
3380
- function: tool.toolSchema
3381
- }));
3382
- }
3383
- /** `thinkingBlocks` carries the turn's reasoning as a single string entry. */
3384
- pushToolMessages(messages, tool, result, thinkingBlocks) {
3385
- const reasoning = typeof thinkingBlocks?.[0] === "string" ? thinkingBlocks[0] : void 0;
3386
- this.pushToolRound(messages, [{
3387
- tool,
3388
- result
3389
- }], reasoning);
3390
- }
3391
- pushToolRound(messages, round, reasoning) {
3392
- if (round.length === 0) return;
3393
- messages.push({
3394
- content: null,
3395
- role: "assistant",
3396
- ...reasoning ? { reasoning_content: reasoning } : {},
3397
- tool_calls: round.map(({ tool }) => ({
3398
- id: tool.id,
3399
- type: "function",
3400
- function: {
3401
- name: tool.name,
3402
- arguments: tool.parameters
3403
- }
3404
- }))
3405
- });
3406
- for (const { tool, result } of round) messages.push({
3407
- role: "tool",
3408
- content: JSON.stringify({ result }),
3409
- tool_call_id: tool.id,
3410
- name: tool.name
3411
- });
3412
- }
3413
- };
3414
- /**
3415
- * The SDK reads an error's detail only from a body's top-level `error` key, so a flat body (vLLM's
3416
- * `{"object":"error","message":...}`) or plain text would surface as "(no body)" and hide a tool refusal.
3417
- */
3418
- function withErrorKey(text) {
3419
- if (!text) return text;
3420
- let parsed;
3421
- try {
3422
- parsed = JSON.parse(text);
3423
- } catch {
3424
- return JSON.stringify({ error: { message: text } });
3425
- }
3426
- if (typeof parsed === "object" && parsed !== null && "error" in parsed) return text;
3427
- return JSON.stringify({ error: parsed });
3428
- }
3429
- function textOf(message) {
3430
- const content = message.content;
3431
- if (typeof content === "string") return content;
3432
- if (!Array.isArray(content)) return "";
3433
- return content.map((part) => typeof part === "string" ? part : part.text ?? "").join("");
3434
- }
3435
- ModelBackend.Ollama, ModelBackend.LocalImage;
3436
- //#endregion
3437
- //#region ../../b4m-core/utils/dist/index.mjs
3438
- /**
3439
- * In-memory cache for admin settings with TTL support and active cleanup
3440
- * Can be easily extended to use Redis for production
3441
- */
3442
- var AdminSettingsCache = class AdminSettingsCache {
3443
- cache = /* @__PURE__ */ new Map();
3444
- individualCache = /* @__PURE__ */ new Map();
3445
- /**
3446
- * Every call through this field is optional-chained (`this.logger.debug?.()`).
3447
- *
3448
- * A cache must not throw because it could not log, and this one is exposed to that: it is a
3449
- * process-wide singleton created with whichever logger happens to reach `getSettingsCache` first.
3450
- * What each caller then does with a throw varies, and it is mostly NOT a degrade-to-defaults
3451
- * guard: `getSettingsByNames` has none at all, the scoped resolver guards one layer out in
3452
- * `resolveAll`, and `resolveSpendLevers` deliberately rethrows to halt spend. So a logger missing
3453
- * a quieter level could surface as a silent wrong VALUE, as an unhandled rejection, or as a hard
3454
- * fail-closed, depending on who asked. `ScopedSettingsCache` is built by the same factory pair
3455
- * and still has one unguarded call - the same hazard, not a solved one.
3456
- */
3457
- logger;
3458
- cleanupInterval = null;
3459
- maxCacheSize = 1e3;
3460
- static DEFAULT_TTL = 3e5;
3461
- static DEVELOPMENT_TTL = 3e4;
3462
- static CLEANUP_INTERVAL = 6e4;
3463
- constructor(logger) {
3464
- this.logger = logger;
3465
- this.startCleanupTimer();
3466
- }
3467
- /**
3468
- * Start periodic cleanup timer (only in persistent environments)
3469
- */
3470
- startCleanupTimer() {
3471
- if (process.env.NODE_ENV !== "production" || process.env.VERCEL || process.env.AWS_LAMBDA_FUNCTION_NAME) {
3472
- this.logger.debug?.("Skipping cleanup timer in serverless environment");
3473
- return;
3474
- }
3475
- this.cleanupInterval = setInterval(() => {
3476
- this.performCleanup();
3477
- }, AdminSettingsCache.CLEANUP_INTERVAL);
3478
- this.logger.debug?.("Started cache cleanup timer");
3479
- }
3480
- /**
3481
- * Stop cleanup timer (for graceful shutdown)
3482
- */
3483
- stopCleanupTimer() {
3484
- if (this.cleanupInterval) {
3485
- clearInterval(this.cleanupInterval);
3486
- this.cleanupInterval = null;
3487
- this.logger.debug?.("Stopped cache cleanup timer");
3488
- }
3489
- }
3490
- /**
3491
- * Active cleanup of expired entries
3492
- */
3493
- performCleanup() {
3494
- const beforeSize = this.cache.size + this.individualCache.size;
3495
- let removedCount = 0;
3496
- for (const [key, entry] of Array.from(this.cache.entries())) if (!this.isValid(entry.timestamp, entry.ttl)) {
3497
- this.cache.delete(key);
3498
- removedCount++;
3499
- }
3500
- for (const [key, entry] of Array.from(this.individualCache.entries())) if (!this.isValid(entry.timestamp, entry.ttl)) {
3501
- this.individualCache.delete(key);
3502
- removedCount++;
3503
- }
3504
- if (this.individualCache.size > this.maxCacheSize) {
3505
- const entries = Array.from(this.individualCache.entries());
3506
- entries.sort((a, b) => a[1].timestamp - b[1].timestamp);
3507
- const toRemove = this.individualCache.size - this.maxCacheSize;
3508
- for (let i = 0; i < toRemove; i++) {
3509
- this.individualCache.delete(entries[i][0]);
3510
- removedCount++;
3511
- }
3512
- this.logger.warn?.(`Emergency cache cleanup: removed ${toRemove} entries due to size limit`);
3513
- }
3514
- if (removedCount > 0) this.logger.debug?.(`Cache cleanup removed ${removedCount} expired entries (${beforeSize} → ${this.cache.size + this.individualCache.size})`);
3515
- }
3516
- /**
3517
- * Get TTL based on environment
3518
- */
3519
- getTTL() {
3520
- return process.env.NODE_ENV === "development" ? AdminSettingsCache.DEVELOPMENT_TTL : AdminSettingsCache.DEFAULT_TTL;
3521
- }
3522
- /**
3523
- * Check if cache entry is valid (not expired)
3524
- */
3525
- isValid(timestamp, ttl) {
3526
- return Date.now() - timestamp < ttl;
3527
- }
3528
- /**
3529
- * Get all admin settings with caching
3530
- */
3531
- async getSettingsMap(db) {
3532
- const cacheKey = "all_settings";
3533
- const cached = this.cache.get(cacheKey);
3534
- if (cached && this.isValid(cached.timestamp, cached.ttl)) {
3535
- this.logger.debug?.("📦 Admin settings cache HIT");
3536
- return cached.data;
3537
- }
3538
- if (cached) this.cache.delete(cacheKey);
3539
- this.logger.debug?.("🔍 Admin settings cache MISS - fetching from database");
3540
- const fetchStart = Date.now();
3541
- const settingsMap = (await db.adminSettings.findAll()).reduce((out, s) => {
3542
- out[s.settingName] = s.settingValue;
3543
- return out;
3544
- }, {});
3545
- const fetchTime = Date.now() - fetchStart;
3546
- this.logger.info?.(`📦 Cached ${Object.keys(settingsMap).length} admin settings in ${fetchTime}ms`);
3547
- const ttl = this.getTTL();
3548
- this.cache.set(cacheKey, {
3549
- data: settingsMap,
3550
- timestamp: Date.now(),
3551
- ttl
3552
- });
3553
- Object.entries(settingsMap).forEach(([key, value]) => {
3554
- this.individualCache.set(key, {
3555
- value,
3556
- timestamp: Date.now(),
3557
- ttl
3558
- });
3559
- });
3560
- return settingsMap;
3561
- }
3562
- /**
3563
- * Get individual admin setting with caching
3564
- */
3565
- async getSettingByName(settingName, db) {
3566
- const cached = this.individualCache.get(settingName);
3567
- if (cached && this.isValid(cached.timestamp, cached.ttl)) {
3568
- this.logger.debug?.(`📦 Individual setting '${settingName}' cache HIT`);
3569
- return cached.value;
3570
- }
3571
- if (cached) this.individualCache.delete(settingName);
3572
- this.logger.debug?.(`🔍 Individual setting '${settingName}' cache MISS - fetching from database`);
3573
- const fetchStart = Date.now();
3574
- const value = (await db.adminSettings.findBySettingName(settingName))?.settingValue ?? null;
3575
- const fetchTime = Date.now() - fetchStart;
3576
- this.logger.debug?.(`📦 Cached individual setting '${settingName}' in ${fetchTime}ms`);
3577
- this.individualCache.set(settingName, {
3578
- value,
3579
- timestamp: Date.now(),
3580
- ttl: this.getTTL()
3581
- });
3582
- return value;
3583
- }
3584
- /**
3585
- * Get multiple admin settings with caching
3586
- */
3587
- async getSettingsByNames(settingNames, db) {
3588
- const result = {};
3589
- const uncachedSettings = [];
3590
- for (const settingName of settingNames) {
3591
- const cached = this.individualCache.get(settingName);
3592
- if (cached && this.isValid(cached.timestamp, cached.ttl)) {
3593
- if (cached.value !== null) result[settingName] = cached.value;
3594
- } else {
3595
- if (cached) this.individualCache.delete(settingName);
3596
- uncachedSettings.push(settingName);
3597
- }
3598
- }
3599
- if (uncachedSettings.length > 0) {
3600
- this.logger.debug?.(`🔍 Batch fetching ${uncachedSettings.length} uncached settings: ${uncachedSettings.join(", ")}`);
3601
- const fetchStart = Date.now();
3602
- const settings = await db.adminSettings.findBySettingNames(uncachedSettings);
3603
- const fetchTime = Date.now() - fetchStart;
3604
- this.logger.debug?.(`📦 Batch fetched ${settings.length} settings in ${fetchTime}ms`);
3605
- const ttl = this.getTTL();
3606
- settings.forEach((setting) => {
3607
- result[setting.settingName] = setting.settingValue;
3608
- this.individualCache.set(setting.settingName, {
3609
- value: setting.settingValue,
3610
- timestamp: Date.now(),
3611
- ttl
3612
- });
3613
- });
3614
- uncachedSettings.forEach((settingName) => {
3615
- if (!settings.some((s) => s.settingName === settingName)) this.individualCache.set(settingName, {
3616
- value: null,
3617
- timestamp: Date.now(),
3618
- ttl
3619
- });
3620
- });
3621
- }
3622
- this.logger.debug?.(`📦 Returned ${Object.keys(result).length} settings (${settingNames.length - uncachedSettings.length} from cache, ${uncachedSettings.length} from DB)`);
3623
- return result;
3624
- }
3625
- /**
3626
- * Invalidate specific setting(s) from cache
3627
- */
3628
- invalidateSetting(settingName) {
3629
- this.individualCache.delete(settingName);
3630
- this.cache.delete("all_settings");
3631
- this.logger.info?.(`🗑️ Invalidated cache for setting: ${settingName}`);
3632
- }
3633
- /**
3634
- * Invalidate all cached admin settings
3635
- */
3636
- invalidateAll() {
3637
- this.cache.clear();
3638
- this.individualCache.clear();
3639
- this.logger.info?.("🗑️ Invalidated all admin settings cache");
3640
- }
3641
- /**
3642
- * Get cache statistics for monitoring
3643
- */
3644
- getStats() {
3645
- const estimateMemoryUsage = () => {
3646
- let totalSize = 0;
3647
- for (const [key, value] of Array.from(this.individualCache.entries())) {
3648
- totalSize += key.length * 2;
3649
- totalSize += (value.value?.length || 0) * 2;
3650
- totalSize += 32;
3651
- }
3652
- return totalSize;
3653
- };
3654
- return {
3655
- totalEntries: this.cache.size,
3656
- individualEntries: this.individualCache.size,
3657
- memoryUsage: {
3658
- approximate: `~${Math.round(estimateMemoryUsage() / 1024)}KB`,
3659
- cacheSize: this.cache.size,
3660
- individualCacheSize: this.individualCache.size
3661
- },
3662
- environment: {
3663
- isServerless: !!(process.env.VERCEL || process.env.AWS_LAMBDA_FUNCTION_NAME),
3664
- hasCleanupTimer: this.cleanupInterval !== null
3665
- }
3666
- };
3667
- }
3668
- /**
3669
- * Warm up the cache by fetching all settings
3670
- */
3671
- async warmUp(db) {
3672
- this.logger.info?.("🔥 Warming up admin settings cache...");
3673
- await this.getSettingsMap(db);
3674
- this.logger.info?.("✅ Admin settings cache warmed up");
3675
- }
3676
- /**
3677
- * Graceful shutdown - cleanup timers
3678
- */
3679
- shutdown() {
3680
- this.stopCleanupTimer();
3681
- this.logger.info?.("🛑 Admin settings cache shutdown complete");
3682
- }
3683
- };
3684
- let globalSettingsCache = null;
3685
- /**
3686
- * Get or create the global settings cache instance
3687
- */
3688
- function getSettingsCache(logger) {
3689
- if (!globalSettingsCache) globalSettingsCache = new AdminSettingsCache(logger || new Logger());
3690
- return globalSettingsCache;
3691
- }
3692
- function getSettingsValue(key, settings, defaultValue) {
3693
- if (key === "enforceCredits" && isEnforceCreditsLocked()) return true;
3694
- const settingConfig = resolveSettingDefinition(key);
3695
- if (!settingConfig) {
3696
- Logger.globalInstance.warn(`Unknown setting key: ${key}`);
3697
- return defaultValue;
3698
- }
3699
- const rawValue = settings[key];
3700
- const parsed = (key === "adminAiConfig" ? AdminAiStoredConfigSchema : settingConfig.schema).safeParse(rawValue);
3701
- if (parsed.success) {
3702
- if (parsed.data === "" && defaultValue !== void 0) return defaultValue;
3703
- return parsed.data;
3704
- } else return defaultValue !== void 0 ? defaultValue : settingConfig.defaultValue;
3705
- }
3706
- /**
3707
- * Retrieves all admin settings from the database and converts them into a key-value map.
3708
- * Uses caching for improved performance.
3709
- */
3710
- async function getSettingsMap(db, options) {
3711
- const logger = options?.logger;
3712
- if (options?.skipCache) return (options?.names ? await db.adminSettings.findBySettingNames(options.names) : await db.adminSettings.findAll()).reduce((out, s) => {
3713
- out[s.settingName] = s.settingValue;
3714
- return out;
3715
- }, {});
3716
- return getSettingsCache(logger).getSettingsMap(db);
3717
- }
3718
- /**
3719
- * Extracts the extension from a file name and returns it in lowercase without the leading dot.
3720
- *
3721
- * @param fileName
3722
- * @returns `string`
3723
- */
3724
- const getFileExtension = (fileName) => {
3725
- return path.extname(fileName).toLowerCase().slice(1);
3726
- };
3727
- const hasFileExtension = (fileName) => getFileExtension(fileName) !== "";
3728
- const isExtensionlessFileName = (fileName) => !hasFileExtension(fileName) && !fileName.endsWith(".");
3729
- /**
3730
- * Returns the MIME type corresponding to a given file extension, or '' if unresolved.
3731
- */
3732
- const getMimeTypeByExtension = (ext) => {
3733
- const lowerExt = ext.toLowerCase();
3734
- return EXT_TO_MIME[lowerExt] ?? "";
3735
- };
3736
- /**
3737
- * Resolve the effective MIME type for an uploaded file: `mimeType` is what to persist (so the
3738
- * chunker keys on a type it can process) and `supported` gates ingest. Under the default
3739
- * `'extension-first'` a name whose extension does not resolve is refused outright, claim or no
3740
- * claim. `'claim-first'` exists for a claim that comes from a trusted server-side source rather
3741
- * than a client (Google Drive's stored metadata), where the user-renamable filename is worth less.
3742
- *
3743
- * @param fileName - Original file name (used to derive the extension).
3744
- * @param claimedMimeType - The claimed MIME type, if any.
3745
- * @param opts.isAcceptable - Predicate gating both extension- and claim-derived types; defaults
3746
- * to `isSupportedFabFileMimeType`.
3747
- * @param opts.precedence - Which of extension/claim is consulted first; defaults to
3748
- * `'extension-first'`.
3749
- * @param opts.extensionlessFallback - Type for a name carrying no extension at all (`LICENSE`,
3750
- * `.env`) that also carried no claim. Omit it to keep a door strict.
3751
- */
3752
- function resolveSupportedMimeType(fileName, claimedMimeType, opts = {}) {
3753
- const { isAcceptable = isSupportedFabFileMimeType, precedence = "extension-first", extensionlessFallback } = opts;
3754
- const ext = getFileExtension(fileName);
3755
- const byExtension = getMimeTypeByExtension(ext);
3756
- const extensionResult = byExtension ? {
3757
- mimeType: byExtension,
3758
- supported: isAcceptable(byExtension)
3759
- } : null;
3760
- if (!extensionResult && ext !== "" && precedence !== "claim-first") return {
3761
- mimeType: "",
3762
- supported: false
3763
- };
3764
- const claimResult = claimedMimeType && isAcceptable(claimedMimeType) ? {
3765
- mimeType: claimedMimeType,
3766
- supported: true
3767
- } : null;
3768
- const resolved = precedence === "claim-first" ? claimResult ?? extensionResult : extensionResult ?? claimResult;
3769
- if (resolved) return resolved;
3770
- if (extensionlessFallback && !claimedMimeType && isExtensionlessFileName(fileName)) return {
3771
- mimeType: extensionlessFallback,
3772
- supported: isAcceptable(extensionlessFallback)
3773
- };
3774
- return {
3775
- mimeType: "",
3776
- supported: false
3777
- };
3778
- }
3779
- const EXT_TO_MIME = Object.assign(Object.create(null), {
3780
- txt: SupportedFabFileMimeTypes.TXT_PLAIN,
3781
- ini: SupportedFabFileMimeTypes.TXT_PLAIN,
3782
- env: SupportedFabFileMimeTypes.TXT_PLAIN,
3783
- conf: SupportedFabFileMimeTypes.TXT_PLAIN,
3784
- log: SupportedFabFileMimeTypes.TXT_PLAIN,
3785
- sql: SupportedFabFileMimeTypes.TXT_PLAIN,
3786
- text: SupportedFabFileMimeTypes.TXT_PLAIN,
3787
- md: SupportedFabFileMimeTypes.TXT_MARKDOWN,
3788
- mdx: SupportedFabFileMimeTypes.TXT_MARKDOWN,
3789
- mmd: SupportedFabFileMimeTypes.TXT_PLAIN,
3790
- html: SupportedFabFileMimeTypes.HTML,
3791
- htm: SupportedFabFileMimeTypes.HTML,
3792
- shtml: SupportedFabFileMimeTypes.HTML,
3793
- csv: SupportedFabFileMimeTypes.CSV,
3794
- jpg: SupportedFabFileMimeTypes.JPG,
3795
- jpeg: SupportedFabFileMimeTypes.JPG,
3796
- jfif: SupportedFabFileMimeTypes.JPG,
3797
- jpe: SupportedFabFileMimeTypes.JPG,
3798
- png: SupportedFabFileMimeTypes.PNG,
3799
- gif: SupportedFabFileMimeTypes.GIF,
3800
- svg: SupportedFabFileMimeTypes.SVG,
3801
- webp: SupportedFabFileMimeTypes.WEBP,
3802
- pdf: SupportedFabFileMimeTypes.PDF,
3803
- json: SupportedFabFileMimeTypes.JSON,
3804
- xml: SupportedFabFileMimeTypes.XML,
3805
- docx: SupportedFabFileMimeTypes.DOCX,
3806
- pptx: SupportedFabFileMimeTypes.PPTX,
3807
- xlsx: SupportedFabFileMimeTypes.XLSX,
3808
- xls: SupportedFabFileMimeTypes.XLS,
3809
- js: SupportedFabFileMimeTypes.JS,
3810
- mjs: SupportedFabFileMimeTypes.JS,
3811
- cjs: SupportedFabFileMimeTypes.JS,
3812
- jsx: SupportedFabFileMimeTypes.JSX,
3813
- ts: SupportedFabFileMimeTypes.TS,
3814
- tsx: SupportedFabFileMimeTypes.TS,
3815
- py: SupportedFabFileMimeTypes.PY,
3816
- java: SupportedFabFileMimeTypes.JAVA,
3817
- cpp: SupportedFabFileMimeTypes.CPP,
3818
- c: SupportedFabFileMimeTypes.CPP,
3819
- h: SupportedFabFileMimeTypes.CPP,
3820
- cs: SupportedFabFileMimeTypes.CS,
3821
- php: SupportedFabFileMimeTypes.PHP,
3822
- rb: SupportedFabFileMimeTypes.RUBY,
3823
- go: SupportedFabFileMimeTypes.GO,
3824
- swift: SupportedFabFileMimeTypes.SWIFT,
3825
- kt: SupportedFabFileMimeTypes.KOTLIN,
3826
- rs: SupportedFabFileMimeTypes.RUST,
3827
- css: SupportedFabFileMimeTypes.CSS,
3828
- less: SupportedFabFileMimeTypes.LESS,
3829
- sass: SupportedFabFileMimeTypes.SASS,
3830
- scss: SupportedFabFileMimeTypes.SCSS,
3831
- yaml: SupportedFabFileMimeTypes.YAML,
3832
- yml: SupportedFabFileMimeTypes.YAML,
3833
- toml: SupportedFabFileMimeTypes.TOML,
3834
- sh: SupportedFabFileMimeTypes.SH,
3835
- bash: SupportedFabFileMimeTypes.BASH,
3836
- mp3: AudioMimeType.MP3,
3837
- wav: AudioMimeType.WAV,
3838
- opus: AudioMimeType.OPUS,
3839
- aac: AudioMimeType.AAC,
3840
- flac: AudioMimeType.FLAC,
3841
- pcm: AudioMimeType.PCM,
3842
- ogg: AudioMimeType.OGG,
3843
- webm: AudioMimeType.WEBM
3844
- });
3845
- /**
3846
- * Coerce any thrown value into a human-readable string.
3847
- *
3848
- * Handles the three common shapes:
3849
- * - Error -> .message
3850
- * - string -> as-is
3851
- * - other -> JSON.stringify with a safe fallback for circular/unstringifiable values
3852
- */
3853
- function extractErrorMessage(error) {
3854
- if (error instanceof Error) return error.message;
3855
- if (typeof error === "string") return error;
3856
- try {
3857
- return JSON.stringify(error);
3858
- } catch {
3859
- return "Unknown error";
3860
- }
3861
- }
3862
- /**
3863
- * Replaces IPv4 and IPv6 addresses in free text with `[IP]`. Used on log text bound for Slack:
3864
- * CloudWatch keeps the full address, the error channel does not (`errorLogSlackMessage.ts`).
3865
- *
3866
- * Both patterns are anchored so they do not fire inside longer tokens: `1.2.3.4.5`, `v1.2.3.4`,
3867
- * `10:00:00` timestamps, MAC addresses and `Foo::bar` paths are left alone. A bare four-part
3868
- * version string such as `1.2.3.4` is scrubbed; that costs nothing in an error card.
3869
- */
3870
- const OCTET = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)";
3871
- new RegExp(`(?<![\\w.])(?:${OCTET}\\.){3}${OCTET}(?!\\.?\\w)`, "g");
3872
- const HEX_GROUP = "[0-9a-f]{1,4}";
3873
- const HEX_RUN = `${HEX_GROUP}(?::${HEX_GROUP}){0,6}`;
3874
- new RegExp(`(?:(?<![\\w:])|(?<=(?<![\\w:])[0-9a-f]*[g-z_]\\w*:))(?:(?:${HEX_GROUP}:){7}${HEX_GROUP}|${HEX_RUN}::(?:${HEX_RUN})?|::${HEX_RUN})(?::\\[IP\\])?(?![\\w:])`, "gi");
3875
- ChatModels.GPT5, ChatModels.GPT5_MINI, ChatModels.GPT5_NANO, ChatModels.GPT5_1, ChatModels.GPT5_2, ChatModels.GPT5_4, ChatModels.GPT5_4_MINI, ChatModels.GPT5_4_NANO, ChatModels.GPT5_5, ChatModels.GPT5_6_SOL, ChatModels.GPT5_6_LUNA, ChatModels.GPT5_6_TERRA;
3876
- //#endregion
3877
- //#region ../sdk/dist/index.mjs
3878
- /**
3879
- * A non-2xx response. `message` is the envelope's `error` (`ErrorResponse` in the spec); branch on `status` and
3880
- * `errorCode`, never on the prose. The deprecated `name` field is deliberately not surfaced. An OAuth body
3881
- * (a snake_case `error` code + `error_description`, no `errorCode`) maps `error` to `errorCode` and
3882
- * `error_description` to `message`.
3883
- */
3884
- var B4mApiError = class B4mApiError extends Error {
3885
- status;
3886
- errorCode;
3887
- requestId;
3888
- retryAfterSeconds;
3889
- body;
3890
- headers;
3891
- constructor(status, body, headers) {
3892
- const record = body && typeof body === "object" ? body : {};
3893
- const error = typeof record.error === "string" ? record.error : void 0;
3894
- const description = typeof record.error_description === "string" ? record.error_description : void 0;
3895
- const oauth = typeof record.errorCode !== "string" && error !== void 0 && /^[a-z_]+$/.test(error) && description !== void 0;
3896
- super((oauth ? description : error) ?? `HTTP ${status}`);
3897
- this.name = "B4mApiError";
3898
- this.status = status;
3899
- this.body = body;
3900
- this.headers = headers;
3901
- if (oauth) this.errorCode = error;
3902
- else if (typeof record.errorCode === "string") this.errorCode = record.errorCode;
3903
- const requestId = typeof record.request_id === "string" ? record.request_id : headers.get("x-request-id");
3904
- if (requestId) this.requestId = requestId;
3905
- const retryAfterSeconds = parseRetryAfterSeconds(headers.get("retry-after"));
3906
- if (retryAfterSeconds !== void 0) this.retryAfterSeconds = retryAfterSeconds;
3907
- }
3908
- static async fromResponse(response) {
3909
- const text = await response.text().catch(() => "");
3910
- let body = text;
3911
- try {
3912
- body = JSON.parse(text);
3913
- } catch {}
3914
- return new B4mApiError(response.status, body, response.headers);
3915
- }
3916
- };
3917
- /**
3918
- * A completions stream that closed without `[DONE]` and without an `error` event: the connection was cut
3919
- * mid-response, so nothing about the request itself failed. Safe to retry when no output was used yet.
3920
- */
3921
- var B4mStreamEndedError = class extends Error {
3922
- constructor() {
3923
- super("completion stream ended before [DONE]");
3924
- this.name = "B4mStreamEndedError";
3925
- }
3926
- };
3927
- /**
3928
- * A polled quest (chat turn, image generation or edit) that did not succeed: it carries `type: "error"`
3929
- * (`reason: 'error'`), ended `stopped` (`'stopped'`), or was still running when the poll's `timeoutMs` ran out
3930
- * (`'timeout'`). `quest` is the last state seen; its `reply` carries the server's explanation.
3931
- */
3932
- var B4mQuestError = class extends Error {
3933
- reason;
3934
- quest;
3935
- constructor(reason, quest) {
3936
- super(reason === "timeout" ? `quest ${quest.id} still ${quest.status ?? "pending"} when the poll timed out` : quest.reply ?? `quest ${quest.id} ${reason === "error" ? "failed" : "was stopped"}`);
3937
- this.name = "B4mQuestError";
3938
- this.reason = reason;
3939
- this.quest = quest;
3940
- }
3941
- };
3942
- /**
3943
- * Normalize a Retry-After header (RFC 7231: delta-seconds or an HTTP-date) to whole, non-negative seconds;
3944
- * undefined when absent or unparseable.
3945
- */
3946
- function parseRetryAfterSeconds(value) {
3947
- if (value === void 0 || value === null) return void 0;
3948
- const raw = String(value).trim();
3949
- if (/^\d+$/.test(raw)) return Number(raw);
3950
- const dateMs = Date.parse(raw);
3951
- if (Number.isNaN(dateMs)) return void 0;
3952
- return Math.max(0, Math.ceil((dateMs - Date.now()) / 1e3));
3953
- }
3954
- const operations = {
3955
- addDataLakeFile: {
3956
- method: "POST",
3957
- path: "/api/v1/data-lakes/{id}/files/{file_id}"
3958
- },
3959
- addProjectFiles: {
3960
- method: "POST",
3961
- path: "/api/v1/projects/{id}/files"
3962
- },
3963
- addProjectSessions: {
3964
- method: "POST",
3965
- path: "/api/v1/projects/{id}/sessions"
3966
- },
3967
- addProjectSystemPrompts: {
3968
- method: "POST",
3969
- path: "/api/v1/projects/{id}/system-prompts"
3970
- },
3971
- approvePendingAction: {
3972
- method: "POST",
3973
- path: "/api/v1/pending-actions/{questId}/approve"
3974
- },
3975
- bulkDeleteFiles: {
3976
- method: "POST",
3977
- path: "/api/v1/files/bulk-delete"
3978
- },
3979
- cancelMusicGeneration: {
3980
- method: "POST",
3981
- path: "/api/v1/music-generations/{id}/cancel"
3982
- },
3983
- cancelSceneComposition: {
3984
- method: "POST",
3985
- path: "/api/v1/scene-compositions/{id}/cancel"
3986
- },
3987
- cancelVideoGeneration: {
3988
- method: "POST",
3989
- path: "/api/v1/video-generations/{id}/cancel"
3990
- },
3991
- chunkFile: {
3992
- method: "POST",
3993
- path: "/api/v1/files/{id}/chunk"
3994
- },
3995
- cloneSession: {
3996
- method: "POST",
3997
- path: "/api/v1/sessions/{id}/clone"
3998
- },
3999
- createAgent: {
4000
- method: "POST",
4001
- path: "/api/v1/agents"
4002
- },
4003
- createAgentFromContext: {
4004
- method: "POST",
4005
- path: "/api/v1/agents/from-context"
4006
- },
4007
- createArtifact: {
4008
- method: "POST",
4009
- path: "/api/v1/artifacts"
4010
- },
4011
- createArtifactVersion: {
4012
- method: "POST",
4013
- path: "/api/v1/artifacts/{id}/versions"
4014
- },
4015
- createCompletion: {
4016
- method: "POST",
4017
- path: "/api/ai/v1/completions"
4018
- },
4019
- createCompletionRun: {
4020
- method: "POST",
4021
- path: "/api/v1/completion-runs"
4022
- },
4023
- createDecision: {
4024
- method: "POST",
4025
- path: "/api/v1/decisions"
4026
- },
4027
- createEmbeddings: {
4028
- method: "POST",
4029
- path: "/api/v1/embeddings"
4030
- },
4031
- createFileUpload: {
4032
- method: "POST",
4033
- path: "/api/v1/files"
4034
- },
4035
- createMusicGeneration: {
4036
- method: "POST",
4037
- path: "/api/v1/music-generations"
4038
- },
4039
- createProject: {
4040
- method: "POST",
4041
- path: "/api/v1/projects"
4042
- },
4043
- createProjectInvite: {
4044
- method: "POST",
4045
- path: "/api/v1/projects/{id}/invites"
4046
- },
4047
- createSceneComposition: {
4048
- method: "POST",
4049
- path: "/api/v1/scene-compositions"
4050
- },
4051
- createSession: {
4052
- method: "POST",
4053
- path: "/api/v1/sessions"
4054
- },
4055
- createSkill: {
4056
- method: "POST",
4057
- path: "/api/v1/skills"
4058
- },
4059
- createTextRefinement: {
4060
- method: "POST",
4061
- path: "/api/v1/text-refinements"
4062
- },
4063
- createTranscription: {
4064
- method: "POST",
4065
- path: "/api/v1/transcriptions"
4066
- },
4067
- createTranscriptionUpload: {
4068
- method: "POST",
4069
- path: "/api/v1/transcriptions/uploads"
4070
- },
4071
- createVideoGeneration: {
4072
- method: "POST",
4073
- path: "/api/v1/video-generations"
4074
- },
4075
- createVoiceSession: {
4076
- method: "POST",
4077
- path: "/api/v1/voice/sessions"
4078
- },
4079
- deleteAgent: {
4080
- method: "DELETE",
4081
- path: "/api/v1/agents/{id}"
4082
- },
4083
- deleteArtifact: {
4084
- method: "DELETE",
4085
- path: "/api/v1/artifacts/{id}"
4086
- },
4087
- deleteFile: {
4088
- method: "DELETE",
4089
- path: "/api/v1/files/{id}"
4090
- },
4091
- deletePersona: {
4092
- method: "DELETE",
4093
- path: "/api/v1/personas/{id}"
4094
- },
4095
- deleteProject: {
4096
- method: "DELETE",
4097
- path: "/api/v1/projects/{id}"
4098
- },
4099
- deleteSession: {
4100
- method: "DELETE",
4101
- path: "/api/sessions/{id}"
4102
- },
4103
- deleteSessionMessage: {
4104
- method: "DELETE",
4105
- path: "/api/v1/sessions/{id}/messages/{messageId}"
4106
- },
4107
- denyPendingAction: {
4108
- method: "POST",
4109
- path: "/api/v1/pending-actions/{questId}/deny"
4110
- },
4111
- editImage: {
4112
- method: "POST",
4113
- path: "/api/v1/image-edits"
4114
- },
4115
- endVoiceSession: {
4116
- method: "POST",
4117
- path: "/api/v1/voice/sessions/{id}/end"
4118
- },
4119
- enhanceAgentField: {
4120
- method: "POST",
4121
- path: "/api/v1/agents/{id}/enhance-field"
4122
- },
4123
- executeTool: {
4124
- method: "POST",
4125
- path: "/api/ai/v1/tools"
4126
- },
4127
- fetchWebPage: {
4128
- method: "POST",
4129
- path: "/api/v1/tools/web-fetch"
4130
- },
4131
- generateAgentAvatar: {
4132
- method: "POST",
4133
- path: "/api/v1/agents/{id}/generate-avatar"
4134
- },
4135
- generateAgentDescription: {
4136
- method: "POST",
4137
- path: "/api/v1/agents/{id}/generate-description"
4138
- },
4139
- generateAgentSystemPrompt: {
4140
- method: "POST",
4141
- path: "/api/v1/agents/{id}/generate-system-prompt"
4142
- },
4143
- generateImage: {
4144
- method: "POST",
4145
- path: "/api/v1/image-generations"
4146
- },
4147
- generateMusic: {
4148
- method: "POST",
4149
- path: "/api/ai/music"
4150
- },
4151
- generateSoundEffect: {
4152
- method: "POST",
4153
- path: "/api/ai/sound-effects"
4154
- },
4155
- getAgent: {
4156
- method: "GET",
4157
- path: "/api/v1/agents/{id}"
4158
- },
4159
- getAgentExecution: {
4160
- method: "GET",
4161
- path: "/api/v1/agent-executions/{id}"
4162
- },
4163
- getArtifact: {
4164
- method: "GET",
4165
- path: "/api/v1/artifacts/{id}"
4166
- },
4167
- getArtifactVersion: {
4168
- method: "GET",
4169
- path: "/api/v1/artifacts/{id}/versions/{version}"
4170
- },
4171
- getClaudeBundleZip: {
4172
- method: "GET",
4173
- path: "/api/v1/skills/market/bundles/{id}/claude-plugin.zip"
4174
- },
4175
- getClaudeMarketplace: {
4176
- method: "GET",
4177
- path: "/api/v1/skills/market/claude-marketplace.json"
4178
- },
4179
- getClaudePluginZip: {
4180
- method: "GET",
4181
- path: "/api/v1/skills/market/{id}/claude-plugin.zip"
4182
- },
4183
- getClientConfig: {
4184
- method: "GET",
4185
- path: "/api/v1/client-config"
4186
- },
4187
- getCompletionRunUsage: {
4188
- method: "GET",
4189
- path: "/api/v1/completion-runs/{runId}/usage"
4190
- },
4191
- getCreditBalance: {
4192
- method: "GET",
4193
- path: "/api/v1/credits"
4194
- },
4195
- getCurrentWeather: {
4196
- method: "POST",
4197
- path: "/api/v1/tools/weather"
4198
- },
4199
- getDataLake: {
4200
- method: "GET",
4201
- path: "/api/v1/data-lakes/{id}"
4202
- },
4203
- getDataLakeFile: {
4204
- method: "GET",
4205
- path: "/api/v1/data-lakes/{id}/files/{file_id}"
4206
- },
4207
- getFile: {
4208
- method: "GET",
4209
- path: "/api/v1/files/{id}"
4210
- },
4211
- getFileLineage: {
4212
- method: "GET",
4213
- path: "/api/v1/files/{id}/lineage"
4214
- },
4215
- getFilesByIds: {
4216
- method: "GET",
4217
- path: "/api/v1/files/by-ids"
4218
- },
4219
- getMe: {
4220
- method: "GET",
4221
- path: "/api/v1/me"
4222
- },
4223
- getMusicGeneration: {
4224
- method: "GET",
4225
- path: "/api/v1/music-generations/{id}"
4226
- },
4227
- getProject: {
4228
- method: "GET",
4229
- path: "/api/v1/projects/{id}"
4230
- },
4231
- getPublicClientConfig: {
4232
- method: "GET",
4233
- path: "/api/v1/client-config/public"
4234
- },
4235
- getQuest: {
4236
- method: "GET",
4237
- path: "/api/v1/quests/{id}"
4238
- },
4239
- getSceneComposition: {
4240
- method: "GET",
4241
- path: "/api/v1/scene-compositions/{id}"
4242
- },
4243
- getSession: {
4244
- method: "GET",
4245
- path: "/api/sessions/{id}"
4246
- },
4247
- getSessionMessage: {
4248
- method: "GET",
4249
- path: "/api/v1/sessions/{id}/messages/{messageId}"
4250
- },
4251
- getSkill: {
4252
- method: "GET",
4253
- path: "/api/v1/skills/{id}"
4254
- },
4255
- getSkillMarketListing: {
4256
- method: "GET",
4257
- path: "/api/v1/skills/market/listings/{id}"
4258
- },
4259
- getVideoGeneration: {
4260
- method: "GET",
4261
- path: "/api/v1/video-generations/{id}"
4262
- },
4263
- getWhatsNewMedia: {
4264
- method: "GET",
4265
- path: "/api/v1/whats-new/media/{id}/{asset}"
4266
- },
4267
- importSkillMarketListing: {
4268
- method: "POST",
4269
- path: "/api/v1/skills/market/listings/{id}/import"
4270
- },
4271
- listAgents: {
4272
- method: "GET",
4273
- path: "/api/v1/agents"
4274
- },
4275
- listArtifactTypes: {
4276
- method: "GET",
4277
- path: "/api/v1/artifacts/types"
4278
- },
4279
- listArtifactVersions: {
4280
- method: "GET",
4281
- path: "/api/v1/artifacts/{id}/versions"
4282
- },
4283
- listArtifacts: {
4284
- method: "GET",
4285
- path: "/api/v1/artifacts"
4286
- },
4287
- listCreditTransactions: {
4288
- method: "GET",
4289
- path: "/api/v1/credits/transactions"
4290
- },
4291
- listDataLakes: {
4292
- method: "GET",
4293
- path: "/api/v1/data-lakes"
4294
- },
4295
- listDecisionModels: {
4296
- method: "GET",
4297
- path: "/api/v1/decision-models"
4298
- },
4299
- listEmbeddingModels: {
4300
- method: "GET",
4301
- path: "/api/v1/embedding-models"
4302
- },
4303
- listFiles: {
4304
- method: "GET",
4305
- path: "/api/v1/files"
4306
- },
4307
- listImageModels: {
4308
- method: "GET",
4309
- path: "/api/v1/image-models"
4310
- },
4311
- listModels: {
4312
- method: "GET",
4313
- path: "/api/v1/models"
4314
- },
4315
- listMusicGenerations: {
4316
- method: "GET",
4317
- path: "/api/v1/music-generations"
4318
- },
4319
- listMusicModels: {
4320
- method: "GET",
4321
- path: "/api/v1/music-models"
4322
- },
4323
- listMySkillMarketListings: {
4324
- method: "GET",
4325
- path: "/api/v1/skills/market/listings/mine"
4326
- },
4327
- listMySkills: {
4328
- method: "GET",
4329
- path: "/api/v1/skills/mine"
4330
- },
4331
- listProjectFiles: {
4332
- method: "GET",
4333
- path: "/api/v1/projects/{id}/files"
4334
- },
4335
- listProjectInvites: {
4336
- method: "GET",
4337
- path: "/api/v1/projects/{id}/invites"
4338
- },
4339
- listProjectSessions: {
4340
- method: "GET",
4341
- path: "/api/v1/projects/{id}/sessions"
4342
- },
4343
- listProjects: {
4344
- method: "GET",
4345
- path: "/api/v1/projects"
4346
- },
4347
- listQuestFiles: {
4348
- method: "GET",
4349
- path: "/api/v1/quests/{id}/files"
4350
- },
4351
- listSceneCompositions: {
4352
- method: "GET",
4353
- path: "/api/v1/scene-compositions"
4354
- },
4355
- listSessionFiles: {
4356
- method: "GET",
4357
- path: "/api/v1/sessions/{id}/files"
4358
- },
4359
- listSessionQuests: {
4360
- method: "GET",
4361
- path: "/api/v1/sessions/{id}/quests"
4362
- },
4363
- listSessions: {
4364
- method: "GET",
4365
- path: "/api/v1/sessions"
4366
- },
4367
- listSkillMarketListings: {
4368
- method: "GET",
4369
- path: "/api/v1/skills/market/listings"
4370
- },
4371
- listSkillMarketReviewQueue: {
4372
- method: "GET",
4373
- path: "/api/v1/skills/market/review-queue"
4374
- },
4375
- listVideoGenerations: {
4376
- method: "GET",
4377
- path: "/api/v1/video-generations"
4378
- },
4379
- listVideoModels: {
4380
- method: "GET",
4381
- path: "/api/v1/video-models"
4382
- },
4383
- listVoices: {
4384
- method: "GET",
4385
- path: "/api/v1/voice/voices"
4386
- },
4387
- listWhatsNew: {
4388
- method: "GET",
4389
- path: "/api/v1/whats-new"
4390
- },
4391
- mintPersona: {
4392
- method: "POST",
4393
- path: "/api/v1/personas"
4394
- },
4395
- postSlackMessage: {
4396
- method: "POST",
4397
- path: "/api/v1/slack/messages"
4398
- },
4399
- publishSkillMarketListing: {
4400
- method: "POST",
4401
- path: "/api/v1/skills/market/listings"
4402
- },
4403
- registerPushToken: {
4404
- method: "POST",
4405
- path: "/api/v1/push-tokens"
4406
- },
4407
- removeDataLakeFile: {
4408
- method: "DELETE",
4409
- path: "/api/v1/data-lakes/{id}/files/{file_id}"
4410
- },
4411
- removeProjectFile: {
4412
- method: "DELETE",
4413
- path: "/api/v1/projects/{id}/files/{file_id}"
4414
- },
4415
- removeProjectMember: {
4416
- method: "DELETE",
4417
- path: "/api/v1/projects/{id}/members/{user_id}"
4418
- },
4419
- removeProjectSession: {
4420
- method: "DELETE",
4421
- path: "/api/v1/projects/{id}/sessions/{session_id}"
4422
- },
4423
- removeProjectSystemPrompt: {
4424
- method: "DELETE",
4425
- path: "/api/v1/projects/{id}/system-prompts/{file_id}"
4426
- },
4427
- rescanSkillMarketVersion: {
4428
- method: "POST",
4429
- path: "/api/v1/skills/market/versions/{vid}/rescan"
4430
- },
4431
- reviewSkillMarketVersion: {
4432
- method: "POST",
4433
- path: "/api/v1/skills/market/versions/{vid}/review"
4434
- },
4435
- searchArtifacts: {
4436
- method: "GET",
4437
- path: "/api/v1/artifacts/search"
4438
- },
4439
- searchDataLake: {
4440
- method: "POST",
4441
- path: "/api/v1/data-lakes/{id}/search"
4442
- },
4443
- searchFiles: {
4444
- method: "GET",
4445
- path: "/api/v1/files/search"
4446
- },
4447
- searchSessions: {
4448
- method: "POST",
4449
- path: "/api/v1/sessions/semantic-search"
4450
- },
4451
- searchWeb: {
4452
- method: "POST",
4453
- path: "/api/v1/tools/web-search"
4454
- },
4455
- sendChatMessage: {
4456
- method: "POST",
4457
- path: "/api/chat"
4458
- },
4459
- startAgentExecution: {
4460
- method: "POST",
4461
- path: "/api/v1/agent-executions"
4462
- },
4463
- submitSkillMarketListingVersion: {
4464
- method: "POST",
4465
- path: "/api/v1/skills/market/listings/{id}/versions"
4466
- },
4467
- synthesizeSpeech: {
4468
- method: "POST",
4469
- path: "/api/ai/tts"
4470
- },
4471
- transferAgentCredits: {
4472
- method: "POST",
4473
- path: "/api/v1/agents/{id}/transfer-credits"
4474
- },
4475
- unregisterPushToken: {
4476
- method: "DELETE",
4477
- path: "/api/v1/push-tokens"
4478
- },
4479
- updateAgent: {
4480
- method: "PATCH",
4481
- path: "/api/v1/agents/{id}"
4482
- },
4483
- updateArtifact: {
4484
- method: "PATCH",
4485
- path: "/api/v1/artifacts/{id}"
4486
- },
4487
- updateFile: {
4488
- method: "PATCH",
4489
- path: "/api/v1/files/{id}"
4490
- },
4491
- updateProject: {
4492
- method: "PATCH",
4493
- path: "/api/v1/projects/{id}"
4494
- },
4495
- updateProjectSystemPrompt: {
4496
- method: "PATCH",
4497
- path: "/api/v1/projects/{id}/system-prompts/{file_id}"
4498
- },
4499
- updateSession: {
4500
- method: "PUT",
4501
- path: "/api/sessions/{id}"
4502
- },
4503
- updateSessionMessage: {
4504
- method: "PUT",
4505
- path: "/api/v1/sessions/{id}/messages/{messageId}"
4506
- },
4507
- updateSkill: {
4508
- method: "PUT",
4509
- path: "/api/v1/skills/{id}"
4510
- },
4511
- withdrawSkillMarketListing: {
4512
- method: "DELETE",
4513
- path: "/api/v1/skills/market/listings/{id}"
4514
- }
4515
- };
4516
- /**
4517
- * Yield each server-sent event's `data` from a fetch body, until `[DONE]`, the end of the stream, or `signal`
4518
- * aborts (which throws the signal's reason). `onDone` is called when `[DONE]` is seen, so a caller can tell it
4519
- * from a truncated stream. Breaking out of the loop early cancels the body.
4520
- */
4521
- async function* parseSse(body, signal, onDone) {
4522
- const queue = [];
4523
- const parser = createParser({ onEvent: (event) => queue.push(event.data) });
4524
- const reader = body.getReader();
4525
- const decoder = new TextDecoder();
4526
- const onAbort = () => void reader.cancel().catch(() => {});
4527
- signal?.addEventListener("abort", onAbort, { once: true });
4528
- let finished = false;
4529
- try {
4530
- for (;;) {
4531
- signal?.throwIfAborted();
4532
- const { done, value } = await reader.read();
4533
- signal?.throwIfAborted();
4534
- parser.feed(done ? decoder.decode() : decoder.decode(value, { stream: true }));
4535
- while (queue.length > 0) {
4536
- const data = queue.shift();
4537
- if (data === "[DONE]") {
4538
- onDone?.();
4539
- return;
4540
- }
4541
- yield data;
4542
- }
4543
- if (done) {
4544
- finished = true;
4545
- return;
4546
- }
4547
- }
4548
- } finally {
4549
- signal?.removeEventListener("abort", onAbort);
4550
- if (!finished) await reader.cancel().catch(() => {});
4551
- }
4552
- }
4553
- const ABSOLUTE_URL = /^https?:\/\//i;
4554
- function buildUrl(baseUrl, path, params, query) {
4555
- const values = params ?? {};
4556
- const resolved = path.replace(/\{([^}]+)\}/g, (_, name) => {
4557
- const value = values[name];
4558
- if (value === void 0 || value === null || value === "" || value === "." || value === "..") throw new Error(`Invalid path parameter ${name}: ${JSON.stringify(value)}`);
4559
- return encodeURIComponent(String(value));
4560
- });
4561
- const search = new URLSearchParams();
4562
- for (const [key, value] of Object.entries(query ?? {})) for (const item of Array.isArray(value) ? value : [value]) if (item !== void 0 && item !== null) search.append(key, String(item));
4563
- const qs = search.toString();
4564
- const relative = resolved.startsWith("/") ? resolved : `/${resolved}`;
4565
- const url = ABSOLUTE_URL.test(resolved) ? resolved : `${baseUrl.replace(/\/+$/, "")}${relative}`;
4566
- return qs ? `${url}${url.includes("?") ? "&" : "?"}${qs}` : url;
4567
- }
4568
- function assertBaseUrl(baseUrl, caller = "createClient") {
4569
- let parsed;
4570
- try {
4571
- parsed = new URL(baseUrl);
4572
- } catch {
4573
- throw new Error(`${caller}: baseUrl must be an absolute http(s) URL, got ${JSON.stringify(baseUrl)}`);
4574
- }
4575
- if (!/^https?:$/.test(parsed.protocol) || parsed.search || parsed.hash) throw new Error(`${caller}: baseUrl must be an http(s) URL with no query or fragment, got ${JSON.stringify(baseUrl)}`);
4576
- }
4577
- function createClient(options) {
4578
- if (!options.baseUrl) throw new Error("createClient: baseUrl is required");
4579
- assertBaseUrl(options.baseUrl);
4580
- const fetchImpl = options.fetch ?? globalThis.fetch;
4581
- async function send(method, path, args = {}) {
4582
- const headers = new Headers(options.headers);
4583
- for (const [name, value] of Object.entries(args.headers ?? {})) headers.set(name, value);
4584
- const token = await options.getAuthToken?.() || options.apiKey;
4585
- if (token) headers.set("authorization", `Bearer ${token}`);
4586
- let body;
4587
- if (args.body !== void 0) {
4588
- headers.set("content-type", "application/json");
4589
- body = JSON.stringify(args.body);
4590
- }
4591
- const response = await fetchImpl(buildUrl(options.baseUrl, path, args.params, args.query), {
4592
- method,
4593
- headers,
4594
- body,
4595
- signal: args.signal,
4596
- ...args.redirect ? { redirect: args.redirect } : {}
4597
- });
4598
- if (!response.ok) throw await B4mApiError.fromResponse(response);
4599
- return response;
4600
- }
4601
- /** Any spec operation, returning the raw 2xx `Response` (for binary or streamed bodies). Non-2xx throws. */
4602
- function raw(operationId, ...[args]) {
4603
- const { method, path } = operations[operationId];
4604
- return send(method, path, args);
4605
- }
4606
- /** Any spec operation, typed from the spec; returns the parsed JSON body (`undefined` for an empty one). A non-JSON 2xx body throws. */
4607
- async function call(operationId, ...rest) {
4608
- const response = await raw(operationId, ...rest);
4609
- const text = await response.text();
4610
- const contentType = response.headers.get("content-type") ?? "";
4611
- if (text && !/json/i.test(contentType)) throw new Error(`${operationId} returned ${contentType || "a non-JSON body"}; use raw(), completions() or the tts/music/soundEffects helpers`);
4612
- return text ? JSON.parse(text) : void 0;
4613
- }
4614
- async function pollQuest(questId, poll = {}) {
4615
- const { intervalMs = 1e3, maxIntervalMs = 5e3, timeoutMs, signal } = poll;
4616
- const deadline = timeoutMs === void 0 ? void 0 : Date.now() + timeoutMs;
4617
- let delay = intervalMs;
4618
- for (;;) {
4619
- const quest = await call("getQuest", {
4620
- params: { id: questId },
4621
- signal
4622
- });
4623
- if (quest.status === "stopped") throw new B4mQuestError("stopped", quest);
4624
- if (quest.type === "error") throw new B4mQuestError("error", quest);
4625
- if (quest.status === "done") return quest;
4626
- if (deadline !== void 0 && Date.now() + delay > deadline) throw new B4mQuestError("timeout", quest);
4627
- await sleep(delay, signal);
4628
- delay = Math.min(delay * 1.5, maxIntervalMs);
4629
- }
4630
- }
4631
- const questHandle = (questId, ack) => ({
4632
- questId,
4633
- ack,
4634
- poll: (poll) => pollQuest(questId, poll)
4635
- });
4636
- async function audio(operationId, body, signal) {
4637
- const { method, path } = operations[operationId];
4638
- const response = await send(method, path, {
4639
- body: {
4640
- ...body,
4641
- encoding: "base64"
4642
- },
4643
- signal
4644
- });
4645
- const contentType = response.headers.get("content-type") ?? "application/octet-stream";
4646
- if (/json/i.test(contentType)) return await response.json();
4647
- const saved = response.headers.get("x-b4m-audio-saved") === "true";
4648
- const header = (name) => saved ? response.headers.get(name) ?? void 0 : void 0;
4649
- const result = {
4650
- delivery: "inline",
4651
- audio: toBase64(new Uint8Array(await response.arrayBuffer())),
4652
- contentType,
4653
- saved
4654
- };
4655
- const fabFileId = header("x-b4m-audio-fab-file-id");
4656
- const fileName = header("x-b4m-audio-file-name");
4657
- const fileUrl = header("x-b4m-audio-file-url");
4658
- if (fabFileId) result.fabFileId = fabFileId;
4659
- if (fileName) result.fileName = fileName;
4660
- if (fileUrl) result.fileUrl = fileUrl;
4661
- return result;
4662
- }
4663
- return {
4664
- call,
4665
- raw,
4666
- /**
4667
- * Stream `POST /api/ai/v1/completions` as parsed events. A non-2xx before the stream throws `B4mApiError`; a
4668
- * server `{ type: 'error' }` event is yielded, not thrown. A stream that ends without `[DONE]` and without an
4669
- * error event throws. `url` overrides the path: an absolute http(s) URL is used as-is, anything else is joined
4670
- * under `baseUrl`. An absolute `url` receives the same `Authorization` header, so pass only an origin you trust.
4671
- */
4672
- async *completions(body, opts = {}) {
4673
- const response = await send("POST", opts.url ?? operations.createCompletion.path, {
4674
- body,
4675
- signal: opts.signal,
4676
- headers: {
4677
- accept: "text/event-stream",
4678
- ...opts.headers
4679
- }
4680
- });
4681
- if (!response.body) return;
4682
- let sawDone = false;
4683
- let sawError = false;
4684
- for await (const data of parseSse(response.body, opts.signal, () => {
4685
- sawDone = true;
4686
- })) {
4687
- let event;
4688
- try {
4689
- event = JSON.parse(data);
4690
- } catch {
4691
- continue;
4692
- }
4693
- if (event.type === "error") sawError = true;
4694
- yield event;
4695
- }
4696
- if (!sawDone && !sawError) throw new B4mStreamEndedError();
4697
- },
4698
- /** `POST /api/chat`, queued (the default): the turn's outcome is on the returned handle's `poll()`. */
4699
- async chat(body, opts = {}) {
4700
- const ack = await call("sendChatMessage", {
4701
- body,
4702
- signal: opts.signal
4703
- });
4704
- return questHandle(ack.id, ack);
4705
- },
4706
- async generateImage(body, opts = {}) {
4707
- const ack = await call("generateImage", {
4708
- body,
4709
- signal: opts.signal
4710
- });
4711
- return questHandle(ack.quest.id, ack);
4712
- },
4713
- /** Edited images arrive on the finished quest's `files[].url`. */
4714
- async editImage(body, opts = {}) {
4715
- const ack = await call("editImage", {
4716
- body,
4717
- signal: opts.signal
4718
- });
4719
- return questHandle(ack.id, ack);
4720
- },
4721
- pollQuest,
4722
- async tts(body, opts = {}) {
4723
- try {
4724
- return {
4725
- kind: "audio",
4726
- data: await audio("synthesizeSpeech", body, opts.signal)
4727
- };
4728
- } catch (error) {
4729
- const tooLarge = error instanceof B4mApiError && error.status === 413 ? error : void 0;
4730
- const data = tooLarge?.body;
4731
- if (!tooLarge || !data?.saved || typeof data.fabFileId !== "string" || typeof data.provider !== "string") throw error;
4732
- const fallbackFrom = tooLarge.headers.get("x-b4m-tts-provider-fallback-from");
4733
- const result = {
4734
- kind: "saved-too-large",
4735
- data: {
4736
- ...data,
4737
- fabFileId: data.fabFileId
4738
- }
4739
- };
4740
- if (fallbackFrom) result.fallbackFrom = fallbackFrom;
4741
- return result;
4742
- }
4743
- },
4744
- /**
4745
- * @deprecated `POST /api/ai/music` sunsets 2027-01-15. Queue a job with
4746
- * `call('createMusicGeneration', ...)` and poll `getMusicGeneration` instead.
4747
- */
4748
- music(body, opts = {}) {
4749
- return audio("generateMusic", body, opts.signal);
4750
- },
4751
- soundEffects(body, opts = {}) {
4752
- return audio("generateSoundEffect", body, opts.signal);
4753
- }
4754
- };
4755
- }
4756
- function sleep(ms, signal) {
4757
- return new Promise((resolve, reject) => {
4758
- if (signal?.aborted) return reject(signal.reason);
4759
- const onAbort = () => {
4760
- clearTimeout(timer);
4761
- reject(signal?.reason);
4762
- };
4763
- const timer = setTimeout(() => {
4764
- signal?.removeEventListener("abort", onAbort);
4765
- resolve();
4766
- }, ms);
4767
- signal?.addEventListener("abort", onAbort, { once: true });
4768
- });
4769
- }
4770
- function toBase64(bytes) {
4771
- let binary = "";
4772
- for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
4773
- return btoa(binary);
4774
- }
4775
- //#endregion
4776
- export { extractErrorMessage as a, resolveSupportedMimeType as c, BaseStorage as d, isPrivateIP as f, parseRetryAfterSeconds as i, OllamaBackend as l, B4mStreamEndedError as n, getSettingsMap as o, Logger as p, createClient as r, getSettingsValue as s, B4mApiError as t, OpenAICompatibleBackend as u };