@bike4mind/cli 3.4.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.
- package/README.md +223 -39
- package/bin/bike4mind-cli.mjs +301 -38
- package/bin/envFlags.d.mts +17 -0
- package/bin/envFlags.mjs +89 -0
- package/bin/hearth-hook.mjs +53 -7
- package/dist/{AgentHistoryStore-ClO2zOn6.mjs → AgentHistoryStore--J3sgO_-.mjs} +9011 -6699
- package/dist/ApiClient-CdO4Gamg.mjs +152 -0
- package/dist/BubblewrapRuntime-3jAbC60G.mjs +157 -0
- package/dist/ConfigStore-CausUCzY.mjs +2 -0
- package/dist/ConfigStore-Dusy6glb.mjs +3364 -0
- package/dist/{ConfigStore-CbVFLXMH.mjs → Logger-C1Wj6xla.mjs} +32880 -20779
- package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
- package/dist/RemoteSkillSource-qTvRkaNA.mjs +455 -0
- package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-CQwYq_uy.mjs} +26 -7
- package/dist/SandboxRuntimeAdapter-BsT2iLky.mjs +190 -0
- package/dist/SandboxRuntimeAdapter-Zg_0th7V.mjs +2 -0
- package/dist/SeatbeltRuntime-C2DEkrjy.mjs +194 -0
- package/dist/{WorkItemsClient-SeNbzvEw.mjs → WorkItemsClient-CxNZaOmc.mjs} +1 -1
- package/dist/agents/defaults/review.md +8 -1
- package/dist/agents/defaults/test.md +8 -1
- package/dist/buildToolSearch-DOb7mx6F.mjs +417 -0
- package/dist/commands/acpCommand.mjs +33 -27
- package/dist/commands/apiCommand.mjs +3 -5
- package/dist/commands/doctorCommand.mjs +2 -2
- package/dist/commands/envCommand.mjs +1 -1
- package/dist/commands/headlessCommand.mjs +118 -36
- package/dist/commands/hostCommand.mjs +2344 -0
- package/dist/commands/mcpCommand.mjs +46 -30
- package/dist/commands/mirrorCommand.mjs +279 -0
- package/dist/commands/modelsCommand.mjs +1117 -0
- package/dist/commands/pluginCommand.mjs +9 -9
- package/dist/commands/skillsCommand.mjs +404 -0
- package/dist/commands/updateCommand.mjs +2 -2
- package/dist/curated-build.json +1 -0
- package/dist/dist-CbViwiS9.mjs +4739 -0
- package/dist/dist-Citbv0y0.mjs +7864 -0
- package/dist/fit-CVWDiavv.mjs +200 -0
- package/dist/index.mjs +1001 -442
- package/dist/modelHub-BSB6qRFP.mjs +1963 -0
- package/dist/modelServers-BaegigV-.mjs +2465 -0
- package/dist/{package-MoDZ9cGj.mjs → package-C9pfAdGF.mjs} +1 -1
- package/dist/{serve-zi-B2iUT.mjs → serve-8wyGb8of.mjs} +1243 -44
- package/dist/store-BYeE0shc.mjs +2 -0
- package/dist/{store-BxmPEI3v.mjs → store-BbvSi3KK.mjs} +26 -2
- package/dist/types-BFIvwByC.mjs +2 -0
- package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
- package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-BAKb8KWP.mjs} +7 -29
- package/package.json +17 -13
- package/dist/BubblewrapRuntime-5bLPTwEC.mjs +0 -72
- package/dist/SandboxRuntimeAdapter-BgLUVTJL.mjs +0 -57
- package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +0 -2
- package/dist/SeatbeltRuntime-C_Y8q8Mr.mjs +0 -124
- package/dist/buildAgent-BeaVbpzH.mjs +0 -1992
- package/dist/dist-DlBq3wHu.mjs +0 -739
- package/dist/store-BkMur6uk.mjs +0 -2
- package/dist/types-I45lMh7Q.mjs +0 -2
|
@@ -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,8 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
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";
|
|
5
|
+
import { t as RemoteSkillSource } from "../RemoteSkillSource-qTvRkaNA.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";
|
|
6
8
|
import { randomUUID } from "crypto";
|
|
7
9
|
import { existsSync, realpathSync, statSync } from "fs";
|
|
8
10
|
import { isAbsolute } from "path";
|
|
@@ -581,23 +583,27 @@ var AcpServer = class {
|
|
|
581
583
|
const config = await this.configStore.load();
|
|
582
584
|
this.configStore.warnPendingMcpApprovals();
|
|
583
585
|
await this.loadCustomCommands();
|
|
584
|
-
const
|
|
585
|
-
if (
|
|
586
|
-
if (
|
|
587
|
-
|
|
588
|
-
throw RequestError.authRequired(void 0, "Authentication expired. Run `b4m /login` again.");
|
|
589
|
-
}
|
|
590
|
-
const apiBaseURL = requireApiUrl(config.apiConfig);
|
|
591
|
-
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);
|
|
592
590
|
const tokenGetter = async () => (await this.configStore.getAuthTokens())?.accessToken ?? null;
|
|
593
|
-
await this.mergeRemoteSkills(config, apiClient);
|
|
591
|
+
if (!apiClient.signedOut) await this.mergeRemoteSkills(config, apiClient);
|
|
594
592
|
const startupLog = [];
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
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;
|
|
601
607
|
const permissionManager = new PermissionManager(new ToolCatalog(), config.trustedTools ?? [], config.tools.disabled ?? []);
|
|
602
608
|
const checkpointStore = new CheckpointStore(this.configStore.getProjectConfigDir() ?? process.cwd());
|
|
603
609
|
const stackSessionId = randomUUID();
|
|
@@ -628,17 +634,16 @@ var AcpServer = class {
|
|
|
628
634
|
onBackgroundStatusChange: () => {},
|
|
629
635
|
onGroupCompletion: () => {}
|
|
630
636
|
});
|
|
631
|
-
const llmWithFallback = config.fallbackModels && config.fallbackModels.length > 0 ? new FallbackLlmBackend(llm, config.fallbackModels, (from, to, error) => logger.debug(`[acp] Model "${from}" failed (${error.message}); falling back to "${to}"`)) : llm;
|
|
632
|
-
const notifyingLlm = new NotifyingLlmBackend(llmWithFallback, backgroundManager);
|
|
633
637
|
const agentToolsRef = { current: null };
|
|
634
|
-
const
|
|
638
|
+
const { llm: toolSearchLlm, toolSearchTool } = buildToolSearch({
|
|
639
|
+
llm,
|
|
640
|
+
models,
|
|
635
641
|
registry: deferredToolRegistry,
|
|
636
642
|
logger,
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
}) : null;
|
|
643
|
+
agentToolsRef
|
|
644
|
+
});
|
|
645
|
+
const llmWithFallback = config.fallbackModels && config.fallbackModels.length > 0 ? new FallbackLlmBackend(toolSearchLlm, config.fallbackModels, (from, to, error) => logger.debug(`[acp] Model "${from}" failed (${error.message}); falling back to "${to}"`)) : toolSearchLlm;
|
|
646
|
+
const notifyingLlm = new NotifyingLlmBackend(llmWithFallback, backgroundManager);
|
|
642
647
|
const cliTools = this.buildCliTools({
|
|
643
648
|
config,
|
|
644
649
|
orchestrator,
|
|
@@ -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 {
|
|
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.
|
|
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.
|
|
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-
|
|
3
|
-
import { c as isNpmPrefixWritable, i as fetchLatestVersion, r as compareSemver } from "../updateChecker-
|
|
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";
|