@bike4mind/cli 4.0.0 → 4.6.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 (51) hide show
  1. package/README.md +86 -4
  2. package/bin/bike4mind-cli.mjs +249 -40
  3. package/bin/envFlags.d.mts +17 -0
  4. package/bin/envFlags.mjs +89 -0
  5. package/dist/{AgentHistoryStore-DgqmcVLN.mjs → AgentHistoryStore--J3sgO_-.mjs} +3794 -1368
  6. package/dist/{ApiClient-_JrM_xWw.mjs → ApiClient-CdO4Gamg.mjs} +22 -3
  7. package/dist/BubblewrapRuntime-3jAbC60G.mjs +157 -0
  8. package/dist/ConfigStore-CausUCzY.mjs +2 -0
  9. package/dist/ConfigStore-Dusy6glb.mjs +3364 -0
  10. package/dist/{ConfigStore-BwqsQ0U9.mjs → Logger-C1Wj6xla.mjs} +32672 -21643
  11. package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
  12. package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-CQwYq_uy.mjs} +26 -7
  13. package/dist/SandboxRuntimeAdapter-BsT2iLky.mjs +190 -0
  14. package/dist/SandboxRuntimeAdapter-Zg_0th7V.mjs +2 -0
  15. package/dist/SeatbeltRuntime-C2DEkrjy.mjs +194 -0
  16. package/dist/{WorkItemsClient-CERTDrhT.mjs → WorkItemsClient-CxNZaOmc.mjs} +1 -1
  17. package/dist/agents/defaults/review.md +8 -1
  18. package/dist/agents/defaults/test.md +8 -1
  19. package/dist/buildToolSearch-DOb7mx6F.mjs +417 -0
  20. package/dist/commands/acpCommand.mjs +25 -19
  21. package/dist/commands/apiCommand.mjs +3 -5
  22. package/dist/commands/doctorCommand.mjs +2 -2
  23. package/dist/commands/envCommand.mjs +1 -1
  24. package/dist/commands/headlessCommand.mjs +117 -36
  25. package/dist/commands/hostCommand.mjs +2344 -0
  26. package/dist/commands/mcpCommand.mjs +45 -30
  27. package/dist/commands/mirrorCommand.mjs +279 -0
  28. package/dist/commands/modelsCommand.mjs +1117 -0
  29. package/dist/commands/pluginCommand.mjs +9 -9
  30. package/dist/commands/skillsCommand.mjs +174 -29
  31. package/dist/commands/updateCommand.mjs +2 -2
  32. package/dist/curated-build.json +1 -0
  33. package/dist/dist-CbViwiS9.mjs +4739 -0
  34. package/dist/dist-Citbv0y0.mjs +7864 -0
  35. package/dist/fit-CVWDiavv.mjs +200 -0
  36. package/dist/index.mjs +853 -417
  37. package/dist/modelHub-BSB6qRFP.mjs +1963 -0
  38. package/dist/modelServers-BaegigV-.mjs +2465 -0
  39. package/dist/{package-CQaam4Dq.mjs → package-C9pfAdGF.mjs} +1 -1
  40. package/dist/{serve-CFxUhjml.mjs → serve-8wyGb8of.mjs} +595 -26
  41. package/dist/types-BFIvwByC.mjs +2 -0
  42. package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
  43. package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-BAKb8KWP.mjs} +7 -29
  44. package/package.json +16 -13
  45. package/dist/BubblewrapRuntime-5bLPTwEC.mjs +0 -72
  46. package/dist/SandboxRuntimeAdapter-BgLUVTJL.mjs +0 -57
  47. package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +0 -2
  48. package/dist/SeatbeltRuntime-C_Y8q8Mr.mjs +0 -124
  49. package/dist/buildToolSearch-D9GEK91u.mjs +0 -2351
  50. package/dist/dist-Ul2qwn5x.mjs +0 -624
  51. package/dist/types-I45lMh7Q.mjs +0 -2
