@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,6 +1,6 @@
1
1
  ---
2
2
  description: Run and analyze test suites, identify failures, suggest fixes
3
- model: claude-sonnet-4-5-20250929
3
+ model: claude-sonnet-5-5
4
4
  allowed-tools:
5
5
  - bash_execute
6
6
  - file_read
@@ -28,19 +28,23 @@ shared-context:
28
28
  You are a test execution and analysis specialist. Your job is to run tests, analyze results, and identify failures.
29
29
 
30
30
  ## Focus Areas
31
+
31
32
  - Running test suites and individual test files
32
33
  - Analyzing test output for failures and errors
33
34
  - Identifying root causes of test failures
34
35
  - Suggesting targeted fixes
35
36
 
36
37
  ## Tool Usage
38
+
37
39
  You have read-only file access plus bash for running tests:
40
+
38
41
  - `bash_execute` - Run test commands (npm test, pnpm test, jest, pytest, etc.)
39
42
  - `file_read` - Read test files and source files to understand failures
40
43
  - `grep_search` - Search for related test patterns or error messages
41
44
  - `glob_files` - Find test files by pattern
42
45
 
43
46
  ## Strategy
47
+
44
48
  1. Identify the test framework in use (check package.json, config files)
45
49
  2. Run the requested tests using `bash_execute`
46
50
  3. Parse output for failures, errors, and warnings
@@ -49,13 +53,16 @@ You have read-only file access plus bash for running tests:
49
53
  6. Provide clear diagnosis and fix suggestions
50
54
 
51
55
  ## Output Format
56
+
52
57
  Provide a structured summary:
58
+
53
59
  1. **Test Results**: Pass/fail counts, which tests failed
54
60
  2. **Failure Analysis**: For each failure - what failed, why, stack trace highlights
55
61
  3. **Root Cause**: Likely cause of each failure
56
62
  4. **Suggested Fixes**: Concrete code changes to fix failures
57
63
 
58
64
  ## Iteration Budget
65
+
59
66
  You have **$MAX_ITERATIONS iterations** for this task (thoroughness: $THOROUGHNESS). Plan your tool usage to complete within this budget. Prioritize the most impactful actions first.
60
67
 
61
68
  Be precise with file:line references. Your summary will be used by the main agent.