@@ -1,2351 +0,0 @@
1
- #!/usr/bin/env node
2
- import { F as generateCliTools, G as createToolSearchTool, U as DeferredToolRegistry, V as buildSystemPrompt, W as ReActAgent, Y as setWebSocketToolExecutor, Z as getPlanModeFilePath, a as loadProjectContext, c as createSseBackend, i as buildProjectAgentStore, l as ServerLlmBackend, n as BackgroundAgentManager, o as McpManager, q as wrapTools, r as SubagentOrchestrator, st as Logger, t as AgentHistoryStore } from "./AgentHistoryStore-DgqmcVLN.mjs";
3
- import { $ as ModelBackend, A as ARTIFACT_REMOVED_PLACEHOLDER, At as isUserInitiatedAbort, B as ChatModels, Et as hasDeliverablePinnedArtifact, Gt as visibleReplyText, P as AudioMimeType, R as CONTEXT_WINDOW_SAFETY_BUFFER_TOKENS, Rt as stripDeliveredArtifactBlocks, V as CompletionReasoningEffortSchema, Z as MODEL_INFO_FIELD_GROUP_OF, b as logger, bt as escapeThinkMarkers, dt as TTS_MAX_INPUT_CHARS, it as PermissionDeniedError, k as ARTIFACT_DELIVERED_PLACEHOLDER, lt as SupportedFabFileMimeTypes, ut as TTS_DEFAULT_MODEL, vt as completionsSupportsToolSearch, wt as getQuestErrorCode, xt as filterToolArtifactMarkup, yt as createThinkMarkerEscaper, zt as stripToolArtifactMarkup } from "./ConfigStore-BwqsQ0U9.mjs";
4
- import "crypto";
5
- import "path";
6
- import { v4 } from "uuid";
7
- import "axios";
8
- import "node:crypto";
9
- import "@aws-sdk/client-bedrock-runtime";
10
- import "openai";
11
- import "file-type";
12
- import "@anthropic-ai/sdk";
13
- import "@aws-sdk/client-cloudwatch";
14
- import "@anthropic-ai/sdk/core/streaming";
15
- import "@google/genai";
16
- import "lodash/pick.js";
17
- import "openai/streaming";
18
- import { Ollama } from "ollama";
19
- import { Agent } from "undici";
20
- import "@aws-sdk/client-sqs";
21
- import "@aws-sdk/client-apigatewaymanagementapi";
22
- import "@aws-sdk/client-lambda";
23
- import WebSocket from "ws";
24
- ChatModels.KIMI_K2_THINKING_BEDROCK, ChatModels.KIMI_K2_5_BEDROCK, ChatModels.DEEPSEEK_R1_BEDROCK, ChatModels.DEEPSEEK_FLASH, ChatModels.DEEPSEEK_V4_PRO, ChatModels.KIMI_K3;
25
- 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_BEDROCK;
26
- ChatModels.CLAUDE_5_SONNET, ChatModels.CLAUDE_5_SONNET_BEDROCK, 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;
27
- ModelBackend.Anthropic, ModelBackend.Gemini, ModelBackend.XAI, ModelBackend.Ollama, ModelBackend.BFL, ModelBackend.LocalImage, ModelBackend.AWS;
28
- //#endregion
29
- //#region ../../b4m-core/llm-adapters/dist/index.mjs
30
- /**
31
- * A tool failure that must end the turn rather than be fed back to the model as a
32
- * recoverable observation: a declined tool (PermissionDeniedError) or an out-of-credits
33
- * error (tagged via `getQuestErrorCode`), neither of which any retry can satisfy.
34
- * Also exempts these from the services tool failure guard (toolFailureGuard.ts).
35
- */
36
- function isTerminalToolError(error) {
37
- return error instanceof PermissionDeniedError || getQuestErrorCode(error) !== void 0;
38
- }
39
- /** Whether the named tool is flagged `endsTurnAfterText` in the offered tool list. */
40
- function isTurnEndingTool(name, tools) {
41
- return tools?.find((tool) => tool.toolSchema.name === name)?.endsTurnAfterText === true;
42
- }
43
- /**
44
- * Whether the tool loop should end the turn after this round's tool batch instead of making
45
- * the follow-up model call. True only when the round already streamed non-empty answer text
46
- * AND every tool it called is flagged `endsTurnAfterText`: the follow-up round would only
47
- * repeat the answer. A tool-only round still recurses so the model gets to answer.
48
- *
49
- * The single decision point for every adapter's tool loop - keep them from drifting.
50
- */
51
- function shouldEndTurnAfterTools(calledToolNames, tools, roundText) {
52
- const names = calledToolNames.filter((name) => Boolean(name));
53
- if (names.length === 0 || !visibleReplyText(roundText).trim()) return false;
54
- return names.every((name) => isTurnEndingTool(name, tools));
55
- }
56
- /**
57
- * Execute an array of async tasks either in parallel (with concurrency limiting)
58
- * or sequentially, returning outcomes in the original order.
59
- *
60
- * Terminal errors (see isTerminalToolError) are always re-thrown immediately: sequential
61
- * breaks the loop on the first one; parallel runs every task to completion (inherent to
62
- * Promise.allSettled) then pre-scans outcomes before returning - accepted because these
63
- * errors are rare in multi-tool batches.
64
- *
65
- * Fault isolation: uses Promise.allSettled so a single failure doesn't abort the batch.
66
- * Order preservation: results are indexed back to the original task array.
67
- */
68
- async function executeToolsBatch(tasks, options) {
69
- const { parallel, maxConcurrency = 8 } = options;
70
- if (parallel && tasks.length > 1) {
71
- const outcomes = (await runWithConcurrency(tasks, maxConcurrency)).map((s) => s.status === "fulfilled" ? {
72
- ok: true,
73
- result: s.value
74
- } : {
75
- ok: false,
76
- error: s.reason
77
- });
78
- for (const outcome of outcomes) if (!outcome.ok && isTerminalToolError(outcome.error)) throw outcome.error;
79
- return outcomes;
80
- }
81
- const outcomes = [];
82
- for (const task of tasks) try {
83
- const result = await task();
84
- outcomes.push({
85
- ok: true,
86
- result
87
- });
88
- } catch (error) {
89
- if (isTerminalToolError(error)) throw error;
90
- outcomes.push({
91
- ok: false,
92
- error
93
- });
94
- }
95
- return outcomes;
96
- }
97
- /**
98
- * Run tasks with bounded concurrency using a worker-pool pattern.
99
- * Spawns up to `limit` workers that pull from a shared task queue.
100
- * Results are stored by index to preserve original ordering.
101
- */
102
- async function runWithConcurrency(tasks, limit) {
103
- if (limit >= tasks.length) return Promise.allSettled(tasks.map((fn) => fn()));
104
- const results = new Array(tasks.length);
105
- let nextIndex = 0;
106
- async function worker() {
107
- while (nextIndex < tasks.length) {
108
- const index = nextIndex++;
109
- try {
110
- results[index] = {
111
- status: "fulfilled",
112
- value: await tasks[index]()
113
- };
114
- } catch (reason) {
115
- results[index] = {
116
- status: "rejected",
117
- reason
118
- };
119
- }
120
- }
121
- }
122
- const workerCount = Math.min(limit, tasks.length);
123
- await Promise.all(Array.from({ length: workerCount }, () => worker()));
124
- return results;
125
- }
126
- /**
127
- * Attaches a tool call's outcome onto its `toolsUsed` entry so it survives into
128
- * `promptMeta.functionCalls.returnValue`/`.success` (see ChatCompletionProcess.ts's mapper
129
- * and utils.ts's `replayableToolCalls`, which gates a whole replay path on at least one
130
- * recorded `returnValue`). Every backend pushes a `toolsUsed` entry before executing the
131
- * tool and only learns the real outcome a few lines later - this is the merge-back.
132
- */
133
- /**
134
- * Cap applied to a persisted `returnValue` before it reaches Mongo (chars, not bytes). Also the
135
- * cap on what a later turn replays back to the model for this call (utils.ts's Priority 2
136
- * reconstruction reads the same persisted, already-truncated value) - this is not a
137
- * persistence-only limit, it is what a continued conversation sees of an older tool result too.
138
- */
139
- const MAX_RECORDED_TOOL_RESULT_CHARS = 8e3;
140
- const TOOL_RESULT_TRUNCATION_NOTICE = "\n[tool result truncated]";
141
- /** Cap on the in-memory full result (chars). */
142
- const MAX_FULL_TOOL_RESULT_CHARS = 2e5;
143
- const FULL_TOOL_RESULT_KEY = "__b4mFullToolResult";
144
- function truncateToolResult(observation) {
145
- if (observation.length <= 8e3) return observation;
146
- return observation.slice(0, MAX_RECORDED_TOOL_RESULT_CHARS) + TOOL_RESULT_TRUNCATION_NOTICE;
147
- }
148
- /**
149
- * Keeps the untruncated result on the entry for the reply parser's echo check (see
150
- * buildToolEchoSources in services). It is non-enumerable so JSON.stringify and spreads skip it:
151
- * `toolsUsed` also leaves the process whole (Research Mode streams each callback's completionInfo
152
- * over the websocket, where API Gateway caps a post at 128 KB), and it must never be persisted.
153
- */
154
- function attachFullToolResult(entry, observation) {
155
- const text = String(observation);
156
- const value = {
157
- text: text.slice(0, MAX_FULL_TOOL_RESULT_CHARS),
158
- truncated: text.length > MAX_FULL_TOOL_RESULT_CHARS
159
- };
160
- Object.defineProperty(entry, FULL_TOOL_RESULT_KEY, {
161
- value,
162
- enumerable: false,
163
- configurable: true,
164
- writable: true
165
- });
166
- }
167
- /** The `artifactType` the named tool declared at registration, for the helpers below. */
168
- function declaredArtifactType(tools, toolName) {
169
- return tools?.find((t) => t.toolSchema.name === toolName)?.artifactType;
170
- }
171
- /**
172
- * Helper function to handle tool result streaming for artifact-generating tools
173
- * This ensures tools like recharts that generate artifacts are streamed immediately
174
- * rather than waiting for recursive completion calls.
175
- *
176
- * Only the emitters in TOOL_ARTIFACT_EMITTERS (or a tool that declared `artifactType`, see
177
- * declaredArtifactType) stream, and only their pinned artifact type: streamed text is parsed
178
- * into reply artifacts, so any other tool's markup would render.
179
- *
180
- * What does stream is still a raw tool artifact rather than reply prose, so `streamCallback`
181
- * receives the channel tag and a public surface drops the text on that tag alone.
182
- */
183
- async function handleToolResultStreaming(toolName, toolResult, streamCallback, artifactType) {
184
- const filtered = filterToolArtifactMarkup(toolName, String(toolResult), artifactType);
185
- if (filtered !== null) await streamCallback([filtered], { channel: "tool-artifact" });
186
- }
187
- /**
188
- * Strips artifact markup from a tool result before it re-enters history, so the model cannot echo
189
- * it into a second card. Live-emitting backends pass `delivered` = whether their tool-artifact
190
- * emit fired. The `hasDeliverablePinnedArtifact` fallback is for the OpenAI Responses path, whose
191
- * artifact reaches the client through sharedToolBuilder extraction instead.
192
- *
193
- * The delivered/removed choice is made once per result and stamped on every block it contains.
194
- * That holds because each emitter emits one pinned block; a result mixing a foreign-type block
195
- * with a pinned one would label both DELIVERED.
196
- */
197
- function stripUnstreamedToolResult(toolName, result, delivered) {
198
- return stripToolArtifactMarkup(result, delivered ?? hasDeliverablePinnedArtifact(toolName, result) ? ARTIFACT_DELIVERED_PLACEHOLDER : ARTIFACT_REMOVED_PLACEHOLDER);
199
- }
200
- /**
201
- * Buffers a recursive completion's text instead of streaming it live, so an <artifact> tag the
202
- * model echoes back (after seeing its own tool result, even sanitized) can be stripped before the
203
- * client ever renders a second, empty card for it. Only removes blocks whose `identifier` matches
204
- * one already delivered this turn (stripDeliveredArtifactBlocks) - a stray "<artifact" the model's
205
- * prose merely mentions, or a genuinely NEW artifact the model composes with a different
206
- * identifier, must not cost the rest of a legitimate reply, unlike the tool-output-facing
207
- * stripToolArtifactMarkup.
208
- *
209
- * One instance is created lazily by whichever level first streams an artifact in a recursive
210
- * chain, and reused UNCHANGED by every deeper level (never recreated per level) - see each
211
- * backend's `_internal.artifactGuard`. A chained tool call's artifact goes through `emitArtifact`
212
- * on this same shared instance, which flushes any text already buffered ahead of it before
213
- * sending the artifact through - so ordering survives even when the chained call happens several
214
- * recursion levels below where the guard was created.
215
- */
216
- function createRecursiveArtifactGuard(cb) {
217
- let buffer = "";
218
- let deliveredMarkup = "";
219
- let meta = {};
220
- const callback = (async (text, info) => {
221
- for (const chunk of text) if (chunk != null) buffer += chunk;
222
- if (info?.inputTokens || info?.outputTokens) meta = { ...info };
223
- });
224
- const emitArtifact = async (results, info) => {
225
- if (buffer) {
226
- const pending = buffer;
227
- buffer = "";
228
- const stripped = stripDeliveredArtifactBlocks(pending, deliveredMarkup);
229
- if (stripped.trim()) await cb([stripped], {});
230
- }
231
- deliveredMarkup += results.join("");
232
- await cb(results, info);
233
- };
234
- const markDelivered = (markup) => {
235
- deliveredMarkup += markup;
236
- };
237
- let flushPromise = null;
238
- const flush = () => {
239
- if (flushPromise) return flushPromise;
240
- const cleaned = stripDeliveredArtifactBlocks(buffer, deliveredMarkup).trim();
241
- let resolve;
242
- let reject;
243
- flushPromise = new Promise((res, rej) => {
244
- resolve = res;
245
- reject = rej;
246
- });
247
- (async () => cb(cleaned ? [cleaned] : [], meta))().then(() => resolve(), reject);
248
- return flushPromise;
249
- };
250
- return {
251
- callback,
252
- emitArtifact,
253
- markDelivered,
254
- flush
255
- };
256
- }
257
- /**
258
- * Drops the messages whose instructions assume a tool is attached (see `IMessage.requiresTool`).
259
- *
260
- * Call this wherever a turn continues with tools removed. Re-sending "you MUST use the X tool" on a
261
- * call that carries no tools leaves the model no valid move, and it answers by emitting the tool call
262
- * as text in the reply - which is exactly what the callers that inject those prompts gate against
263
- * when they decide whether to add them in the first place.
264
- *
265
- * Drops on the presence of the marker, not on which tool it names, because every call site today
266
- * removes the whole tool set at once. A site that ever drops only SOME tools would need to compare
267
- * `requiresTool` against the survivors instead.
268
- */
269
- const stripToolDependentMessages = (messages) => messages.filter((message) => !message.requiresTool);
270
- /**
271
- * Anthropic's hard ceiling on `cache_control` markers per request. Exceeding it fails the
272
- * WHOLE request with `ValidationException: A maximum of 4 blocks with cache_control may be
273
- * provided`, which is non-retryable - so an over-budget request loses the turn outright,
274
- * after the user has already waited for it.
275
- * See https://docs.claude.com/en/docs/build-with-claude/prompt-caching (tools, system and messages
276
- * all count toward the same four).
277
- */
278
- const MAX_CACHE_CONTROL_BLOCKS = 4;
279
- /**
280
- * Does this block already carry a marker? Re-marking one costs no budget.
281
- *
282
- * Tests the VALUE, not just key presence: a block carrying an explicit
283
- * `cache_control: undefined` is not a marker as far as the provider is concerned, and counting
284
- * it would spend budget on nothing and drop a breakpoint we could have kept.
285
- */
286
- function hasMarker(block) {
287
- return !!block && typeof block === "object" && !!block.cache_control;
288
- }
289
- /**
290
- * Markers already on the request. Callers upstream attach their own before this runs -
291
- * `bedrockBackend/anthropic.ts` marks each system block flagged `cache: true` (the mid-stack
292
- * shareable-prefix breakpoint) - so this adapter's budget is whatever they left, not the full four.
293
- */
294
- function censusMarkers(params) {
295
- const { tools, system, messages } = markerSites(params);
296
- return {
297
- tools: tools.length,
298
- system: system.length,
299
- messages: messages.length,
300
- total: tools.length + system.length + messages.length
301
- };
302
- }
303
- function markerSites(params) {
304
- const sitesIn = (region, value) => Array.isArray(value) ? value.flatMap((block, index) => hasMarker(block) ? [{
305
- region,
306
- index
307
- }] : []) : [];
308
- const messages = [];
309
- if (Array.isArray(params.messages)) params.messages.forEach((message, messageIndex) => {
310
- const content = message?.content;
311
- if (!Array.isArray(content)) return;
312
- content.forEach((block, index) => {
313
- const inner = block?.content;
314
- if (Array.isArray(inner)) inner.forEach((innerBlock, nested) => {
315
- if (hasMarker(innerBlock)) messages.push({
316
- region: "messages",
317
- index,
318
- message: messageIndex,
319
- nested
320
- });
321
- });
322
- if (hasMarker(block)) messages.push({
323
- region: "messages",
324
- index,
325
- message: messageIndex
326
- });
327
- });
328
- });
329
- return {
330
- tools: sitesIn("tools", params.tools),
331
- system: sitesIn("system", params.system),
332
- messages
333
- };
334
- }
335
- /**
336
- * Anthropic-specific caching adapter
337
- * Adds explicit cache_control markers to content blocks
338
- */
339
- var AnthropicCachingAdapter = class {
340
- applyCaching(apiParams, strategy, logger) {
341
- if (!strategy.enableCaching) return apiParams;
342
- const ttl = strategy.cacheTTL ?? "5m";
343
- const modifiedParams = { ...apiParams };
344
- const cacheControl = {
345
- type: "ephemeral",
346
- ...ttl === "1h" ? { ttl } : {}
347
- };
348
- const inbound = censusMarkers(modifiedParams);
349
- let budget = MAX_CACHE_CONTROL_BLOCKS - inbound.total;
350
- const dropped = [];
351
- /** Claim one marker slot, or record the miss. Re-marking a marked block is free. */
352
- const claim = (name, alreadyMarked) => {
353
- if (alreadyMarked) return true;
354
- if (budget <= 0) {
355
- dropped.push(name);
356
- return false;
357
- }
358
- budget -= 1;
359
- return true;
360
- };
361
- const systemParam = modifiedParams.system;
362
- if (strategy.cacheSystemPrompt && systemParam) {
363
- const systemArray = Array.isArray(systemParam) ? [...systemParam] : [{
364
- type: "text",
365
- text: systemParam
366
- }];
367
- if (systemArray.length > 0) {
368
- const lastBlock = systemArray[systemArray.length - 1];
369
- if (claim("system", hasMarker(lastBlock))) {
370
- systemArray[systemArray.length - 1] = {
371
- ...lastBlock,
372
- cache_control: cacheControl
373
- };
374
- modifiedParams.system = systemArray;
375
- }
376
- }
377
- }
378
- const messagesParam = modifiedParams.messages;
379
- if (strategy.cacheConversationHistory && Array.isArray(messagesParam) && messagesParam.length > 0) {
380
- const messages = [...messagesParam];
381
- let anchorIndex = messages.length - 1 - (strategy.historyCacheExcludeTrailingCount ?? 0);
382
- while (anchorIndex >= 0 && messages[anchorIndex].role === "system") anchorIndex--;
383
- if (anchorIndex >= 0) {
384
- const anchorMsg = messages[anchorIndex];
385
- const msgContent = anchorMsg.content;
386
- let contentArray;
387
- if (typeof msgContent === "string") contentArray = [{
388
- type: "text",
389
- text: msgContent
390
- }];
391
- else if (Array.isArray(msgContent)) contentArray = [...msgContent];
392
- if (contentArray && contentArray.length > 0) {
393
- const lastBlock = contentArray[contentArray.length - 1];
394
- if (claim("history", hasMarker(lastBlock))) {
395
- contentArray[contentArray.length - 1] = {
396
- ...lastBlock,
397
- cache_control: cacheControl
398
- };
399
- messages[anchorIndex] = {
400
- ...anchorMsg,
401
- content: contentArray
402
- };
403
- modifiedParams.messages = messages;
404
- }
405
- }
406
- }
407
- }
408
- const tools = modifiedParams.tools;
409
- const markIndex = Array.isArray(tools) ? tools.findLastIndex((t) => {
410
- const tool = t;
411
- const isServerTool = typeof tool.type === "string" && !("input_schema" in tool);
412
- return tool.defer_loading !== true && !isServerTool;
413
- }) : -1;
414
- if (strategy.cacheTools && Array.isArray(tools) && markIndex >= 0) {
415
- const toolsCopy = [...tools];
416
- const markTool = toolsCopy[markIndex];
417
- if (claim("tools", hasMarker(markTool))) {
418
- toolsCopy[markIndex] = {
419
- ...markTool,
420
- cache_control: cacheControl
421
- };
422
- modifiedParams.tools = toolsCopy;
423
- }
424
- }
425
- const outbound = censusMarkers(modifiedParams);
426
- const census = {
427
- inbound,
428
- outbound,
429
- limit: MAX_CACHE_CONTROL_BLOCKS
430
- };
431
- if (outbound.total >= MAX_CACHE_CONTROL_BLOCKS) {
432
- const message = "[PromptCache] cache_control census at the ceiling";
433
- if (logger) logger.info(message, census);
434
- else console.info(message, JSON.stringify(census));
435
- } else if (logger) logger.debug("[PromptCache] cache_control census", census);
436
- if (outbound.total > MAX_CACHE_CONTROL_BLOCKS) {
437
- 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`;
438
- const detail = {
439
- inbound,
440
- outbound,
441
- limit: MAX_CACHE_CONTROL_BLOCKS
442
- };
443
- if (logger) logger.warn(message, detail);
444
- else console.warn(message, JSON.stringify(detail));
445
- } else if (dropped.length > 0) {
446
- const message = `[PromptCache] cache_control budget exhausted (limit ${MAX_CACHE_CONTROL_BLOCKS}); skipped breakpoints: ${dropped.join(", ")}`;
447
- const detail = {
448
- dropped,
449
- inbound,
450
- outbound,
451
- limit: MAX_CACHE_CONTROL_BLOCKS
452
- };
453
- if (logger) logger.warn(message, detail);
454
- else console.warn(message, JSON.stringify(detail));
455
- }
456
- return modifiedParams;
457
- }
458
- extractCacheStats(response, model) {
459
- const usage = response.usage;
460
- if (!usage) return void 0;
461
- const cacheReadTokens = usage.cache_read_input_tokens || 0;
462
- const cacheWriteTokens = usage.cache_creation_input_tokens || 0;
463
- const uncachedTokens = usage.input_tokens || 0;
464
- const totalInputTokens = cacheReadTokens + cacheWriteTokens + uncachedTokens;
465
- const cacheHitRate = totalInputTokens > 0 ? cacheReadTokens / totalInputTokens * 100 : 0;
466
- const costSavingsPercent = cacheHitRate * .9;
467
- const estimatedLatencyReduction = cacheHitRate * .85;
468
- return {
469
- provider: ModelBackend.Anthropic,
470
- model,
471
- totalInputTokens,
472
- cacheReadTokens,
473
- cacheWriteTokens,
474
- uncachedTokens,
475
- cacheHitRate,
476
- costSavingsPercent,
477
- estimatedLatencyReduction,
478
- providerMetadata: { hadCacheWrite: cacheWriteTokens > 0 }
479
- };
480
- }
481
- };
482
- /**
483
- * OpenAI-specific caching adapter
484
- * OpenAI caching is AUTOMATIC - no explicit markers needed
485
- * Just ensure static content is at the beginning of prompts
486
- */
487
- var OpenAICachingAdapter = class {
488
- applyCaching(apiParams, strategy) {
489
- return apiParams;
490
- }
491
- extractCacheStats(response, model) {
492
- const usage = response.usage;
493
- if (!usage) return void 0;
494
- const totalInputTokens = usage.prompt_tokens || 0;
495
- const cachedTokens = usage.prompt_tokens_details?.cached_tokens || 0;
496
- const cacheHitRate = totalInputTokens > 0 ? cachedTokens / totalInputTokens * 100 : 0;
497
- const costSavingsPercent = cacheHitRate * .9;
498
- const estimatedLatencyReduction = cacheHitRate * .8;
499
- return {
500
- provider: ModelBackend.OpenAI,
501
- model,
502
- totalInputTokens,
503
- cacheReadTokens: cachedTokens,
504
- cacheWriteTokens: 0,
505
- uncachedTokens: totalInputTokens - cachedTokens,
506
- cacheHitRate,
507
- costSavingsPercent,
508
- estimatedLatencyReduction,
509
- providerMetadata: { automatic: true }
510
- };
511
- }
512
- };
513
- /**
514
- * Gemini-specific caching adapter
515
- * Gemini 2.5+ supports IMPLICIT (automatic) caching by default
516
- * Explicit caching via Vertex AI API is optional (not implemented yet)
517
- */
518
- var GeminiCachingAdapter = class {
519
- applyCaching(apiParams, strategy) {
520
- return apiParams;
521
- }
522
- extractCacheStats(response, model) {
523
- const usage = response.usageMetadata;
524
- if (!usage) return void 0;
525
- const totalInputTokens = usage.promptTokenCount || 0;
526
- const cachedTokens = usage.cachedContentTokenCount || 0;
527
- const cacheHitRate = totalInputTokens > 0 ? cachedTokens / totalInputTokens * 100 : 0;
528
- const costSavingsPercent = cacheHitRate * (model.includes("2.5") ? .9 : .75);
529
- const estimatedLatencyReduction = cacheHitRate * .75;
530
- return {
531
- provider: ModelBackend.Gemini,
532
- model,
533
- totalInputTokens,
534
- cacheReadTokens: cachedTokens,
535
- cacheWriteTokens: 0,
536
- uncachedTokens: totalInputTokens - cachedTokens,
537
- cacheHitRate,
538
- costSavingsPercent,
539
- estimatedLatencyReduction,
540
- providerMetadata: { implicit: true }
541
- };
542
- }
543
- };
544
- /**
545
- * Cached prompt tokens from a raw provider usage object, across every spelling in use:
546
- * OpenAI Chat Completions nests them under `prompt_tokens_details`, the OpenAI
547
- * Responses API under `input_tokens_details`, Moonshot publishes a flat
548
- * `cached_tokens` alongside the OpenAI-shaped nesting, and DeepSeek its own flat
549
- * `prompt_cache_hit_tokens`. Reading only one spelling silently bills every cache
550
- * hit on the other transports at the full input rate.
551
- *
552
- * DeepSeek's own spelling leads, because it is the number its invoice is computed
553
- * from; the OpenAI-shaped ones it also sends are the fallback for a proxy that
554
- * forwards only those.
555
- */
556
- function cachedTokensFromUsage(usage) {
557
- if (!usage) return 0;
558
- const candidates = [
559
- usage.prompt_cache_hit_tokens,
560
- usage.cached_tokens,
561
- usage.prompt_tokens_details?.cached_tokens,
562
- usage.input_tokens_details?.cached_tokens
563
- ];
564
- for (const value of candidates) if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
565
- return 0;
566
- }
567
- /**
568
- * xAI Grok-specific caching adapter
569
- * Caching is automatic with optional conversation ID for cache affinity
570
- */
571
- var XAICachingAdapter = class {
572
- applyCaching(apiParams, strategy) {
573
- return apiParams;
574
- }
575
- getHeaders(strategy) {
576
- const headers = {};
577
- if (strategy.conversationId) headers["x-grok-conv-id"] = strategy.conversationId;
578
- return headers;
579
- }
580
- extractCacheStats(response, model) {
581
- const usage = response.usage;
582
- if (!usage) return void 0;
583
- const totalInputTokens = usage.prompt_tokens || 0;
584
- const cachedTokens = cachedTokensFromUsage(usage);
585
- const cacheHitRate = totalInputTokens > 0 ? cachedTokens / totalInputTokens * 100 : 0;
586
- const costSavingsPercent = cacheHitRate * .65;
587
- const estimatedLatencyReduction = cacheHitRate * .7;
588
- return {
589
- provider: ModelBackend.XAI,
590
- model,
591
- totalInputTokens,
592
- cacheReadTokens: cachedTokens,
593
- cacheWriteTokens: 0,
594
- uncachedTokens: totalInputTokens - cachedTokens,
595
- cacheHitRate,
596
- costSavingsPercent,
597
- estimatedLatencyReduction,
598
- providerMetadata: {
599
- automatic: true,
600
- conversationId: usage.x_grok_conv_id
601
- }
602
- };
603
- }
604
- };
605
- /**
606
- * Moonshot (Kimi) context caching. Automatic, like xAI's: there is no parameter,
607
- * no header, and no explicit cache-creation call. A prompt only becomes cacheable
608
- * once it exceeds 256 tokens, so short turns legitimately report a 0% hit rate.
609
- * @see https://platform.kimi.ai/docs/guide/use-context-caching-feature-of-kimi-api
610
- */
611
- var KimiCachingAdapter = class {
612
- applyCaching(apiParams, _strategy) {
613
- return apiParams;
614
- }
615
- extractCacheStats(response, model) {
616
- const usage = response.usage;
617
- if (!usage) return void 0;
618
- const totalInputTokens = usage.prompt_tokens || 0;
619
- const details = usage.prompt_tokens_details;
620
- const cachedTokens = usage.cached_tokens || details?.cached_tokens || 0;
621
- const cacheHitRate = totalInputTokens > 0 ? cachedTokens / totalInputTokens * 100 : 0;
622
- const costSavingsPercent = cacheHitRate * .9;
623
- const estimatedLatencyReduction = cacheHitRate * .7;
624
- return {
625
- provider: ModelBackend.Kimi,
626
- model,
627
- totalInputTokens,
628
- cacheReadTokens: cachedTokens,
629
- cacheWriteTokens: 0,
630
- uncachedTokens: Math.max(0, totalInputTokens - cachedTokens),
631
- cacheHitRate,
632
- costSavingsPercent,
633
- estimatedLatencyReduction,
634
- providerMetadata: {
635
- automatic: true,
636
- minimumCacheablePromptTokens: 256
637
- }
638
- };
639
- }
640
- };
641
- /**
642
- * DeepSeek context caching. Automatic, like Moonshot's and xAI's: no parameter,
643
- * no header, no explicit cache-creation call. The adapter exists only to read
644
- * the counters back out.
645
- * @see https://api-docs.deepseek.com/guides/kv_cache
646
- */
647
- var DeepSeekCachingAdapter = class {
648
- applyCaching(apiParams, _strategy) {
649
- return apiParams;
650
- }
651
- extractCacheStats(response, model) {
652
- const usage = response.usage;
653
- if (!usage) return void 0;
654
- const totalInputTokens = usage.prompt_tokens || 0;
655
- const cachedTokens = cachedTokensFromUsage(usage);
656
- const cacheHitRate = totalInputTokens > 0 ? cachedTokens / totalInputTokens * 100 : 0;
657
- const costSavingsPercent = cacheHitRate * .98;
658
- const estimatedLatencyReduction = cacheHitRate * .7;
659
- return {
660
- provider: ModelBackend.DeepSeek,
661
- model,
662
- totalInputTokens,
663
- cacheReadTokens: cachedTokens,
664
- cacheWriteTokens: 0,
665
- uncachedTokens: Math.max(0, totalInputTokens - cachedTokens),
666
- cacheHitRate,
667
- costSavingsPercent,
668
- estimatedLatencyReduction,
669
- providerMetadata: { automatic: true }
670
- };
671
- }
672
- };
673
- /**
674
- * No-op adapter for providers without caching support
675
- */
676
- var NoOpCachingAdapter = class {
677
- applyCaching(apiParams) {
678
- return apiParams;
679
- }
680
- extractCacheStats() {}
681
- };
682
- 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.BFL, new NoOpCachingAdapter(), ModelBackend.VoyageAI, new NoOpCachingAdapter(), ModelBackend.AWS, new NoOpCachingAdapter(), ModelBackend.LocalImage, new NoOpCachingAdapter();
683
- new Logger();
684
- 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;
685
- 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;
686
- /**
687
- * Models served by ConverseBedrockBackend. Adding a Converse-compatible Bedrock model is a
688
- * `ChatModels` entry plus a record here: routing (getLlmByModel's Bedrock branch), the
689
- * Bedrock listing (UndifferentiatedBedrockBackend) and request shaping all read this table.
690
- */
691
- const CONVERSE_BEDROCK_MODELS = [{
692
- id: ChatModels.NOVA_PRO_BEDROCK,
693
- type: "text",
694
- name: "Amazon Nova Pro",
695
- backend: ModelBackend.Bedrock,
696
- contextWindow: 3e5,
697
- max_tokens: 1e4,
698
- can_stream: true,
699
- pricing: { 3e5: {
700
- input: 8e-7,
701
- output: 32e-7
702
- } },
703
- inlineReasoningTag: "thinking",
704
- supportsVision: true,
705
- supportsTools: true,
706
- supportsImageVariation: false,
707
- releaseDate: "2024-12-03",
708
- rank: 5,
709
- description: "Amazon's Nova Pro via AWS Bedrock - multimodal (text and images), tool use, and a 300K-token context window."
710
- }];
711
- new Set(CONVERSE_BEDROCK_MODELS.map((m) => String(m.id)));
712
- ChatModels.DEEPSEEK_R1_BEDROCK, ModelBackend.Bedrock, ChatModels.DEEPSEEK_V3_1, ModelBackend.Bedrock;
713
- /** Ollama `done_reason` (chat/generate responses). */
714
- function normalizeOllamaDoneReason(reason) {
715
- if (!reason) return void 0;
716
- switch (reason) {
717
- case "length": return "max_tokens";
718
- default: return reason;
719
- }
720
- }
721
- ChatModels.DEEPSEEK_FLASH, ChatModels.DEEPSEEK_V4_PRO;
722
- /** Type guard: does this message already carry OpenAI-style `tool_calls`? */
723
- function hasToolCalls(msg) {
724
- return msg.role === "assistant" && "tool_calls" in msg;
725
- }
726
- function isToolUseBlock(block) {
727
- return block.type === "tool_use";
728
- }
729
- function isToolResultBlock(block) {
730
- return block.type === "tool_result";
731
- }
732
- function isTextBlock(block) {
733
- return block.type === "text";
734
- }
735
- /**
736
- * Convert a single IMessage from B4M standard format to OpenAI-compatible format.
737
- * Returns an array because a single user message with multiple tool_result blocks
738
- * expands into multiple OpenAI 'tool' role messages.
739
- *
740
- * Messages already in OpenAI format (with `tool_calls` property) pass through unchanged.
741
- * Messages without tool_use/tool_result content blocks pass through unchanged.
742
- */
743
- function convertMessageToOpenAIFormat(msg, options = {}) {
744
- if (hasToolCalls(msg)) {
745
- const reasoningContent = msg.reasoning_content;
746
- return [{
747
- role: "assistant",
748
- content: null,
749
- tool_calls: msg.tool_calls,
750
- ...options.preserveReasoningContent && typeof reasoningContent === "string" ? { reasoning_content: reasoningContent } : {}
751
- }];
752
- }
753
- if (msg.role === "assistant" && Array.isArray(msg.content)) {
754
- const contentBlocks = msg.content;
755
- const toolUseBlocks = contentBlocks.filter(isToolUseBlock);
756
- if (toolUseBlocks.length > 0) {
757
- const textParts = contentBlocks.filter(isTextBlock).map((block) => block.text).filter(Boolean);
758
- return [{
759
- role: "assistant",
760
- content: textParts.length > 0 ? textParts.join("\n") : null,
761
- tool_calls: toolUseBlocks.map((block) => ({
762
- id: block.id,
763
- type: "function",
764
- function: {
765
- name: block.name,
766
- arguments: JSON.stringify(block.input)
767
- }
768
- }))
769
- }];
770
- }
771
- }
772
- if (msg.role === "user" && Array.isArray(msg.content)) {
773
- const toolResultBlocks = msg.content.filter(isToolResultBlock);
774
- if (toolResultBlocks.length > 0) return toolResultBlocks.map((block) => ({
775
- role: "tool",
776
- content: block.content,
777
- tool_call_id: block.tool_use_id
778
- }));
779
- }
780
- if (msg.requiresTool !== void 0 || msg.cache !== void 0 || msg.perTurn !== void 0) {
781
- const { requiresTool: _requiresTool, cache: _cache, perTurn: _perTurn, ...providerSafe } = msg;
782
- return [providerSafe];
783
- }
784
- return [msg];
785
- }
786
- /**
787
- * Convert an array of IMessages from B4M standard format to OpenAI-compatible format.
788
- * Returns OpenAIFormattedMessage[] - callers targeting OpenAI SDK types should cast at the boundary.
789
- */
790
- function convertMessagesToOpenAIFormat(messages, options = {}) {
791
- return messages.flatMap((msg) => convertMessageToOpenAIFormat(msg, options));
792
- }
793
- ChatModels.KIMI_K3;
794
- ChatModels.KIMI_K2_7_CODE, ChatModels.KIMI_K2_7_CODE_HIGHSPEED, ChatModels.KIMI_K2_6, ChatModels.KIMI_K2_5;
795
- ChatModels.KIMI_K2_7_CODE, ChatModels.KIMI_K2_7_CODE_HIGHSPEED;
796
- ChatModels.KIMI_K2_7_CODE, ChatModels.KIMI_K2_7_CODE_HIGHSPEED, ChatModels.KIMI_K2_6;
797
- ChatModels.KIMI_K3, ChatModels.KIMI_K2_7_CODE, ChatModels.KIMI_K2_7_CODE_HIGHSPEED, ChatModels.KIMI_K2_6, ChatModels.KIMI_K2_5;
798
- /**
799
- * Ollama's native /api/chat requires tool-call arguments as an object and rejects a JSON string
800
- * with a 400. Unparseable or non-object input is kept under `_raw` rather than dropped.
801
- */
802
- function toOllamaToolArguments(args) {
803
- if (args !== null && typeof args === "object" && !Array.isArray(args)) return args;
804
- if (typeof args !== "string" || args.trim() === "") return {};
805
- try {
806
- const parsed = JSON.parse(args);
807
- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
808
- } catch {}
809
- return { _raw: args };
810
- }
811
- var OllamaBackend = class OllamaBackend {
812
- _host;
813
- _api;
814
- _logger;
815
- _clientHost;
816
- _clientHeaders;
817
- _agent;
818
- currentModel = "";
819
- constructor(host, logger) {
820
- this._logger = logger ?? new Logger();
821
- this._host = host ?? "http://localhost:11434";
822
- const url = new URL(this._host);
823
- const headers = {};
824
- if (url.username && url.password) {
825
- headers.Authorization = `Basic ${Buffer.from(`${url.username}:${url.password}`).toString("base64")}`;
826
- url.username = "";
827
- url.password = "";
828
- }
829
- this._agent = new Agent({
830
- headersTimeout: 18e5,
831
- bodyTimeout: 36e5
832
- });
833
- this._clientHost = url.toString();
834
- this._clientHeaders = headers;
835
- this._api = this.createClient();
836
- }
837
- /**
838
- * Build an Ollama client. The `ollama` package takes no per-request
839
- * AbortSignal (it only attaches an internal controller to streaming requests
840
- * and exposes a client-wide abort()), so cancellation has to be bound into
841
- * the fetch of a client made for that one request - hence the optional
842
- * `signal`. The undici Agent is shared across clients so connection pooling
843
- * and the raised timeouts survive.
844
- */
845
- createClient(signal) {
846
- const fetchWithTimeout = (input, init) => globalThis.fetch(input, {
847
- ...init,
848
- dispatcher: this._agent,
849
- ...signal && { signal: init?.signal ? AbortSignal.any([init.signal, signal]) : signal }
850
- });
851
- return new Ollama({
852
- host: this._clientHost,
853
- headers: this._clientHeaders,
854
- fetch: fetchWithTimeout
855
- });
856
- }
857
- /** Rejects when Ollama is unreachable; getAvailableModels needs a down host to differ from an empty one. */
858
- async getModelInfo() {
859
- const models = await this._api.list();
860
- const isSelfHost = process.env.B4M_SELF_HOST === "true";
861
- return await Promise.all(models.models.map(async (model) => {
862
- const { capabilities, contextWindow: reportedContextWindow } = await this.getModelDetailsCached(model.name);
863
- const contextWindow = OllamaBackend.effectiveContextWindow(reportedContextWindow);
864
- return {
865
- id: model.name,
866
- type: "text",
867
- name: model.name,
868
- backend: ModelBackend.Ollama,
869
- contextWindow,
870
- max_tokens: OllamaBackend.advertisedOutputCap(contextWindow),
871
- supportsImageVariation: false,
872
- pricing: { [contextWindow]: {
873
- input: 0,
874
- output: 0
875
- } },
876
- freeToRun: true,
877
- supportsVision: capabilities.includes("vision"),
878
- supportsTools: capabilities.includes("tools"),
879
- can_think: capabilities.includes("thinking"),
880
- can_stream: true,
881
- logoFile: "Ollama_Logo.svg",
882
- rank: 1,
883
- 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.`
884
- };
885
- }));
886
- }
887
- /** Ollama's default when a model doesn't report a context length. */
888
- static DEFAULT_CONTEXT_WINDOW = 8192;
889
- /**
890
- * Ceiling on the num_ctx we ask Ollama to allocate. Models advertise windows
891
- * far larger than a dev box can hold in KV cache (262K on qwen3.5), so the
892
- * useful value is the model's window capped at something affordable rather
893
- * than the advertised maximum. Override with OLLAMA_MAX_NUM_CTX.
894
- */
895
- static DEFAULT_MAX_NUM_CTX = 32768;
896
- /**
897
- * Output ceiling we advertise for a local model. Half of what we allocate, because advertising
898
- * the whole window made the server's context - output - buffer negative and emptied the prompt.
899
- *
900
- * Halving alone is not enough at the bottom of the range: OLLAMA_MAX_NUM_CTX accepts any positive
901
- * value, so an operator setting 2000 would leave exactly zero input budget for every local model
902
- * at once. The second bound keeps input room for any window ABOVE the safety buffer.
903
- *
904
- * At or below the buffer nothing here can: a 500-token window yields a cap of 1 and still leaves
905
- * 500 - 1 - 1000 negative. Clamping the window up to hide that would advertise more context than
906
- * the model has, which is the misreporting this whole change removes, so the honest answer is
907
- * that such a model cannot serve a chat prompt at all.
908
- */
909
- static advertisedOutputCap(contextWindow) {
910
- const halved = Math.floor(contextWindow / 2);
911
- return Math.max(1, Math.min(halved, contextWindow - CONTEXT_WINDOW_SAFETY_BUFFER_TOKENS - 1));
912
- }
913
- /** A model's reported window clamped to what we are willing to allocate. */
914
- static effectiveContextWindow(reported) {
915
- const configuredCap = Number(process.env.OLLAMA_MAX_NUM_CTX);
916
- const cap = Number.isFinite(configuredCap) && configuredCap > 0 ? configuredCap : OllamaBackend.DEFAULT_MAX_NUM_CTX;
917
- return Math.min(reported, cap);
918
- }
919
- /** Per-model /api/show results, so the tool-call recursion shows once, not per round. */
920
- _modelDetails = /* @__PURE__ */ new Map();
921
- getModelDetailsCached(model) {
922
- let details = this._modelDetails.get(model);
923
- if (!details) {
924
- details = this.getModelDetails(model);
925
- this._modelDetails.set(model, details);
926
- }
927
- return details;
928
- }
929
- /**
930
- * Fetch a model's capabilities and context window from Ollama (/api/show).
931
- * capabilities is e.g. ['completion', 'tools', 'vision']; the context length
932
- * lives in model_info under "<architecture>.context_length" (e.g.
933
- * "qwen2.context_length"). Returns safe defaults on any error so a transient
934
- * show() failure degrades gracefully instead of dropping the whole list.
935
- */
936
- async getModelDetails(model) {
937
- try {
938
- const info = await this._api.show({ model });
939
- const capabilities = info.capabilities ?? [];
940
- const raw = info.model_info;
941
- const ctx = (raw instanceof Map ? Array.from(raw.entries()) : Object.entries(raw ?? {})).find(([k]) => k.endsWith(".context_length"))?.[1];
942
- return {
943
- capabilities,
944
- contextWindow: typeof ctx === "number" && ctx > 0 ? ctx : OllamaBackend.DEFAULT_CONTEXT_WINDOW
945
- };
946
- } catch (error) {
947
- this._logger.debug(`[OllamaBackend] Could not fetch details for ${model}:`, error);
948
- return {
949
- capabilities: [],
950
- contextWindow: OllamaBackend.DEFAULT_CONTEXT_WINDOW
951
- };
952
- }
953
- }
954
- /**
955
- * Ollama model parameters for a request. Everything here is silently dropped
956
- * if the `options` object is omitted, which is why num_ctx matters most:
957
- * without it the server falls back to its own 4096 default and truncates the
958
- * prompt from the front, taking the tool block with it - so a large turn
959
- * makes a tool-capable model answer that it has no tools. Sizing from the
960
- * model's own reported window keeps that consistent with the context length
961
- * the picker advertises.
962
- */
963
- async buildModelOptions(model, options) {
964
- const { contextWindow } = await this.getModelDetailsCached(model);
965
- const numCtx = OllamaBackend.effectiveContextWindow(contextWindow);
966
- return {
967
- num_ctx: numCtx,
968
- ...typeof options.temperature === "number" && { temperature: options.temperature },
969
- ...typeof options.maxTokens === "number" && { num_predict: Math.min(options.maxTokens, numCtx) }
970
- };
971
- }
972
- async complete(model, messages, options, callback) {
973
- this.currentModel = model;
974
- const toolCallCount = options._internal?.toolCallCount ?? 0;
975
- const maxToolCalls = options._internal?.maxToolCalls ?? 10;
976
- const priorToolsUsed = options._internal?.accumToolsUsed ?? [];
977
- const priorInputTokens = options._internal?.accumInputTokens ?? 0;
978
- const priorOutputTokens = options._internal?.accumOutputTokens ?? 0;
979
- const toolsAvailable = (options.tools?.length ?? 0) > 0;
980
- const offerTools = toolsAvailable && toolCallCount < maxToolCalls;
981
- if (toolsAvailable && !offerTools) this._logger.warn(`[OllamaBackend] Max tool calls (${maxToolCalls}) reached; answering without tools.`);
982
- const formattedTools = offerTools ? this.formatTools(options.tools ?? []) : [];
983
- const baseRequest = {
984
- model,
985
- messages: this.buildMessages(offerTools ? messages : stripToolDependentMessages(messages)),
986
- options: await this.buildModelOptions(model, options),
987
- ...formattedTools.length > 0 && { tools: formattedTools },
988
- ...typeof options.thinking?.enabled === "boolean" && { think: options.thinking.enabled }
989
- };
990
- try {
991
- const round = await this.runChatRound(baseRequest, options, callback, { buffer: offerTools });
992
- const inputTokens = priorInputTokens + (round.completionInfo.inputTokens ?? 0);
993
- const outputTokens = priorOutputTokens + (round.completionInfo.outputTokens ?? 0);
994
- let toolCalls = this.normalizeToolCalls(round.toolCalls);
995
- if (toolCalls.length === 0 && offerTools) toolCalls = this.parseContentToolCall(round.content, options.tools ?? []);
996
- const toolsUsed = [...priorToolsUsed, ...toolCalls.map((tc) => ({
997
- name: tc.name,
998
- arguments: tc.arguments,
999
- id: tc.id
1000
- }))];
1001
- if (toolCalls.length === 0) {
1002
- await callback([offerTools ? round.content : ""], {
1003
- inputTokens,
1004
- outputTokens,
1005
- ...toolsUsed.length > 0 && { toolsUsed },
1006
- ...round.completionInfo.stopReason ? { stopReason: round.completionInfo.stopReason } : {}
1007
- });
1008
- return;
1009
- }
1010
- if (options.executeTools === false) {
1011
- await callback([""], {
1012
- inputTokens,
1013
- outputTokens,
1014
- toolsUsed
1015
- });
1016
- return;
1017
- }
1018
- const resolved = toolCalls.map((tc) => ({
1019
- tc,
1020
- toolFn: options.tools?.find((t) => t.toolSchema.name === tc.name)?.toolFn
1021
- })).filter((r) => !!r.toolFn);
1022
- const unknownCalls = toolCalls.filter((tc) => !options.tools?.some((t) => t.toolSchema.name === tc.name));
1023
- for (const tc of unknownCalls) this.pushToolMessages(messages, {
1024
- id: tc.id,
1025
- name: tc.name,
1026
- parameters: tc.arguments || "{}"
1027
- }, `Error: tool "${tc.name}" is not available. Do not call it again; answer directly or use a listed tool.`);
1028
- const outcomes = await executeToolsBatch(resolved.map(({ tc, toolFn }) => async () => {
1029
- let params = {};
1030
- try {
1031
- params = JSON.parse(tc.arguments || "{}");
1032
- } catch {}
1033
- this._logger.debug(`[OllamaBackend] Executing tool ${tc.name}`);
1034
- return String(await toolFn(params));
1035
- }), {
1036
- parallel: options.parallelToolExecution !== false,
1037
- maxConcurrency: options.maxParallelTools
1038
- });
1039
- const inheritedArtifactGuard = options._internal?.artifactGuard;
1040
- let artifactGuard = inheritedArtifactGuard;
1041
- const observations = [];
1042
- for (let i = 0; i < outcomes.length; i++) {
1043
- const outcome = outcomes[i];
1044
- const { tc } = resolved[i];
1045
- const params = tc.arguments || "{}";
1046
- if (outcome.ok) {
1047
- let emitted = false;
1048
- await handleToolResultStreaming(tc.name, outcome.result, async (results, artifactInfo) => {
1049
- emitted = true;
1050
- if (!artifactGuard) artifactGuard = createRecursiveArtifactGuard(callback);
1051
- await artifactGuard.emitArtifact(results, {
1052
- toolsUsed,
1053
- ...artifactInfo
1054
- });
1055
- }, declaredArtifactType(options.tools, tc.name));
1056
- observations[i] = stripUnstreamedToolResult(tc.name, outcome.result, emitted);
1057
- this.pushToolMessages(messages, {
1058
- id: tc.id,
1059
- name: tc.name,
1060
- parameters: params
1061
- }, observations[i]);
1062
- } else {
1063
- if (outcome.error instanceof PermissionDeniedError) throw outcome.error;
1064
- const errorMsg = stripToolArtifactMarkup(`Error running ${tc.name}: ${outcome.error instanceof Error ? outcome.error.message : "Unknown error"}`, ARTIFACT_REMOVED_PLACEHOLDER);
1065
- observations[i] = errorMsg;
1066
- this.pushToolMessages(messages, {
1067
- id: tc.id,
1068
- name: tc.name,
1069
- parameters: params
1070
- }, errorMsg);
1071
- }
1072
- }
1073
- const executedToolsUsed = [...priorToolsUsed, ...resolved.map(({ tc }, i) => {
1074
- const entry = {
1075
- name: tc.name,
1076
- arguments: tc.arguments,
1077
- id: tc.id,
1078
- returnValue: truncateToolResult(String(observations[i])),
1079
- success: outcomes[i].ok
1080
- };
1081
- attachFullToolResult(entry, observations[i]);
1082
- return entry;
1083
- })];
1084
- if (options.abortSignal?.aborted) {
1085
- await (artifactGuard?.callback ?? callback)([""], {
1086
- inputTokens,
1087
- outputTokens,
1088
- toolsUsed: executedToolsUsed
1089
- });
1090
- if (!inheritedArtifactGuard && artifactGuard) await artifactGuard.flush();
1091
- return;
1092
- }
1093
- if (round.toolCalls.length > 0 && shouldEndTurnAfterTools(toolCalls.map((tc) => tc.name), options.tools, round.content)) {
1094
- this._logger.info("[Tool Execution] Ending turn: answer already produced, only end-of-turn tools ran", {
1095
- model,
1096
- toolsExecuted: toolCalls.map((tc) => tc.name)
1097
- });
1098
- await (artifactGuard?.callback ?? callback)([round.content], {
1099
- inputTokens,
1100
- outputTokens,
1101
- toolsUsed: executedToolsUsed,
1102
- stopReason: "tool_use"
1103
- });
1104
- if (!inheritedArtifactGuard && artifactGuard) await artifactGuard.flush();
1105
- return;
1106
- }
1107
- await this.complete(model, messages, {
1108
- ...options,
1109
- _internal: {
1110
- ...options._internal,
1111
- toolCallCount: toolCallCount + 1,
1112
- accumToolsUsed: executedToolsUsed,
1113
- accumInputTokens: inputTokens,
1114
- accumOutputTokens: outputTokens,
1115
- artifactGuard
1116
- }
1117
- }, artifactGuard?.callback ?? callback);
1118
- if (!inheritedArtifactGuard && artifactGuard) await artifactGuard.flush();
1119
- } catch (error) {
1120
- if (error instanceof Error && isUserInitiatedAbort(error, options.abortSignal)) this._logger.debug("[OllamaBackend] Ollama request cancelled by the caller");
1121
- else this._logger.error("[OllamaBackend] Error during Ollama API call:", error);
1122
- throw error;
1123
- }
1124
- }
1125
- /**
1126
- * Run a single Ollama chat turn. Streams text chunks to `callback` unless
1127
- * `buffer` is set (used for tool-eligible rounds, where the content is
1128
- * withheld until we know whether it is a tool call or the final answer).
1129
- * Returns the full text, any native tool calls, and token usage.
1130
- */
1131
- async runChatRound(baseRequest, options, callback, { buffer }) {
1132
- const toolCalls = [];
1133
- let content = "";
1134
- let inputTokens = 0;
1135
- let outputTokens = 0;
1136
- let doneReason;
1137
- const api = options.abortSignal ? this.createClient(options.abortSignal) : this._api;
1138
- if (options.stream) {
1139
- const response = await api.chat({
1140
- ...baseRequest,
1141
- stream: true
1142
- });
1143
- let startedThinking = false;
1144
- let stoppedThinking = false;
1145
- let thinkingFieldOpen = false;
1146
- const thinkEscaper = createThinkMarkerEscaper();
1147
- for await (const chunk of response) {
1148
- if (chunk.message.tool_calls?.length) toolCalls.push(...chunk.message.tool_calls);
1149
- let piece = "";
1150
- const thinkPiece = chunk.message.thinking || "";
1151
- if (thinkPiece) {
1152
- if (!thinkingFieldOpen) {
1153
- piece += "<think>";
1154
- thinkingFieldOpen = true;
1155
- }
1156
- piece += thinkEscaper.push(thinkPiece);
1157
- }
1158
- const contentPiece = chunk.message.content || "";
1159
- if (contentPiece) {
1160
- if (thinkingFieldOpen) {
1161
- piece += thinkEscaper.flush();
1162
- piece += "</think>";
1163
- thinkingFieldOpen = false;
1164
- }
1165
- startedThinking = startedThinking || contentPiece.includes("<think>");
1166
- stoppedThinking = stoppedThinking || contentPiece.includes("</think>");
1167
- piece += contentPiece;
1168
- }
1169
- if (chunk.done && (thinkingFieldOpen || startedThinking && !stoppedThinking)) {
1170
- if (thinkingFieldOpen) piece += thinkEscaper.flush();
1171
- piece = `${piece}</think>`;
1172
- thinkingFieldOpen = false;
1173
- }
1174
- content += piece;
1175
- inputTokens = Math.max(inputTokens, chunk.prompt_eval_count || 0);
1176
- outputTokens += chunk.eval_count || 0;
1177
- if (chunk.done_reason) doneReason = chunk.done_reason;
1178
- if (!buffer && piece) await callback([piece], {
1179
- inputTokens,
1180
- outputTokens
1181
- });
1182
- }
1183
- } else {
1184
- const response = await api.chat({
1185
- ...baseRequest,
1186
- stream: false
1187
- });
1188
- if (response.message.tool_calls?.length) toolCalls.push(...response.message.tool_calls);
1189
- const think = response.message.thinking || "";
1190
- content = (think ? `<think>${escapeThinkMarkers(think)}</think>` : "") + (response.message.content || "");
1191
- inputTokens = response.prompt_eval_count || 0;
1192
- outputTokens = response.eval_count || 0;
1193
- doneReason = response.done_reason;
1194
- if (!buffer) await callback([content], {
1195
- inputTokens,
1196
- outputTokens
1197
- });
1198
- }
1199
- const stopReason = normalizeOllamaDoneReason(doneReason);
1200
- return {
1201
- content,
1202
- toolCalls,
1203
- completionInfo: {
1204
- inputTokens,
1205
- outputTokens,
1206
- ...stopReason ? { stopReason } : {}
1207
- }
1208
- };
1209
- }
1210
- /**
1211
- * Normalize Ollama's native tool_calls into the shared NormalizedToolCall shape.
1212
- *
1213
- * Ids are real uuids, not a position-derived string. A prior version keyed ids off
1214
- * `accumulated-count + round-local-index`, but the accumulated count is measured AFTER
1215
- * hallucinated calls are filtered out while the round-local index is assigned BEFORE that
1216
- * filter runs, so the two can drift and mint the same id for two different real calls across
1217
- * rounds - replayableToolCalls dedupes by id and silently drops the later one. A uuid makes
1218
- * the whole collision class unrepresentable, matching how the other backends already mint ids.
1219
- */
1220
- normalizeToolCalls(toolCalls) {
1221
- return toolCalls.map((tc) => ({
1222
- name: tc.function.name,
1223
- arguments: JSON.stringify(tc.function.arguments ?? {}),
1224
- id: `ollama-tool-${v4()}`
1225
- }));
1226
- }
1227
- /**
1228
- * Some smaller models emit tool calls as plain message content instead of
1229
- * using the native tool_calls field: a bare {"name":...,"arguments":{...}},
1230
- * the same wrapped in a ```json fence, or several such objects run together
1231
- * ({...} {...}). Recover every such object that names an available tool; if
1232
- * none match, the content is a normal answer.
1233
- *
1234
- * Guards against false positives: reasoning traces (<think>...</think>) are
1235
- * stripped first. The search source is a leading bare object (only when the
1236
- * reply STARTS with one) plus every fenced body - so a call wrapped in a fence
1237
- * after preamble prose is recovered, a bare call is not lost just because the
1238
- * reply also contains an unrelated fence, and JSON merely quoted mid-prose
1239
- * ("the math_evaluate tool takes {...}") is ignored. The seen-set dedupes any
1240
- * overlap between the two sources.
1241
- *
1242
- * Because any fenced block is a search source, a fenced EXAMPLE of a real
1243
- * (authorized) tool is also recovered and executed. This stays bounded to
1244
- * authorized tools (tryParseToolCallJson requires a name present in `tools`),
1245
- * so there is no privilege escalation - only a wider trigger surface.
1246
- */
1247
- parseContentToolCall(content, tools) {
1248
- const withoutThink = content.replace(/<think>[\s\S]*?<\/think>/gi, "").trim();
1249
- const fenced = this.extractFencedBlocks(withoutThink);
1250
- const source = [withoutThink.startsWith("{") ? withoutThink : "", ...fenced].join("\n");
1251
- if (!source.trim()) return [];
1252
- const calls = [];
1253
- const seen = /* @__PURE__ */ new Set();
1254
- for (const candidate of this.extractJsonObjects(source)) {
1255
- const call = this.tryParseToolCallJson(candidate, tools);
1256
- if (!call) continue;
1257
- const key = `${call.name}:${call.arguments}`;
1258
- if (seen.has(key)) continue;
1259
- seen.add(key);
1260
- calls.push({
1261
- ...call,
1262
- id: `ollama-content-tool-${v4()}`
1263
- });
1264
- }
1265
- return calls;
1266
- }
1267
- /**
1268
- * Return the body of every ```-fenced block, so a tool call the model wrapped
1269
- * in a fence after preamble prose can be isolated from the surrounding text.
1270
- */
1271
- extractFencedBlocks(content) {
1272
- const blocks = [];
1273
- const fenceRegex = /```[^\n]*\n?([\s\S]*?)```/g;
1274
- let match;
1275
- while ((match = fenceRegex.exec(content)) !== null) blocks.push(match[1]);
1276
- return blocks;
1277
- }
1278
- /**
1279
- * Extract every balanced top-level {...} substring from arbitrary text. String
1280
- * contents are respected so braces inside JSON strings don't throw off nesting,
1281
- * and code fences / prose around the objects are ignored. Handles multiple
1282
- * objects run together, which is how some models emit parallel tool calls.
1283
- */
1284
- extractJsonObjects(content) {
1285
- const objects = [];
1286
- let depth = 0;
1287
- let start = -1;
1288
- let inString = false;
1289
- let escaped = false;
1290
- for (let i = 0; i < content.length; i++) {
1291
- const ch = content[i];
1292
- if (inString) {
1293
- if (escaped) escaped = false;
1294
- else if (ch === "\\") escaped = true;
1295
- else if (ch === "\"") inString = false;
1296
- continue;
1297
- }
1298
- if (ch === "\"") inString = true;
1299
- else if (ch === "{") {
1300
- if (depth === 0) start = i;
1301
- depth++;
1302
- } else if (ch === "}" && depth > 0) {
1303
- depth--;
1304
- if (depth === 0 && start !== -1) {
1305
- objects.push(content.slice(start, i + 1));
1306
- start = -1;
1307
- }
1308
- }
1309
- }
1310
- return objects;
1311
- }
1312
- /**
1313
- * Parse one candidate string as a tool call naming a known tool. Models
1314
- * improvise the shape, so accept the common ones:
1315
- * {"name":"t","arguments":{...}} (Ollama/most)
1316
- * {"function":"t","arguments":{...}} (function-as-name)
1317
- * {"function":{"name":"t","arguments":{}}} (OpenAI-style nested)
1318
- * plus "parameters"/"args" aliases for the arguments.
1319
- */
1320
- tryParseToolCallJson(text, tools) {
1321
- const trimmed = text.trim();
1322
- if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return null;
1323
- let parsed;
1324
- try {
1325
- parsed = JSON.parse(trimmed);
1326
- } catch {
1327
- return null;
1328
- }
1329
- if (!parsed || typeof parsed !== "object") return null;
1330
- const obj = parsed;
1331
- let name;
1332
- let args;
1333
- const fn = obj.function;
1334
- if (fn && typeof fn === "object") {
1335
- name = fn.name;
1336
- args = fn.arguments;
1337
- } else name = obj.name ?? obj.function ?? obj.tool ?? obj.tool_name;
1338
- if (args === void 0) args = obj.arguments ?? obj.parameters ?? obj.args ?? {};
1339
- if (typeof name !== "string" || !tools.some((t) => t.toolSchema.name === name)) return null;
1340
- return {
1341
- name,
1342
- arguments: typeof args === "string" ? args : JSON.stringify(args ?? {})
1343
- };
1344
- }
1345
- pushToolMessages(messages, tool, result, _thinkingBlocks) {
1346
- messages.push({
1347
- content: "",
1348
- role: "assistant",
1349
- tool_calls: [{ function: {
1350
- name: tool.name,
1351
- arguments: toOllamaToolArguments(tool.parameters)
1352
- } }]
1353
- });
1354
- messages.push({
1355
- role: "tool",
1356
- tool_name: tool.name,
1357
- content: result
1358
- });
1359
- }
1360
- /**
1361
- * Convert ICompletionOptionTools into Ollama's Tool schema format.
1362
- */
1363
- formatTools(tools) {
1364
- return tools.map((tool) => ({
1365
- type: "function",
1366
- function: {
1367
- ...tool.toolSchema,
1368
- parameters: {
1369
- ...tool.toolSchema.parameters,
1370
- required: tool.toolSchema.parameters.required ?? []
1371
- }
1372
- }
1373
- }));
1374
- }
1375
- /**
1376
- * Map IMessage[] to Ollama's Message[], preserving tool_calls for multi-turn
1377
- * tool conversations (added by pushToolMessages).
1378
- * First converts B4M standard format (tool_use/tool_result) to OpenAI-compatible
1379
- * format since Ollama uses the same tool_calls/role:tool convention.
1380
- */
1381
- buildMessages(messages) {
1382
- return convertMessagesToOpenAIFormat(messages).map((msg) => {
1383
- const raw = msg;
1384
- const mapped = {
1385
- role: msg.role,
1386
- content: ""
1387
- };
1388
- if (Array.isArray(msg.content)) {
1389
- const texts = [];
1390
- const images = [];
1391
- for (const block of msg.content) if (block.type === "text" && typeof block.text === "string") texts.push(block.text);
1392
- else if (block.type === "image") {
1393
- if (block.source.type === "base64") images.push(block.source.data);
1394
- else this._logger.debug("[OllamaBackend] Dropping non-base64 image block; Ollama requires inline base64.");
1395
- } else if (block.type === "image_url") {
1396
- const dataUrl = block.image_url.url.match(/^data:[^,]*;base64,(.+)$/s);
1397
- if (dataUrl) images.push(dataUrl[1]);
1398
- else this._logger.debug("[OllamaBackend] Dropping non-data image_url; Ollama requires inline base64.");
1399
- }
1400
- mapped.content = texts.join("\n");
1401
- if (images.length > 0) mapped.images = images;
1402
- } else mapped.content = msg.content != null ? String(msg.content) : "";
1403
- if (Array.isArray(raw.tool_calls)) mapped.tool_calls = raw.tool_calls.map((call) => ({
1404
- ...call,
1405
- function: {
1406
- ...call.function,
1407
- arguments: toOllamaToolArguments(call.function?.arguments)
1408
- }
1409
- }));
1410
- if (typeof raw.tool_name === "string") mapped.tool_name = raw.tool_name;
1411
- return mapped;
1412
- });
1413
- }
1414
- async listModels() {
1415
- try {
1416
- this._logger.debug("[OllamaBackend] Listing models from Ollama");
1417
- const response = await this._api.list();
1418
- this._logger.debug("[OllamaBackend] Models listed from Ollama:", response.models);
1419
- return response.models;
1420
- } catch (error) {
1421
- this._logger.error("[OllamaBackend] Error listing models from Ollama:", error);
1422
- 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}`);
1423
- throw error;
1424
- }
1425
- }
1426
- };
1427
- ChatModels.O1_PREVIEW, ChatModels.O1_MINI, ChatModels.O1, ChatModels.O3_MINI, ChatModels.O3, ChatModels.O4_MINI;
1428
- ChatModels.GPT5, ChatModels.GPT5_MINI, ChatModels.GPT5_NANO, ChatModels.GPT5_CHAT_LATEST;
1429
- ChatModels.GPT5_1, ChatModels.GPT5_1_CHAT_LATEST;
1430
- ChatModels.GPT5_2, ChatModels.GPT5_2_CHAT_LATEST;
1431
- ChatModels.GPT5_4, ChatModels.GPT5_4_MINI, ChatModels.GPT5_4_MINI_2026_03_17, ChatModels.GPT5_4_NANO;
1432
- ChatModels.GPT5_5;
1433
- ChatModels.GPT5_6_SOL, ChatModels.GPT5_6_LUNA, ChatModels.GPT5_6_TERRA;
1434
- ModelBackend.Bedrock, ModelBackend.AWS, ModelBackend.OpenAI, ModelBackend.Anthropic, ModelBackend.Gemini, ModelBackend.Ollama, ModelBackend.BFL, ModelBackend.XAI, ModelBackend.Kimi, ModelBackend.DeepSeek, ModelBackend.LocalImage, ModelBackend.VoyageAI;
1435
- Object.values(ModelBackend);
1436
- Object.entries(MODEL_INFO_FIELD_GROUP_OF);
1437
- CompletionReasoningEffortSchema.options;
1438
- ModelBackend.Ollama, ModelBackend.LocalImage;
1439
- Object.assign(Object.create(null), {
1440
- txt: SupportedFabFileMimeTypes.TXT_PLAIN,
1441
- ini: SupportedFabFileMimeTypes.TXT_PLAIN,
1442
- env: SupportedFabFileMimeTypes.TXT_PLAIN,
1443
- conf: SupportedFabFileMimeTypes.TXT_PLAIN,
1444
- log: SupportedFabFileMimeTypes.TXT_PLAIN,
1445
- sql: SupportedFabFileMimeTypes.TXT_PLAIN,
1446
- text: SupportedFabFileMimeTypes.TXT_PLAIN,
1447
- md: SupportedFabFileMimeTypes.TXT_MARKDOWN,
1448
- mdx: SupportedFabFileMimeTypes.TXT_MARKDOWN,
1449
- mmd: SupportedFabFileMimeTypes.TXT_PLAIN,
1450
- html: SupportedFabFileMimeTypes.HTML,
1451
- htm: SupportedFabFileMimeTypes.HTML,
1452
- shtml: SupportedFabFileMimeTypes.HTML,
1453
- csv: SupportedFabFileMimeTypes.CSV,
1454
- jpg: SupportedFabFileMimeTypes.JPG,
1455
- jpeg: SupportedFabFileMimeTypes.JPG,
1456
- jfif: SupportedFabFileMimeTypes.JPG,
1457
- jpe: SupportedFabFileMimeTypes.JPG,
1458
- png: SupportedFabFileMimeTypes.PNG,
1459
- gif: SupportedFabFileMimeTypes.GIF,
1460
- svg: SupportedFabFileMimeTypes.SVG,
1461
- webp: SupportedFabFileMimeTypes.WEBP,
1462
- pdf: SupportedFabFileMimeTypes.PDF,
1463
- json: SupportedFabFileMimeTypes.JSON,
1464
- xml: SupportedFabFileMimeTypes.XML,
1465
- docx: SupportedFabFileMimeTypes.DOCX,
1466
- pptx: SupportedFabFileMimeTypes.PPTX,
1467
- xlsx: SupportedFabFileMimeTypes.XLSX,
1468
- xls: SupportedFabFileMimeTypes.XLS,
1469
- js: SupportedFabFileMimeTypes.JS,
1470
- mjs: SupportedFabFileMimeTypes.JS,
1471
- cjs: SupportedFabFileMimeTypes.JS,
1472
- jsx: SupportedFabFileMimeTypes.JSX,
1473
- ts: SupportedFabFileMimeTypes.TS,
1474
- tsx: SupportedFabFileMimeTypes.TS,
1475
- py: SupportedFabFileMimeTypes.PY,
1476
- java: SupportedFabFileMimeTypes.JAVA,
1477
- cpp: SupportedFabFileMimeTypes.CPP,
1478
- c: SupportedFabFileMimeTypes.CPP,
1479
- h: SupportedFabFileMimeTypes.CPP,
1480
- cs: SupportedFabFileMimeTypes.CS,
1481
- php: SupportedFabFileMimeTypes.PHP,
1482
- rb: SupportedFabFileMimeTypes.RUBY,
1483
- go: SupportedFabFileMimeTypes.GO,
1484
- swift: SupportedFabFileMimeTypes.SWIFT,
1485
- kt: SupportedFabFileMimeTypes.KOTLIN,
1486
- rs: SupportedFabFileMimeTypes.RUST,
1487
- css: SupportedFabFileMimeTypes.CSS,
1488
- less: SupportedFabFileMimeTypes.LESS,
1489
- sass: SupportedFabFileMimeTypes.SASS,
1490
- scss: SupportedFabFileMimeTypes.SCSS,
1491
- yaml: SupportedFabFileMimeTypes.YAML,
1492
- yml: SupportedFabFileMimeTypes.YAML,
1493
- toml: SupportedFabFileMimeTypes.TOML,
1494
- sh: SupportedFabFileMimeTypes.SH,
1495
- bash: SupportedFabFileMimeTypes.BASH,
1496
- mp3: AudioMimeType.MP3,
1497
- wav: AudioMimeType.WAV,
1498
- opus: AudioMimeType.OPUS,
1499
- aac: AudioMimeType.AAC,
1500
- flac: AudioMimeType.FLAC,
1501
- pcm: AudioMimeType.PCM,
1502
- ogg: AudioMimeType.OGG,
1503
- webm: AudioMimeType.WEBM
1504
- });
1505
- /**
1506
- * Coerce any thrown value into a human-readable string.
1507
- *
1508
- * Handles the three common shapes:
1509
- * - Error -> .message
1510
- * - string -> as-is
1511
- * - other -> JSON.stringify with a safe fallback for circular/unstringifiable values
1512
- */
1513
- function extractErrorMessage(error) {
1514
- if (error instanceof Error) return error.message;
1515
- if (typeof error === "string") return error;
1516
- try {
1517
- return JSON.stringify(error);
1518
- } catch {
1519
- return "Unknown error";
1520
- }
1521
- }
1522
- 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;
1523
- TTS_DEFAULT_MODEL.openai;
1524
- TTS_MAX_INPUT_CHARS.openai;
1525
- TTS_MAX_INPUT_CHARS.elevenlabs;
1526
- TTS_DEFAULT_MODEL.elevenlabs;
1527
- //#endregion
1528
- //#region src/llm/NotifyingLlmBackend.ts
1529
- /**
1530
- * LLM backend wrapper that injects background agent notifications
1531
- * into the message array before each completion call.
1532
- *
1533
- * When a background agent completes (or fails), the notification
1534
- * appears as a system message so the main agent naturally sees it
1535
- * in context - no polling required.
1536
- */
1537
- var NotifyingLlmBackend = class {
1538
- constructor(inner, backgroundManager) {
1539
- this.inner = inner;
1540
- this.backgroundManager = backgroundManager;
1541
- }
1542
- get currentModel() {
1543
- return this.inner.currentModel;
1544
- }
1545
- set currentModel(model) {
1546
- this.inner.currentModel = model;
1547
- }
1548
- async complete(model, messages, options, callback) {
1549
- const notifications = this.backgroundManager.drainNotifications();
1550
- let effectiveMessages = messages;
1551
- if (notifications.length > 0) {
1552
- const notificationMessage = {
1553
- role: "user",
1554
- content: `[System Notification]\n\n${notifications.join("\n\n---\n\n")}\n\nPlease acknowledge these background agent results and incorporate them into your current work.`
1555
- };
1556
- effectiveMessages = [...messages, notificationMessage];
1557
- }
1558
- return this.inner.complete(model, effectiveMessages, options, callback);
1559
- }
1560
- pushToolMessages(messages, tool, result) {
1561
- return this.inner.pushToolMessages(messages, tool, result);
1562
- }
1563
- async getModelInfo() {
1564
- return this.inner.getModelInfo();
1565
- }
1566
- };
1567
- //#endregion
1568
- //#region src/tools/deferredToolRegistry.ts
1569
- const deferredToolRegistry = new DeferredToolRegistry({ logger });
1570
- //#endregion
1571
- //#region src/llm/MultiLlmBackend.ts
1572
- /**
1573
- * Routes completions between B4M server and a local Ollama instance
1574
- * based on the selected model's backend type.
1575
- */
1576
- var MultiLlmBackend = class {
1577
- constructor(serverBackend, ollamaBackend, serverModels, ollamaModels, initialModel) {
1578
- this.serverBackend = serverBackend;
1579
- this.ollamaBackend = ollamaBackend;
1580
- this.serverModels = serverModels;
1581
- this.ollamaModels = ollamaModels;
1582
- this.currentModel = initialModel;
1583
- this.ollamaModelIds = new Set(ollamaModels.map((m) => m.id));
1584
- }
1585
- get activeBackend() {
1586
- return this.ollamaModelIds.has(this.currentModel) ? this.ollamaBackend : this.serverBackend;
1587
- }
1588
- async complete(model, messages, options, callback) {
1589
- return (this.ollamaModelIds.has(model) ? this.ollamaBackend : this.serverBackend).complete(model, messages, options, callback);
1590
- }
1591
- pushToolMessages(messages, tool, result, thinkingBlocks) {
1592
- this.activeBackend.pushToolMessages(messages, tool, result, thinkingBlocks);
1593
- }
1594
- async getModelInfo() {
1595
- return [...this.serverModels, ...this.ollamaModels];
1596
- }
1597
- };
1598
- //#endregion
1599
- //#region src/ws/WebSocketConnectionManager.ts
1600
- const useWsPolyfill = typeof globalThis.WebSocket === "undefined";
1601
- const WS = useWsPolyfill ? WebSocket : globalThis.WebSocket;
1602
- /**
1603
- * Manages a persistent WebSocket connection for CLI <-> server communication.
1604
- * Handles heartbeat, reconnection, and message routing by requestId.
1605
- *
1606
- * Uses Node.js built-in WebSocket (Node 22+) with `ws` package fallback for Node 20.
1607
- */
1608
- var WebSocketConnectionManager = class {
1609
- /**
1610
- * @param verifySession - Optional. Called when a connect ATTEMPT fails (the socket closed
1611
- * without ever opening) - exactly the signal an auth-rejected handshake produces. Omit to
1612
- * preserve the old always-retry-forever behavior.
1613
- */
1614
- constructor(wsUrl, getToken, verifySession) {
1615
- this.ws = null;
1616
- this.heartbeatInterval = null;
1617
- this.reconnectAttempts = 0;
1618
- this.maxReconnectDelay = 3e4;
1619
- this.handlers = /* @__PURE__ */ new Map();
1620
- this.actionHandlers = /* @__PURE__ */ new Map();
1621
- this.disconnectHandlers = /* @__PURE__ */ new Set();
1622
- this.revokedHandlers = /* @__PURE__ */ new Set();
1623
- this.reconnectTimer = null;
1624
- this.connected = false;
1625
- this.connecting = false;
1626
- this.closed = false;
1627
- this.openedThisAttempt = false;
1628
- this.verifyingSession = false;
1629
- this.revoked = false;
1630
- this.wsUrl = wsUrl;
1631
- this.getToken = getToken;
1632
- this.verifySession = verifySession;
1633
- }
1634
- /**
1635
- * Connect to the WebSocket server.
1636
- * Resolves when connection is established, rejects on failure.
1637
- */
1638
- async connect() {
1639
- if (this.connected || this.connecting) return;
1640
- this.connecting = true;
1641
- this.openedThisAttempt = false;
1642
- const token = await this.getToken();
1643
- if (!token) {
1644
- this.connecting = false;
1645
- throw new Error("No access token available for WebSocket connection");
1646
- }
1647
- return new Promise((resolve, reject) => {
1648
- logger.debug(`[WS] Connecting to ${this.wsUrl}...`);
1649
- if (useWsPolyfill) this.ws = new WebSocket(this.wsUrl, { headers: { "Sec-WebSocket-Protocol": `access_token.${token}` } });
1650
- else this.ws = new WS(this.wsUrl, [`access_token.${token}`]);
1651
- this.ws.onopen = () => {
1652
- logger.debug("[WS] Connected");
1653
- this.connected = true;
1654
- this.connecting = false;
1655
- this.openedThisAttempt = true;
1656
- this.reconnectAttempts = 0;
1657
- this.startHeartbeat();
1658
- resolve();
1659
- };
1660
- this.ws.onmessage = (event) => {
1661
- try {
1662
- const data = typeof event.data === "string" ? event.data : event.data.toString();
1663
- const message = JSON.parse(data);
1664
- const requestId = message.requestId;
1665
- if (requestId && this.handlers.has(requestId)) this.handlers.get(requestId)(message);
1666
- else {
1667
- const action = message.action;
1668
- if (action && this.actionHandlers.has(action)) this.actionHandlers.get(action)(message);
1669
- else logger.debug(`[WS] Unhandled message: ${action || "unknown"}`);
1670
- }
1671
- } catch (err) {
1672
- logger.debug(`[WS] Failed to parse message: ${err}`);
1673
- }
1674
- };
1675
- this.ws.onclose = () => {
1676
- logger.debug("[WS] Connection closed");
1677
- const openedThisAttempt = this.openedThisAttempt;
1678
- this.cleanup();
1679
- this.notifyDisconnect();
1680
- if (this.closed || this.revoked) return;
1681
- if (openedThisAttempt || !this.verifySession) {
1682
- this.scheduleReconnect();
1683
- return;
1684
- }
1685
- this.verifyThenReconnect();
1686
- };
1687
- this.ws.onerror = (err) => {
1688
- const detail = err.error?.message || String(err);
1689
- logger.debug(`[WS] Error: ${detail}`);
1690
- if (this.connecting) {
1691
- this.connecting = false;
1692
- this.connected = false;
1693
- reject(/* @__PURE__ */ new Error(`WebSocket connection failed: ${detail}`));
1694
- }
1695
- };
1696
- });
1697
- }
1698
- /** Whether the connection is currently established */
1699
- get isConnected() {
1700
- return this.connected;
1701
- }
1702
- /**
1703
- * Send a JSON message over the WebSocket connection.
1704
- */
1705
- send(data) {
1706
- if (!this.ws || this.ws.readyState !== WS.OPEN) throw new Error("WebSocket is not connected");
1707
- const payload = JSON.stringify(data);
1708
- const sizeKB = (payload.length / 1024).toFixed(1);
1709
- logger.debug(`[WS] Sending ${sizeKB} KB (action: ${data.action})`);
1710
- if (payload.length > 32e3) logger.warn(`[WS] Payload ${sizeKB} KB exceeds API Gateway 32 KB frame limit — connection will be closed`);
1711
- this.ws.send(payload);
1712
- }
1713
- /**
1714
- * Register a handler for messages matching a specific requestId.
1715
- */
1716
- onRequest(requestId, handler) {
1717
- this.handlers.set(requestId, handler);
1718
- }
1719
- /**
1720
- * Remove a handler for a specific requestId.
1721
- */
1722
- offRequest(requestId) {
1723
- this.handlers.delete(requestId);
1724
- }
1725
- /**
1726
- * Register a handler for messages matching a specific action type.
1727
- * Used for server-pushed commands like keep_command.
1728
- */
1729
- onAction(action, handler) {
1730
- this.actionHandlers.set(action, handler);
1731
- }
1732
- /**
1733
- * Remove a handler for a specific action type.
1734
- */
1735
- offAction(action) {
1736
- this.actionHandlers.delete(action);
1737
- }
1738
- /**
1739
- * Register a handler that fires when the connection drops.
1740
- */
1741
- onDisconnect(handler) {
1742
- this.disconnectHandlers.add(handler);
1743
- }
1744
- /**
1745
- * Remove a disconnect handler.
1746
- */
1747
- offDisconnect(handler) {
1748
- this.disconnectHandlers.delete(handler);
1749
- }
1750
- /**
1751
- * Register a handler that fires once the session is confirmed revoked (verifySession
1752
- * returned false) and the reconnect loop has permanently stopped.
1753
- */
1754
- onRevoked(handler) {
1755
- this.revokedHandlers.add(handler);
1756
- }
1757
- /**
1758
- * Remove a revoked handler.
1759
- */
1760
- offRevoked(handler) {
1761
- this.revokedHandlers.delete(handler);
1762
- }
1763
- /** Whether the session has been confirmed revoked (reconnecting has permanently stopped). */
1764
- get isRevoked() {
1765
- return this.revoked;
1766
- }
1767
- /**
1768
- * Close the connection and stop all heartbeat/reconnect logic.
1769
- */
1770
- disconnect() {
1771
- this.closed = true;
1772
- this.cleanup();
1773
- if (this.ws) {
1774
- this.ws.close();
1775
- this.ws = null;
1776
- }
1777
- this.handlers.clear();
1778
- this.actionHandlers.clear();
1779
- this.disconnectHandlers.clear();
1780
- this.revokedHandlers.clear();
1781
- }
1782
- startHeartbeat() {
1783
- this.stopHeartbeat();
1784
- this.heartbeatInterval = setInterval(() => {
1785
- if (this.ws && this.ws.readyState === WS.OPEN) {
1786
- this.ws.send(JSON.stringify({ action: "heartbeat" }));
1787
- logger.debug("[WS] Heartbeat sent");
1788
- }
1789
- }, 3e5);
1790
- }
1791
- stopHeartbeat() {
1792
- if (this.heartbeatInterval) {
1793
- clearInterval(this.heartbeatInterval);
1794
- this.heartbeatInterval = null;
1795
- }
1796
- }
1797
- cleanup() {
1798
- this.connected = false;
1799
- this.connecting = false;
1800
- this.stopHeartbeat();
1801
- if (this.reconnectTimer) {
1802
- clearTimeout(this.reconnectTimer);
1803
- this.reconnectTimer = null;
1804
- }
1805
- }
1806
- notifyDisconnect() {
1807
- for (const handler of this.disconnectHandlers) try {
1808
- handler();
1809
- } catch {}
1810
- }
1811
- notifyRevoked() {
1812
- for (const handler of this.revokedHandlers) try {
1813
- handler();
1814
- } catch {}
1815
- }
1816
- /**
1817
- * Called when a connect attempt fails to open at all - the signal a 401 handshake refusal
1818
- * produces. Verifies the session via the injected `verifySession` (single-flighted) before
1819
- * deciding whether to keep retrying. A verification that itself errors (network blip, 5xx)
1820
- * is treated as transient - only an explicit `false` result stops the loop.
1821
- */
1822
- async verifyThenReconnect() {
1823
- if (this.verifyingSession) return;
1824
- this.verifyingSession = true;
1825
- try {
1826
- if (!await this.verifySession()) {
1827
- logger.debug("[WS] Session verification failed - session revoked, stopping reconnect");
1828
- this.revoked = true;
1829
- this.notifyRevoked();
1830
- return;
1831
- }
1832
- } catch (err) {
1833
- logger.debug(`[WS] Session verification errored - treating as transient: ${err}`);
1834
- } finally {
1835
- this.verifyingSession = false;
1836
- }
1837
- this.scheduleReconnect();
1838
- }
1839
- scheduleReconnect() {
1840
- if (this.closed || this.revoked) return;
1841
- this.reconnectAttempts++;
1842
- const delay = Math.min(1e3 * Math.pow(2, this.reconnectAttempts - 1), this.maxReconnectDelay);
1843
- logger.debug(`[WS] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);
1844
- this.reconnectTimer = setTimeout(async () => {
1845
- this.reconnectTimer = null;
1846
- if (this.closed) return;
1847
- try {
1848
- await this.connect();
1849
- } catch {
1850
- logger.debug("[WS] Reconnection failed");
1851
- }
1852
- }, delay);
1853
- }
1854
- };
1855
- //#endregion
1856
- //#region src/bootstrap/buildLlmBackend.ts
1857
- /** Production wiring: real transport classes + the ToolRouter singleton. */
1858
- const defaultLlmBackendDeps = {
1859
- connectWebSocket: async (wsUrl, tokenGetter, verifySession) => {
1860
- const ws = new WebSocketConnectionManager(wsUrl, tokenGetter, verifySession);
1861
- ws.onRevoked(() => {
1862
- logger.warn("Session revoked - run `b4m login` again. WebSocket reconnect stopped.");
1863
- });
1864
- try {
1865
- await ws.connect();
1866
- } catch (err) {
1867
- ws.disconnect();
1868
- throw err;
1869
- }
1870
- return ws;
1871
- },
1872
- clearWebSocketToolExecutor: () => setWebSocketToolExecutor(null),
1873
- createServerBackend: (opts) => new ServerLlmBackend(opts),
1874
- createOllamaBackend: (host) => new OllamaBackend(host, {
1875
- debug: (...args) => logger.debug(args.map(String).join(" ")),
1876
- info: (...args) => logger.info(args.map(String).join(" ")),
1877
- warn: (...args) => logger.warn(args.map(String).join(" ")),
1878
- error: (...args) => logger.error(args.map(String).join(" "))
1879
- }),
1880
- createMultiBackend: (server, ollama, serverModels, ollamaModels, defaultModel) => new MultiLlmBackend(server, ollama, serverModels, ollamaModels, defaultModel)
1881
- };
1882
- /**
1883
- * True when some enabled feature module consumes realtime server events. Only
1884
- * Tavern does today (TavernModule.registerWsHandlers -> TavernActivityStream);
1885
- * keep this in sync with the module registration in index.tsx. Everything else
1886
- * runs socket-free, so the common path never opens a WebSocket.
1887
- */
1888
- function needsFeatureEventSocket(config) {
1889
- return config.features?.tavern === true;
1890
- }
1891
- /**
1892
- * Connect the events-only socket that feature modules register handlers on.
1893
- * Returns null when it isn't needed, isn't advertised, or won't connect - a
1894
- * feature's live updates degrading is never a reason to fail startup, since
1895
- * completions no longer depend on this socket at all.
1896
- */
1897
- async function connectFeatureEventSocket(config, websocketUrl, deps, auth) {
1898
- if (!needsFeatureEventSocket(config)) return null;
1899
- if (!websocketUrl) {
1900
- logger.debug("[WS] No websocketUrl in server config - feature live updates disabled");
1901
- return null;
1902
- }
1903
- try {
1904
- return await deps.connectWebSocket(websocketUrl, auth.tokenGetter, auth.verifySession);
1905
- } catch (err) {
1906
- logger.warn(`Realtime socket unavailable - live feature updates are disabled: ${err instanceof Error ? err.message : String(err)}`);
1907
- return null;
1908
- }
1909
- }
1910
- /**
1911
- * Resolve the model to use from the available list: the requested default if
1912
- * present, otherwise the first available model. Pure - exported for testing.
1913
- */
1914
- function resolveModelInfo(models, defaultModel) {
1915
- return models.find((m) => m.id === defaultModel) || models[0];
1916
- }
1917
- /**
1918
- * Build the LLM backend: HTTP+SSE transport (ServerLlmBackend), optional Ollama
1919
- * multiplexing. Resolves the default model and pins it on the backend.
1920
- *
1921
- * The WebSocket COMPLETION transport was removed - completions always use SSE,
1922
- * because relays that emit the generic `streamed_chat_completion` action drop
1923
- * every CLI chunk. The socket itself is still connected, but only when a
1924
- * WS-consuming feature module is enabled, and only to carry that module's events
1925
- * (see `wsManager`); Keep relay and WS server-side tool execution stay off.
1926
- *
1927
- * Pure bootstrap seam: no React hooks, no Zustand state.
1928
- */
1929
- async function buildLlmBackend(input, deps = defaultLlmBackendDeps) {
1930
- const { config, apiClient, startupLog, tokenGetter } = input;
1931
- const sse = await createSseBackend({
1932
- apiClient,
1933
- model: config.defaultModel
1934
- }, {
1935
- createServerBackend: deps.createServerBackend,
1936
- clearWebSocketToolExecutor: deps.clearWebSocketToolExecutor
1937
- });
1938
- let llm = sse.llm;
1939
- const wsManager = await connectFeatureEventSocket(config, sse.serverConfig.websocketUrl, deps, {
1940
- tokenGetter,
1941
- verifySession: () => apiClient.checkSessionValid()
1942
- });
1943
- const ollamaHost = input.ollamaHost ?? process.env.B4M_OLLAMA_HOST;
1944
- let models;
1945
- if (ollamaHost) {
1946
- const ollamaBackend = deps.createOllamaBackend(ollamaHost);
1947
- const ollamaListing = ollamaBackend.getModelInfo().then((listed) => ({ models: listed }), (error) => {
1948
- const message = extractErrorMessage(error);
1949
- logger.warn(`Error fetching model info from Ollama: ${message}`);
1950
- return {
1951
- models: [],
1952
- error: message
1953
- };
1954
- });
1955
- const [serverModels, ollama] = await Promise.all([llm.getModelInfo(), ollamaListing]);
1956
- const ollamaModels = ollama.models;
1957
- if (serverModels.length === 0 && ollamaModels.length === 0) throw new Error(ollama.error !== void 0 ? `No models available from server, and Ollama at ${ollamaHost} is unreachable: ${ollama.error}` : `No models available from server or Ollama at ${ollamaHost}.\nPull a model: ollama pull qwen3.5`);
1958
- if (ollama.error !== void 0) startupLog.push(`\u26a0\ufe0f Ollama at ${ollamaHost} is unreachable: ${ollama.error}`);
1959
- else if (ollamaModels.length === 0) startupLog.push(`⚠️ No models found in Ollama at ${ollamaHost}. Pull one with: ollama pull qwen3.5`);
1960
- const serverBackend = llm;
1961
- llm = deps.createMultiBackend(serverBackend, ollamaBackend, serverModels, ollamaModels, config.defaultModel);
1962
- models = await llm.getModelInfo();
1963
- startupLog.push(`🦙 Self-hosted Ollama: ${ollamaModels.length} model(s) added to picker`);
1964
- } else {
1965
- models = await llm.getModelInfo();
1966
- if (models.length === 0) throw new Error("No models available from server.");
1967
- }
1968
- logger.debug(`📋 Available models: ${models.map((m) => m.id).join(", ")}`);
1969
- const modelInfo = resolveModelInfo(models, config.defaultModel);
1970
- if (modelInfo.id !== config.defaultModel) {
1971
- logger.warn(`⚠️ Requested model '${config.defaultModel}' not available`);
1972
- logger.warn(`🤖 Using fallback model: ${modelInfo.id}`);
1973
- }
1974
- llm.currentModel = modelInfo.id;
1975
- return {
1976
- llm,
1977
- wsManager,
1978
- models,
1979
- modelInfo
1980
- };
1981
- }
1982
- //#endregion
1983
- //#region src/bootstrap/buildSupportingStores.ts
1984
- /**
1985
- * Build the supporting stores and orchestration the agent needs: CLI tools
1986
- * (permission-wrapped + server-routed), MCP manager, agent store, context
1987
- * files, the deferred-tool registry partition, the subagent orchestrator, and
1988
- * the background-agent manager.
1989
- *
1990
- * Pure bootstrap seam: no React hooks, no Zustand state. React-owned values
1991
- * (permission/user-question prompt functions, the agent context, and the
1992
- * background-agent status callbacks) are passed in. Tool *assembly* that weaves
1993
- * the React workflow-store refs (decision/blocker/review-gate tools) stays in
1994
- * the shell; this module returns only the agent-construction materials.
1995
- */
1996
- async function buildSupportingStores(input) {
1997
- const { config, llm, modelId, permissionManager, apiClient, configStore, customCommandStore, checkpointStore, sandboxOrchestrator, additionalDirectories, agentContext, promptFn, userQuestionFn, startupLog, silentLogger, onBackgroundStatusChange, onGroupCompletion, onSubagentUsage } = input;
1998
- const { tools: b4mTools } = await generateCliTools(config.userId, llm, modelId, permissionManager, promptFn, agentContext, configStore, apiClient, void 0, userQuestionFn, checkpointStore, sandboxOrchestrator, additionalDirectories);
1999
- const mcpManager = new McpManager(config);
2000
- const builtinAgentsDir = new URL("../agents/defaults/", import.meta.url).pathname;
2001
- const agentStore = buildProjectAgentStore(builtinAgentsDir, configStore);
2002
- const [, , contextResult] = await Promise.all([
2003
- mcpManager.initialize(),
2004
- agentStore.loadAgents(),
2005
- loadProjectContext(configStore)
2006
- ]);
2007
- const mcpTools = wrapTools(mcpManager.getTools(), {
2008
- permissionManager,
2009
- showPermissionPrompt: promptFn,
2010
- agentContext,
2011
- configStore,
2012
- apiClient,
2013
- sandboxOrchestrator,
2014
- allowedDirectories: additionalDirectories
2015
- });
2016
- const deferredB4mToolNames = /* @__PURE__ */ new Set([
2017
- "math_evaluate",
2018
- "dice_roll",
2019
- "current_datetime",
2020
- "recent_changes",
2021
- "prompt_enhancement"
2022
- ]);
2023
- const deferredB4mTools = b4mTools.filter((t) => deferredB4mToolNames.has(t.toolSchema.name));
2024
- const loadedB4mTools = b4mTools.filter((t) => !deferredB4mToolNames.has(t.toolSchema.name));
2025
- deferredToolRegistry.register([...mcpTools, ...deferredB4mTools]);
2026
- if (mcpTools.length > 0) {
2027
- const serverSummaries = mcpManager.getToolCount().map((s) => `${s.serverName} (${s.count})`).join(", ");
2028
- startupLog.push(`🛠️ Loaded ${loadedB4mTools.length} B4M + ${mcpTools.length} MCP tool(s, ${deferredB4mTools.length + mcpTools.length} deferred): ${serverSummaries}`);
2029
- } else {
2030
- const suffix = deferredB4mTools.length > 0 ? ` (${deferredB4mTools.length} deferred)` : "";
2031
- startupLog.push(`🛠️ Loaded ${loadedB4mTools.length} B4M tool(s)${suffix}, no MCP tools`);
2032
- }
2033
- const agentSummary = agentStore.getSummary();
2034
- startupLog.push(`🤖 Loaded ${agentSummary.total} agent(s): ${agentSummary.builtin} built-in, ${agentSummary.global} global, ${agentSummary.project} project`);
2035
- const historyStore = new AgentHistoryStore(config.preferences.subagentHistoryTtlMs ?? 36e5);
2036
- const orchestrator = new SubagentOrchestrator({
2037
- userId: config.userId,
2038
- llm,
2039
- logger: silentLogger,
2040
- permissionManager,
2041
- showPermissionPrompt: promptFn,
2042
- configStore,
2043
- apiClient,
2044
- agentStore,
2045
- customCommandStore,
2046
- enableParallelToolExecution: config.preferences.enableParallelToolExecution === true,
2047
- showUserQuestion: userQuestionFn,
2048
- checkpointStore,
2049
- onSubagentUsage,
2050
- historyStore,
2051
- sandboxOrchestrator,
2052
- additionalDirectories
2053
- });
2054
- const backgroundManager = new BackgroundAgentManager(orchestrator);
2055
- backgroundManager.setOnStatusChange(onBackgroundStatusChange);
2056
- backgroundManager.setOnGroupCompletion(onGroupCompletion);
2057
- return {
2058
- mcpManager,
2059
- agentStore,
2060
- contextResult,
2061
- mcpTools,
2062
- loadedB4mTools,
2063
- deferredB4mTools,
2064
- orchestrator,
2065
- backgroundManager,
2066
- historyStore
2067
- };
2068
- }
2069
- //#endregion
2070
- //#region src/bootstrap/buildAgent.ts
2071
- /**
2072
- * Construct the main ReAct agent with the system prompt selected by config
2073
- * variant, wire the tool_search closure to the agent's live tools array, and
2074
- * record the agent in the shared observation context.
2075
- *
2076
- * Pure bootstrap seam: no React hooks, no Zustand state. The interaction-mode
2077
- * subscription (`useCliStore.subscribe`) stays in the shell and uses the
2078
- * returned `buildPromptForMode`. Ordering is load-bearing: agent built ->
2079
- * agentToolsRef wired -> agentContext.currentAgent set, all here, before the
2080
- * shell registers the subscription (which guards on currentAgent === agent).
2081
- */
2082
- function buildAgent(input) {
2083
- const { config, modelId, notifyingLlm, allTools, agentContext, agentToolsRef, silentLogger, sessionId, initialInteractionMode, contextContent, agentStore, customCommandStore, enableSkillTool, additionalDirectories, featureModulePrompts } = input;
2084
- const promptVariant = config.preferences.promptVariant ?? "current";
2085
- const buildPromptForMode = (mode) => buildSystemPrompt(promptVariant, {
2086
- contextContent,
2087
- agentStore,
2088
- customCommands: customCommandStore.getModelReachableCommands(),
2089
- enableSkillTool,
2090
- enableDynamicAgentCreation: config.preferences.enableDynamicAgentCreation === true,
2091
- additionalDirectories,
2092
- featureModulePrompts: featureModulePrompts || void 0,
2093
- planModeFilePath: mode === "plan" ? getPlanModeFilePath(sessionId) : void 0,
2094
- appendSystemPrompt: process.env.B4M_APPEND_SYSTEM_PROMPT,
2095
- deferredToolNames: deferredToolRegistry.getDirectoryNames()
2096
- });
2097
- const cliSystemPrompt = buildPromptForMode(initialInteractionMode);
2098
- const maxIterations = config.preferences.maxIterations === null ? 999999 : config.preferences.maxIterations;
2099
- const agent = new ReActAgent({
2100
- userId: config.userId,
2101
- logger: silentLogger,
2102
- llm: notifyingLlm,
2103
- model: modelId,
2104
- tools: allTools,
2105
- maxIterations,
2106
- maxTokens: config.preferences.maxTokens,
2107
- temperature: config.preferences.temperature,
2108
- systemPrompt: cliSystemPrompt,
2109
- unknownToolResolver: async (toolName) => deferredToolRegistry.get(toolName) ?? null
2110
- });
2111
- agentToolsRef.current = agent.getTools();
2112
- agentContext.currentAgent = agent;
2113
- return {
2114
- agent,
2115
- buildPromptForMode
2116
- };
2117
- }
2118
- /**
2119
- * The `tool_reference` blocks a `toolReference` tool_search result serializes to, or null for any
2120
- * other text (a no-match hint, a mutateTools result, or a result with an appended warning).
2121
- * Extra keys are tolerated so a field added to the core serializer does not silently disable the
2122
- * native path, and dropped because the provider rejects a `tool_reference` block with any other field.
2123
- */
2124
- function parseToolReferences(text) {
2125
- let parsed;
2126
- try {
2127
- parsed = JSON.parse(text);
2128
- } catch {
2129
- return null;
2130
- }
2131
- if (!Array.isArray(parsed) || parsed.length === 0) return null;
2132
- const isReference = (block) => typeof block === "object" && block !== null && block.type === "tool_reference" && typeof block.tool_name === "string";
2133
- return parsed.every(isReference) ? parsed.map(({ type, tool_name }) => ({
2134
- type,
2135
- tool_name
2136
- })) : null;
2137
- }
2138
- /**
2139
- * The CLI's `tool_search`: one schema, with the load strategy picked per call so a `/model` switch or a
2140
- * fallback model takes effect on the next search. Both strategies share the registry's search and
2141
- * ranking. With `toolReference` the matched tools are still added to the live list, because the agent
2142
- * executes only tools it holds; ToolSearchLlmBackend keeps them deferred on the wire.
2143
- */
2144
- function createCliToolSearchTool(options) {
2145
- const { registry, logger, toolListAccessor, useToolReference } = options;
2146
- const mutating = createToolSearchTool({
2147
- registry,
2148
- logger,
2149
- toolListAccessor
2150
- });
2151
- const referencing = createToolSearchTool({
2152
- registry,
2153
- logger,
2154
- loadStrategy: "toolReference"
2155
- });
2156
- return {
2157
- toolSchema: mutating.toolSchema,
2158
- toolFn: async (params) => {
2159
- if (!useToolReference()) return mutating.toolFn(params);
2160
- const result = await referencing.toolFn(params);
2161
- const references = parseToolReferences(result);
2162
- if (references) {
2163
- const liveTools = toolListAccessor();
2164
- const liveNames = new Set(liveTools.map((t) => t.toolSchema.name));
2165
- for (const tool of registry.getByNames(references.map((r) => r.tool_name))) {
2166
- if (liveNames.has(tool.toolSchema.name)) continue;
2167
- liveNames.add(tool.toolSchema.name);
2168
- liveTools.push(tool);
2169
- }
2170
- }
2171
- return result;
2172
- }
2173
- };
2174
- }
2175
- //#endregion
2176
- //#region src/llm/ToolSearchLlmBackend.ts
2177
- /**
2178
- * Same gate the completions endpoint applies (cliCompletionsToolSearch.ts), so the CLI never sends
2179
- * `tool_reference` blocks the server would refuse. A model missing from `models` reads false.
2180
- */
2181
- function modelServesToolReference(models, modelId) {
2182
- const model = models.find((m) => m.id === modelId);
2183
- return model !== void 0 && completionsSupportsToolSearch(model);
2184
- }
2185
- function toolSearchCallIds(messages) {
2186
- const ids = /* @__PURE__ */ new Set();
2187
- for (const message of messages) {
2188
- if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
2189
- for (const block of message.content) if (block?.type === "tool_use" && block.name === "tool_search" && typeof block.id === "string") ids.add(block.id);
2190
- }
2191
- return ids;
2192
- }
2193
- /**
2194
- * Rewrites the content of each tool_search result that holds serialized references. `rewrite`
2195
- * returning undefined leaves that result as is. Returns `messages` itself when nothing changed.
2196
- */
2197
- function rewriteToolSearchResults(messages, rewrite) {
2198
- const callIds = toolSearchCallIds(messages);
2199
- if (callIds.size === 0) return messages;
2200
- let changed = false;
2201
- const result = messages.map((message) => {
2202
- if (message.role !== "user" || !Array.isArray(message.content)) return message;
2203
- let messageChanged = false;
2204
- const content = message.content.map((block) => {
2205
- if (block?.type !== "tool_result" || typeof block.content !== "string") return block;
2206
- if (typeof block.tool_use_id !== "string" || !callIds.has(block.tool_use_id)) return block;
2207
- const references = parseToolReferences(block.content);
2208
- const replacement = references ? rewrite(references) : void 0;
2209
- if (replacement === void 0) return block;
2210
- messageChanged = true;
2211
- return {
2212
- ...block,
2213
- content: replacement
2214
- };
2215
- });
2216
- if (!messageChanged) return message;
2217
- changed = true;
2218
- return {
2219
- ...message,
2220
- content
2221
- };
2222
- });
2223
- return changed ? result : messages;
2224
- }
2225
- function asDeferred(tool) {
2226
- const { cache_control: _cacheControl, ...toolSchema } = tool.toolSchema;
2227
- return {
2228
- ...tool,
2229
- toolSchema: {
2230
- ...toolSchema,
2231
- defer_loading: true
2232
- }
2233
- };
2234
- }
2235
- /**
2236
- * Shapes one request's tools and tool_search results for the model it is sent to. History keeps
2237
- * tool_search results as the serialized text the tool returned, so it stays valid across a model switch.
2238
- *
2239
- * - Native tool search: the live tools other than registry ones, then every registry tool in registry
2240
- * order with `defer_loading: true`, so the array stays byte-identical across a tool load and the
2241
- * prompt cache holds. Serialized references become `tool_reference` blocks. A registry tool the live
2242
- * list holds with no reference left in history (loaded by mutateTools before a model switch, or by
2243
- * the unknown-tool resolver) is sent non-deferred so it stays callable.
2244
- * - Otherwise: tools unchanged, and any references from an earlier native turn become text, since
2245
- * the endpoint refuses `tool_reference` there. Referenced tools are already in the live list.
2246
- *
2247
- * Requests without `tool_search` (sub-agents, summaries) pass through untouched.
2248
- */
2249
- function prepareToolSearchRequest(request, registry, native) {
2250
- const { messages, tools } = request;
2251
- if (registry.size() === 0 || !tools.some((t) => t.toolSchema.name === "tool_search")) return request;
2252
- if (!native) {
2253
- const textMessages = rewriteToolSearchResults(messages, (references) => `Loaded ${references.length} tool schema(s): ${references.map((r) => r.tool_name).join(", ")}. These are now callable in your next message.`);
2254
- return textMessages === messages ? request : {
2255
- messages: textMessages,
2256
- tools
2257
- };
2258
- }
2259
- const registryTools = registry.getAll();
2260
- const wireTools = tools.filter((t) => !registry.has(t.toolSchema.name));
2261
- const wireNames = new Set([...wireTools, ...registryTools].map((t) => t.toolSchema.name));
2262
- const referenced = /* @__PURE__ */ new Set();
2263
- const wireMessages = rewriteToolSearchResults(messages, (references) => {
2264
- const resolved = references.filter((r) => wireNames.has(r.tool_name));
2265
- if (resolved.length === 0) return void 0;
2266
- for (const reference of resolved) referenced.add(reference.tool_name);
2267
- return resolved.length === references.length ? references : resolved;
2268
- });
2269
- const liveNames = new Set(tools.map((t) => t.toolSchema.name));
2270
- for (const tool of registryTools) {
2271
- const name = tool.toolSchema.name;
2272
- wireTools.push(liveNames.has(name) && !referenced.has(name) ? tool : asDeferred(tool));
2273
- }
2274
- if (wireTools.every((t) => t.toolSchema.defer_loading === true)) return request;
2275
- return {
2276
- messages: wireMessages,
2277
- tools: wireTools
2278
- };
2279
- }
2280
- /**
2281
- * Decorator that applies prepareToolSearchRequest per call, for the model each call actually goes to.
2282
- * Sits inside FallbackLlmBackend so a fallback model is shaped for itself.
2283
- */
2284
- var ToolSearchLlmBackend = class {
2285
- constructor(inner, registry, models) {
2286
- this.inner = inner;
2287
- this.registry = registry;
2288
- this.models = models;
2289
- this.lastToolSearchRequestNative = false;
2290
- }
2291
- get currentModel() {
2292
- return this.inner.currentModel;
2293
- }
2294
- set currentModel(model) {
2295
- this.inner.currentModel = model;
2296
- }
2297
- /** Whether the last request offering tool_search went to a native tool search model. */
2298
- servesToolReference() {
2299
- return this.lastToolSearchRequestNative;
2300
- }
2301
- async complete(model, messages, options, callback) {
2302
- const tools = options.tools ?? [];
2303
- if (!tools.some((t) => t.toolSchema.name === "tool_search")) return this.inner.complete(model, messages, options, callback);
2304
- const native = modelServesToolReference(this.models, model);
2305
- this.lastToolSearchRequestNative = native;
2306
- const prepared = prepareToolSearchRequest({
2307
- messages,
2308
- tools
2309
- }, this.registry, native);
2310
- const preparedOptions = prepared.tools === tools ? options : {
2311
- ...options,
2312
- tools: prepared.tools
2313
- };
2314
- return this.inner.complete(model, prepared.messages, preparedOptions, callback);
2315
- }
2316
- pushToolMessages(messages, tool, result, thinkingBlocks) {
2317
- this.inner.pushToolMessages(messages, tool, result, thinkingBlocks);
2318
- }
2319
- async getModelInfo() {
2320
- return this.inner.getModelInfo();
2321
- }
2322
- };
2323
- //#endregion
2324
- //#region src/bootstrap/buildToolSearch.ts
2325
- /**
2326
- * The main agent's tool_search and the backend that shapes its requests per model: native tool search
2327
- * (`toolReference` + `defer_loading`) where the model serves it, `mutateTools` everywhere else. With no
2328
- * deferred tools there is no tool_search and the backend is returned unwrapped.
2329
- */
2330
- function buildToolSearch(input) {
2331
- const { llm, models, registry, logger, agentToolsRef } = input;
2332
- if (registry.size() === 0) return {
2333
- llm,
2334
- toolSearchTool: null
2335
- };
2336
- const toolSearchLlm = new ToolSearchLlmBackend(llm, registry, models);
2337
- return {
2338
- llm: toolSearchLlm,
2339
- toolSearchTool: createCliToolSearchTool({
2340
- registry,
2341
- logger,
2342
- toolListAccessor: () => {
2343
- if (!agentToolsRef.current) throw new Error("tool_search invoked before agent context was wired");
2344
- return agentToolsRef.current;
2345
- },
2346
- useToolReference: () => toolSearchLlm.servesToolReference()
2347
- })
2348
- };
2349
- }
2350
- //#endregion
2351
- export { deferredToolRegistry as a, buildLlmBackend as i, buildAgent as n, NotifyingLlmBackend as o, buildSupportingStores as r, buildToolSearch as t };