@@ -0,0 +1,417 @@
1
+ #!/usr/bin/env node
2
+ import { U as generateCliTools, a as loadProjectContext, bt as getPlanModeFilePath, ft as DeferredToolRegistry, gt as wrapTools, i as buildProjectAgentStore, mt as createToolSearchTool, n as BackgroundAgentManager, o as McpManager, pt as ReActAgent, r as SubagentOrchestrator, t as AgentHistoryStore, ut as buildSystemPrompt } from "./AgentHistoryStore--J3sgO_-.mjs";
3
+ import { st as completionsSupportsToolSearch, t as logger } from "./Logger-C1Wj6xla.mjs";
4
+ //#region src/llm/NotifyingLlmBackend.ts
5
+ /**
6
+ * LLM backend wrapper that injects background agent notifications
7
+ * into the message array before each completion call.
8
+ *
9
+ * When a background agent completes (or fails), the notification
10
+ * appears as a system message so the main agent naturally sees it
11
+ * in context - no polling required.
12
+ */
13
+ var NotifyingLlmBackend = class {
14
+ constructor(inner, backgroundManager) {
15
+ this.inner = inner;
16
+ this.backgroundManager = backgroundManager;
17
+ }
18
+ get currentModel() {
19
+ return this.inner.currentModel;
20
+ }
21
+ set currentModel(model) {
22
+ this.inner.currentModel = model;
23
+ }
24
+ async complete(model, messages, options, callback) {
25
+ const notifications = this.backgroundManager.drainNotifications();
26
+ let effectiveMessages = messages;
27
+ if (notifications.length > 0) {
28
+ const notificationMessage = {
29
+ role: "user",
30
+ 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.`
31
+ };
32
+ effectiveMessages = [...messages, notificationMessage];
33
+ }
34
+ return this.inner.complete(model, effectiveMessages, options, callback);
35
+ }
36
+ pushToolMessages(messages, tool, result) {
37
+ return this.inner.pushToolMessages(messages, tool, result);
38
+ }
39
+ async getModelInfo() {
40
+ return this.inner.getModelInfo();
41
+ }
42
+ };
43
+ //#endregion
44
+ //#region src/tools/deferredToolRegistry.ts
45
+ const deferredToolRegistry = new DeferredToolRegistry({ logger });
46
+ //#endregion
47
+ //#region src/bootstrap/buildSupportingStores.ts
48
+ /**
49
+ * Build the supporting stores and orchestration the agent needs: CLI tools
50
+ * (permission-wrapped + server-routed), MCP manager, agent store, context
51
+ * files, the deferred-tool registry partition, the subagent orchestrator, and
52
+ * the background-agent manager.
53
+ *
54
+ * Pure bootstrap seam: no React hooks, no Zustand state. React-owned values
55
+ * (permission/user-question prompt functions, the agent context, and the
56
+ * background-agent status callbacks) are passed in. Tool *assembly* that weaves
57
+ * the React workflow-store refs (decision/blocker/review-gate tools) stays in
58
+ * the shell; this module returns only the agent-construction materials.
59
+ */
60
+ async function buildSupportingStores(input) {
61
+ const { config, llm, modelId, permissionManager, apiClient, configStore, customCommandStore, checkpointStore, sandboxOrchestrator, additionalDirectories, agentContext, promptFn, userQuestionFn, startupLog, silentLogger, onBackgroundStatusChange, onGroupCompletion, onSubagentUsage, isCancelled } = input;
62
+ const { tools: b4mTools } = await generateCliTools(config.userId, llm, modelId, permissionManager, promptFn, agentContext, configStore, apiClient, void 0, userQuestionFn, checkpointStore, sandboxOrchestrator, additionalDirectories, void 0, isCancelled);
63
+ const mcpManager = new McpManager(config);
64
+ const builtinAgentsDir = new URL("../agents/defaults/", import.meta.url).pathname;
65
+ const agentStore = buildProjectAgentStore(builtinAgentsDir, configStore);
66
+ const [, , contextResult] = await Promise.all([
67
+ mcpManager.initialize(),
68
+ agentStore.loadAgents(),
69
+ loadProjectContext(configStore)
70
+ ]);
71
+ const mcpTools = wrapTools(mcpManager.getTools(), {
72
+ permissionManager,
73
+ showPermissionPrompt: promptFn,
74
+ agentContext,
75
+ configStore,
76
+ apiClient,
77
+ sandboxOrchestrator,
78
+ allowedDirectories: additionalDirectories,
79
+ isCancelled
80
+ });
81
+ const deferredB4mToolNames = /* @__PURE__ */ new Set([
82
+ "math_evaluate",
83
+ "dice_roll",
84
+ "current_datetime",
85
+ "recent_changes",
86
+ "prompt_enhancement"
87
+ ]);
88
+ const deferredB4mTools = b4mTools.filter((t) => deferredB4mToolNames.has(t.toolSchema.name));
89
+ const loadedB4mTools = b4mTools.filter((t) => !deferredB4mToolNames.has(t.toolSchema.name));
90
+ deferredToolRegistry.register([...mcpTools, ...deferredB4mTools]);
91
+ if (mcpTools.length > 0) {
92
+ const serverSummaries = mcpManager.getToolCount().map((s) => `${s.serverName} (${s.count})`).join(", ");
93
+ startupLog.push(`🛠️ Loaded ${loadedB4mTools.length} B4M + ${mcpTools.length} MCP tool(s, ${deferredB4mTools.length + mcpTools.length} deferred): ${serverSummaries}`);
94
+ } else {
95
+ const suffix = deferredB4mTools.length > 0 ? ` (${deferredB4mTools.length} deferred)` : "";
96
+ startupLog.push(`🛠️ Loaded ${loadedB4mTools.length} B4M tool(s)${suffix}, no MCP tools`);
97
+ }
98
+ const agentSummary = agentStore.getSummary();
99
+ startupLog.push(`🤖 Loaded ${agentSummary.total} agent(s): ${agentSummary.builtin} built-in, ${agentSummary.global} global, ${agentSummary.project} project`);
100
+ const historyStore = new AgentHistoryStore(config.preferences.subagentHistoryTtlMs ?? 36e5);
101
+ const orchestrator = new SubagentOrchestrator({
102
+ userId: config.userId,
103
+ llm,
104
+ logger: silentLogger,
105
+ permissionManager,
106
+ showPermissionPrompt: promptFn,
107
+ configStore,
108
+ apiClient,
109
+ agentStore,
110
+ customCommandStore,
111
+ enableParallelToolExecution: config.preferences.enableParallelToolExecution === true,
112
+ showUserQuestion: userQuestionFn,
113
+ checkpointStore,
114
+ onSubagentUsage,
115
+ historyStore,
116
+ sandboxOrchestrator,
117
+ additionalDirectories,
118
+ isCancelled
119
+ });
120
+ const backgroundManager = new BackgroundAgentManager(orchestrator);
121
+ backgroundManager.setOnStatusChange(onBackgroundStatusChange);
122
+ backgroundManager.setOnGroupCompletion(onGroupCompletion);
123
+ return {
124
+ mcpManager,
125
+ agentStore,
126
+ contextResult,
127
+ mcpTools,
128
+ loadedB4mTools,
129
+ deferredB4mTools,
130
+ orchestrator,
131
+ backgroundManager,
132
+ historyStore
133
+ };
134
+ }
135
+ //#endregion
136
+ //#region src/bootstrap/buildAgent.ts
137
+ /**
138
+ * Construct the main ReAct agent with the system prompt selected by config
139
+ * variant, wire the tool_search closure to the agent's live tools array, and
140
+ * record the agent in the shared observation context.
141
+ *
142
+ * Pure bootstrap seam: no React hooks, no Zustand state. The interaction-mode
143
+ * subscription (`useCliStore.subscribe`) stays in the shell and uses the
144
+ * returned `buildPromptForMode`. Ordering is load-bearing: agent built ->
145
+ * agentToolsRef wired -> agentContext.currentAgent set, all here, before the
146
+ * shell registers the subscription (which guards on currentAgent === agent).
147
+ */
148
+ function buildAgent(input) {
149
+ const { config, modelId, notifyingLlm, allTools, agentContext, agentToolsRef, silentLogger, sessionId, initialInteractionMode, contextContent, agentStore, customCommandStore, enableSkillTool, additionalDirectories, featureModulePrompts } = input;
150
+ const promptVariant = config.preferences.promptVariant ?? "current";
151
+ const buildPromptForMode = (mode) => buildSystemPrompt(promptVariant, {
152
+ contextContent,
153
+ agentStore,
154
+ customCommands: customCommandStore.getModelReachableCommands(),
155
+ enableSkillTool,
156
+ enableDynamicAgentCreation: config.preferences.enableDynamicAgentCreation === true,
157
+ additionalDirectories,
158
+ featureModulePrompts: featureModulePrompts || void 0,
159
+ planModeFilePath: mode === "plan" ? getPlanModeFilePath(sessionId) : void 0,
160
+ appendSystemPrompt: process.env.B4M_APPEND_SYSTEM_PROMPT,
161
+ deferredToolNames: deferredToolRegistry.getDirectoryNames()
162
+ });
163
+ const cliSystemPrompt = buildPromptForMode(initialInteractionMode);
164
+ const maxIterations = config.preferences.maxIterations === null ? 999999 : config.preferences.maxIterations;
165
+ const agent = new ReActAgent({
166
+ userId: config.userId,
167
+ logger: silentLogger,
168
+ llm: notifyingLlm,
169
+ model: modelId,
170
+ tools: allTools,
171
+ maxIterations,
172
+ maxTokens: config.preferences.maxTokens,
173
+ temperature: config.preferences.temperature,
174
+ systemPrompt: cliSystemPrompt,
175
+ unknownToolResolver: async (toolName) => deferredToolRegistry.get(toolName) ?? null
176
+ });
177
+ agentToolsRef.current = agent.getTools();
178
+ agentContext.currentAgent = agent;
179
+ return {
180
+ agent,
181
+ buildPromptForMode
182
+ };
183
+ }
184
+ /**
185
+ * The `tool_reference` blocks a `toolReference` tool_search result serializes to, or null for any
186
+ * other text (a no-match hint, a mutateTools result, or a result with an appended warning).
187
+ * Extra keys are tolerated so a field added to the core serializer does not silently disable the
188
+ * native path, and dropped because the provider rejects a `tool_reference` block with any other field.
189
+ */
190
+ function parseToolReferences(text) {
191
+ let parsed;
192
+ try {
193
+ parsed = JSON.parse(text);
194
+ } catch {
195
+ return null;
196
+ }
197
+ if (!Array.isArray(parsed) || parsed.length === 0) return null;
198
+ const isReference = (block) => typeof block === "object" && block !== null && block.type === "tool_reference" && typeof block.tool_name === "string";
199
+ return parsed.every(isReference) ? parsed.map(({ type, tool_name }) => ({
200
+ type,
201
+ tool_name
202
+ })) : null;
203
+ }
204
+ /**
205
+ * The CLI's `tool_search`: one schema, with the load strategy picked per call so a `/model` switch or a
206
+ * fallback model takes effect on the next search. Both strategies share the registry's search and
207
+ * ranking. With `toolReference` the matched tools are still added to the live list, because the agent
208
+ * executes only tools it holds; ToolSearchLlmBackend keeps them deferred on the wire.
209
+ */
210
+ function createCliToolSearchTool(options) {
211
+ const { registry, logger, toolListAccessor, useToolReference } = options;
212
+ const mutating = createToolSearchTool({
213
+ registry,
214
+ logger,
215
+ toolListAccessor
216
+ });
217
+ const referencing = createToolSearchTool({
218
+ registry,
219
+ logger,
220
+ loadStrategy: "toolReference"
221
+ });
222
+ return {
223
+ toolSchema: mutating.toolSchema,
224
+ toolFn: async (params) => {
225
+ if (!useToolReference()) return mutating.toolFn(params);
226
+ const result = await referencing.toolFn(params);
227
+ const references = parseToolReferences(result);
228
+ if (references) {
229
+ const liveTools = toolListAccessor();
230
+ const liveNames = new Set(liveTools.map((t) => t.toolSchema.name));
231
+ for (const tool of registry.getByNames(references.map((r) => r.tool_name))) {
232
+ if (liveNames.has(tool.toolSchema.name)) continue;
233
+ liveNames.add(tool.toolSchema.name);
234
+ liveTools.push(tool);
235
+ }
236
+ }
237
+ return result;
238
+ }
239
+ };
240
+ }
241
+ //#endregion
242
+ //#region src/llm/ToolSearchLlmBackend.ts
243
+ /**
244
+ * Same gate the completions endpoint applies (cliCompletionsToolSearch.ts), so the CLI never sends
245
+ * `tool_reference` blocks the server would refuse. A model missing from `models` reads false.
246
+ */
247
+ function modelServesToolReference(models, modelId) {
248
+ const model = models.find((m) => m.id === modelId);
249
+ return model !== void 0 && completionsSupportsToolSearch(model);
250
+ }
251
+ function toolSearchCallIds(messages) {
252
+ const ids = /* @__PURE__ */ new Set();
253
+ for (const message of messages) {
254
+ if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
255
+ for (const block of message.content) if (block?.type === "tool_use" && block.name === "tool_search" && typeof block.id === "string") ids.add(block.id);
256
+ }
257
+ return ids;
258
+ }
259
+ /**
260
+ * Rewrites the content of each tool_search result that holds serialized references. `rewrite`
261
+ * returning undefined leaves that result as is. Returns `messages` itself when nothing changed.
262
+ */
263
+ function rewriteToolSearchResults(messages, rewrite) {
264
+ const callIds = toolSearchCallIds(messages);
265
+ if (callIds.size === 0) return messages;
266
+ let changed = false;
267
+ const result = messages.map((message) => {
268
+ if (message.role !== "user" || !Array.isArray(message.content)) return message;
269
+ let messageChanged = false;
270
+ const content = message.content.map((block) => {
271
+ if (block?.type !== "tool_result" || typeof block.content !== "string") return block;
272
+ if (typeof block.tool_use_id !== "string" || !callIds.has(block.tool_use_id)) return block;
273
+ const references = parseToolReferences(block.content);
274
+ const replacement = references ? rewrite(references) : void 0;
275
+ if (replacement === void 0) return block;
276
+ messageChanged = true;
277
+ return {
278
+ ...block,
279
+ content: replacement
280
+ };
281
+ });
282
+ if (!messageChanged) return message;
283
+ changed = true;
284
+ return {
285
+ ...message,
286
+ content
287
+ };
288
+ });
289
+ return changed ? result : messages;
290
+ }
291
+ function asDeferred(tool) {
292
+ const { cache_control: _cacheControl, ...toolSchema } = tool.toolSchema;
293
+ return {
294
+ ...tool,
295
+ toolSchema: {
296
+ ...toolSchema,
297
+ defer_loading: true
298
+ }
299
+ };
300
+ }
301
+ /**
302
+ * Shapes one request's tools and tool_search results for the model it is sent to. History keeps
303
+ * tool_search results as the serialized text the tool returned, so it stays valid across a model switch.
304
+ *
305
+ * - Native tool search: the live tools other than registry ones, then every registry tool in registry
306
+ * order with `defer_loading: true`, so the array stays byte-identical across a tool load and the
307
+ * prompt cache holds. Serialized references become `tool_reference` blocks. A registry tool the live
308
+ * list holds with no reference left in history (loaded by mutateTools before a model switch, or by
309
+ * the unknown-tool resolver) is sent non-deferred so it stays callable.
310
+ * - Otherwise: tools unchanged, and any references from an earlier native turn become text, since
311
+ * the endpoint refuses `tool_reference` there. Referenced tools are already in the live list.
312
+ *
313
+ * Requests without `tool_search` (sub-agents, summaries) pass through untouched.
314
+ */
315
+ function prepareToolSearchRequest(request, registry, native) {
316
+ const { messages, tools } = request;
317
+ if (registry.size() === 0 || !tools.some((t) => t.toolSchema.name === "tool_search")) return request;
318
+ if (!native) {
319
+ 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.`);
320
+ return textMessages === messages ? request : {
321
+ messages: textMessages,
322
+ tools
323
+ };
324
+ }
325
+ const registryTools = registry.getAll();
326
+ const wireTools = tools.filter((t) => !registry.has(t.toolSchema.name));
327
+ const wireNames = new Set([...wireTools, ...registryTools].map((t) => t.toolSchema.name));
328
+ const referenced = /* @__PURE__ */ new Set();
329
+ const wireMessages = rewriteToolSearchResults(messages, (references) => {
330
+ const resolved = references.filter((r) => wireNames.has(r.tool_name));
331
+ if (resolved.length === 0) return void 0;
332
+ for (const reference of resolved) referenced.add(reference.tool_name);
333
+ return resolved.length === references.length ? references : resolved;
334
+ });
335
+ const liveNames = new Set(tools.map((t) => t.toolSchema.name));
336
+ for (const tool of registryTools) {
337
+ const name = tool.toolSchema.name;
338
+ wireTools.push(liveNames.has(name) && !referenced.has(name) ? tool : asDeferred(tool));
339
+ }
340
+ if (wireTools.every((t) => t.toolSchema.defer_loading === true)) return request;
341
+ return {
342
+ messages: wireMessages,
343
+ tools: wireTools
344
+ };
345
+ }
346
+ /**
347
+ * Decorator that applies prepareToolSearchRequest per call, for the model each call actually goes to.
348
+ * Sits inside FallbackLlmBackend so a fallback model is shaped for itself.
349
+ */
350
+ var ToolSearchLlmBackend = class {
351
+ constructor(inner, registry, models) {
352
+ this.inner = inner;
353
+ this.registry = registry;
354
+ this.models = models;
355
+ this.lastToolSearchRequestNative = false;
356
+ }
357
+ get currentModel() {
358
+ return this.inner.currentModel;
359
+ }
360
+ set currentModel(model) {
361
+ this.inner.currentModel = model;
362
+ }
363
+ /** Whether the last request offering tool_search went to a native tool search model. */
364
+ servesToolReference() {
365
+ return this.lastToolSearchRequestNative;
366
+ }
367
+ async complete(model, messages, options, callback) {
368
+ const tools = options.tools ?? [];
369
+ if (!tools.some((t) => t.toolSchema.name === "tool_search")) return this.inner.complete(model, messages, options, callback);
370
+ const native = modelServesToolReference(this.models, model);
371
+ this.lastToolSearchRequestNative = native;
372
+ const prepared = prepareToolSearchRequest({
373
+ messages,
374
+ tools
375
+ }, this.registry, native);
376
+ const preparedOptions = prepared.tools === tools ? options : {
377
+ ...options,
378
+ tools: prepared.tools
379
+ };
380
+ return this.inner.complete(model, prepared.messages, preparedOptions, callback);
381
+ }
382
+ pushToolMessages(messages, tool, result, thinkingBlocks) {
383
+ this.inner.pushToolMessages(messages, tool, result, thinkingBlocks);
384
+ }
385
+ async getModelInfo() {
386
+ return this.inner.getModelInfo();
387
+ }
388
+ };
389
+ //#endregion
390
+ //#region src/bootstrap/buildToolSearch.ts
391
+ /**
392
+ * The main agent's tool_search and the backend that shapes its requests per model: native tool search
393
+ * (`toolReference` + `defer_loading`) where the model serves it, `mutateTools` everywhere else. With no
394
+ * deferred tools there is no tool_search and the backend is returned unwrapped.
395
+ */
396
+ function buildToolSearch(input) {
397
+ const { llm, models, registry, logger, agentToolsRef } = input;
398
+ if (registry.size() === 0) return {
399
+ llm,
400
+ toolSearchTool: null
401
+ };
402
+ const toolSearchLlm = new ToolSearchLlmBackend(llm, registry, models);
403
+ return {
404
+ llm: toolSearchLlm,
405
+ toolSearchTool: createCliToolSearchTool({
406
+ registry,
407
+ logger,
408
+ toolListAccessor: () => {
409
+ if (!agentToolsRef.current) throw new Error("tool_search invoked before agent context was wired");
410
+ return agentToolsRef.current;
411
+ },
412
+ useToolReference: () => toolSearchLlm.servesToolReference()
413
+ })
414
+ };
415
+ }
416
+ //#endregion
417
+ export { NotifyingLlmBackend as a, deferredToolRegistry as i, buildAgent as n, buildSupportingStores as r, buildToolSearch as t };
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { A as createAgentDelegateTool, C as createTodoStore, D as createCoordinateTaskTool, N as PermissionManager, O as createResumeAgentTool, P as buildCliToolList, Q as CustomCommandStore, S as createFindDefinitionTool, T as createSkillTool, Y as setWebSocketToolExecutor, b as createGetFileStructureTool, j as FallbackLlmBackend, k as createBackgroundAgentTools, nt as SessionStore, s as buildSandbox, tt as CheckpointStore, w as createWriteTodosTool } from "../AgentHistoryStore-DgqmcVLN.mjs";
3
- import { b as logger, i as ToolCatalog, p as requireApiUrl, t as ConfigStore } from "../ConfigStore-BwqsQ0U9.mjs";
2
+ import { A as createTodoStore, D as createGetFileStructureTool, Et as SessionStore, F as createResumeAgentTool, H as buildCliToolList, I as createBackgroundAgentTools, L as createAgentDelegateTool, M as createSkillTool, P as createCoordinateTaskTool, R as FallbackLlmBackend, V as PermissionManager, Z as NoLocalModelsError, at as signInUncheckedHeadlessMessage, c as checkSavedSignIn, f as buildLlmBackend, j as createWriteTodosTool, k as createFindDefinitionTool, l as settleSignInRefresh, s as buildSandbox, tt as SIGN_IN_EXPIRED_HEADLESS, vt as setWebSocketToolExecutor, wt as CheckpointStore, xt as CustomCommandStore } from "../AgentHistoryStore--J3sgO_-.mjs";
3
+ import { c as ToolCatalog, t as ConfigStore, v as requireApiUrl } from "../ConfigStore-Dusy6glb.mjs";
4
+ import { t as logger } from "../Logger-C1Wj6xla.mjs";
4
5
  import { t as RemoteSkillSource } from "../RemoteSkillSource-qTvRkaNA.mjs";
5
- import { a as deferredToolRegistry, i as buildLlmBackend, n as buildAgent, o as NotifyingLlmBackend, r as buildSupportingStores, t as buildToolSearch } from "../buildToolSearch-D9GEK91u.mjs";
6
- import { t as ApiClient } from "../ApiClient-_JrM_xWw.mjs";
6
+ import { t as ApiClient } from "../ApiClient-CdO4Gamg.mjs";
7
+ import { a as NotifyingLlmBackend, i as deferredToolRegistry, n as buildAgent, r as buildSupportingStores, t as buildToolSearch } from "../buildToolSearch-DOb7mx6F.mjs";
7
8
  import { randomUUID } from "crypto";
8
9
  import { existsSync, realpathSync, statSync } from "fs";
9
10
  import { isAbsolute } from "path";
@@ -582,23 +583,27 @@ var AcpServer = class {
582
583
  const config = await this.configStore.load();
583
584
  this.configStore.warnPendingMcpApprovals();
584
585
  await this.loadCustomCommands();
585
- const authTokens = await this.configStore.getAuthTokens();
586
- if (!authTokens) throw RequestError.authRequired(void 0, "Not authenticated. Run `b4m /login` first.");
587
- if (new Date(authTokens.expiresAt) <= /* @__PURE__ */ new Date()) {
588
- await this.configStore.clearAuthTokens();
589
- throw RequestError.authRequired(void 0, "Authentication expired. Run `b4m /login` again.");
590
- }
591
- const apiBaseURL = requireApiUrl(config.apiConfig);
592
- const apiClient = new ApiClient(apiBaseURL, this.configStore);
586
+ const signIn = await checkSavedSignIn(this.configStore, (rejected) => new ApiClient(requireApiUrl(config.apiConfig), this.configStore).refreshSession(rejected));
587
+ if (signIn.status === "expired") process.stderr.write(`${SIGN_IN_EXPIRED_HEADLESS}\n`);
588
+ if (signIn.status === "unchecked") process.stderr.write(`${signInUncheckedHeadlessMessage(signIn.reason)}\n`);
589
+ const apiClient = signIn.status === "signed-in" ? new ApiClient(requireApiUrl(config.apiConfig), this.configStore) : ApiClient.whileSignedOut(this.configStore);
593
590
  const tokenGetter = async () => (await this.configStore.getAuthTokens())?.accessToken ?? null;
594
- await this.mergeRemoteSkills(config, apiClient);
591
+ if (!apiClient.signedOut) await this.mergeRemoteSkills(config, apiClient);
595
592
  const startupLog = [];
596
- const { llm, wsManager, models, modelInfo } = await buildLlmBackend({
597
- config,
598
- apiClient,
599
- tokenGetter,
600
- startupLog
601
- });
593
+ let built;
594
+ try {
595
+ built = await buildLlmBackend({
596
+ config,
597
+ apiClient,
598
+ tokenGetter,
599
+ startupLog,
600
+ ...apiClient.signedOut && { detectOllama: true }
601
+ });
602
+ } catch (error) {
603
+ if (error instanceof NoLocalModelsError) throw RequestError.authRequired(void 0, error.message);
604
+ throw error;
605
+ }
606
+ const { llm, wsManager, models, modelInfo } = built;
602
607
  const permissionManager = new PermissionManager(new ToolCatalog(), config.trustedTools ?? [], config.tools.disabled ?? []);
603
608
  const checkpointStore = new CheckpointStore(this.configStore.getProjectConfigDir() ?? process.cwd());
604
609
  const stackSessionId = randomUUID();
@@ -816,6 +821,7 @@ async function handleAcpCommand(options) {
816
821
  server = new AcpServer(connection.signal, options.version);
817
822
  await connection.closed;
818
823
  await server.close();
824
+ await settleSignInRefresh();
819
825
  }
820
826
  //#endregion
821
827
  export { handleAcpCommand };
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { m as resolveApiEndpoint, t as ConfigStore, y as parseApiUrl } from "../ConfigStore-BwqsQ0U9.mjs";
2
+ import { T as parseApiUrl, t as ConfigStore, y as resolveApiEndpoint } from "../ConfigStore-Dusy6glb.mjs";
3
3
  //#region src/commands/apiCommand.ts
4
4
  /**
5
5
  * External API config command (--api-url / --reset-api)
@@ -23,15 +23,13 @@ async function handleApiCommand(options) {
23
23
  process.exit(1);
24
24
  }
25
25
  const { url } = result;
26
- await configStore.setCustomApiUrl(url);
27
- await configStore.clearAuthTokens();
26
+ await configStore.withRefreshLock(() => configStore.setCustomApiUrlSignedOut(url));
28
27
  console.log(`\n✅ API URL set to ${url}`);
29
28
  console.log("🔓 Authentication cleared");
30
29
  console.log("💡 Run `b4m` to authenticate against the new API.\n");
31
30
  return;
32
31
  }
33
- await configStore.setCustomApiUrl(null);
34
- await configStore.clearAuthTokens();
32
+ await configStore.withRefreshLock(() => configStore.setCustomApiUrlSignedOut(null));
35
33
  const endpoint = resolveApiEndpoint();
36
34
  console.log("\n✅ Custom API URL cleared");
37
35
  console.log("🔓 Authentication cleared");
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { t as version } from "../package-CQaam4Dq.mjs";
3
- import { c as isNpmPrefixWritable, i as fetchLatestVersion, r as compareSemver } from "../updateChecker-CCLVVdH0.mjs";
2
+ import { t as version } from "../package-C9pfAdGF.mjs";
3
+ import { c as isNpmPrefixWritable, i as fetchLatestVersion, r as compareSemver } from "../updateChecker-BAKb8KWP.mjs";
4
4
  import { t as checkRipgrep } from "../ripgrepCheck-BmkyTK2i.mjs";
5
5
  import { existsSync } from "fs";
6
6
  import { homedir } from "os";
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as ConfigStore } from "../ConfigStore-BwqsQ0U9.mjs";
2
+ import { t as ConfigStore } from "../ConfigStore-Dusy6glb.mjs";
3
3
  //#region src/commands/envCommand.ts
4
4
  /**
5
5
  * Environment switching for the `--dev` / `--prod` launch flags.