@bike4mind/cli 4.0.0 → 4.8.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 +184 -4
- package/bin/bike4mind-cli.mjs +249 -40
- package/bin/envFlags.d.mts +17 -0
- package/bin/envFlags.mjs +89 -0
- package/dist/{AgentHistoryStore-DgqmcVLN.mjs → AgentHistoryStore-Bvmcy2kf.mjs} +3807 -1375
- package/dist/{ApiClient-_JrM_xWw.mjs → ApiClient-Yp2LPlX3.mjs} +22 -3
- package/dist/BubblewrapRuntime-OI4qFPNB.mjs +157 -0
- package/dist/ConfigStore-Bo4od3Eu.mjs +2 -0
- package/dist/ConfigStore-CP1W86Ui.mjs +3438 -0
- package/dist/{ConfigStore-BwqsQ0U9.mjs → Logger-3RbeTZ9o.mjs} +34769 -22138
- package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
- package/dist/{RemoteSkillSource-qTvRkaNA.mjs → RemoteSkillSource-D_F99yBR.mjs} +5 -0
- package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-lpxVEFO7.mjs} +26 -7
- package/dist/SandboxRuntimeAdapter-C3xICJtQ.mjs +190 -0
- package/dist/SandboxRuntimeAdapter-u6c_IrjP.mjs +2 -0
- package/dist/SeatbeltRuntime-Ccd_QbjX.mjs +194 -0
- package/dist/{WorkItemsClient-CERTDrhT.mjs → WorkItemsClient-D4sFGL9X.mjs} +1 -1
- package/dist/agents/defaults/review.md +8 -1
- package/dist/agents/defaults/test.md +8 -1
- package/dist/buildToolSearch-CqHKSLtG.mjs +417 -0
- package/dist/commands/acpCommand.mjs +26 -20
- 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 -37
- package/dist/commands/hostCommand.mjs +2344 -0
- package/dist/commands/mcpCommand.mjs +45 -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 +175 -30
- package/dist/commands/updateCommand.mjs +2 -2
- package/dist/curated-build.json +1 -0
- package/dist/dist-BPhZ0dCz.mjs +4776 -0
- package/dist/dist-K7a9yOUb.mjs +7864 -0
- package/dist/fit-BOnDsgbk.mjs +200 -0
- package/dist/{grepSearch-BgoOOwGe-B388GxRD.mjs → grepSearch-CLtEqT4j-BnKPtNWr.mjs} +2 -2
- package/dist/index.mjs +3215 -508
- package/dist/modelHub-BSB6qRFP.mjs +1963 -0
- package/dist/modelServers-B7zI5XnO.mjs +2465 -0
- package/dist/{package-CQaam4Dq.mjs → package-WlxLVpUb.mjs} +1 -1
- package/dist/{serve-CFxUhjml.mjs → serve-DpsV0mag.mjs} +599 -26
- package/dist/store-Bpdo9Syo.mjs +2 -0
- package/dist/{store-BbvSi3KK.mjs → store-xeJRhBtO.mjs} +2 -0
- package/dist/types-BFIvwByC.mjs +2 -0
- package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
- package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-Boq0RruU.mjs} +7 -29
- package/package.json +17 -14
- 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/buildToolSearch-D9GEK91u.mjs +0 -2351
- package/dist/dist-Ul2qwn5x.mjs +0 -624
- package/dist/store-BYeE0shc.mjs +0 -2
- package/dist/types-I45lMh7Q.mjs +0 -2
|
@@ -0,0 +1,3438 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { T as ChatModels, t as logger } from "./Logger-3RbeTZ9o.mjs";
|
|
3
|
+
import { t as DEFAULT_SANDBOX_CONFIG } from "./types-CxrzVXel.mjs";
|
|
4
|
+
import { existsSync, promises } from "fs";
|
|
5
|
+
import { homedir, hostname } from "os";
|
|
6
|
+
import path from "path";
|
|
7
|
+
import { v4 } from "uuid";
|
|
8
|
+
import * as path$2 from "node:path";
|
|
9
|
+
import * as fs from "node:fs";
|
|
10
|
+
import { z as z$1 } from "zod";
|
|
11
|
+
import axios, { isAxiosError } from "axios";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
import { isDeepStrictEqual } from "node:util";
|
|
14
|
+
import { homedir as homedir$1 } from "node:os";
|
|
15
|
+
//#region src/utils/sanitizeTerminalText.ts
|
|
16
|
+
/**
|
|
17
|
+
* The one escaping layer for untrusted text written to the terminal: model
|
|
18
|
+
* output (replies, thoughts, tool arguments), tool and MCP results, file names
|
|
19
|
+
* and paths, history entries, and error messages from remote services.
|
|
20
|
+
*
|
|
21
|
+
* Display only. Apply it at the render site, never to text sent to the model,
|
|
22
|
+
* stored in the transcript, or parsed for input (image-paste detection needs
|
|
23
|
+
* the raw escapes). The CLI's own styling (Ink color props, cli-highlight,
|
|
24
|
+
* hardcoded SGR codes) is applied after sanitizing, so it is unaffected.
|
|
25
|
+
*
|
|
26
|
+
* Two modes:
|
|
27
|
+
* - sanitizeTerminalText strips: for flowing content such as replies and
|
|
28
|
+
* tool output, where the hostile bytes are noise.
|
|
29
|
+
* - escapeTerminalControlChars makes them visible as `\xHH` / `\uHHHH`: for
|
|
30
|
+
* approval prompts, where the user must see exactly what they approve.
|
|
31
|
+
* Guarded by sanitizeTerminalText.test.ts (hostile-input table) and
|
|
32
|
+
* terminalRenderSites.test.tsx (render sites that must route through here).
|
|
33
|
+
*/
|
|
34
|
+
const ESCAPE_SEQUENCE = /(?:\x1b\[|\x9b)[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]|(?:\x1b[\]PX^_]|[\x90\x98\x9d\x9e\x9f])[^\x07\x1b\x90\x98\x9c-\x9f]*(?:\x07|\x1b\\|\x9c)|\x1b[\x20-\x2f]*[\x30-\x7e]/g;
|
|
35
|
+
const CONTROL_CHAR = /[\x00-\x08\x0b-\x1f\x7f-\x9f\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g;
|
|
36
|
+
const PROSE_CONTROL_CHAR = /[\x00-\x08\x0b-\x1f\x7f-\x9f\u202A-\u202E\u2066-\u2069]/g;
|
|
37
|
+
/** Strip terminal control sequences and characters from untrusted text for display. */
|
|
38
|
+
function sanitizeTerminalText(text) {
|
|
39
|
+
return text.replace(/\r\n/g, "\n").replace(ESCAPE_SEQUENCE, "").replace(CONTROL_CHAR, "");
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Escape the same control characters into a visible form instead of removing
|
|
43
|
+
* them. ESC becomes `\x1b`, so a whole sequence reads as e.g. `\x1b[2K` and
|
|
44
|
+
* cannot act. Tab and newline are left intact.
|
|
45
|
+
*/
|
|
46
|
+
function escapeTerminalControlChars(text, opts = {}) {
|
|
47
|
+
return text.replace(opts.keepBidiMarks ? PROSE_CONTROL_CHAR : CONTROL_CHAR, (ch) => {
|
|
48
|
+
const code = ch.charCodeAt(0);
|
|
49
|
+
return code > 255 ? `\\u${code.toString(16).padStart(4, "0")}` : `\\x${code.toString(16).padStart(2, "0")}`;
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region ../../b4m-core/client-auth/dist/index.mjs
|
|
54
|
+
/**
|
|
55
|
+
* OAuth 2.0 Device Authorization Flow client
|
|
56
|
+
* Implements RFC 8628 for clients that cannot host a redirect URI
|
|
57
|
+
*/
|
|
58
|
+
var DeviceFlowClient = class {
|
|
59
|
+
apiClient;
|
|
60
|
+
clientId;
|
|
61
|
+
refreshTimeoutMs;
|
|
62
|
+
constructor(options) {
|
|
63
|
+
this.clientId = options.clientId;
|
|
64
|
+
this.refreshTimeoutMs = options.refreshTimeoutMs ?? 25e3;
|
|
65
|
+
this.apiClient = axios.create({
|
|
66
|
+
baseURL: options.baseUrl,
|
|
67
|
+
headers: { "Content-Type": "application/json" }
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Initiate device authorization flow
|
|
72
|
+
* Returns device code, user code, and verification URL
|
|
73
|
+
*/
|
|
74
|
+
async initiateDeviceFlow(signal) {
|
|
75
|
+
return (await this.apiClient.post("/api/oauth/device/initiate", { client_id: this.clientId }, { signal })).data;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Poll for access token
|
|
79
|
+
* Returns token response if approved, or throws error with status
|
|
80
|
+
*/
|
|
81
|
+
async pollForToken(deviceCode, signal) {
|
|
82
|
+
try {
|
|
83
|
+
const response = await this.apiClient.post("/api/oauth/device/token", {
|
|
84
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
85
|
+
device_code: deviceCode,
|
|
86
|
+
client_id: this.clientId
|
|
87
|
+
}, {
|
|
88
|
+
validateStatus: () => true,
|
|
89
|
+
signal
|
|
90
|
+
});
|
|
91
|
+
if ("error" in response.data) throw new Error(response.data.error);
|
|
92
|
+
return response.data;
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (axios.isAxiosError(error) && error.response?.data?.error) throw new Error(error.response.data.error);
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Wait for user authorization with automatic polling
|
|
100
|
+
* Implements exponential backoff and respects server's interval
|
|
101
|
+
*/
|
|
102
|
+
async waitForAuthorization(deviceCode, interval, onStatus, signal) {
|
|
103
|
+
let pollInterval = interval * 1e3;
|
|
104
|
+
const maxInterval = 3e4;
|
|
105
|
+
onStatus?.("Waiting for user authorization...");
|
|
106
|
+
await this.sleep(pollInterval, signal);
|
|
107
|
+
while (true) {
|
|
108
|
+
signal?.throwIfAborted();
|
|
109
|
+
try {
|
|
110
|
+
return await this.pollForToken(deviceCode, signal);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
signal?.throwIfAborted();
|
|
113
|
+
if (error instanceof Error) {
|
|
114
|
+
const errorMessage = error.message;
|
|
115
|
+
if (errorMessage === "authorization_pending") {
|
|
116
|
+
onStatus?.("Waiting for user authorization...");
|
|
117
|
+
await this.sleep(pollInterval, signal);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (errorMessage === "slow_down") {
|
|
121
|
+
pollInterval = Math.min(pollInterval + 5e3, maxInterval);
|
|
122
|
+
onStatus?.("Slowing down polling...");
|
|
123
|
+
await this.sleep(pollInterval, signal);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (errorMessage === "access_denied") throw new Error("User denied the authorization request");
|
|
127
|
+
if (errorMessage === "expired_token") throw new Error("Authorization code has expired");
|
|
128
|
+
throw error;
|
|
129
|
+
}
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Refresh an expired access token
|
|
136
|
+
*/
|
|
137
|
+
async refreshToken(refreshToken) {
|
|
138
|
+
return (await this.apiClient.post("/api/oauth/refresh", {
|
|
139
|
+
grant_type: "refresh_token",
|
|
140
|
+
refresh_token: refreshToken,
|
|
141
|
+
client_id: this.clientId
|
|
142
|
+
}, {
|
|
143
|
+
timeout: this.refreshTimeoutMs,
|
|
144
|
+
signal: AbortSignal.timeout(this.refreshTimeoutMs)
|
|
145
|
+
})).data;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Sleep for specified milliseconds
|
|
149
|
+
*/
|
|
150
|
+
sleep(ms, signal) {
|
|
151
|
+
return new Promise((resolve, reject) => {
|
|
152
|
+
if (signal?.aborted) {
|
|
153
|
+
reject(signal.reason);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const onAbort = () => {
|
|
157
|
+
clearTimeout(timer);
|
|
158
|
+
reject(signal?.reason);
|
|
159
|
+
};
|
|
160
|
+
const timer = setTimeout(() => {
|
|
161
|
+
signal?.removeEventListener("abort", onAbort);
|
|
162
|
+
resolve();
|
|
163
|
+
}, ms);
|
|
164
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
/**
|
|
169
|
+
* Thrown by the response interceptor only when the session is DEFINITIVELY revoked - the
|
|
170
|
+
* refresh token was rejected (400/401 invalid_grant), or a request still 401s after a
|
|
171
|
+
* successful refresh. A transient refresh outage (5xx / network / timeout) throws a plain
|
|
172
|
+
* Error instead, so callers that must distinguish "log out" from "retry" (e.g.
|
|
173
|
+
* checkSessionValid / a WS reconnect loop) can key on the type. The human-readable
|
|
174
|
+
* message is preserved on both paths so existing `error.message.includes(...)` callers are
|
|
175
|
+
* unaffected.
|
|
176
|
+
*
|
|
177
|
+
* It does NOT mean the stored tokens were discarded: only the rejected-refresh path clears
|
|
178
|
+
* them (and reports it through `onTokensCleared`). A 401 that survived a successful refresh
|
|
179
|
+
* keeps them, so that session may still be restorable.
|
|
180
|
+
*/
|
|
181
|
+
var SessionRevokedError = class extends Error {
|
|
182
|
+
constructor(message) {
|
|
183
|
+
super(message);
|
|
184
|
+
this.name = "SessionRevokedError";
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
/**
|
|
188
|
+
* 401 with no credential at all (no API key, no stored tokens): a config gap, not an expiry.
|
|
189
|
+
* Not a SessionRevokedError, so checkSessionValid still reports "not revoked". The host's message
|
|
190
|
+
* should keep `Authentication failed` for string-matching callers.
|
|
191
|
+
*/
|
|
192
|
+
var NotAuthenticatedError = class extends Error {
|
|
193
|
+
constructor(message) {
|
|
194
|
+
super(message);
|
|
195
|
+
this.name = "NotAuthenticatedError";
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
/** A captured session no longer owns this operation. */
|
|
199
|
+
var SessionChangedError = class extends Error {
|
|
200
|
+
beforeRequest;
|
|
201
|
+
constructor(beforeRequest = false) {
|
|
202
|
+
super("The account or environment changed. Please try again from the current session.");
|
|
203
|
+
this.beforeRequest = beforeRequest;
|
|
204
|
+
this.name = "SessionChangedError";
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
/** Enough of an error body to classify it; a 401 body is a few hundred bytes. */
|
|
208
|
+
const ERROR_BODY_LIMIT = 65536;
|
|
209
|
+
function isReadableStream(data) {
|
|
210
|
+
return typeof data === "object" && data !== null && typeof data.pipe === "function" && typeof data[Symbol.asyncIterator] === "function";
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* A `responseType: 'stream'` request hands back its error body as a stream, which neither
|
|
214
|
+
* `isPassThrough401` nor the caller can read synchronously. Buffered into a string in place, so
|
|
215
|
+
* both see the same body. A read that fails leaves an empty string rather than a spent stream.
|
|
216
|
+
*/
|
|
217
|
+
async function bufferStreamedBody(response) {
|
|
218
|
+
if (!response || !isReadableStream(response.data)) return;
|
|
219
|
+
const decoder = new TextDecoder();
|
|
220
|
+
let text = "";
|
|
221
|
+
try {
|
|
222
|
+
for await (const chunk of response.data) {
|
|
223
|
+
text += typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
|
|
224
|
+
if (text.length >= ERROR_BODY_LIMIT) break;
|
|
225
|
+
}
|
|
226
|
+
} catch {}
|
|
227
|
+
response.data = text.slice(0, ERROR_BODY_LIMIT);
|
|
228
|
+
}
|
|
229
|
+
function isExpired(tokens) {
|
|
230
|
+
return new Date(tokens.expiresAt).getTime() <= Date.now();
|
|
231
|
+
}
|
|
232
|
+
function bearerToken(config) {
|
|
233
|
+
const header = config?.headers?.Authorization;
|
|
234
|
+
return typeof header === "string" && header.startsWith("Bearer ") ? header.slice(7) : void 0;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* Authenticated API client for B4M services.
|
|
238
|
+
* Injects access tokens from the supplied {@link TokenStore} and refreshes them on a 401.
|
|
239
|
+
*/
|
|
240
|
+
var AuthenticatedApiClient = class AuthenticatedApiClient {
|
|
241
|
+
options;
|
|
242
|
+
client;
|
|
243
|
+
tokenStore;
|
|
244
|
+
oauthClient;
|
|
245
|
+
logger;
|
|
246
|
+
apiKey;
|
|
247
|
+
isPassThrough401;
|
|
248
|
+
onTokensCleared;
|
|
249
|
+
onStillUnauthorized;
|
|
250
|
+
refreshUnexpiredOn401;
|
|
251
|
+
reauthMessages;
|
|
252
|
+
/** The one refresh exchange in flight, shared by every caller - see {@link refreshSession}. */
|
|
253
|
+
refreshState = { inFlight: null };
|
|
254
|
+
sessionAdapters = /* @__PURE__ */ new WeakMap();
|
|
255
|
+
constructor(options) {
|
|
256
|
+
this.options = options;
|
|
257
|
+
this.tokenStore = options.tokenStore;
|
|
258
|
+
this.oauthClient = options.oauthClient;
|
|
259
|
+
this.logger = options.logger;
|
|
260
|
+
this.apiKey = options.apiKey;
|
|
261
|
+
this.isPassThrough401 = options.isPassThrough401;
|
|
262
|
+
this.onTokensCleared = options.onTokensCleared;
|
|
263
|
+
this.onStillUnauthorized = options.onStillUnauthorized;
|
|
264
|
+
this.refreshUnexpiredOn401 = options.refreshUnexpiredOn401 ?? false;
|
|
265
|
+
this.reauthMessages = {
|
|
266
|
+
notLoggedIn: "Authentication failed: not logged in.",
|
|
267
|
+
...options.reauthMessages,
|
|
268
|
+
refreshUnavailable: options.reauthMessages.refreshUnavailable ?? options.reauthMessages.refreshFailed
|
|
269
|
+
};
|
|
270
|
+
const { refreshUnavailable, stillUnauthorized, notLoggedIn } = this.reauthMessages;
|
|
271
|
+
this.client = axios.create({
|
|
272
|
+
baseURL: options.baseUrl,
|
|
273
|
+
timeout: options.timeoutMs,
|
|
274
|
+
headers: {
|
|
275
|
+
"Content-Type": "application/json",
|
|
276
|
+
...options.headers
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
this.client.interceptors.request.use(async (config) => {
|
|
280
|
+
if (this.apiKey) {
|
|
281
|
+
this.assertSession(null, !("_retry" in config && config._retry === true));
|
|
282
|
+
this.guardTransport(config, null);
|
|
283
|
+
config.headers["x-api-key"] = this.apiKey;
|
|
284
|
+
return config;
|
|
285
|
+
}
|
|
286
|
+
const tokens = await this.tokenStore.getAuthTokens();
|
|
287
|
+
this.assertSession(tokens, !("_retry" in config && config._retry === true));
|
|
288
|
+
if (this.options.isSessionCurrent && !tokens) throw new SessionChangedError(!("_retry" in config && config._retry === true));
|
|
289
|
+
this.guardTransport(config, tokens);
|
|
290
|
+
if (tokens) config.headers.Authorization = `Bearer ${tokens.accessToken}`;
|
|
291
|
+
return config;
|
|
292
|
+
}, (error) => Promise.reject(error));
|
|
293
|
+
this.client.interceptors.response.use((response) => response, async (error) => {
|
|
294
|
+
const originalRequest = error.config;
|
|
295
|
+
if (error.response?.status === 401) this.logger.debug("AUTH: Received 401 Unauthorized");
|
|
296
|
+
else if (error.response?.status === 403) this.logger.error("AUTH: Received 403 Forbidden");
|
|
297
|
+
if (this.apiKey) return Promise.reject(error);
|
|
298
|
+
if (error.response?.status === 401) await bufferStreamedBody(error.response);
|
|
299
|
+
if (error.response?.status === 401 && this.isPassThrough401?.(error.response.data)) return Promise.reject(error);
|
|
300
|
+
if (error.response?.status === 401 && !originalRequest._retry) {
|
|
301
|
+
originalRequest._retry = true;
|
|
302
|
+
const tokens = await this.tokenStore.getAuthTokens();
|
|
303
|
+
this.assertSession(tokens);
|
|
304
|
+
if (!tokens) throw new NotAuthenticatedError(notLoggedIn);
|
|
305
|
+
const sentAccessToken = bearerToken(originalRequest);
|
|
306
|
+
if (sentAccessToken !== tokens.accessToken && !isExpired(tokens) && !this.refreshState.inFlight) {
|
|
307
|
+
this.logger.debug("AUTH: Retrying with the access token stored since this request was sent");
|
|
308
|
+
originalRequest.headers.Authorization = `Bearer ${tokens.accessToken}`;
|
|
309
|
+
return this.client(originalRequest);
|
|
310
|
+
}
|
|
311
|
+
if (!this.refreshUnexpiredOn401 && !isExpired(tokens) && !this.refreshState.inFlight) {
|
|
312
|
+
this.logger.debug("AUTH: Access token has not expired, skipping refresh - 401 is likely transient");
|
|
313
|
+
return Promise.reject(error);
|
|
314
|
+
}
|
|
315
|
+
let refreshed;
|
|
316
|
+
try {
|
|
317
|
+
refreshed = await this.refreshSession(sentAccessToken);
|
|
318
|
+
} catch (refreshError) {
|
|
319
|
+
if (refreshError instanceof SessionRevokedError || refreshError instanceof NotAuthenticatedError || refreshError instanceof SessionChangedError) throw refreshError;
|
|
320
|
+
this.logger.warn("AUTH: Token refresh temporarily unavailable");
|
|
321
|
+
throw new Error(refreshUnavailable);
|
|
322
|
+
}
|
|
323
|
+
originalRequest.headers.Authorization = `Bearer ${refreshed.accessToken}`;
|
|
324
|
+
this.logger.debug("AUTH: Retrying request with new token");
|
|
325
|
+
return this.client(originalRequest);
|
|
326
|
+
}
|
|
327
|
+
if (error.response?.status === 401 && originalRequest._retry) {
|
|
328
|
+
const current = await this.readStoredTokens();
|
|
329
|
+
this.assertSession(current);
|
|
330
|
+
this.logger.debug("AUTH: Token refresh retry failed");
|
|
331
|
+
if (current?.accessToken === bearerToken(originalRequest)) this.onStillUnauthorized?.("a request was still refused after the session was refreshed");
|
|
332
|
+
throw new SessionRevokedError(stillUnauthorized);
|
|
333
|
+
}
|
|
334
|
+
return Promise.reject(error);
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Exchange the stored refresh token for a new access token, and persist the result.
|
|
339
|
+
*
|
|
340
|
+
* Single flight: every caller in this process - a 401 here, a host's proactive timer - shares
|
|
341
|
+
* one exchange, so a burst of 401s spends one rotation rather than one each.
|
|
342
|
+
*
|
|
343
|
+
* `rejectedAccessToken` is the access token the caller found wanting. When the store (re-read
|
|
344
|
+
* from storage, not a cache) already holds a different, unexpired one, another flow or another
|
|
345
|
+
* process refreshed first, and that token is returned with no exchange at all.
|
|
346
|
+
* A caller that passes no `rejectedAccessToken` never takes this adopt path: it always exchanges.
|
|
347
|
+
*
|
|
348
|
+
* Rejects with {@link SessionRevokedError} only when the refresh endpoint answered 400/401 -
|
|
349
|
+
* the one case in which the stored tokens are cleared. Any other failure (network, timeout,
|
|
350
|
+
* 5xx, 429) is rethrown as-is and leaves the tokens untouched.
|
|
351
|
+
*/
|
|
352
|
+
async refreshSession(rejectedAccessToken) {
|
|
353
|
+
await this.readStoredTokens();
|
|
354
|
+
if (!this.refreshState.inFlight) this.refreshState.inFlight = this.lockedExchange(rejectedAccessToken).finally(() => {
|
|
355
|
+
this.refreshState.inFlight = null;
|
|
356
|
+
});
|
|
357
|
+
const refreshed = await this.refreshState.inFlight;
|
|
358
|
+
this.assertSession(refreshed);
|
|
359
|
+
return refreshed;
|
|
360
|
+
}
|
|
361
|
+
/** A session-bound client that shares refresh rotations with this client. */
|
|
362
|
+
withSessionGuard(isSessionCurrent) {
|
|
363
|
+
const inherited = this.options.isSessionCurrent;
|
|
364
|
+
const fork = new AuthenticatedApiClient({
|
|
365
|
+
...this.options,
|
|
366
|
+
isSessionCurrent: (tokens) => (inherited === void 0 || inherited(tokens) === true) && isSessionCurrent(tokens) === true
|
|
367
|
+
});
|
|
368
|
+
fork.refreshState = this.refreshState;
|
|
369
|
+
return fork;
|
|
370
|
+
}
|
|
371
|
+
assertSession(tokens, beforeRequest = false) {
|
|
372
|
+
if (this.options.isSessionCurrent && this.options.isSessionCurrent(tokens) !== true) throw new SessionChangedError(beforeRequest);
|
|
373
|
+
}
|
|
374
|
+
guardTransport(config, tokens) {
|
|
375
|
+
if (!this.options.isSessionCurrent) return;
|
|
376
|
+
const selected = axios.getAdapter(config.adapter ?? this.client.defaults.adapter);
|
|
377
|
+
const adapter = this.sessionAdapters.get(selected) ?? selected;
|
|
378
|
+
const guarded = (request) => {
|
|
379
|
+
this.assertSession(tokens, !("_retry" in request && request._retry === true));
|
|
380
|
+
return adapter(request);
|
|
381
|
+
};
|
|
382
|
+
this.sessionAdapters.set(guarded, adapter);
|
|
383
|
+
config.adapter = guarded;
|
|
384
|
+
}
|
|
385
|
+
async lockedExchange(rejectedAccessToken) {
|
|
386
|
+
const store = this.tokenStore;
|
|
387
|
+
if (!store.withRefreshLock) return this.exchangeRefreshToken(rejectedAccessToken, void 0);
|
|
388
|
+
const seen = await this.readStoredTokens();
|
|
389
|
+
return store.withRefreshLock(() => this.exchangeRefreshToken(rejectedAccessToken, seen?.refreshToken));
|
|
390
|
+
}
|
|
391
|
+
/** `seenRefreshToken`: the refresh token stored before waiting on the refresh lock, if one was taken. */
|
|
392
|
+
async exchangeRefreshToken(rejectedAccessToken, seenRefreshToken) {
|
|
393
|
+
const presented = await this.readStoredTokens();
|
|
394
|
+
if (!presented) throw new NotAuthenticatedError(this.reauthMessages.notLoggedIn);
|
|
395
|
+
const rotatedWhileWaiting = seenRefreshToken !== void 0 && presented.refreshToken !== seenRefreshToken;
|
|
396
|
+
const rejectedWasReplaced = rejectedAccessToken !== void 0 && presented.accessToken !== rejectedAccessToken;
|
|
397
|
+
if ((rotatedWhileWaiting || rejectedWasReplaced) && !isExpired(presented)) {
|
|
398
|
+
this.logger.debug("AUTH: Stored tokens were already refreshed elsewhere, adopting them");
|
|
399
|
+
return presented;
|
|
400
|
+
}
|
|
401
|
+
this.logger.debug("AUTH: Attempting token refresh");
|
|
402
|
+
let response;
|
|
403
|
+
this.assertSession(presented);
|
|
404
|
+
try {
|
|
405
|
+
response = await this.oauthClient.refreshToken(presented.refreshToken);
|
|
406
|
+
} catch (refreshError) {
|
|
407
|
+
if (this.options.isSessionCurrent) await this.readStoredTokens();
|
|
408
|
+
const status = isAxiosError(refreshError) ? refreshError.response?.status : void 0;
|
|
409
|
+
if (status !== 400 && status !== 401) throw refreshError;
|
|
410
|
+
const current = await this.readStoredTokens();
|
|
411
|
+
if (current && current.refreshToken !== presented.refreshToken) {
|
|
412
|
+
this.logger.warn("AUTH: Refresh rejected for a token already replaced in storage; keeping the newer one");
|
|
413
|
+
return current;
|
|
414
|
+
}
|
|
415
|
+
if (current) {
|
|
416
|
+
const reason = `refresh token rejected by the server (HTTP ${status})`;
|
|
417
|
+
this.logger.warn(`AUTH: Clearing stored tokens: ${reason}`);
|
|
418
|
+
this.assertSession(current);
|
|
419
|
+
const cleared = await this.tokenStore.clearAuthTokens(presented.refreshToken);
|
|
420
|
+
const now = await this.readStoredTokens();
|
|
421
|
+
this.assertSession(now);
|
|
422
|
+
if (now && (now.accessToken !== presented.accessToken || now.refreshToken !== presented.refreshToken || now.userId !== presented.userId)) return now;
|
|
423
|
+
if (!now && cleared !== false) this.onTokensCleared?.(reason);
|
|
424
|
+
}
|
|
425
|
+
throw new SessionRevokedError(this.reauthMessages.refreshFailed);
|
|
426
|
+
}
|
|
427
|
+
this.logger.debug("AUTH: Token refresh successful");
|
|
428
|
+
const current = await this.readStoredTokens();
|
|
429
|
+
this.assertSession(current);
|
|
430
|
+
if (!current) throw new NotAuthenticatedError(this.reauthMessages.notLoggedIn);
|
|
431
|
+
if (current.refreshToken !== presented.refreshToken) {
|
|
432
|
+
this.logger.debug("AUTH: Stored tokens changed during refresh, keeping the stored ones");
|
|
433
|
+
return current;
|
|
434
|
+
}
|
|
435
|
+
const next = {
|
|
436
|
+
accessToken: response.access_token,
|
|
437
|
+
refreshToken: response.refresh_token ?? presented.refreshToken,
|
|
438
|
+
expiresAt: new Date(Date.now() + response.expires_in * 1e3).toISOString(),
|
|
439
|
+
userId: presented.userId
|
|
440
|
+
};
|
|
441
|
+
if (await this.tokenStore.setAuthTokens(next, presented.refreshToken) === false) {
|
|
442
|
+
const now = await this.readStoredTokens();
|
|
443
|
+
if (!now) throw new NotAuthenticatedError(this.reauthMessages.notLoggedIn);
|
|
444
|
+
return now;
|
|
445
|
+
}
|
|
446
|
+
return next;
|
|
447
|
+
}
|
|
448
|
+
async readStoredTokens() {
|
|
449
|
+
const tokens = await (this.tokenStore.reloadAuthTokens ? this.tokenStore.reloadAuthTokens() : this.tokenStore.getAuthTokens());
|
|
450
|
+
this.assertSession(tokens);
|
|
451
|
+
return tokens;
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Make a GET request
|
|
455
|
+
*/
|
|
456
|
+
async get(url, config) {
|
|
457
|
+
return (await this.client.get(url, config)).data;
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Make a POST request
|
|
461
|
+
*/
|
|
462
|
+
async post(url, data, config) {
|
|
463
|
+
this.logger.debug("[ApiClient] POST request");
|
|
464
|
+
const response = await this.client.post(url, data, config);
|
|
465
|
+
this.logger.debug(`[ApiClient] Response status: ${response.status}`);
|
|
466
|
+
return response.data;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Make a PUT request
|
|
470
|
+
*/
|
|
471
|
+
async put(url, data, config) {
|
|
472
|
+
return (await this.client.put(url, data, config)).data;
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Make a DELETE request
|
|
476
|
+
*/
|
|
477
|
+
async delete(url, config) {
|
|
478
|
+
return (await this.client.delete(url, config)).data;
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Get the underlying axios instance for advanced use cases (e.g., streaming)
|
|
482
|
+
*/
|
|
483
|
+
getAxiosInstance() {
|
|
484
|
+
return this.client;
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Check if user is authenticated
|
|
488
|
+
*/
|
|
489
|
+
async isAuthenticated() {
|
|
490
|
+
if (this.options.isSessionCurrent) return await this.readStoredTokens() !== null;
|
|
491
|
+
return this.tokenStore.isAuthenticated();
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Get current user information
|
|
495
|
+
*/
|
|
496
|
+
async getCurrentUser() {
|
|
497
|
+
try {
|
|
498
|
+
const tokens = await this.readStoredTokens();
|
|
499
|
+
if (!tokens) return null;
|
|
500
|
+
return { id: tokens.userId };
|
|
501
|
+
} catch {
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Verifies the session is still valid via a cheap authed GET. The response interceptor
|
|
507
|
+
* above already attempts a token refresh and retries on 401, so a resolved call means the
|
|
508
|
+
* session is valid (fresh or transparently refreshed). Returns false ONLY on a
|
|
509
|
+
* `SessionRevokedError` (the refresh token was rejected, or a 401 survived a refresh);
|
|
510
|
+
* every other outcome - a transient refresh outage, a network blip, or the interceptor's
|
|
511
|
+
* fresh-token 401 skip - is treated as transient and returns true, so callers keep
|
|
512
|
+
* retrying rather than tearing down on a blip.
|
|
513
|
+
*
|
|
514
|
+
* Used by the CLI's WebSocketConnectionManager to distinguish "session revoked" from
|
|
515
|
+
* "transient network issue" when a WS connect attempt fails to open - a WS close event
|
|
516
|
+
* carries no HTTP status, so this is the only way to tell the two apart.
|
|
517
|
+
*/
|
|
518
|
+
async checkSessionValid() {
|
|
519
|
+
try {
|
|
520
|
+
await this.get("/api/identify");
|
|
521
|
+
return true;
|
|
522
|
+
} catch (err) {
|
|
523
|
+
return !(err instanceof SessionRevokedError);
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
};
|
|
527
|
+
/**
|
|
528
|
+
* Normalize an API URL for use as a per-environment token cache key.
|
|
529
|
+
*
|
|
530
|
+
* Without normalization, `https://x.com` and `https://x.com/` (or `HTTPS://X.com`) would
|
|
531
|
+
* create separate cache entries, defeating token reuse when the user switches back to an
|
|
532
|
+
* environment they already authenticated against.
|
|
533
|
+
*/
|
|
534
|
+
function normalizeEnvKey(url) {
|
|
535
|
+
return url.toLowerCase().replace(/\/+$/, "");
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* Treat a token as "authenticated" only when it has an `expiresAt` in the future. A caller
|
|
539
|
+
* that auto-refreshes on startup still wants this, so a UI does not claim a saved login is
|
|
540
|
+
* being reused when it is actually about to trigger a re-auth.
|
|
541
|
+
*/
|
|
542
|
+
function isAuthTokenValid(auth) {
|
|
543
|
+
if (!auth) return false;
|
|
544
|
+
return new Date(auth.expiresAt) > /* @__PURE__ */ new Date();
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Stash the active token under the environment being left and restore the one cached for the
|
|
548
|
+
* environment being entered, so flipping between a hosted and a self-hosted instance does not
|
|
549
|
+
* force a re-login each time. Pure: the caller decides how to persist the result.
|
|
550
|
+
*
|
|
551
|
+
* A missing entry for the target environment yields `auth: undefined` - the caller prompts to
|
|
552
|
+
* log in.
|
|
553
|
+
*/
|
|
554
|
+
function swapActiveEnvAuth(state, prevUrl, nextUrl) {
|
|
555
|
+
const prevKey = normalizeEnvKey(prevUrl);
|
|
556
|
+
const nextKey = normalizeEnvKey(nextUrl);
|
|
557
|
+
if (prevKey === nextKey) return {
|
|
558
|
+
auth: state.auth,
|
|
559
|
+
authByEnv: state.authByEnv ?? {},
|
|
560
|
+
changed: false
|
|
561
|
+
};
|
|
562
|
+
const authByEnv = { ...state.authByEnv || {} };
|
|
563
|
+
if (state.auth) authByEnv[prevKey] = state.auth;
|
|
564
|
+
else delete authByEnv[prevKey];
|
|
565
|
+
return {
|
|
566
|
+
auth: authByEnv[nextKey],
|
|
567
|
+
authByEnv,
|
|
568
|
+
changed: true
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
/** Local development server a client's `--dev` / dev build points at. */
|
|
572
|
+
const LOCAL_DEV_URL = "http://localhost:3000";
|
|
573
|
+
/**
|
|
574
|
+
* Normalize and validate a user-supplied API URL. The single source of truth for what counts
|
|
575
|
+
* as an acceptable endpoint across every client. Trims surrounding whitespace, strips trailing
|
|
576
|
+
* slashes, and requires an http(s) origin.
|
|
577
|
+
*
|
|
578
|
+
* Returns a discriminated result rather than throwing so each caller can render the failure in
|
|
579
|
+
* its own idiom (a CLI `process.exit`, an Ink error line, a form field, ...).
|
|
580
|
+
*/
|
|
581
|
+
function parseApiUrl(raw) {
|
|
582
|
+
const url = raw.trim().replace(/\/+$/, "");
|
|
583
|
+
if (!url) return { error: "Please enter a URL." };
|
|
584
|
+
let parsed;
|
|
585
|
+
try {
|
|
586
|
+
parsed = new URL(url);
|
|
587
|
+
} catch {
|
|
588
|
+
return { error: `Invalid URL: ${url}` };
|
|
589
|
+
}
|
|
590
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return { error: `Only http:// and https:// URLs are supported (got ${parsed.protocol}//)` };
|
|
591
|
+
return { url };
|
|
592
|
+
}
|
|
593
|
+
/**
|
|
594
|
+
* Resolve which backend to talk to, in precedence order: an explicit user choice, the
|
|
595
|
+
* build-time default, then the local dev server for a dev run. Never returns an empty URL -
|
|
596
|
+
* callers get `unconfigured` instead.
|
|
597
|
+
*
|
|
598
|
+
* Where each input comes from is the host's business: this package reads no environment.
|
|
599
|
+
*/
|
|
600
|
+
function selectApiEndpoint(inputs) {
|
|
601
|
+
if (inputs.customUrl) return {
|
|
602
|
+
status: "configured",
|
|
603
|
+
url: inputs.customUrl,
|
|
604
|
+
source: "custom"
|
|
605
|
+
};
|
|
606
|
+
if (inputs.bakedDefault) return {
|
|
607
|
+
status: "configured",
|
|
608
|
+
url: inputs.bakedDefault,
|
|
609
|
+
source: "baked-default"
|
|
610
|
+
};
|
|
611
|
+
if (inputs.devFallback) return {
|
|
612
|
+
status: "configured",
|
|
613
|
+
url: LOCAL_DEV_URL,
|
|
614
|
+
source: "dev-default"
|
|
615
|
+
};
|
|
616
|
+
return { status: "unconfigured" };
|
|
617
|
+
}
|
|
618
|
+
//#endregion
|
|
619
|
+
//#region src/utils/apiUrl.ts
|
|
620
|
+
/**
|
|
621
|
+
* Default service endpoint, baked in at build time via tsdown's `env` option
|
|
622
|
+
* (see `packages/cli/tsdown.config.ts`). The hosted publisher builds with its own
|
|
623
|
+
* service as the default; a fork sets `B4M_DEFAULT_API_URL` to publish under a
|
|
624
|
+
* different brand, so a fork's bundle never embeds the upstream brand literal.
|
|
625
|
+
* Empty when unset - the user then supplies an endpoint via `/set-api` or the
|
|
626
|
+
* `--dev` flag.
|
|
627
|
+
*/
|
|
628
|
+
function getDefaultApiUrl() {
|
|
629
|
+
return "https://app.bike4mind.com";
|
|
630
|
+
}
|
|
631
|
+
/**
|
|
632
|
+
* True when the CLI is running from TypeScript source rather than a built
|
|
633
|
+
* `dist/` bundle (a `pnpm link --global` checkout, `pnpm dev`, etc). The bin
|
|
634
|
+
* sets `B4M_SOURCE_MODE=1` in this case (see `bin/bike4mind-cli.mjs`).
|
|
635
|
+
*
|
|
636
|
+
* It matters here because build-time brand defaults (`B4M_DEFAULT_API_URL`) are
|
|
637
|
+
* only injected into a real build - a source run always sees them empty. Rather
|
|
638
|
+
* than leave a contributor unconfigured, we default source runs to the local dev
|
|
639
|
+
* server, which is almost always what they want.
|
|
640
|
+
*/
|
|
641
|
+
function isSourceMode() {
|
|
642
|
+
return process.env.B4M_SOURCE_MODE === "1";
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* Marketing/credits page shown when the user runs out of credits. Build-time
|
|
646
|
+
* injected like {@link getDefaultApiUrl}; empty for an unbranded fork, in which
|
|
647
|
+
* case the "purchase more credits" line is omitted entirely.
|
|
648
|
+
*/
|
|
649
|
+
function getCreditsUrl() {
|
|
650
|
+
return "";
|
|
651
|
+
}
|
|
652
|
+
/**
|
|
653
|
+
* Resolve which backend the CLI should talk to, feeding the CLI's build-time brand
|
|
654
|
+
* defaults into the shared precedence rule (custom URL, then baked default, then the
|
|
655
|
+
* local dev server for a source run, then unconfigured).
|
|
656
|
+
*
|
|
657
|
+
* Never returns an empty URL - callers get `unconfigured` instead.
|
|
658
|
+
*/
|
|
659
|
+
function resolveApiEndpoint(configApiConfig) {
|
|
660
|
+
return selectApiEndpoint({
|
|
661
|
+
customUrl: configApiConfig?.customUrl,
|
|
662
|
+
bakedDefault: getDefaultApiUrl(),
|
|
663
|
+
devFallback: isSourceMode()
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Thrown when a network operation needs an endpoint but none is configured.
|
|
668
|
+
* The message is user-facing and actionable - it tells the developer exactly
|
|
669
|
+
* how to point the CLI at a backend.
|
|
670
|
+
*/
|
|
671
|
+
var ApiEndpointUnconfiguredError = class extends Error {
|
|
672
|
+
constructor() {
|
|
673
|
+
super("No API endpoint configured. Point the CLI at a backend first:\n b4m --dev # local dev server (http://localhost:3000)\n b4m --api-url <url> # a hosted or self-hosted instance");
|
|
674
|
+
this.name = "ApiEndpointUnconfiguredError";
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
/**
|
|
678
|
+
* Resolve the API URL for a network call, failing loud when unconfigured.
|
|
679
|
+
* Use this at the network boundary (constructing an `ApiClient` / `OAuthClient`)
|
|
680
|
+
* so a missing endpoint throws an actionable error instead of an empty
|
|
681
|
+
* `baseURL` producing an opaque "Invalid URL".
|
|
682
|
+
*/
|
|
683
|
+
function requireApiUrl(configApiConfig) {
|
|
684
|
+
const endpoint = resolveApiEndpoint(configApiConfig);
|
|
685
|
+
if (endpoint.status === "unconfigured") throw new ApiEndpointUnconfiguredError();
|
|
686
|
+
return endpoint.url;
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* Get human-readable API type name for display (banner, `/api-info`).
|
|
690
|
+
*/
|
|
691
|
+
function getEnvironmentName(configApiConfig) {
|
|
692
|
+
const endpoint = resolveApiEndpoint(configApiConfig);
|
|
693
|
+
if (endpoint.status === "unconfigured") return "Unconfigured";
|
|
694
|
+
if (endpoint.source === "baked-default") return "Production";
|
|
695
|
+
if (endpoint.source === "dev-default") return "Local Dev";
|
|
696
|
+
if (/^https?:\/\/(localhost|127\.0\.0\.1)(:|\/|$)/i.test(endpoint.url)) return "Local Dev";
|
|
697
|
+
return "Self-Hosted";
|
|
698
|
+
}
|
|
699
|
+
//#endregion
|
|
700
|
+
//#region src/tools/gateway/coreToolDescriptors.ts
|
|
701
|
+
const CORE = { kind: "core" };
|
|
702
|
+
const CLI = { kind: "cli" };
|
|
703
|
+
const pureCompute = () => ({
|
|
704
|
+
source: CORE,
|
|
705
|
+
effect: "none",
|
|
706
|
+
approval: "auto_approve"
|
|
707
|
+
});
|
|
708
|
+
const sessionTool = () => ({
|
|
709
|
+
source: CLI,
|
|
710
|
+
effect: "session",
|
|
711
|
+
approval: "auto_approve"
|
|
712
|
+
});
|
|
713
|
+
const reader = (source = CORE, extra = {}) => ({
|
|
714
|
+
source,
|
|
715
|
+
effect: "read",
|
|
716
|
+
approval: "prompt_default",
|
|
717
|
+
...extra
|
|
718
|
+
});
|
|
719
|
+
const fileWriter = () => ({
|
|
720
|
+
source: CORE,
|
|
721
|
+
effect: "write",
|
|
722
|
+
approval: "prompt_always",
|
|
723
|
+
writePathArg: "path"
|
|
724
|
+
});
|
|
725
|
+
const lattice = () => ({
|
|
726
|
+
source: CORE,
|
|
727
|
+
effect: "none",
|
|
728
|
+
approval: "prompt_default"
|
|
729
|
+
});
|
|
730
|
+
/**
|
|
731
|
+
* Descriptors for every tool the CLI builds itself or gets from @bike4mind/services:
|
|
732
|
+
* generateCliTools, buildCliToolList and the subagent-injected tools. A tool missing here
|
|
733
|
+
* resolves to the unknown fallback in toolCatalog.ts; coreToolCompleteness.test.ts
|
|
734
|
+
* fails when a generated tool has no entry.
|
|
735
|
+
*/
|
|
736
|
+
const CORE_TOOL_DESCRIPTORS = new Map(Object.entries({
|
|
737
|
+
math_evaluate: pureCompute(),
|
|
738
|
+
current_datetime: pureCompute(),
|
|
739
|
+
dice_roll: pureCompute(),
|
|
740
|
+
prompt_enhancement: pureCompute(),
|
|
741
|
+
find_definition: {
|
|
742
|
+
source: CLI,
|
|
743
|
+
effect: "read",
|
|
744
|
+
approval: "auto_approve"
|
|
745
|
+
},
|
|
746
|
+
peer_list: {
|
|
747
|
+
source: CLI,
|
|
748
|
+
effect: "read",
|
|
749
|
+
approval: "prompt_default"
|
|
750
|
+
},
|
|
751
|
+
peer_status: {
|
|
752
|
+
source: CLI,
|
|
753
|
+
effect: "read",
|
|
754
|
+
approval: "prompt_default"
|
|
755
|
+
},
|
|
756
|
+
peer_send: {
|
|
757
|
+
source: CLI,
|
|
758
|
+
effect: "execute",
|
|
759
|
+
approval: "auto_approve"
|
|
760
|
+
},
|
|
761
|
+
ask_user_question: {
|
|
762
|
+
source: CORE,
|
|
763
|
+
effect: "session",
|
|
764
|
+
approval: "auto_approve"
|
|
765
|
+
},
|
|
766
|
+
agent_delegate: sessionTool(),
|
|
767
|
+
check_agent_status: sessionTool(),
|
|
768
|
+
list_background_agents: sessionTool(),
|
|
769
|
+
cancel_background_agent: sessionTool(),
|
|
770
|
+
resume_agent: sessionTool(),
|
|
771
|
+
create_dynamic_agent: sessionTool(),
|
|
772
|
+
coordinate_task: sessionTool(),
|
|
773
|
+
decompose_task: sessionTool(),
|
|
774
|
+
shared_context_read: sessionTool(),
|
|
775
|
+
shared_context_write: sessionTool(),
|
|
776
|
+
write_todos: sessionTool(),
|
|
777
|
+
read_prior_todos: sessionTool(),
|
|
778
|
+
log_decision: sessionTool(),
|
|
779
|
+
track_blocker: sessionTool(),
|
|
780
|
+
resolve_blocker: sessionTool(),
|
|
781
|
+
request_review_gate: sessionTool(),
|
|
782
|
+
work_item_create: sessionTool(),
|
|
783
|
+
work_item_update: sessionTool(),
|
|
784
|
+
work_item_close: sessionTool(),
|
|
785
|
+
work_item_ready: sessionTool(),
|
|
786
|
+
work_item_graph: sessionTool(),
|
|
787
|
+
tool_search: sessionTool(),
|
|
788
|
+
create_file: fileWriter(),
|
|
789
|
+
edit_local_file: fileWriter(),
|
|
790
|
+
delete_file: fileWriter(),
|
|
791
|
+
edit_file: {
|
|
792
|
+
source: CORE,
|
|
793
|
+
effect: "write",
|
|
794
|
+
approval: "prompt_always"
|
|
795
|
+
},
|
|
796
|
+
bash_execute: {
|
|
797
|
+
source: CORE,
|
|
798
|
+
effect: "execute",
|
|
799
|
+
approval: "prompt_always",
|
|
800
|
+
openWorld: true,
|
|
801
|
+
commandArg: "command",
|
|
802
|
+
sandbox: "command"
|
|
803
|
+
},
|
|
804
|
+
shell_execute: {
|
|
805
|
+
source: CORE,
|
|
806
|
+
effect: "execute",
|
|
807
|
+
approval: "prompt_always",
|
|
808
|
+
openWorld: true
|
|
809
|
+
},
|
|
810
|
+
write_shell_stdin: {
|
|
811
|
+
source: CORE,
|
|
812
|
+
effect: "execute",
|
|
813
|
+
approval: "prompt_always",
|
|
814
|
+
commandArg: "chars"
|
|
815
|
+
},
|
|
816
|
+
kill_background_shell: {
|
|
817
|
+
source: CORE,
|
|
818
|
+
effect: "execute",
|
|
819
|
+
approval: "prompt_always"
|
|
820
|
+
},
|
|
821
|
+
git_commit: {
|
|
822
|
+
source: CORE,
|
|
823
|
+
effect: "write",
|
|
824
|
+
approval: "prompt_always"
|
|
825
|
+
},
|
|
826
|
+
git_push: {
|
|
827
|
+
source: CORE,
|
|
828
|
+
effect: "write",
|
|
829
|
+
approval: "prompt_always",
|
|
830
|
+
openWorld: true
|
|
831
|
+
},
|
|
832
|
+
skill: {
|
|
833
|
+
source: CLI,
|
|
834
|
+
effect: "execute",
|
|
835
|
+
approval: "prompt_always"
|
|
836
|
+
},
|
|
837
|
+
weather_info: reader(CORE, { openWorld: true }),
|
|
838
|
+
web_search: reader(CORE, { openWorld: true }),
|
|
839
|
+
web_fetch: reader(CORE, { openWorld: true }),
|
|
840
|
+
decide: reader(CORE, { openWorld: true }),
|
|
841
|
+
deep_research: reader(CORE, { openWorld: true }),
|
|
842
|
+
check_shell_output: reader(),
|
|
843
|
+
list_background_shells: reader(),
|
|
844
|
+
file_read: reader(),
|
|
845
|
+
grep_search: reader(),
|
|
846
|
+
glob_files: reader(),
|
|
847
|
+
get_file_tree: reader(),
|
|
848
|
+
get_file_structure: reader(CLI),
|
|
849
|
+
recent_changes: reader(),
|
|
850
|
+
git_status: reader(),
|
|
851
|
+
git_diff: reader(),
|
|
852
|
+
git_log: reader(),
|
|
853
|
+
git_branch: reader(),
|
|
854
|
+
lattice_create_model: lattice(),
|
|
855
|
+
lattice_add_entity: lattice(),
|
|
856
|
+
lattice_set_value: lattice(),
|
|
857
|
+
lattice_create_rule: lattice(),
|
|
858
|
+
lattice_query: lattice(),
|
|
859
|
+
lattice_explain: lattice()
|
|
860
|
+
}));
|
|
861
|
+
//#endregion
|
|
862
|
+
//#region src/tools/gateway/toolPolicy.ts
|
|
863
|
+
/**
|
|
864
|
+
* Every policy decision about a tool, derived from its descriptor. `undefined` is a tool the
|
|
865
|
+
* catalog could not resolve; it keeps the pre-descriptor fallback (prompt_default, read-only)
|
|
866
|
+
* because feature-module and plugin tools do not register descriptors yet.
|
|
867
|
+
*/
|
|
868
|
+
const UNKNOWN_TOOL_CATEGORY = "prompt_default";
|
|
869
|
+
const READ_ONLY_EFFECTS = /* @__PURE__ */ new Set([
|
|
870
|
+
"none",
|
|
871
|
+
"session",
|
|
872
|
+
"read"
|
|
873
|
+
]);
|
|
874
|
+
/**
|
|
875
|
+
* How far a source's own declarations are believed. Core, cli and builtin-module tools ship in
|
|
876
|
+
* this repo and are reviewed, so their descriptor is taken as written. A plugin is third-party
|
|
877
|
+
* code the user installed and enabled: it can be trusted per tool after a prompt, but cannot
|
|
878
|
+
* skip the first prompt or claim to be read-only. MCP tools and lifecycle hooks always prompt.
|
|
879
|
+
*/
|
|
880
|
+
function categoryCeiling(source) {
|
|
881
|
+
switch (source.kind) {
|
|
882
|
+
case "mcp":
|
|
883
|
+
case "hook": return "prompt_always";
|
|
884
|
+
case "plugin": return "prompt_default";
|
|
885
|
+
default: return;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
function believesDeclaredEffect(source) {
|
|
889
|
+
return categoryCeiling(source) === void 0;
|
|
890
|
+
}
|
|
891
|
+
function toolCategory(descriptor) {
|
|
892
|
+
if (!descriptor) return UNKNOWN_TOOL_CATEGORY;
|
|
893
|
+
const ceiling = categoryCeiling(descriptor.source);
|
|
894
|
+
if (ceiling === "prompt_always") return ceiling;
|
|
895
|
+
if (ceiling === "prompt_default" && descriptor.approval === "auto_approve") return ceiling;
|
|
896
|
+
return descriptor.approval;
|
|
897
|
+
}
|
|
898
|
+
/** Whether a prompt_default trust decision can be persisted for the tool. */
|
|
899
|
+
function canTrustTool(descriptor) {
|
|
900
|
+
return toolCategory(descriptor) !== "prompt_always";
|
|
901
|
+
}
|
|
902
|
+
/** Read-only tools run in plan mode and in parallel batches; the rest are blocked / sequential. */
|
|
903
|
+
function isReadOnlyTool(descriptor) {
|
|
904
|
+
if (!descriptor) return true;
|
|
905
|
+
if (!believesDeclaredEffect(descriptor.source)) return false;
|
|
906
|
+
return READ_ONLY_EFFECTS.has(descriptor.effect);
|
|
907
|
+
}
|
|
908
|
+
/** The shell command text the risk gate classifies, when the tool has one in `args`. */
|
|
909
|
+
function commandTextOf(descriptor, args) {
|
|
910
|
+
return stringArg(args, descriptor?.commandArg);
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* The argument holding the command the OS sandbox wraps, or undefined when the tool is not
|
|
914
|
+
* sandboxed. Only core tools may declare it: a sandboxed call can skip the prompt in
|
|
915
|
+
* auto-allow mode, so a plugin or MCP descriptor must not be able to claim it.
|
|
916
|
+
*/
|
|
917
|
+
function sandboxedCommandArg(descriptor) {
|
|
918
|
+
if (descriptor?.sandbox !== "command" || descriptor.source.kind !== "core") return void 0;
|
|
919
|
+
return descriptor.commandArg;
|
|
920
|
+
}
|
|
921
|
+
/** The path a file-writing tool will write, when the tool declares one and `args` carries it. */
|
|
922
|
+
function writePathOf(descriptor, args) {
|
|
923
|
+
const writePath = stringArg(args, descriptor?.writePathArg);
|
|
924
|
+
return writePath ? writePath : void 0;
|
|
925
|
+
}
|
|
926
|
+
function stringArg(args, field) {
|
|
927
|
+
if (!field || args === null || typeof args !== "object") return void 0;
|
|
928
|
+
const value = args[field];
|
|
929
|
+
return typeof value === "string" ? value : void 0;
|
|
930
|
+
}
|
|
931
|
+
//#endregion
|
|
932
|
+
//#region src/tools/gateway/toolCatalog.ts
|
|
933
|
+
const MCP_PREFIX = "mcp__";
|
|
934
|
+
const HOOK_PREFIXES = ["agent_hook:", "skill_hook:"];
|
|
935
|
+
function isHookName(toolName) {
|
|
936
|
+
return HOOK_PREFIXES.some((prefix) => toolName.startsWith(prefix));
|
|
937
|
+
}
|
|
938
|
+
/**
|
|
939
|
+
* Resolve a tool name without a catalog instance: the core table, then the MCP namespace
|
|
940
|
+
* (`mcp__<server>__<tool>`), then the lifecycle-hook namespaces. Undefined means unknown.
|
|
941
|
+
* ToolCatalog.resolve falls back to this after its registered descriptors.
|
|
942
|
+
*/
|
|
943
|
+
function resolveStaticToolDescriptor(toolName) {
|
|
944
|
+
const core = CORE_TOOL_DESCRIPTORS.get(toolName);
|
|
945
|
+
if (core) return core;
|
|
946
|
+
if (toolName.startsWith(MCP_PREFIX)) return {
|
|
947
|
+
source: {
|
|
948
|
+
kind: "mcp",
|
|
949
|
+
server: toolName.slice(5).split("__")[0]
|
|
950
|
+
},
|
|
951
|
+
effect: "execute",
|
|
952
|
+
approval: "prompt_always"
|
|
953
|
+
};
|
|
954
|
+
if (isHookName(toolName)) return {
|
|
955
|
+
source: { kind: "hook" },
|
|
956
|
+
effect: "execute",
|
|
957
|
+
approval: "prompt_always"
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
/**
|
|
961
|
+
* Name -> descriptor lookup for one CLI process or ACP stack. Entry points create one and hand
|
|
962
|
+
* it to their PermissionManager, which the permission gateway and the agent's read-only
|
|
963
|
+
* predicate read it through.
|
|
964
|
+
*/
|
|
965
|
+
var ToolCatalog = class {
|
|
966
|
+
constructor() {
|
|
967
|
+
this.registered = /* @__PURE__ */ new Map();
|
|
968
|
+
}
|
|
969
|
+
/**
|
|
970
|
+
* Add a descriptor for a tool the core table does not know. Core names and the MCP and hook
|
|
971
|
+
* namespaces are reserved: nothing can re-declare a core tool, or declare itself into a
|
|
972
|
+
* namespace whose descriptor comes from the name alone, with a lower tier.
|
|
973
|
+
*/
|
|
974
|
+
register(toolName, descriptor) {
|
|
975
|
+
if (toolName.startsWith(MCP_PREFIX) || isHookName(toolName)) throw new Error(`Tool name "${toolName}" is in a reserved namespace and cannot be registered`);
|
|
976
|
+
if (CORE_TOOL_DESCRIPTORS.has(toolName)) throw new Error(`Tool "${toolName}" is a core tool and already has a descriptor`);
|
|
977
|
+
if (this.registered.has(toolName)) throw new Error(`Tool "${toolName}" already has a registered descriptor`);
|
|
978
|
+
this.registered.set(toolName, descriptor);
|
|
979
|
+
}
|
|
980
|
+
resolve(toolName) {
|
|
981
|
+
return this.registered.get(toolName) ?? resolveStaticToolDescriptor(toolName);
|
|
982
|
+
}
|
|
983
|
+
category(toolName) {
|
|
984
|
+
return toolCategory(this.resolve(toolName));
|
|
985
|
+
}
|
|
986
|
+
canTrust(toolName) {
|
|
987
|
+
return canTrustTool(this.resolve(toolName));
|
|
988
|
+
}
|
|
989
|
+
isReadOnly(toolName) {
|
|
990
|
+
return isReadOnlyTool(this.resolve(toolName));
|
|
991
|
+
}
|
|
992
|
+
};
|
|
993
|
+
const PROJECT_CONTEXT_FILES = [
|
|
994
|
+
"CLAUDE.local.md",
|
|
995
|
+
"CLAUDE.md",
|
|
996
|
+
"AGENTS.md",
|
|
997
|
+
"AI.local.md",
|
|
998
|
+
"AI.md",
|
|
999
|
+
"INSTRUCTIONS.md"
|
|
1000
|
+
];
|
|
1001
|
+
const GLOBAL_CONTEXT_FILES = ["AI.local.md", "AI.md"];
|
|
1002
|
+
/**
|
|
1003
|
+
* Format file size for display
|
|
1004
|
+
*/
|
|
1005
|
+
function formatFileSize(bytes) {
|
|
1006
|
+
if (bytes < 1024) return `${bytes}B`;
|
|
1007
|
+
if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)}KB`;
|
|
1008
|
+
return `${(bytes / 1048576).toFixed(1)}MB`;
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Try to read a context file from a directory
|
|
1012
|
+
*
|
|
1013
|
+
* Security: Only reads regular files (not directories or symlinks) within the specified directory.
|
|
1014
|
+
* Files must be under 100KB to prevent abuse. Symlinks are rejected to prevent reading
|
|
1015
|
+
* files outside the intended directory.
|
|
1016
|
+
*
|
|
1017
|
+
* @param dir - The directory to read from (must be a controlled location)
|
|
1018
|
+
* @param filename - The filename to read (must not contain path separators)
|
|
1019
|
+
* @param source - Whether this is a 'global' or 'project' context file
|
|
1020
|
+
* @returns The file result, an error object, or null if file doesn't exist
|
|
1021
|
+
*/
|
|
1022
|
+
function tryReadContextFile(dir, filename, source) {
|
|
1023
|
+
const filePath = path$2.join(dir, filename);
|
|
1024
|
+
try {
|
|
1025
|
+
const stats = fs.lstatSync(filePath);
|
|
1026
|
+
if (stats.isDirectory()) return null;
|
|
1027
|
+
if (stats.isSymbolicLink()) return { error: `${source === "global" ? "Global" : "Project"} ${filename} is a symlink (not allowed for security)` };
|
|
1028
|
+
if (stats.size > 102400) return { error: `${source === "global" ? "Global" : "Project"} ${filename} exceeds 100KB limit (${formatFileSize(stats.size)})` };
|
|
1029
|
+
return {
|
|
1030
|
+
filename,
|
|
1031
|
+
content: fs.readFileSync(filePath, "utf-8"),
|
|
1032
|
+
source,
|
|
1033
|
+
path: filePath
|
|
1034
|
+
};
|
|
1035
|
+
} catch (err) {
|
|
1036
|
+
if (err.code === "ENOENT") return null;
|
|
1037
|
+
if (err.code === "EACCES") return { error: `Cannot read ${source} ${filename}: permission denied` };
|
|
1038
|
+
return { error: `Cannot read ${source} ${filename}: ${err instanceof Error ? err.message : "Unknown error"}` };
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* Find the first context file in a directory from a list of candidates
|
|
1043
|
+
*/
|
|
1044
|
+
function findContextFile(dir, candidates, source) {
|
|
1045
|
+
for (const filename of candidates) {
|
|
1046
|
+
const result = tryReadContextFile(dir, filename, source);
|
|
1047
|
+
if (result === null) continue;
|
|
1048
|
+
if ("error" in result) return {
|
|
1049
|
+
result: null,
|
|
1050
|
+
error: result.error
|
|
1051
|
+
};
|
|
1052
|
+
return {
|
|
1053
|
+
result,
|
|
1054
|
+
error: null
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
return {
|
|
1058
|
+
result: null,
|
|
1059
|
+
error: null
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* Merge global and project context into a single string
|
|
1064
|
+
*/
|
|
1065
|
+
function mergeContextContent(global, project) {
|
|
1066
|
+
if (global && project) return `${global.content}\n\n---\n\n${project.content}`;
|
|
1067
|
+
if (global) return global.content;
|
|
1068
|
+
if (project) return project.content;
|
|
1069
|
+
return "";
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Load context files from global and project directories
|
|
1073
|
+
*
|
|
1074
|
+
* Global files are loaded from ~/.bike4mind/
|
|
1075
|
+
* Project files are loaded from `projectDir`. When it is null the project layer
|
|
1076
|
+
* is SKIPPED entirely (not defaulted to cwd) - the folder-trust gate passes null
|
|
1077
|
+
* for an untrusted project so its repo context file is never loaded.
|
|
1078
|
+
*
|
|
1079
|
+
* Returns the first matching file from each layer based on priority order
|
|
1080
|
+
*/
|
|
1081
|
+
async function loadContextFiles(projectDir) {
|
|
1082
|
+
const errors = [];
|
|
1083
|
+
const globalDir = path$2.join(homedir$1(), ".bike4mind");
|
|
1084
|
+
const [globalResult, projectResult] = await Promise.all([Promise.resolve(findContextFile(globalDir, GLOBAL_CONTEXT_FILES, "global")), Promise.resolve(projectDir ? findContextFile(projectDir, PROJECT_CONTEXT_FILES, "project") : {
|
|
1085
|
+
result: null,
|
|
1086
|
+
error: null
|
|
1087
|
+
})]);
|
|
1088
|
+
if (globalResult.error) errors.push(globalResult.error);
|
|
1089
|
+
if (projectResult.error) errors.push(projectResult.error);
|
|
1090
|
+
const mergedContent = mergeContextContent(globalResult.result, projectResult.result);
|
|
1091
|
+
return {
|
|
1092
|
+
globalContext: globalResult.result,
|
|
1093
|
+
projectContext: projectResult.result,
|
|
1094
|
+
mergedContent,
|
|
1095
|
+
errors
|
|
1096
|
+
};
|
|
1097
|
+
}
|
|
1098
|
+
/**
|
|
1099
|
+
* Extract "# Compact Instructions" or "## Compact Instructions" section from CLAUDE.md content
|
|
1100
|
+
*
|
|
1101
|
+
* This section provides project-specific instructions for how conversations should be
|
|
1102
|
+
* summarized when compacting context.
|
|
1103
|
+
*
|
|
1104
|
+
* @param contextContent - The merged context content from CLAUDE.md files
|
|
1105
|
+
* @returns The extracted instructions content, or undefined if not found
|
|
1106
|
+
*/
|
|
1107
|
+
function extractCompactInstructions(contextContent) {
|
|
1108
|
+
const match = contextContent.match(/^#{1,2}\s*Compact\s*Instructions\s*$/im);
|
|
1109
|
+
if (!match || match.index === void 0) return;
|
|
1110
|
+
const startIndex = match.index + match[0].length;
|
|
1111
|
+
const remainingContent = contextContent.slice(startIndex);
|
|
1112
|
+
const endIndex = remainingContent.match(/^#{1,2}\s+\S/m)?.index ?? remainingContent.length;
|
|
1113
|
+
return remainingContent.slice(0, endIndex).trim() || void 0;
|
|
1114
|
+
}
|
|
1115
|
+
//#endregion
|
|
1116
|
+
//#region src/storage/lockDir.ts
|
|
1117
|
+
var LockLostError = class extends Error {
|
|
1118
|
+
constructor(lockPath) {
|
|
1119
|
+
super(`Lost the lock ${lockPath}: another b4m process may have taken it over`);
|
|
1120
|
+
this.name = "LockLostError";
|
|
1121
|
+
}
|
|
1122
|
+
};
|
|
1123
|
+
const OWNER = "owner";
|
|
1124
|
+
const OWNER_READ_TRIES = 5;
|
|
1125
|
+
const RELEASE_TRIES = 5;
|
|
1126
|
+
const RETRY_PAUSE_MS = 20;
|
|
1127
|
+
/** Nonces of the locks this process holds now, so a lock it left behind is told apart from one it still holds. */
|
|
1128
|
+
const liveNonces = /* @__PURE__ */ new Set();
|
|
1129
|
+
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1130
|
+
const codeOf = (error) => error?.code;
|
|
1131
|
+
/** True when no process `pid` exists on this host. EPERM means one exists that this user cannot signal. */
|
|
1132
|
+
function holderIsGone(pid) {
|
|
1133
|
+
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) return false;
|
|
1134
|
+
try {
|
|
1135
|
+
process.kill(pid, 0);
|
|
1136
|
+
return false;
|
|
1137
|
+
} catch (error) {
|
|
1138
|
+
return codeOf(error) === "ESRCH";
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
/** The lock's owner record, or null when there is none. Transient read errors (EBUSY on Windows) are retried, then thrown. */
|
|
1142
|
+
async function readOwner(lockPath) {
|
|
1143
|
+
for (let attempt = 1;; attempt++) try {
|
|
1144
|
+
const parsed = JSON.parse(await promises.readFile(path.join(lockPath, OWNER), "utf-8"));
|
|
1145
|
+
return typeof parsed === "object" && parsed !== null ? parsed : null;
|
|
1146
|
+
} catch (error) {
|
|
1147
|
+
const code = codeOf(error);
|
|
1148
|
+
if (code === "ENOENT" || code === "ENOTDIR" || error instanceof SyntaxError) return null;
|
|
1149
|
+
if (attempt >= OWNER_READ_TRIES) throw error;
|
|
1150
|
+
await pause(RETRY_PAUSE_MS);
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
async function isStale(lockPath, staleMs) {
|
|
1154
|
+
let mtimeMs;
|
|
1155
|
+
try {
|
|
1156
|
+
mtimeMs = (await promises.stat(lockPath)).mtimeMs;
|
|
1157
|
+
} catch {
|
|
1158
|
+
return false;
|
|
1159
|
+
}
|
|
1160
|
+
const age = Date.now() - mtimeMs;
|
|
1161
|
+
if (age > staleMs || age < -staleMs) return true;
|
|
1162
|
+
if (age <= staleMs * 2 / 3) return false;
|
|
1163
|
+
const owner = await readOwner(lockPath).catch(() => null);
|
|
1164
|
+
if (!owner || owner.hostname !== hostname()) return false;
|
|
1165
|
+
if (owner.pid === process.pid) return typeof owner.nonce === "string" && !liveNonces.has(owner.nonce);
|
|
1166
|
+
return holderIsGone(owner.pid);
|
|
1167
|
+
}
|
|
1168
|
+
/**
|
|
1169
|
+
* Moves a stale lock aside, then deletes it only if it is still stale there. One found fresh once moved (a new lock
|
|
1170
|
+
* made since the check) stays aside: its holder finds the lock lost at its next check instead of sharing it.
|
|
1171
|
+
* Returns whether the lock is gone, so the caller can retry without pausing.
|
|
1172
|
+
*/
|
|
1173
|
+
async function breakIfStale(lockPath, staleMs) {
|
|
1174
|
+
if (!await isStale(lockPath, staleMs)) return false;
|
|
1175
|
+
const aside = `${lockPath}.${v4()}.stale`;
|
|
1176
|
+
try {
|
|
1177
|
+
await promises.rename(lockPath, aside);
|
|
1178
|
+
} catch (error) {
|
|
1179
|
+
return codeOf(error) === "ENOENT";
|
|
1180
|
+
}
|
|
1181
|
+
if (await isStale(aside, staleMs)) await promises.rm(aside, {
|
|
1182
|
+
recursive: true,
|
|
1183
|
+
force: true
|
|
1184
|
+
}).catch(() => void 0);
|
|
1185
|
+
return true;
|
|
1186
|
+
}
|
|
1187
|
+
/** Removes broken-aside locks, and the old scheme's `*.aside` files, that have outlived the stale limit. */
|
|
1188
|
+
async function sweepOrphans(lockPath, staleMs) {
|
|
1189
|
+
const dir = path.dirname(lockPath);
|
|
1190
|
+
const prefix = `${path.basename(lockPath)}.`;
|
|
1191
|
+
const names = await promises.readdir(dir).catch(() => []);
|
|
1192
|
+
for (const name of names) {
|
|
1193
|
+
if (!name.startsWith(prefix) || !(name.endsWith(".stale") || name.endsWith(".aside"))) continue;
|
|
1194
|
+
const entry = path.join(dir, name);
|
|
1195
|
+
try {
|
|
1196
|
+
if (Date.now() - (await promises.stat(entry)).mtimeMs > staleMs) await promises.rm(entry, {
|
|
1197
|
+
recursive: true,
|
|
1198
|
+
force: true
|
|
1199
|
+
});
|
|
1200
|
+
} catch {}
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
/** Takes the lock, and returns a performance.now() reading from no later than its last touch. */
|
|
1204
|
+
async function acquire(lockPath, nonce, opts) {
|
|
1205
|
+
const deadline = performance.now() + opts.waitMs;
|
|
1206
|
+
await promises.mkdir(path.dirname(lockPath), { recursive: true });
|
|
1207
|
+
await sweepOrphans(lockPath, opts.staleMs);
|
|
1208
|
+
let retriedPastDeadline = false;
|
|
1209
|
+
for (;;) {
|
|
1210
|
+
let retryNow = false;
|
|
1211
|
+
const attemptAt = performance.now();
|
|
1212
|
+
try {
|
|
1213
|
+
await promises.mkdir(lockPath);
|
|
1214
|
+
try {
|
|
1215
|
+
const owner = JSON.stringify({
|
|
1216
|
+
pid: process.pid,
|
|
1217
|
+
hostname: hostname(),
|
|
1218
|
+
nonce
|
|
1219
|
+
});
|
|
1220
|
+
await promises.writeFile(path.join(lockPath, OWNER), owner, {
|
|
1221
|
+
flag: "wx",
|
|
1222
|
+
mode: 384
|
|
1223
|
+
});
|
|
1224
|
+
const now = /* @__PURE__ */ new Date();
|
|
1225
|
+
await promises.utimes(lockPath, now, now).catch(() => void 0);
|
|
1226
|
+
return attemptAt;
|
|
1227
|
+
} catch (error) {
|
|
1228
|
+
const code = codeOf(error);
|
|
1229
|
+
if (code !== "ENOENT" && code !== "EEXIST") {
|
|
1230
|
+
await promises.rmdir(lockPath).catch(() => void 0);
|
|
1231
|
+
throw error;
|
|
1232
|
+
}
|
|
1233
|
+
}
|
|
1234
|
+
} catch (error) {
|
|
1235
|
+
const code = codeOf(error);
|
|
1236
|
+
if (!(code === "EEXIST" || process.platform === "win32" && (code === "EPERM" || code === "EACCES"))) throw error;
|
|
1237
|
+
retryNow = await breakIfStale(lockPath, opts.staleMs);
|
|
1238
|
+
}
|
|
1239
|
+
if (retryNow && (performance.now() < deadline || !retriedPastDeadline)) {
|
|
1240
|
+
retriedPastDeadline ||= performance.now() >= deadline;
|
|
1241
|
+
continue;
|
|
1242
|
+
}
|
|
1243
|
+
if (performance.now() >= deadline) throw new Error(`${opts.heldMessage} (${lockPath} is held)`);
|
|
1244
|
+
await pause(opts.pollMs);
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Deletes the lock if it is still this holder's, and returns false when it is not. Windows can refuse the delete
|
|
1249
|
+
* briefly while another process reads the lock.
|
|
1250
|
+
*/
|
|
1251
|
+
async function release(lockPath, nonce) {
|
|
1252
|
+
let owner;
|
|
1253
|
+
try {
|
|
1254
|
+
owner = await readOwner(lockPath);
|
|
1255
|
+
} catch {
|
|
1256
|
+
return true;
|
|
1257
|
+
}
|
|
1258
|
+
if (owner?.nonce !== nonce) return false;
|
|
1259
|
+
for (let attempt = 1;; attempt++) try {
|
|
1260
|
+
await promises.rm(lockPath, {
|
|
1261
|
+
recursive: true,
|
|
1262
|
+
force: true
|
|
1263
|
+
});
|
|
1264
|
+
return true;
|
|
1265
|
+
} catch (error) {
|
|
1266
|
+
const code = codeOf(error);
|
|
1267
|
+
if (attempt >= RELEASE_TRIES || !(code === "EPERM" || code === "EBUSY" || code === "EACCES")) return true;
|
|
1268
|
+
await pause(RETRY_PAUSE_MS * attempt);
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
/**
|
|
1272
|
+
* Runs `work` holding the lock directory `lockPath` against other processes. Not reentrant. Rejects with
|
|
1273
|
+
* LockLostError when the lock was taken from this holder while `work` ran, even if `work` itself succeeded.
|
|
1274
|
+
*/
|
|
1275
|
+
async function withLockDir(lockPath, work, opts) {
|
|
1276
|
+
const nonce = v4();
|
|
1277
|
+
let lastTouch = await acquire(lockPath, nonce, opts);
|
|
1278
|
+
liveNonces.add(nonce);
|
|
1279
|
+
const lost = new AbortController();
|
|
1280
|
+
const assertHeld = async () => {
|
|
1281
|
+
if (!lost.signal.aborted && performance.now() - lastTouch > opts.staleMs * 2 / 3) lost.abort(new LockLostError(lockPath));
|
|
1282
|
+
if (!lost.signal.aborted && (await readOwner(lockPath))?.nonce !== nonce) lost.abort(new LockLostError(lockPath));
|
|
1283
|
+
if (lost.signal.aborted) throw lost.signal.reason;
|
|
1284
|
+
};
|
|
1285
|
+
let stopped = false;
|
|
1286
|
+
let timer;
|
|
1287
|
+
let beating = Promise.resolve();
|
|
1288
|
+
const beat = async () => {
|
|
1289
|
+
try {
|
|
1290
|
+
await assertHeld();
|
|
1291
|
+
const touchedAt = performance.now();
|
|
1292
|
+
const now = /* @__PURE__ */ new Date();
|
|
1293
|
+
await promises.utimes(lockPath, now, now);
|
|
1294
|
+
lastTouch = touchedAt;
|
|
1295
|
+
} catch {}
|
|
1296
|
+
if (!stopped && !lost.signal.aborted) schedule();
|
|
1297
|
+
};
|
|
1298
|
+
const schedule = () => {
|
|
1299
|
+
timer = setTimeout(() => {
|
|
1300
|
+
beating = beat();
|
|
1301
|
+
}, opts.staleMs / 3);
|
|
1302
|
+
timer.unref?.();
|
|
1303
|
+
};
|
|
1304
|
+
schedule();
|
|
1305
|
+
let result;
|
|
1306
|
+
let stillHeld = true;
|
|
1307
|
+
try {
|
|
1308
|
+
result = await work({
|
|
1309
|
+
signal: lost.signal,
|
|
1310
|
+
assertHeld
|
|
1311
|
+
});
|
|
1312
|
+
} finally {
|
|
1313
|
+
stopped = true;
|
|
1314
|
+
clearTimeout(timer);
|
|
1315
|
+
await beating;
|
|
1316
|
+
stillHeld = await release(lockPath, nonce);
|
|
1317
|
+
liveNonces.delete(nonce);
|
|
1318
|
+
}
|
|
1319
|
+
if (!stillHeld && !lost.signal.aborted) lost.abort(new LockLostError(lockPath));
|
|
1320
|
+
if (lost.signal.aborted) throw lost.signal.reason;
|
|
1321
|
+
return result;
|
|
1322
|
+
}
|
|
1323
|
+
//#endregion
|
|
1324
|
+
//#region src/storage/ConfigStore.ts
|
|
1325
|
+
/**
|
|
1326
|
+
* Zod schema for sandbox filesystem configuration
|
|
1327
|
+
*/
|
|
1328
|
+
const SandboxFilesystemSchema = z$1.object({
|
|
1329
|
+
allowedReadPaths: z$1.array(z$1.string()).default(DEFAULT_SANDBOX_CONFIG.filesystem.allowedReadPaths),
|
|
1330
|
+
deniedPaths: z$1.array(z$1.string()).default(DEFAULT_SANDBOX_CONFIG.filesystem.deniedPaths),
|
|
1331
|
+
writeOnlyToWorkingDir: z$1.boolean().default(true)
|
|
1332
|
+
});
|
|
1333
|
+
/**
|
|
1334
|
+
* Zod schema for sandbox network configuration
|
|
1335
|
+
*/
|
|
1336
|
+
const SandboxNetworkSchema = z$1.object({
|
|
1337
|
+
enabled: z$1.boolean().default(false),
|
|
1338
|
+
allowedDomains: z$1.array(z$1.string()).default(DEFAULT_SANDBOX_CONFIG.network.allowedDomains)
|
|
1339
|
+
});
|
|
1340
|
+
/**
|
|
1341
|
+
* Zod schema for sandbox platform configuration
|
|
1342
|
+
*/
|
|
1343
|
+
const SandboxPlatformSchema = z$1.object({
|
|
1344
|
+
linux: z$1.object({
|
|
1345
|
+
runtime: z$1.literal("bubblewrap").default("bubblewrap"),
|
|
1346
|
+
seccompProfile: z$1.string().optional()
|
|
1347
|
+
}).default({ runtime: "bubblewrap" }),
|
|
1348
|
+
macos: z$1.object({
|
|
1349
|
+
runtime: z$1.literal("seatbelt").default("seatbelt"),
|
|
1350
|
+
profileTemplate: z$1.string().default("default")
|
|
1351
|
+
}).default({
|
|
1352
|
+
runtime: "seatbelt",
|
|
1353
|
+
profileTemplate: "default"
|
|
1354
|
+
})
|
|
1355
|
+
});
|
|
1356
|
+
/**
|
|
1357
|
+
* Zod schema for full sandbox configuration
|
|
1358
|
+
*/
|
|
1359
|
+
const SandboxConfigSchema = z$1.object({
|
|
1360
|
+
enabled: z$1.boolean().default(false),
|
|
1361
|
+
mode: z$1.enum([
|
|
1362
|
+
"disabled",
|
|
1363
|
+
"auto-allow",
|
|
1364
|
+
"permissions"
|
|
1365
|
+
]).default("disabled"),
|
|
1366
|
+
filesystem: SandboxFilesystemSchema.default(DEFAULT_SANDBOX_CONFIG.filesystem),
|
|
1367
|
+
network: SandboxNetworkSchema.default(DEFAULT_SANDBOX_CONFIG.network),
|
|
1368
|
+
excludedCommands: z$1.array(z$1.string()).default(DEFAULT_SANDBOX_CONFIG.excludedCommands),
|
|
1369
|
+
allowUnsandboxedCommands: z$1.boolean().default(true),
|
|
1370
|
+
allowContainerSockets: z$1.boolean().default(false),
|
|
1371
|
+
platform: SandboxPlatformSchema.default(DEFAULT_SANDBOX_CONFIG.platform)
|
|
1372
|
+
}).refine((config) => {
|
|
1373
|
+
if (config.enabled && config.mode === "disabled") return false;
|
|
1374
|
+
if (!config.enabled && config.mode !== "disabled") return false;
|
|
1375
|
+
return true;
|
|
1376
|
+
}, { message: "Sandbox config inconsistency: enabled and mode must agree. If enabled=true, mode must be \"auto-allow\" or \"permissions\". If mode=\"disabled\", enabled must be false." });
|
|
1377
|
+
/**
|
|
1378
|
+
* Partial sandbox config schema for project/local overrides
|
|
1379
|
+
*/
|
|
1380
|
+
const PartialSandboxConfigSchema = z$1.object({
|
|
1381
|
+
enabled: z$1.boolean().optional(),
|
|
1382
|
+
mode: z$1.enum([
|
|
1383
|
+
"disabled",
|
|
1384
|
+
"auto-allow",
|
|
1385
|
+
"permissions"
|
|
1386
|
+
]).optional(),
|
|
1387
|
+
filesystem: z$1.object({
|
|
1388
|
+
allowedReadPaths: z$1.array(z$1.string()).optional(),
|
|
1389
|
+
deniedPaths: z$1.array(z$1.string()).optional(),
|
|
1390
|
+
writeOnlyToWorkingDir: z$1.boolean().optional()
|
|
1391
|
+
}).optional(),
|
|
1392
|
+
network: z$1.object({
|
|
1393
|
+
enabled: z$1.boolean().optional(),
|
|
1394
|
+
allowedDomains: z$1.array(z$1.string()).optional()
|
|
1395
|
+
}).optional(),
|
|
1396
|
+
excludedCommands: z$1.array(z$1.string()).optional(),
|
|
1397
|
+
allowUnsandboxedCommands: z$1.boolean().optional(),
|
|
1398
|
+
allowContainerSockets: z$1.boolean().optional(),
|
|
1399
|
+
platform: SandboxPlatformSchema.optional()
|
|
1400
|
+
}).optional();
|
|
1401
|
+
/**
|
|
1402
|
+
* Zod schema for authentication tokens
|
|
1403
|
+
*/
|
|
1404
|
+
const AuthTokensSchema = z$1.object({
|
|
1405
|
+
accessToken: z$1.string(),
|
|
1406
|
+
refreshToken: z$1.string(),
|
|
1407
|
+
expiresAt: z$1.string(),
|
|
1408
|
+
userId: z$1.string()
|
|
1409
|
+
});
|
|
1410
|
+
/**
|
|
1411
|
+
* Zod schema for API configuration
|
|
1412
|
+
*/
|
|
1413
|
+
const ApiConfigSchema = z$1.object({
|
|
1414
|
+
customUrl: z$1.url().optional(),
|
|
1415
|
+
endpointChosen: z$1.boolean().optional()
|
|
1416
|
+
});
|
|
1417
|
+
/**
|
|
1418
|
+
* MCP Server schema - individual server configuration
|
|
1419
|
+
*/
|
|
1420
|
+
const McpServerSchema = z$1.object({
|
|
1421
|
+
name: z$1.string(),
|
|
1422
|
+
type: z$1.enum(["stdio", "http"]).optional(),
|
|
1423
|
+
command: z$1.string().optional(),
|
|
1424
|
+
args: z$1.array(z$1.string()).optional(),
|
|
1425
|
+
url: z$1.string().optional(),
|
|
1426
|
+
headers: z$1.record(z$1.string(), z$1.string()).optional(),
|
|
1427
|
+
env: z$1.record(z$1.string(), z$1.string()).prefault({}),
|
|
1428
|
+
enabled: z$1.boolean().prefault(true)
|
|
1429
|
+
}).superRefine(mcpServerTransportRefine);
|
|
1430
|
+
/**
|
|
1431
|
+
* A valid MCP server is exactly one of:
|
|
1432
|
+
* - stdio: has `command` (spawned child process)
|
|
1433
|
+
* - http: has `url` (streamable-HTTP endpoint)
|
|
1434
|
+
* Rejecting malformed configs at parse time (not connect time) surfaces errors early.
|
|
1435
|
+
*/
|
|
1436
|
+
function mcpServerTransportRefine(server, ctx) {
|
|
1437
|
+
const hasCommand = typeof server.command === "string" && server.command.trim() !== "";
|
|
1438
|
+
const hasUrl = typeof server.url === "string" && server.url.trim() !== "";
|
|
1439
|
+
if (hasCommand && hasUrl) ctx.addIssue({
|
|
1440
|
+
code: "custom",
|
|
1441
|
+
message: "MCP server cannot set both \"command\" (stdio) and \"url\" (http)"
|
|
1442
|
+
});
|
|
1443
|
+
else if (!hasCommand && !hasUrl) ctx.addIssue({
|
|
1444
|
+
code: "custom",
|
|
1445
|
+
message: "MCP server must set either \"command\" (stdio) or \"url\" (http)"
|
|
1446
|
+
});
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* MCP Servers can be specified in two formats:
|
|
1450
|
+
* 1. Array format (B4M native): [{ "name": "...", "command": "...", ... }]
|
|
1451
|
+
* 2. Object format (portable): { "name": { "command": "...", ... } }
|
|
1452
|
+
*/
|
|
1453
|
+
const McpServersSchema = z$1.union([z$1.array(McpServerSchema), z$1.record(z$1.string(), z$1.object({
|
|
1454
|
+
type: z$1.enum(["stdio", "http"]).optional(),
|
|
1455
|
+
command: z$1.string().optional(),
|
|
1456
|
+
args: z$1.array(z$1.string()).optional(),
|
|
1457
|
+
url: z$1.string().optional(),
|
|
1458
|
+
headers: z$1.record(z$1.string(), z$1.string()).optional(),
|
|
1459
|
+
env: z$1.record(z$1.string(), z$1.string()).optional(),
|
|
1460
|
+
enabled: z$1.boolean().optional()
|
|
1461
|
+
}).superRefine(mcpServerTransportRefine))]);
|
|
1462
|
+
/**
|
|
1463
|
+
* Normalize MCP servers to internal array format
|
|
1464
|
+
* Accepts both array and object formats
|
|
1465
|
+
*/
|
|
1466
|
+
function normalizeMcpServers(servers) {
|
|
1467
|
+
if (Array.isArray(servers)) return servers.map((server) => ({
|
|
1468
|
+
name: server.name,
|
|
1469
|
+
type: server.type,
|
|
1470
|
+
command: server.command,
|
|
1471
|
+
args: server.args,
|
|
1472
|
+
url: server.url,
|
|
1473
|
+
headers: server.headers,
|
|
1474
|
+
env: server.env || {},
|
|
1475
|
+
enabled: server.enabled ?? true
|
|
1476
|
+
}));
|
|
1477
|
+
else return Object.entries(servers).map(([name, config]) => ({
|
|
1478
|
+
name,
|
|
1479
|
+
type: config.type,
|
|
1480
|
+
command: config.command,
|
|
1481
|
+
args: config.args,
|
|
1482
|
+
url: config.url,
|
|
1483
|
+
headers: config.headers,
|
|
1484
|
+
env: config.env || {},
|
|
1485
|
+
enabled: config.enabled ?? true
|
|
1486
|
+
}));
|
|
1487
|
+
}
|
|
1488
|
+
/**
|
|
1489
|
+
* Zod schema for CliConfig validation
|
|
1490
|
+
* Defaults fill missing fields on load (auto-migration)
|
|
1491
|
+
*/
|
|
1492
|
+
const CliConfigSchema = z$1.object({
|
|
1493
|
+
version: z$1.string(),
|
|
1494
|
+
userId: z$1.string(),
|
|
1495
|
+
auth: AuthTokensSchema.optional(),
|
|
1496
|
+
authByEnv: z$1.record(z$1.string(), AuthTokensSchema).optional(),
|
|
1497
|
+
defaultModel: z$1.string(),
|
|
1498
|
+
apiConfig: ApiConfigSchema.optional(),
|
|
1499
|
+
toolApiKeys: z$1.object({
|
|
1500
|
+
openweather: z$1.string().optional(),
|
|
1501
|
+
serper: z$1.string().optional()
|
|
1502
|
+
}).optional(),
|
|
1503
|
+
mcpServers: McpServersSchema,
|
|
1504
|
+
preferences: z$1.object({
|
|
1505
|
+
maxTokens: z$1.number().optional(),
|
|
1506
|
+
temperature: z$1.number(),
|
|
1507
|
+
autoSave: z$1.boolean(),
|
|
1508
|
+
autoCompact: z$1.boolean().prefault(true),
|
|
1509
|
+
autoUpdate: z$1.boolean().optional(),
|
|
1510
|
+
theme: z$1.enum(["light", "dark"]),
|
|
1511
|
+
exportFormat: z$1.enum(["markdown", "json"]),
|
|
1512
|
+
maxIterations: z$1.number().nullable().prefault(10),
|
|
1513
|
+
enableSkillTool: z$1.boolean().prefault(true),
|
|
1514
|
+
enableWorkItemTools: z$1.boolean().prefault(false),
|
|
1515
|
+
/**
|
|
1516
|
+
* When false (or set via the `--no-remote-skills` CLI flag / the
|
|
1517
|
+
* `B4M_NO_REMOTE_SKILLS=1` env var), the CLI skips fetching skills from
|
|
1518
|
+
* the B4M backend's `/api/skills` endpoint and runs with local files only.
|
|
1519
|
+
* Defaults to true so authenticated users get cross-machine skill sync
|
|
1520
|
+
* out of the box.
|
|
1521
|
+
*/
|
|
1522
|
+
enableRemoteSkills: z$1.boolean().prefault(true),
|
|
1523
|
+
enableDynamicAgentCreation: z$1.boolean().prefault(false),
|
|
1524
|
+
enableCoordinatorMode: z$1.boolean().prefault(false),
|
|
1525
|
+
postEditDiagnostics: z$1.boolean().prefault(false),
|
|
1526
|
+
/**
|
|
1527
|
+
* System-prompt variant. 'current' uses the elaborate behavioral-scaffolding
|
|
1528
|
+
* prompt; 'minimal' uses a pi-style short prompt. See packages/cli/src/core/prompts.ts.
|
|
1529
|
+
* Defaults to 'current' for backward compatibility; switch via /config or by
|
|
1530
|
+
* editing the config file directly.
|
|
1531
|
+
*/
|
|
1532
|
+
promptVariant: z$1.enum(["current", "minimal"]).prefault("current"),
|
|
1533
|
+
showThoughts: z$1.boolean().optional(),
|
|
1534
|
+
subagentHistoryTtlMs: z$1.number().optional()
|
|
1535
|
+
}),
|
|
1536
|
+
tools: z$1.object({
|
|
1537
|
+
enabled: z$1.array(z$1.string()),
|
|
1538
|
+
disabled: z$1.array(z$1.string()),
|
|
1539
|
+
config: z$1.record(z$1.string(), z$1.any())
|
|
1540
|
+
}),
|
|
1541
|
+
features: z$1.preprocess((v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).filter(([, val]) => typeof val === "boolean")) : v, z$1.object({
|
|
1542
|
+
tavern: z$1.boolean().optional(),
|
|
1543
|
+
hearth: z$1.boolean().optional()
|
|
1544
|
+
}).catchall(z$1.boolean())).prefault({}),
|
|
1545
|
+
trustedTools: z$1.array(z$1.string()).prefault([]),
|
|
1546
|
+
trustedProjects: z$1.array(z$1.string()).prefault([]),
|
|
1547
|
+
trustedMcpDefinitions: z$1.record(z$1.string(), z$1.array(z$1.string())).prefault({}),
|
|
1548
|
+
sandbox: SandboxConfigSchema.optional(),
|
|
1549
|
+
additionalDirectories: z$1.array(z$1.string()).prefault([]),
|
|
1550
|
+
fallbackModels: z$1.array(z$1.string()).optional(),
|
|
1551
|
+
ollamaHost: z$1.string().optional(),
|
|
1552
|
+
localDefaultModel: z$1.string().optional(),
|
|
1553
|
+
modelServerCredentials: z$1.record(z$1.string(), z$1.object({ secret: z$1.string() })).optional()
|
|
1554
|
+
});
|
|
1555
|
+
/**
|
|
1556
|
+
* Zod schema for ProjectConfig validation
|
|
1557
|
+
*/
|
|
1558
|
+
const ProjectConfigSchema = z$1.object({
|
|
1559
|
+
tools: z$1.object({
|
|
1560
|
+
enabled: z$1.array(z$1.string()).optional(),
|
|
1561
|
+
denied: z$1.array(z$1.string()).optional(),
|
|
1562
|
+
config: z$1.record(z$1.string(), z$1.any()).optional()
|
|
1563
|
+
}).optional(),
|
|
1564
|
+
defaultModel: z$1.string().optional(),
|
|
1565
|
+
mcpServers: McpServersSchema.optional(),
|
|
1566
|
+
preferences: z$1.object({
|
|
1567
|
+
maxTokens: z$1.number().optional(),
|
|
1568
|
+
temperature: z$1.number().optional(),
|
|
1569
|
+
autoSave: z$1.boolean().optional(),
|
|
1570
|
+
autoCompact: z$1.boolean().optional(),
|
|
1571
|
+
theme: z$1.enum(["light", "dark"]).optional(),
|
|
1572
|
+
exportFormat: z$1.enum(["markdown", "json"]).optional(),
|
|
1573
|
+
enableSkillTool: z$1.boolean().optional(),
|
|
1574
|
+
enableWorkItemTools: z$1.boolean().optional(),
|
|
1575
|
+
enableDynamicAgentCreation: z$1.boolean().optional(),
|
|
1576
|
+
enableCoordinatorMode: z$1.boolean().optional(),
|
|
1577
|
+
promptVariant: z$1.enum(["current", "minimal"]).optional()
|
|
1578
|
+
}).optional(),
|
|
1579
|
+
sandbox: PartialSandboxConfigSchema,
|
|
1580
|
+
additionalDirectories: z$1.array(z$1.string()).optional()
|
|
1581
|
+
});
|
|
1582
|
+
/**
|
|
1583
|
+
* Zod schema for ProjectLocalConfig validation
|
|
1584
|
+
*/
|
|
1585
|
+
const ProjectLocalConfigSchema = z$1.object({
|
|
1586
|
+
trustedTools: z$1.array(z$1.string()).optional(),
|
|
1587
|
+
toolApiKeys: z$1.object({
|
|
1588
|
+
openweather: z$1.string().optional(),
|
|
1589
|
+
serper: z$1.string().optional()
|
|
1590
|
+
}).optional(),
|
|
1591
|
+
preferences: z$1.object({
|
|
1592
|
+
maxTokens: z$1.number().optional(),
|
|
1593
|
+
temperature: z$1.number().optional(),
|
|
1594
|
+
autoSave: z$1.boolean().optional(),
|
|
1595
|
+
autoCompact: z$1.boolean().optional(),
|
|
1596
|
+
theme: z$1.enum(["light", "dark"]).optional(),
|
|
1597
|
+
exportFormat: z$1.enum(["markdown", "json"]).optional(),
|
|
1598
|
+
enableSkillTool: z$1.boolean().optional(),
|
|
1599
|
+
enableWorkItemTools: z$1.boolean().optional(),
|
|
1600
|
+
enableDynamicAgentCreation: z$1.boolean().optional(),
|
|
1601
|
+
enableCoordinatorMode: z$1.boolean().optional()
|
|
1602
|
+
}).optional(),
|
|
1603
|
+
mcpServers: McpServersSchema.optional(),
|
|
1604
|
+
sandbox: PartialSandboxConfigSchema
|
|
1605
|
+
});
|
|
1606
|
+
/**
|
|
1607
|
+
* The output budget every pre-migration config was born with, back when
|
|
1608
|
+
* `preferences.maxTokens` was required and DEFAULT_CONFIG supplied this value. It is
|
|
1609
|
+
* indistinguishable from a user who deliberately typed 4096, and the migration reverts
|
|
1610
|
+
* it either way - acceptable only because the cleanup runs ONCE (see CONFIG_SCHEMA_VERSION):
|
|
1611
|
+
* a user who wanted 4096 sets it again and keeps it, while an install that never chose it
|
|
1612
|
+
* stops being capped by it. A value-keyed rule with no marker would instead make 4096
|
|
1613
|
+
* permanently unrepresentable, even though the /config select still offers it.
|
|
1614
|
+
*/
|
|
1615
|
+
const LEGACY_PINNED_MAX_TOKENS = 4096;
|
|
1616
|
+
/** Rewrites the old environment-based API config in place to the current simple form. */
|
|
1617
|
+
function migrateApiConfig(raw) {
|
|
1618
|
+
const old = raw.apiConfig;
|
|
1619
|
+
if (typeof old !== "object" || old === null || !("environment" in old)) return;
|
|
1620
|
+
const { environment, customUrl } = old;
|
|
1621
|
+
raw.apiConfig = environment === "custom" && customUrl ? { customUrl } : {};
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* The default model every config was born with before 0.3.0. It is deprecated, so each
|
|
1625
|
+
* chat on it was served by its successor anyway and counted as a deprecated-model request.
|
|
1626
|
+
*/
|
|
1627
|
+
const LEGACY_DEFAULT_MODEL = ChatModels.CLAUDE_4_5_SONNET;
|
|
1628
|
+
/** The one-time upgrade of a file not yet at CONFIG_SCHEMA_VERSION, in place. */
|
|
1629
|
+
function upgradeConfig(raw) {
|
|
1630
|
+
const preferences = raw.preferences;
|
|
1631
|
+
if ((raw.version === void 0 || raw.version === "0.1.0") && typeof preferences === "object" && preferences?.maxTokens === LEGACY_PINNED_MAX_TOKENS) delete preferences.maxTokens;
|
|
1632
|
+
if (raw.defaultModel === LEGACY_DEFAULT_MODEL) raw.defaultModel = DEFAULT_CONFIG.defaultModel;
|
|
1633
|
+
raw.version = CONFIG_SCHEMA_VERSION;
|
|
1634
|
+
}
|
|
1635
|
+
/** A refresh lock whose heartbeat stopped this long ago (ms) is abandoned. */
|
|
1636
|
+
const REFRESH_LOCK_STALE_MS = 3e4;
|
|
1637
|
+
const REFRESH_LOCK_WAIT_MS = 4e4;
|
|
1638
|
+
const REFRESH_LOCK_POLL_MS = 100;
|
|
1639
|
+
/** The config write lock is held only from a read of the file to its rename. */
|
|
1640
|
+
const CONFIG_LOCK_STALE_MS = 1e4;
|
|
1641
|
+
const CONFIG_LOCK_WAIT_MS = 15e3;
|
|
1642
|
+
const CONFIG_LOCK_POLL_MS = 10;
|
|
1643
|
+
function isJsonObject(value) {
|
|
1644
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1645
|
+
}
|
|
1646
|
+
/** A change that would replace a list or map in the file with a value of another shape, dropping what it holds. */
|
|
1647
|
+
var ShapeMismatchError = class extends Error {
|
|
1648
|
+
constructor(..._args) {
|
|
1649
|
+
super(..._args);
|
|
1650
|
+
this.path = [];
|
|
1651
|
+
}
|
|
1652
|
+
};
|
|
1653
|
+
/** A save refused over a file that failed validation; `key` names the top-level setting that caused it, if one did. */
|
|
1654
|
+
var RefusedSaveError = class extends Error {
|
|
1655
|
+
constructor(message, key) {
|
|
1656
|
+
super(message);
|
|
1657
|
+
this.key = key;
|
|
1658
|
+
}
|
|
1659
|
+
};
|
|
1660
|
+
/** An MCP toggle refused before any write because the user config does not save the server. */
|
|
1661
|
+
var McpToggleRefusedError = class extends Error {};
|
|
1662
|
+
const shapeOf = (value) => Array.isArray(value) ? "array" : isJsonObject(value) ? "object" : "scalar";
|
|
1663
|
+
const hasOwnKey = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
|
|
1664
|
+
const ownValue = (value, key) => hasOwnKey(value, key) ? value[key] : void 0;
|
|
1665
|
+
/**
|
|
1666
|
+
* Applies what changed from `base` to `next` onto `target`, a value as the file holds it, and keeps everything else
|
|
1667
|
+
* in `target`: keys set or removed in objects, items added or removed in arrays, any other value replaced. Throws
|
|
1668
|
+
* ShapeMismatchError rather than replace a `target` of another shape when either is a list or map.
|
|
1669
|
+
*/
|
|
1670
|
+
function applyChanges(target, base, next, explicit = false) {
|
|
1671
|
+
if (explicit === false && isDeepStrictEqual(base, next)) return target;
|
|
1672
|
+
const empty = isJsonObject(next) && Object.keys(next).length === 0 || Array.isArray(next) && next.length === 0;
|
|
1673
|
+
if (base === void 0 && target === void 0 && empty) return void 0;
|
|
1674
|
+
if (target !== void 0 && shapeOf(target) !== shapeOf(next)) throw new ShapeMismatchError();
|
|
1675
|
+
if (explicit === true) return next;
|
|
1676
|
+
if (isJsonObject(next)) {
|
|
1677
|
+
const from = isJsonObject(base) ? base : {};
|
|
1678
|
+
const out = Object.create(null);
|
|
1679
|
+
if (isJsonObject(target)) for (const key of Object.keys(target)) out[key] = target[key];
|
|
1680
|
+
const requestedKeys = isJsonObject(explicit) ? Object.keys(explicit) : [];
|
|
1681
|
+
for (const key of /* @__PURE__ */ new Set([
|
|
1682
|
+
...Object.keys(from),
|
|
1683
|
+
...Object.keys(next),
|
|
1684
|
+
...requestedKeys
|
|
1685
|
+
])) {
|
|
1686
|
+
const nextValue = ownValue(next, key);
|
|
1687
|
+
const requested = isJsonObject(explicit) && hasOwnKey(explicit, key);
|
|
1688
|
+
if (nextValue === void 0) {
|
|
1689
|
+
if (requested || ownValue(from, key) !== void 0) delete out[key];
|
|
1690
|
+
continue;
|
|
1691
|
+
}
|
|
1692
|
+
let value;
|
|
1693
|
+
try {
|
|
1694
|
+
const intent = requested ? isJsonObject(explicit[key]) ? explicit[key] : true : false;
|
|
1695
|
+
value = applyChanges(out[key], ownValue(from, key), nextValue, intent);
|
|
1696
|
+
} catch (error) {
|
|
1697
|
+
if (error instanceof ShapeMismatchError) error.path.unshift(key);
|
|
1698
|
+
throw error;
|
|
1699
|
+
}
|
|
1700
|
+
if (value === void 0) delete out[key];
|
|
1701
|
+
else out[key] = value;
|
|
1702
|
+
}
|
|
1703
|
+
return out;
|
|
1704
|
+
}
|
|
1705
|
+
if (Array.isArray(next) && Array.isArray(target)) {
|
|
1706
|
+
const from = Array.isArray(base) ? base : [];
|
|
1707
|
+
const has = (list, item) => list.some((entry) => isDeepStrictEqual(entry, item));
|
|
1708
|
+
const kept = target.filter((item) => has(next, item) || !has(from, item));
|
|
1709
|
+
return [...kept, ...next.filter((item) => !has(from, item) && !has(kept, item))];
|
|
1710
|
+
}
|
|
1711
|
+
return next;
|
|
1712
|
+
}
|
|
1713
|
+
/** Sets `server` in the file's mcpServers, array or name-keyed map, replacing any entry with its name. */
|
|
1714
|
+
function upsertRawMcpServer(raw, server) {
|
|
1715
|
+
const servers = raw.mcpServers;
|
|
1716
|
+
if (servers === void 0) raw.mcpServers = [server];
|
|
1717
|
+
else if (Array.isArray(servers)) raw.mcpServers = [...servers.filter((entry) => !(isJsonObject(entry) && entry.name === server.name)), server];
|
|
1718
|
+
else if (isJsonObject(servers)) {
|
|
1719
|
+
const { name, ...entry } = server;
|
|
1720
|
+
Object.defineProperty(servers, name, {
|
|
1721
|
+
value: entry,
|
|
1722
|
+
enumerable: true,
|
|
1723
|
+
configurable: true,
|
|
1724
|
+
writable: true
|
|
1725
|
+
});
|
|
1726
|
+
} else throw new ShapeMismatchError();
|
|
1727
|
+
return true;
|
|
1728
|
+
}
|
|
1729
|
+
/** Removes the server named `name` from the file's mcpServers, array or name-keyed map. */
|
|
1730
|
+
function removeRawMcpServer(raw, name) {
|
|
1731
|
+
const servers = raw.mcpServers;
|
|
1732
|
+
if (Array.isArray(servers)) {
|
|
1733
|
+
const kept = servers.filter((entry) => !(isJsonObject(entry) && entry.name === name));
|
|
1734
|
+
raw.mcpServers = kept;
|
|
1735
|
+
return kept.length !== servers.length;
|
|
1736
|
+
}
|
|
1737
|
+
if (isJsonObject(servers) && hasOwnKey(servers, name)) {
|
|
1738
|
+
delete servers[name];
|
|
1739
|
+
return true;
|
|
1740
|
+
}
|
|
1741
|
+
return false;
|
|
1742
|
+
}
|
|
1743
|
+
/** The file's own entry for the server named `name` in mcpServers, array or name-keyed map. */
|
|
1744
|
+
function rawMcpServerEntry(raw, name) {
|
|
1745
|
+
const servers = raw.mcpServers;
|
|
1746
|
+
const entry = Array.isArray(servers) ? servers.find((item) => isJsonObject(item) && item.name === name) : isJsonObject(servers) ? ownValue(servers, name) : void 0;
|
|
1747
|
+
return isJsonObject(entry) ? entry : void 0;
|
|
1748
|
+
}
|
|
1749
|
+
/** Sets `enabled` on the server named `name` in the file's mcpServers; false when the file has no such server. */
|
|
1750
|
+
function setRawMcpServerEnabled(raw, name, enabled) {
|
|
1751
|
+
const entry = rawMcpServerEntry(raw, name);
|
|
1752
|
+
if (!entry) return false;
|
|
1753
|
+
entry.enabled = enabled;
|
|
1754
|
+
return true;
|
|
1755
|
+
}
|
|
1756
|
+
/** Drops the items `drop` matches from the file's list at `key`; a value that is not a list is left alone. */
|
|
1757
|
+
function removeRawListItems(raw, key, drop) {
|
|
1758
|
+
const list = raw[key];
|
|
1759
|
+
if (!Array.isArray(list)) return false;
|
|
1760
|
+
const kept = list.filter((item) => !drop(item));
|
|
1761
|
+
raw[key] = kept;
|
|
1762
|
+
return kept.length !== list.length;
|
|
1763
|
+
}
|
|
1764
|
+
/**
|
|
1765
|
+
* Schema version of the on-disk config, and the marker that makes the migrations in
|
|
1766
|
+
* `load()` one-time. A file stamped with anything else gets the upgrade pass and is
|
|
1767
|
+
* rewritten at the current version; a file already at it is left alone. Bump this when
|
|
1768
|
+
* adding a migration, and gate the new step on the version it needs to run from.
|
|
1769
|
+
*/
|
|
1770
|
+
const CONFIG_SCHEMA_VERSION = "0.3.0";
|
|
1771
|
+
/**
|
|
1772
|
+
* Default configuration
|
|
1773
|
+
*/
|
|
1774
|
+
const DEFAULT_CONFIG = {
|
|
1775
|
+
version: CONFIG_SCHEMA_VERSION,
|
|
1776
|
+
userId: v4(),
|
|
1777
|
+
defaultModel: ChatModels.CLAUDE_5_5_SONNET,
|
|
1778
|
+
toolApiKeys: {
|
|
1779
|
+
openweather: void 0,
|
|
1780
|
+
serper: void 0
|
|
1781
|
+
},
|
|
1782
|
+
mcpServers: [],
|
|
1783
|
+
preferences: {
|
|
1784
|
+
temperature: .7,
|
|
1785
|
+
autoSave: true,
|
|
1786
|
+
autoCompact: true,
|
|
1787
|
+
theme: "dark",
|
|
1788
|
+
exportFormat: "markdown",
|
|
1789
|
+
maxIterations: 10,
|
|
1790
|
+
enableSkillTool: true,
|
|
1791
|
+
enableWorkItemTools: false,
|
|
1792
|
+
enableRemoteSkills: true,
|
|
1793
|
+
enableDynamicAgentCreation: false,
|
|
1794
|
+
enableCoordinatorMode: false,
|
|
1795
|
+
postEditDiagnostics: false,
|
|
1796
|
+
promptVariant: "current"
|
|
1797
|
+
},
|
|
1798
|
+
tools: {
|
|
1799
|
+
enabled: [],
|
|
1800
|
+
disabled: [
|
|
1801
|
+
"blog_publish",
|
|
1802
|
+
"blog_edit",
|
|
1803
|
+
"blog_draft"
|
|
1804
|
+
],
|
|
1805
|
+
config: {}
|
|
1806
|
+
},
|
|
1807
|
+
trustedTools: [],
|
|
1808
|
+
trustedProjects: [],
|
|
1809
|
+
trustedMcpDefinitions: {},
|
|
1810
|
+
additionalDirectories: []
|
|
1811
|
+
};
|
|
1812
|
+
/**
|
|
1813
|
+
* Find project config directory by searching up the directory tree
|
|
1814
|
+
* Looks for git repository root (.git directory)
|
|
1815
|
+
* Falls back to current working directory if no git repo found
|
|
1816
|
+
*/
|
|
1817
|
+
function findProjectConfigDir(startDir = currentWorkingDir()) {
|
|
1818
|
+
if (startDir === null) return null;
|
|
1819
|
+
let currentDir = startDir;
|
|
1820
|
+
const { root } = path.parse(currentDir);
|
|
1821
|
+
while (currentDir !== root) {
|
|
1822
|
+
const gitPath = path.join(currentDir, ".git");
|
|
1823
|
+
try {
|
|
1824
|
+
if (existsSync(gitPath)) return currentDir;
|
|
1825
|
+
} catch {}
|
|
1826
|
+
currentDir = path.dirname(currentDir);
|
|
1827
|
+
}
|
|
1828
|
+
return currentWorkingDir();
|
|
1829
|
+
}
|
|
1830
|
+
/** The working directory, or null when it was removed after this process started in it. */
|
|
1831
|
+
function currentWorkingDir() {
|
|
1832
|
+
try {
|
|
1833
|
+
return process.cwd();
|
|
1834
|
+
} catch {
|
|
1835
|
+
return null;
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
/**
|
|
1839
|
+
* Canonicalize a path via realpath, returning null if it doesn't exist or can't
|
|
1840
|
+
* be resolved. Used so a symlinked or relative project root is compared against
|
|
1841
|
+
* the trust set by its real location, and a resolve failure fails safe
|
|
1842
|
+
* (untrusted) rather than crashing the launch.
|
|
1843
|
+
*/
|
|
1844
|
+
async function safeRealpath(p) {
|
|
1845
|
+
try {
|
|
1846
|
+
return await promises.realpath(p);
|
|
1847
|
+
} catch {
|
|
1848
|
+
return null;
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
/**
|
|
1852
|
+
* Load project config from .bike4mind/config.json
|
|
1853
|
+
* Returns null if file doesn't exist (this is normal - config.json is optional)
|
|
1854
|
+
*/
|
|
1855
|
+
async function loadProjectConfig(projectDir) {
|
|
1856
|
+
const configPath = path.join(projectDir, ".bike4mind", "config.json");
|
|
1857
|
+
try {
|
|
1858
|
+
const data = await promises.readFile(configPath, "utf-8");
|
|
1859
|
+
const rawConfig = JSON.parse(data);
|
|
1860
|
+
const validated = ProjectConfigSchema.parse(rawConfig);
|
|
1861
|
+
return {
|
|
1862
|
+
...validated,
|
|
1863
|
+
mcpServers: validated.mcpServers ? normalizeMcpServers(validated.mcpServers) : void 0
|
|
1864
|
+
};
|
|
1865
|
+
} catch (error) {
|
|
1866
|
+
if (error.code === "ENOENT") return null;
|
|
1867
|
+
if (error instanceof z$1.ZodError) {
|
|
1868
|
+
console.error("Project config validation error:", error.issues);
|
|
1869
|
+
return null;
|
|
1870
|
+
}
|
|
1871
|
+
console.error("Failed to load project config:", error);
|
|
1872
|
+
return null;
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
/**
|
|
1876
|
+
* Load project-local config from .bike4mind/local.json
|
|
1877
|
+
*/
|
|
1878
|
+
async function loadProjectLocalConfig(projectDir) {
|
|
1879
|
+
const configPath = path.join(projectDir, ".bike4mind", "local.json");
|
|
1880
|
+
try {
|
|
1881
|
+
const data = await promises.readFile(configPath, "utf-8");
|
|
1882
|
+
const rawConfig = JSON.parse(data);
|
|
1883
|
+
const validated = ProjectLocalConfigSchema.parse(rawConfig);
|
|
1884
|
+
return {
|
|
1885
|
+
...validated,
|
|
1886
|
+
mcpServers: validated.mcpServers ? normalizeMcpServers(validated.mcpServers) : void 0
|
|
1887
|
+
};
|
|
1888
|
+
} catch (error) {
|
|
1889
|
+
if (error.code === "ENOENT") return null;
|
|
1890
|
+
if (error instanceof z$1.ZodError) {
|
|
1891
|
+
console.error("Project local config validation error:", error.issues);
|
|
1892
|
+
return null;
|
|
1893
|
+
}
|
|
1894
|
+
console.error("Failed to load project local config:", error);
|
|
1895
|
+
return null;
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
/**
|
|
1899
|
+
* Zod schema for .mcp.json format (project-level MCP server configuration)
|
|
1900
|
+
* Supports both array and object formats for flexibility
|
|
1901
|
+
*/
|
|
1902
|
+
const McpJsonConfigSchema = z$1.object({ mcpServers: McpServersSchema });
|
|
1903
|
+
/**
|
|
1904
|
+
* Load project MCP configuration from .mcp.json
|
|
1905
|
+
* Returns null if file doesn't exist (this is normal - .mcp.json is optional)
|
|
1906
|
+
*
|
|
1907
|
+
* Supports both formats:
|
|
1908
|
+
* - Object format: { "mcpServers": { "name": { "command": "...", ... } } }
|
|
1909
|
+
* - Array format: { "mcpServers": [{ "name": "...", "command": "...", ... }] }
|
|
1910
|
+
*/
|
|
1911
|
+
async function loadMcpJsonConfig(projectDir) {
|
|
1912
|
+
const mcpConfigPath = path.join(projectDir, ".mcp.json");
|
|
1913
|
+
try {
|
|
1914
|
+
const data = await promises.readFile(mcpConfigPath, "utf-8");
|
|
1915
|
+
const rawConfig = JSON.parse(data);
|
|
1916
|
+
return normalizeMcpServers(McpJsonConfigSchema.parse(rawConfig).mcpServers);
|
|
1917
|
+
} catch (error) {
|
|
1918
|
+
if (error.code === "ENOENT") return null;
|
|
1919
|
+
if (error instanceof z$1.ZodError) {
|
|
1920
|
+
console.error(".mcp.json validation error:", error.issues);
|
|
1921
|
+
return null;
|
|
1922
|
+
}
|
|
1923
|
+
console.error("Failed to load .mcp.json:", error);
|
|
1924
|
+
return null;
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
/**
|
|
1928
|
+
* Load an explicit `--mcp-config <file>` (claude shape: `{ "mcpServers": {...} }`).
|
|
1929
|
+
* Unlike `.mcp.json` this is an absolute path passed at launch, not project-relative.
|
|
1930
|
+
* Returns null on missing/malformed file (a bad config must not brick the launch).
|
|
1931
|
+
*/
|
|
1932
|
+
async function loadMcpConfigFile(filePath) {
|
|
1933
|
+
try {
|
|
1934
|
+
const data = await promises.readFile(filePath, "utf-8");
|
|
1935
|
+
const rawConfig = JSON.parse(data);
|
|
1936
|
+
return normalizeMcpServers(McpJsonConfigSchema.parse(rawConfig).mcpServers);
|
|
1937
|
+
} catch (error) {
|
|
1938
|
+
if (error.code === "ENOENT") {
|
|
1939
|
+
console.error(`--mcp-config file not found: ${filePath}`);
|
|
1940
|
+
return null;
|
|
1941
|
+
}
|
|
1942
|
+
if (error instanceof z$1.ZodError) {
|
|
1943
|
+
console.error("--mcp-config validation error:", error.issues);
|
|
1944
|
+
return null;
|
|
1945
|
+
}
|
|
1946
|
+
console.error("Failed to load --mcp-config file:", error);
|
|
1947
|
+
return null;
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
/**
|
|
1951
|
+
* Merge MCP servers from multiple configs
|
|
1952
|
+
* Later configs can override earlier ones by name
|
|
1953
|
+
*/
|
|
1954
|
+
function mergeMcpServers(...serverArrays) {
|
|
1955
|
+
const serverMap = /* @__PURE__ */ new Map();
|
|
1956
|
+
for (const servers of serverArrays) if (servers) for (const server of servers) serverMap.set(server.name, server);
|
|
1957
|
+
return Array.from(serverMap.values());
|
|
1958
|
+
}
|
|
1959
|
+
/** Sandbox modes ordered from weakest to strongest posture. */
|
|
1960
|
+
const SANDBOX_MODE_RANK = {
|
|
1961
|
+
disabled: 0,
|
|
1962
|
+
"auto-allow": 1,
|
|
1963
|
+
permissions: 2
|
|
1964
|
+
};
|
|
1965
|
+
function intersectStrings(a, b) {
|
|
1966
|
+
const set = new Set(a);
|
|
1967
|
+
return b.filter((x) => set.has(x));
|
|
1968
|
+
}
|
|
1969
|
+
function unionStrings(a, b) {
|
|
1970
|
+
return Array.from(/* @__PURE__ */ new Set([...a, ...b]));
|
|
1971
|
+
}
|
|
1972
|
+
/** True when `target` is `root` itself or nested under it (no `..` escape). */
|
|
1973
|
+
function isWithin(root, target) {
|
|
1974
|
+
const rel = path.relative(root, target);
|
|
1975
|
+
return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
1976
|
+
}
|
|
1977
|
+
/**
|
|
1978
|
+
* Merge a repo-sourced sandbox override onto the user's base posture so it can
|
|
1979
|
+
* only ever TIGHTEN it, never loosen it. A repo layer may enable the sandbox,
|
|
1980
|
+
* raise the mode (disabled < auto-allow < permissions) but never select
|
|
1981
|
+
* auto-allow itself, add denied paths, narrow read paths / domains / excluded
|
|
1982
|
+
* commands, turn the network filter on, and force allowUnsandboxedCommands and
|
|
1983
|
+
* allowContainerSockets off.
|
|
1984
|
+
* Every loosening value is ignored with a warning. `platform` is ignored.
|
|
1985
|
+
*/
|
|
1986
|
+
function tightenSandbox(base, repo) {
|
|
1987
|
+
const b = base ?? DEFAULT_SANDBOX_CONFIG;
|
|
1988
|
+
if (!repo) return b;
|
|
1989
|
+
const warn = (what) => logger.warn(`Ignoring repo sandbox override that would loosen posture: ${what}`);
|
|
1990
|
+
const result = {
|
|
1991
|
+
...b,
|
|
1992
|
+
filesystem: { ...b.filesystem },
|
|
1993
|
+
network: { ...b.network }
|
|
1994
|
+
};
|
|
1995
|
+
if (repo.enabled === true) result.enabled = true;
|
|
1996
|
+
else if (repo.enabled === false && b.enabled) warn("sandbox.enabled=false");
|
|
1997
|
+
if (repo.mode !== void 0) {
|
|
1998
|
+
if (repo.mode === "auto-allow") warn("sandbox.mode=auto-allow");
|
|
1999
|
+
else if (SANDBOX_MODE_RANK[repo.mode] >= SANDBOX_MODE_RANK[b.mode]) result.mode = repo.mode;
|
|
2000
|
+
else warn(`sandbox.mode=${repo.mode} weaker than ${b.mode}`);
|
|
2001
|
+
}
|
|
2002
|
+
if (repo.filesystem) {
|
|
2003
|
+
const fsr = repo.filesystem;
|
|
2004
|
+
if (fsr.deniedPaths) result.filesystem.deniedPaths = unionStrings(result.filesystem.deniedPaths, fsr.deniedPaths);
|
|
2005
|
+
if (fsr.allowedReadPaths) result.filesystem.allowedReadPaths = intersectStrings(result.filesystem.allowedReadPaths, fsr.allowedReadPaths);
|
|
2006
|
+
if (fsr.writeOnlyToWorkingDir === true) result.filesystem.writeOnlyToWorkingDir = true;
|
|
2007
|
+
else if (fsr.writeOnlyToWorkingDir === false && b.filesystem.writeOnlyToWorkingDir) warn("filesystem.writeOnlyToWorkingDir=false");
|
|
2008
|
+
}
|
|
2009
|
+
if (repo.network) {
|
|
2010
|
+
const nr = repo.network;
|
|
2011
|
+
if (nr.enabled === true) result.network.enabled = true;
|
|
2012
|
+
else if (nr.enabled === false && b.network.enabled) warn("network.enabled=false");
|
|
2013
|
+
if (nr.allowedDomains) result.network.allowedDomains = intersectStrings(result.network.allowedDomains, nr.allowedDomains);
|
|
2014
|
+
}
|
|
2015
|
+
if (repo.excludedCommands) result.excludedCommands = intersectStrings(result.excludedCommands, repo.excludedCommands);
|
|
2016
|
+
if (repo.allowUnsandboxedCommands === false) result.allowUnsandboxedCommands = false;
|
|
2017
|
+
else if (repo.allowUnsandboxedCommands === true && !b.allowUnsandboxedCommands) warn("allowUnsandboxedCommands=true");
|
|
2018
|
+
if (repo.allowContainerSockets === false) result.allowContainerSockets = false;
|
|
2019
|
+
else if (repo.allowContainerSockets === true && !b.allowContainerSockets) warn("allowContainerSockets=true");
|
|
2020
|
+
if (result.enabled && result.mode === "disabled") result.mode = "permissions";
|
|
2021
|
+
if (!result.enabled) result.mode = "disabled";
|
|
2022
|
+
return result;
|
|
2023
|
+
}
|
|
2024
|
+
/**
|
|
2025
|
+
* Fold repo-sourced MCP servers under the global set so a repo entry can never
|
|
2026
|
+
* REPLACE a same-named global server. Global definitions always win; repo
|
|
2027
|
+
* entries only fill names global does not already use. Later repo layers win
|
|
2028
|
+
* over earlier ones for names global does not define.
|
|
2029
|
+
*/
|
|
2030
|
+
function mergeMcpServersGlobalWins(global, ...repoLayers) {
|
|
2031
|
+
const byName = /* @__PURE__ */ new Map();
|
|
2032
|
+
for (const layer of repoLayers) {
|
|
2033
|
+
if (!layer) continue;
|
|
2034
|
+
for (const server of layer) byName.set(server.name, server);
|
|
2035
|
+
}
|
|
2036
|
+
if (global) for (const server of global) byName.set(server.name, server);
|
|
2037
|
+
return Array.from(byName.values());
|
|
2038
|
+
}
|
|
2039
|
+
/**
|
|
2040
|
+
* Approval fingerprint of a repo MCP server: sha256 over every field that
|
|
2041
|
+
* decides what gets spawned (full env/header VALUES included, so a changed
|
|
2042
|
+
* token re-prompts). Only the hash is persisted. Distinct from
|
|
2043
|
+
* McpManager.hashServerConfig, a truncated cache key that ignores headers.
|
|
2044
|
+
*/
|
|
2045
|
+
function fingerprintMcpServer(s) {
|
|
2046
|
+
const sortKeys = (o) => Object.fromEntries(Object.entries(o ?? {}).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
2047
|
+
const { name, type, command, args, url } = s;
|
|
2048
|
+
return createHash("sha256").update(JSON.stringify({
|
|
2049
|
+
name,
|
|
2050
|
+
type,
|
|
2051
|
+
command,
|
|
2052
|
+
args,
|
|
2053
|
+
url,
|
|
2054
|
+
env: sortKeys(s.env),
|
|
2055
|
+
headers: sortKeys(s.headers)
|
|
2056
|
+
})).digest("hex");
|
|
2057
|
+
}
|
|
2058
|
+
/** Env keys whose values change what code a spawned process runs; shown to the user at approval. */
|
|
2059
|
+
const LOADER_ENV_KEY = /^(PATH|NODE_OPTIONS|NODE_PATH|BASH_ENV|ENV|RUBYOPT|PERL5OPT|PERL5LIB|LD_.*|DYLD_.*|PYTHON.*)$/i;
|
|
2060
|
+
/**
|
|
2061
|
+
* Merge configs with priority: global -> project -> local, with the invariant
|
|
2062
|
+
* that repo layers may only TIGHTEN the user's global security posture, never
|
|
2063
|
+
* loosen it. Sandbox goes through `tightenSandbox`; the repo `trustedTools`
|
|
2064
|
+
* union is filtered to tools that can actually be trusted and aren't globally
|
|
2065
|
+
* disabled; and any tool a repo tries to re-enable while it is disabled is
|
|
2066
|
+
* dropped. `mcpServers` is NOT merged here - callers fold repo servers in via
|
|
2067
|
+
* `mergeMcpServersGlobalWins` where all repo layers are visible together.
|
|
2068
|
+
*/
|
|
2069
|
+
function mergeConfigs(global, project, local) {
|
|
2070
|
+
const merged = { ...global };
|
|
2071
|
+
if (project) {
|
|
2072
|
+
if (project.defaultModel) merged.defaultModel = project.defaultModel;
|
|
2073
|
+
if (project.preferences) merged.preferences = {
|
|
2074
|
+
...merged.preferences,
|
|
2075
|
+
...project.preferences
|
|
2076
|
+
};
|
|
2077
|
+
if (project.tools) merged.tools = {
|
|
2078
|
+
...merged.tools,
|
|
2079
|
+
enabled: [...merged.tools.enabled || [], ...project.tools.enabled || []],
|
|
2080
|
+
disabled: [...merged.tools.disabled, ...project.tools.denied || []],
|
|
2081
|
+
config: {
|
|
2082
|
+
...merged.tools.config,
|
|
2083
|
+
...project.tools.config
|
|
2084
|
+
}
|
|
2085
|
+
};
|
|
2086
|
+
if (project.sandbox) merged.sandbox = tightenSandbox(merged.sandbox, project.sandbox);
|
|
2087
|
+
}
|
|
2088
|
+
if (local) {
|
|
2089
|
+
if (local.trustedTools) {
|
|
2090
|
+
const trustedSet = /* @__PURE__ */ new Set([...merged.trustedTools || [], ...local.trustedTools]);
|
|
2091
|
+
merged.trustedTools = Array.from(trustedSet);
|
|
2092
|
+
}
|
|
2093
|
+
if (local.toolApiKeys) merged.toolApiKeys = {
|
|
2094
|
+
...merged.toolApiKeys,
|
|
2095
|
+
...local.toolApiKeys
|
|
2096
|
+
};
|
|
2097
|
+
if (local.preferences) merged.preferences = {
|
|
2098
|
+
...merged.preferences,
|
|
2099
|
+
...local.preferences
|
|
2100
|
+
};
|
|
2101
|
+
if (local.sandbox) merged.sandbox = tightenSandbox(merged.sandbox, local.sandbox);
|
|
2102
|
+
}
|
|
2103
|
+
const disabledSet = new Set(merged.tools.disabled);
|
|
2104
|
+
merged.tools = {
|
|
2105
|
+
...merged.tools,
|
|
2106
|
+
enabled: merged.tools.enabled.filter((t) => !disabledSet.has(t))
|
|
2107
|
+
};
|
|
2108
|
+
const globalTrusted = new Set(global.trustedTools || []);
|
|
2109
|
+
merged.trustedTools = (merged.trustedTools || []).filter((t) => globalTrusted.has(t) || canTrustTool(resolveStaticToolDescriptor(t)) && !disabledSet.has(t));
|
|
2110
|
+
return merged;
|
|
2111
|
+
}
|
|
2112
|
+
/**
|
|
2113
|
+
* Manages CLI configuration stored as JSON
|
|
2114
|
+
*/
|
|
2115
|
+
var ConfigStore = class {
|
|
2116
|
+
constructor(configPath) {
|
|
2117
|
+
this.config = null;
|
|
2118
|
+
this.projectConfigDir = null;
|
|
2119
|
+
this.globalConfig = null;
|
|
2120
|
+
this.serial = Promise.resolve();
|
|
2121
|
+
this.configLock = null;
|
|
2122
|
+
this.fallbackBase = null;
|
|
2123
|
+
this.projectRealPath = null;
|
|
2124
|
+
this.projectTrusted = false;
|
|
2125
|
+
this.rawProjectConfig = null;
|
|
2126
|
+
this.rawProjectLocalConfig = null;
|
|
2127
|
+
this.rawMcpJsonServers = null;
|
|
2128
|
+
this.pendingMcpApprovals = [];
|
|
2129
|
+
this.pendingMcpWarned = false;
|
|
2130
|
+
this.injectedMcpNames = /* @__PURE__ */ new Set();
|
|
2131
|
+
this.projectMcpNames = /* @__PURE__ */ new Set();
|
|
2132
|
+
this.strictMcpConfig = false;
|
|
2133
|
+
this.configPath = configPath || path.join(homedir(), ".bike4mind", "config.json");
|
|
2134
|
+
}
|
|
2135
|
+
/**
|
|
2136
|
+
* Initialize config directory
|
|
2137
|
+
*/
|
|
2138
|
+
async init() {
|
|
2139
|
+
const dir = path.dirname(this.configPath);
|
|
2140
|
+
try {
|
|
2141
|
+
await promises.mkdir(dir, { recursive: true });
|
|
2142
|
+
} catch (error) {
|
|
2143
|
+
console.error("Failed to initialize config directory:", error);
|
|
2144
|
+
throw error;
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
/**
|
|
2148
|
+
* Load configuration from disk with Zod validation
|
|
2149
|
+
* Merges global -> project -> local configs
|
|
2150
|
+
*/
|
|
2151
|
+
async load() {
|
|
2152
|
+
if (this.config) return this.config;
|
|
2153
|
+
try {
|
|
2154
|
+
let globalConfig;
|
|
2155
|
+
let globalFailedValidation = false;
|
|
2156
|
+
try {
|
|
2157
|
+
try {
|
|
2158
|
+
const mode = (await promises.stat(this.configPath)).mode & 511;
|
|
2159
|
+
if (mode !== 384) {
|
|
2160
|
+
console.warn(`⚠️ Config file has insecure permissions (${mode.toString(8)}). Setting to 0600...`);
|
|
2161
|
+
await promises.chmod(this.configPath, 384);
|
|
2162
|
+
}
|
|
2163
|
+
} catch (statError) {}
|
|
2164
|
+
const data = await promises.readFile(this.configPath, "utf-8");
|
|
2165
|
+
let rawConfig;
|
|
2166
|
+
try {
|
|
2167
|
+
rawConfig = JSON.parse(data);
|
|
2168
|
+
} catch {
|
|
2169
|
+
throw new Error(`Could not load ${this.configPath}: it is not valid JSON.`);
|
|
2170
|
+
}
|
|
2171
|
+
migrateApiConfig(rawConfig);
|
|
2172
|
+
if (rawConfig.version !== CONFIG_SCHEMA_VERSION) {
|
|
2173
|
+
upgradeConfig(rawConfig);
|
|
2174
|
+
try {
|
|
2175
|
+
rawConfig = await this.writeUpgradedConfig() ?? rawConfig;
|
|
2176
|
+
} catch {}
|
|
2177
|
+
}
|
|
2178
|
+
const validated = CliConfigSchema.parse(rawConfig);
|
|
2179
|
+
const normalizedMcpServers = normalizeMcpServers(validated.mcpServers);
|
|
2180
|
+
globalConfig = {
|
|
2181
|
+
...DEFAULT_CONFIG,
|
|
2182
|
+
...validated,
|
|
2183
|
+
auth: validated.auth,
|
|
2184
|
+
mcpServers: normalizedMcpServers,
|
|
2185
|
+
preferences: {
|
|
2186
|
+
...DEFAULT_CONFIG.preferences,
|
|
2187
|
+
...validated.preferences
|
|
2188
|
+
},
|
|
2189
|
+
tools: {
|
|
2190
|
+
...DEFAULT_CONFIG.tools,
|
|
2191
|
+
...validated.tools
|
|
2192
|
+
},
|
|
2193
|
+
toolApiKeys: {
|
|
2194
|
+
...DEFAULT_CONFIG.toolApiKeys,
|
|
2195
|
+
...validated.toolApiKeys || {}
|
|
2196
|
+
},
|
|
2197
|
+
trustedTools: validated.trustedTools || []
|
|
2198
|
+
};
|
|
2199
|
+
} catch (error) {
|
|
2200
|
+
if (error.code === "ENOENT") globalConfig = structuredClone(DEFAULT_CONFIG);
|
|
2201
|
+
else if (error instanceof z$1.ZodError) {
|
|
2202
|
+
console.error("Global config validation error:", error.issues);
|
|
2203
|
+
console.error("Using default configuration");
|
|
2204
|
+
globalFailedValidation = true;
|
|
2205
|
+
globalConfig = structuredClone(DEFAULT_CONFIG);
|
|
2206
|
+
} else throw error;
|
|
2207
|
+
}
|
|
2208
|
+
this.globalConfig = globalConfig;
|
|
2209
|
+
this.fallbackBase = globalFailedValidation ? structuredClone(globalConfig) : null;
|
|
2210
|
+
this.projectConfigDir = null;
|
|
2211
|
+
this.projectRealPath = null;
|
|
2212
|
+
this.projectTrusted = false;
|
|
2213
|
+
this.rawProjectConfig = null;
|
|
2214
|
+
this.rawProjectLocalConfig = null;
|
|
2215
|
+
this.rawMcpJsonServers = null;
|
|
2216
|
+
if (process.env.B4M_NO_PROJECT_CONFIG !== "1") {
|
|
2217
|
+
this.projectConfigDir = findProjectConfigDir();
|
|
2218
|
+
if (this.projectConfigDir) {
|
|
2219
|
+
this.projectRealPath = await safeRealpath(this.projectConfigDir) ?? this.projectConfigDir;
|
|
2220
|
+
this.projectTrusted = (globalConfig.trustedProjects || []).includes(this.projectRealPath);
|
|
2221
|
+
if (this.projectTrusted) {
|
|
2222
|
+
const loaded = await this.loadProjectLayers();
|
|
2223
|
+
if (loaded.hasConfig) logger.debug(`📁 Project config loaded from: ${this.projectConfigDir}/.bike4mind/`);
|
|
2224
|
+
if (loaded.mcpCount > 0) logger.debug(`📁 Project MCP config loaded from: ${this.projectConfigDir}/.mcp.json`);
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
this.config = await this.computeMerged();
|
|
2229
|
+
return this.config;
|
|
2230
|
+
} catch (error) {
|
|
2231
|
+
if (error instanceof z$1.ZodError) {
|
|
2232
|
+
console.error("Config validation error:", error.issues);
|
|
2233
|
+
console.error("Resetting to default configuration");
|
|
2234
|
+
return this.reset();
|
|
2235
|
+
}
|
|
2236
|
+
console.error("Failed to load config:", error);
|
|
2237
|
+
throw error;
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
/**
|
|
2241
|
+
* Load the raw repo config layers for the current project root. Called only
|
|
2242
|
+
* for a trusted root; stores them on `this` so trust changes can re-merge
|
|
2243
|
+
* without re-reading the global config file.
|
|
2244
|
+
*/
|
|
2245
|
+
async loadProjectLayers() {
|
|
2246
|
+
if (!this.projectConfigDir) return {
|
|
2247
|
+
hasConfig: false,
|
|
2248
|
+
mcpCount: 0
|
|
2249
|
+
};
|
|
2250
|
+
this.rawProjectConfig = await loadProjectConfig(this.projectConfigDir);
|
|
2251
|
+
this.rawProjectLocalConfig = await loadProjectLocalConfig(this.projectConfigDir);
|
|
2252
|
+
this.rawMcpJsonServers = await loadMcpJsonConfig(this.projectConfigDir);
|
|
2253
|
+
return {
|
|
2254
|
+
hasConfig: !!this.rawProjectConfig,
|
|
2255
|
+
mcpCount: this.rawMcpJsonServers?.length ?? 0
|
|
2256
|
+
};
|
|
2257
|
+
}
|
|
2258
|
+
/**
|
|
2259
|
+
* Build the merged effective config from the global layer plus the raw repo
|
|
2260
|
+
* layers - but only when the project is trusted, so an untrusted root
|
|
2261
|
+
* contributes nothing. Repo MCP servers are folded in global-wins (a repo
|
|
2262
|
+
* name can never replace a global server); an explicit `--mcp-config` is host-
|
|
2263
|
+
* injected (not repo-sourced) and keeps its override-by-name / strict scope.
|
|
2264
|
+
*/
|
|
2265
|
+
async computeMerged() {
|
|
2266
|
+
const global = this.globalConfig;
|
|
2267
|
+
const project = this.projectTrusted ? this.rawProjectConfig : null;
|
|
2268
|
+
const local = this.projectTrusted ? this.rawProjectLocalConfig : null;
|
|
2269
|
+
const mcpJson = this.projectTrusted ? this.rawMcpJsonServers : null;
|
|
2270
|
+
const merged = mergeConfigs(global, project, local);
|
|
2271
|
+
const globalNames = new Set((global.mcpServers ?? []).map((s) => s.name));
|
|
2272
|
+
const repoServers = mergeMcpServersGlobalWins(void 0, mcpJson, project?.mcpServers, local?.mcpServers).filter((s) => !globalNames.has(s.name));
|
|
2273
|
+
this.projectMcpNames = new Set(repoServers.map((s) => s.name));
|
|
2274
|
+
this.injectedMcpNames = /* @__PURE__ */ new Set();
|
|
2275
|
+
this.strictMcpConfig = false;
|
|
2276
|
+
const approved = new Set(this.projectRealPath && global.trustedMcpDefinitions?.[this.projectRealPath] || []);
|
|
2277
|
+
const approvedRepo = [];
|
|
2278
|
+
this.pendingMcpApprovals = [];
|
|
2279
|
+
for (const s of repoServers) {
|
|
2280
|
+
if (!s.enabled) {
|
|
2281
|
+
approvedRepo.push(s);
|
|
2282
|
+
continue;
|
|
2283
|
+
}
|
|
2284
|
+
(approved.has(fingerprintMcpServer(s)) ? approvedRepo : this.pendingMcpApprovals).push(s);
|
|
2285
|
+
}
|
|
2286
|
+
merged.mcpServers = mergeMcpServersGlobalWins(global.mcpServers, approvedRepo);
|
|
2287
|
+
const mcpConfigFile = process.env.B4M_MCP_CONFIG_FILE;
|
|
2288
|
+
if (mcpConfigFile) {
|
|
2289
|
+
const injected = await loadMcpConfigFile(mcpConfigFile);
|
|
2290
|
+
this.injectedMcpNames = new Set((injected ?? []).map((s) => s.name));
|
|
2291
|
+
if (process.env.B4M_STRICT_MCP_CONFIG === "1") {
|
|
2292
|
+
this.strictMcpConfig = true;
|
|
2293
|
+
merged.mcpServers = injected ?? [];
|
|
2294
|
+
this.pendingMcpApprovals = [];
|
|
2295
|
+
} else if (injected) {
|
|
2296
|
+
merged.mcpServers = mergeMcpServers(merged.mcpServers, injected);
|
|
2297
|
+
const injectedNames = new Set(injected.map((s) => s.name));
|
|
2298
|
+
this.pendingMcpApprovals = this.pendingMcpApprovals.filter((s) => !injectedNames.has(s.name));
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
return merged;
|
|
2302
|
+
}
|
|
2303
|
+
/** Repo MCP servers held back pending approval of their exact definition. */
|
|
2304
|
+
getPendingMcpApprovals() {
|
|
2305
|
+
return this.pendingMcpApprovals.map((s) => ({
|
|
2306
|
+
name: s.name,
|
|
2307
|
+
fingerprint: fingerprintMcpServer(s),
|
|
2308
|
+
transport: s.type ?? (s.url ? "http" : "stdio"),
|
|
2309
|
+
command: s.command,
|
|
2310
|
+
args: s.args,
|
|
2311
|
+
url: s.url,
|
|
2312
|
+
envKeys: Object.keys(s.env ?? {}),
|
|
2313
|
+
envValues: Object.fromEntries(Object.entries(s.env ?? {}).filter(([k]) => LOADER_ENV_KEY.test(k))),
|
|
2314
|
+
headerKeys: Object.keys(s.headers ?? {})
|
|
2315
|
+
}));
|
|
2316
|
+
}
|
|
2317
|
+
/**
|
|
2318
|
+
* Approve pending repo MCP servers for the current (trusted) root. Persists the
|
|
2319
|
+
* fingerprints the user was SHOWN, not a re-read by name, so a definition that
|
|
2320
|
+
* changed while the prompt was open stays pending.
|
|
2321
|
+
*/
|
|
2322
|
+
async approveMcpServers(servers) {
|
|
2323
|
+
await this.load();
|
|
2324
|
+
const root = this.projectRealPath;
|
|
2325
|
+
if (!root || !this.projectTrusted) return;
|
|
2326
|
+
const g = this.globalConfig;
|
|
2327
|
+
const defs = g.trustedMcpDefinitions ??= {};
|
|
2328
|
+
defs[root] = [.../* @__PURE__ */ new Set([...defs[root] ?? [], ...servers.map((s) => s.fingerprint)])];
|
|
2329
|
+
await this.save();
|
|
2330
|
+
}
|
|
2331
|
+
/** Warn once (stderr) about repo MCP servers skipped for lack of approval. */
|
|
2332
|
+
warnPendingMcpApprovals() {
|
|
2333
|
+
if (this.pendingMcpWarned || this.pendingMcpApprovals.length === 0) return;
|
|
2334
|
+
this.pendingMcpWarned = true;
|
|
2335
|
+
const names = sanitizeTerminalText(this.pendingMcpApprovals.map((s) => s.name).join(", "));
|
|
2336
|
+
const root = escapeTerminalControlChars(this.projectRealPath ?? "").replace(/\n/g, "\\n");
|
|
2337
|
+
logger.warn(`Skipping ${this.pendingMcpApprovals.length} unapproved repo MCP server(s): ${names}. Run b4m interactively in ${root} to approve them.`);
|
|
2338
|
+
}
|
|
2339
|
+
/** Whether the current project root is trusted (folder-trust gate). */
|
|
2340
|
+
isProjectTrusted() {
|
|
2341
|
+
return this.projectTrusted;
|
|
2342
|
+
}
|
|
2343
|
+
/** Canonicalized project root discovered this session, or null. */
|
|
2344
|
+
getProjectRealPath() {
|
|
2345
|
+
return this.projectRealPath;
|
|
2346
|
+
}
|
|
2347
|
+
/** The realpath'd roots the user has explicitly trusted. */
|
|
2348
|
+
getTrustedProjects() {
|
|
2349
|
+
return this.globalConfig?.trustedProjects ? [...this.globalConfig.trustedProjects] : [];
|
|
2350
|
+
}
|
|
2351
|
+
/**
|
|
2352
|
+
* Whether the current project root ships any repo-committed b4m files that the
|
|
2353
|
+
* trust gate governs. Used to decide whether the startup trust prompt is even
|
|
2354
|
+
* worth showing (nothing to gate = no prompt).
|
|
2355
|
+
*/
|
|
2356
|
+
projectHasB4mFiles() {
|
|
2357
|
+
const root = this.projectConfigDir;
|
|
2358
|
+
if (!root) return false;
|
|
2359
|
+
return [
|
|
2360
|
+
[".bike4mind", "config.json"],
|
|
2361
|
+
[".bike4mind", "local.json"],
|
|
2362
|
+
[".bike4mind", "agents"],
|
|
2363
|
+
[".bike4mind", "commands"],
|
|
2364
|
+
[".mcp.json"],
|
|
2365
|
+
[".claude", "agents"],
|
|
2366
|
+
[".claude", "skills"],
|
|
2367
|
+
[".claude", "commands"],
|
|
2368
|
+
...PROJECT_CONTEXT_FILES.map((name) => [name])
|
|
2369
|
+
].some((parts) => existsSync(path.join(root, ...parts)));
|
|
2370
|
+
}
|
|
2371
|
+
/**
|
|
2372
|
+
* Trust a project root (default: the current one). Persists the realpath'd
|
|
2373
|
+
* root to the global `trustedProjects` and, when it's the current root, loads
|
|
2374
|
+
* its repo layers and re-merges so they take effect for this session.
|
|
2375
|
+
*/
|
|
2376
|
+
async trustProject(root) {
|
|
2377
|
+
await this.load();
|
|
2378
|
+
const target = root ? await safeRealpath(root) : this.projectRealPath;
|
|
2379
|
+
if (!target) return false;
|
|
2380
|
+
const g = this.globalConfig;
|
|
2381
|
+
if (!g.trustedProjects) g.trustedProjects = [];
|
|
2382
|
+
if (!g.trustedProjects.includes(target)) g.trustedProjects.push(target);
|
|
2383
|
+
await this.save();
|
|
2384
|
+
if (target === this.projectRealPath && this.projectConfigDir && process.env.B4M_NO_PROJECT_CONFIG !== "1") {
|
|
2385
|
+
this.projectTrusted = true;
|
|
2386
|
+
await this.loadProjectLayers();
|
|
2387
|
+
this.config = await this.computeMerged();
|
|
2388
|
+
}
|
|
2389
|
+
return true;
|
|
2390
|
+
}
|
|
2391
|
+
/**
|
|
2392
|
+
* Revoke trust for a project root (default: the current one). Next launch
|
|
2393
|
+
* re-prompts and repo layers stay inert until re-trusted. Revoking the current
|
|
2394
|
+
* root drops its raw layers so nothing repo-sourced survives in this session.
|
|
2395
|
+
*/
|
|
2396
|
+
async untrustProject(root) {
|
|
2397
|
+
await this.load();
|
|
2398
|
+
const target = root ? await safeRealpath(root) : this.projectRealPath;
|
|
2399
|
+
if (!target) return;
|
|
2400
|
+
const untrust = (config) => {
|
|
2401
|
+
config.trustedProjects = (config.trustedProjects || []).filter((p) => p !== target);
|
|
2402
|
+
if (config.trustedMcpDefinitions) delete config.trustedMcpDefinitions[target];
|
|
2403
|
+
};
|
|
2404
|
+
untrust(this.globalConfig);
|
|
2405
|
+
if (target === this.projectRealPath) {
|
|
2406
|
+
this.projectTrusted = false;
|
|
2407
|
+
this.rawProjectConfig = null;
|
|
2408
|
+
this.rawProjectLocalConfig = null;
|
|
2409
|
+
this.rawMcpJsonServers = null;
|
|
2410
|
+
}
|
|
2411
|
+
if (await this.patchInFallback(untrust, (raw) => {
|
|
2412
|
+
const dropped = removeRawListItems(raw, "trustedProjects", (p) => p === target);
|
|
2413
|
+
const definitions = raw.trustedMcpDefinitions;
|
|
2414
|
+
if (!isJsonObject(definitions) || !hasOwnKey(definitions, target)) return dropped;
|
|
2415
|
+
delete definitions[target];
|
|
2416
|
+
return true;
|
|
2417
|
+
})) return;
|
|
2418
|
+
await this.save();
|
|
2419
|
+
}
|
|
2420
|
+
/**
|
|
2421
|
+
* Read the features map straight from the global config file, bypassing the
|
|
2422
|
+
* in-memory cache. save() merges over this so concurrent writers (the
|
|
2423
|
+
* interactive session vs `b4m plugin add`) don't clobber each other's keys.
|
|
2424
|
+
*/
|
|
2425
|
+
async readDiskFeatures() {
|
|
2426
|
+
const text = await this.readConfigText();
|
|
2427
|
+
const features = (text === null ? null : this.parseConfigText(text))?.features;
|
|
2428
|
+
if (!isJsonObject(features)) return {};
|
|
2429
|
+
return Object.fromEntries(Object.entries(features).filter(([, v]) => typeof v === "boolean"));
|
|
2430
|
+
}
|
|
2431
|
+
/**
|
|
2432
|
+
* Merge a features save against the current on-disk map. Start from disk and
|
|
2433
|
+
* apply only the keys the caller actually CHANGED relative to the snapshot it
|
|
2434
|
+
* loaded - so a concurrent writer's edit to a key this caller didn't touch
|
|
2435
|
+
* survives, and a key this caller removed is dropped. This is what makes the
|
|
2436
|
+
* cross-process guarantee hold even for conflicting edits, not just new keys.
|
|
2437
|
+
*/
|
|
2438
|
+
mergeFeatures(disk, snapshot, incoming) {
|
|
2439
|
+
const base = snapshot ?? {};
|
|
2440
|
+
const next = incoming ?? base;
|
|
2441
|
+
const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
|
2442
|
+
const merged = { ...disk };
|
|
2443
|
+
for (const key of Object.keys(next)) {
|
|
2444
|
+
const value = next[key];
|
|
2445
|
+
if (value !== void 0 && (!has(base, key) || base[key] !== value)) merged[key] = value;
|
|
2446
|
+
}
|
|
2447
|
+
for (const key of Object.keys(base)) if (!has(next, key)) delete merged[key];
|
|
2448
|
+
return merged;
|
|
2449
|
+
}
|
|
2450
|
+
/**
|
|
2451
|
+
* `b4m models` writes defaultModel, ollamaHost and localDefaultModel from its own process, so like features
|
|
2452
|
+
* they are taken from disk unless this caller's patch sets them.
|
|
2453
|
+
*/
|
|
2454
|
+
async mergeModelFields(next, snapshot, patch) {
|
|
2455
|
+
const text = await this.readConfigText();
|
|
2456
|
+
const disk = text === null ? null : this.parseConfigText(text);
|
|
2457
|
+
if (!disk) return next;
|
|
2458
|
+
const wholeConfig = patch !== void 0 && Object.prototype.hasOwnProperty.call(patch, "version");
|
|
2459
|
+
const changed = (key) => patch !== void 0 && Object.prototype.hasOwnProperty.call(patch, key) && (!wholeConfig || patch[key] !== snapshot[key]);
|
|
2460
|
+
const optional = (key) => changed(key) || disk[key] !== void 0 && typeof disk[key] !== "string" ? next[key] : disk[key];
|
|
2461
|
+
const credentials = CliConfigSchema.shape.modelServerCredentials.safeParse(disk.modelServerCredentials);
|
|
2462
|
+
return {
|
|
2463
|
+
...next,
|
|
2464
|
+
defaultModel: changed("defaultModel") || typeof disk.defaultModel !== "string" ? next.defaultModel : disk.defaultModel,
|
|
2465
|
+
ollamaHost: optional("ollamaHost"),
|
|
2466
|
+
localDefaultModel: optional("localDefaultModel"),
|
|
2467
|
+
modelServerCredentials: patch !== void 0 && Object.prototype.hasOwnProperty.call(patch, "modelServerCredentials") && (!wholeConfig || patch.modelServerCredentials !== snapshot.modelServerCredentials) ? next.modelServerCredentials : credentials.success ? credentials.data : next.modelServerCredentials
|
|
2468
|
+
};
|
|
2469
|
+
}
|
|
2470
|
+
/** The saved credentials as the file has them now, not as this store loaded them. */
|
|
2471
|
+
async readModelServerCredentials() {
|
|
2472
|
+
try {
|
|
2473
|
+
return await this.readModelServerCredentialsStrict();
|
|
2474
|
+
} catch (error) {
|
|
2475
|
+
logger.debug(`Could not read model server credentials: ${error instanceof Error ? error.message : String(error)}`);
|
|
2476
|
+
return {};
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
/** Throws when the file exists but cannot be read, so a write never replaces credentials it failed to read. */
|
|
2480
|
+
async readModelServerCredentialsStrict() {
|
|
2481
|
+
let text;
|
|
2482
|
+
try {
|
|
2483
|
+
text = await promises.readFile(this.configPath, "utf-8");
|
|
2484
|
+
} catch (error) {
|
|
2485
|
+
if (error instanceof Error && "code" in error && error.code === "ENOENT") return {};
|
|
2486
|
+
throw error;
|
|
2487
|
+
}
|
|
2488
|
+
const raw = this.parseConfigText(text);
|
|
2489
|
+
const parsed = z$1.object({ modelServerCredentials: CliConfigSchema.shape.modelServerCredentials }).safeParse(raw);
|
|
2490
|
+
if (!parsed.success) throw new Error(`${this.configPath} has malformed model server credentials.`);
|
|
2491
|
+
return parsed.data.modelServerCredentials ?? {};
|
|
2492
|
+
}
|
|
2493
|
+
/** Writes through a 0600 temp file and a rename, so a reader in another process never sees a half-written file. */
|
|
2494
|
+
async writeConfigFile(contents) {
|
|
2495
|
+
const target = await promises.realpath(this.configPath).catch(() => this.configPath);
|
|
2496
|
+
const temp = `${target}.${process.pid}.${v4()}.tmp`;
|
|
2497
|
+
try {
|
|
2498
|
+
await promises.writeFile(temp, contents, {
|
|
2499
|
+
encoding: "utf-8",
|
|
2500
|
+
mode: 384
|
|
2501
|
+
});
|
|
2502
|
+
if (!this.configLock) throw new Error(`Refusing to write ${this.configPath} without holding its write lock`);
|
|
2503
|
+
await this.configLock.assertHeld();
|
|
2504
|
+
await promises.rename(temp, target);
|
|
2505
|
+
} catch (error) {
|
|
2506
|
+
await promises.rm(temp, { force: true });
|
|
2507
|
+
throw error;
|
|
2508
|
+
}
|
|
2509
|
+
}
|
|
2510
|
+
/**
|
|
2511
|
+
* Writes the upgraded file under the config write lock, from a fresh read so a save another process made since
|
|
2512
|
+
* load() read the file is kept. Returns what it wrote, or null when the file is gone or not a JSON object.
|
|
2513
|
+
*/
|
|
2514
|
+
async writeUpgradedConfig() {
|
|
2515
|
+
return this.withConfigWriteLock(async () => {
|
|
2516
|
+
const text = await this.readConfigText();
|
|
2517
|
+
const raw = text === null ? null : this.parseConfigText(text);
|
|
2518
|
+
if (!raw) return null;
|
|
2519
|
+
migrateApiConfig(raw);
|
|
2520
|
+
if (raw.version !== CONFIG_SCHEMA_VERSION) {
|
|
2521
|
+
upgradeConfig(raw);
|
|
2522
|
+
if (CliConfigSchema.safeParse(raw).success) await this.writeConfigFile(JSON.stringify(raw, null, 2));
|
|
2523
|
+
}
|
|
2524
|
+
return raw;
|
|
2525
|
+
});
|
|
2526
|
+
}
|
|
2527
|
+
/** Reloads from the file so the write below carries what other processes saved (a refreshed sign-in token). */
|
|
2528
|
+
async reloadFromDisk() {
|
|
2529
|
+
this.config = null;
|
|
2530
|
+
this.globalConfig = null;
|
|
2531
|
+
await this.load();
|
|
2532
|
+
}
|
|
2533
|
+
/** Read-modify-write against the file, so a login in another terminal is not undone. */
|
|
2534
|
+
async setModelServerCredential(serverId, secret) {
|
|
2535
|
+
await this.updateModelServerCredentials((current) => ({
|
|
2536
|
+
...current,
|
|
2537
|
+
[serverId]: { secret }
|
|
2538
|
+
}));
|
|
2539
|
+
}
|
|
2540
|
+
async clearModelServerCredential(serverId) {
|
|
2541
|
+
await this.load();
|
|
2542
|
+
const clear = (config) => {
|
|
2543
|
+
const saved = config.modelServerCredentials;
|
|
2544
|
+
if (!saved || !hasOwnKey(saved, serverId)) return;
|
|
2545
|
+
const { [serverId]: dropped, ...kept } = saved;
|
|
2546
|
+
config.modelServerCredentials = kept;
|
|
2547
|
+
};
|
|
2548
|
+
if (this.fallbackBase) clear(this.globalConfig);
|
|
2549
|
+
const clearInFile = (raw) => {
|
|
2550
|
+
const credentials = raw.modelServerCredentials;
|
|
2551
|
+
if (!isJsonObject(credentials) || !hasOwnKey(credentials, serverId)) return false;
|
|
2552
|
+
delete credentials[serverId];
|
|
2553
|
+
return true;
|
|
2554
|
+
};
|
|
2555
|
+
if (await this.patchInFallback(clear, clearInFile)) return;
|
|
2556
|
+
await this.updateModelServerCredentials((current) => {
|
|
2557
|
+
const { [serverId]: removed, ...rest } = current;
|
|
2558
|
+
return rest;
|
|
2559
|
+
});
|
|
2560
|
+
}
|
|
2561
|
+
async updateModelServerCredentials(change) {
|
|
2562
|
+
await this.lockedWrite(async () => {
|
|
2563
|
+
const next = change(await this.readModelServerCredentialsStrict());
|
|
2564
|
+
await this.writeGlobal({ modelServerCredentials: next });
|
|
2565
|
+
}, () => this.reloadFromDisk());
|
|
2566
|
+
}
|
|
2567
|
+
/**
|
|
2568
|
+
* Save configuration to disk
|
|
2569
|
+
*/
|
|
2570
|
+
async save(config) {
|
|
2571
|
+
await this.exclusive(() => this.persistGlobal(config));
|
|
2572
|
+
}
|
|
2573
|
+
/** Serializes this store's reads and writes of the config file, so one never interleaves with another. */
|
|
2574
|
+
exclusive(work) {
|
|
2575
|
+
const run = this.serial.then(work, work);
|
|
2576
|
+
this.serial = run.catch(() => void 0);
|
|
2577
|
+
return run;
|
|
2578
|
+
}
|
|
2579
|
+
/**
|
|
2580
|
+
* Runs a read-modify-write of the config file under exclusive() and then the config write lock. Lock order
|
|
2581
|
+
* everywhere: the refresh lock, then exclusive(), then the config write lock. Loading (which may reset and write)
|
|
2582
|
+
* happens before the write lock is taken, since that lock is not reentrant.
|
|
2583
|
+
*/
|
|
2584
|
+
lockedWrite(work, prepare) {
|
|
2585
|
+
return this.exclusive(async () => {
|
|
2586
|
+
if (prepare) await prepare();
|
|
2587
|
+
if (!this.globalConfig) await this.load();
|
|
2588
|
+
await this.init();
|
|
2589
|
+
return this.withConfigWriteLock(work);
|
|
2590
|
+
});
|
|
2591
|
+
}
|
|
2592
|
+
withConfigWriteLock(work) {
|
|
2593
|
+
return withLockDir(path.join(path.dirname(this.configPath), "config.json.lock"), async (held) => {
|
|
2594
|
+
this.configLock = held;
|
|
2595
|
+
try {
|
|
2596
|
+
return await work();
|
|
2597
|
+
} finally {
|
|
2598
|
+
this.configLock = null;
|
|
2599
|
+
}
|
|
2600
|
+
}, {
|
|
2601
|
+
waitMs: CONFIG_LOCK_WAIT_MS,
|
|
2602
|
+
staleMs: CONFIG_LOCK_STALE_MS,
|
|
2603
|
+
pollMs: CONFIG_LOCK_POLL_MS,
|
|
2604
|
+
heldMessage: "Another b4m process is still saving settings"
|
|
2605
|
+
});
|
|
2606
|
+
}
|
|
2607
|
+
/**
|
|
2608
|
+
* The sign-in and backend fields as the file holds them now; another process may have signed in or switched
|
|
2609
|
+
* since this store loaded. No file, or JSON that is not an object, means none are set. A file that cannot be read
|
|
2610
|
+
* or parsed rejects, so a save never writes this store's copy over a sign-in it failed to read. A field in an
|
|
2611
|
+
* unexpected shape is returned as found, so a write carries it through unchanged.
|
|
2612
|
+
*/
|
|
2613
|
+
async diskAuthFields() {
|
|
2614
|
+
const text = await this.readConfigText();
|
|
2615
|
+
const disk = text === null ? null : this.parseConfigText(text);
|
|
2616
|
+
return {
|
|
2617
|
+
auth: disk?.auth,
|
|
2618
|
+
authByEnv: disk?.authByEnv,
|
|
2619
|
+
apiConfig: disk?.apiConfig
|
|
2620
|
+
};
|
|
2621
|
+
}
|
|
2622
|
+
/**
|
|
2623
|
+
* Writes the global layer. The sign-in and backend fields are written as the file holds them, so a stale or
|
|
2624
|
+
* signed-out process cannot undo another's sign-in; only `authFields` writers (a backend change, a reset) set them.
|
|
2625
|
+
*/
|
|
2626
|
+
async persistGlobal(config, opts) {
|
|
2627
|
+
await this.init();
|
|
2628
|
+
if (!this.globalConfig) await this.load();
|
|
2629
|
+
await this.withConfigWriteLock(() => this.writeGlobal(config, opts));
|
|
2630
|
+
}
|
|
2631
|
+
/** persistGlobal's read-modify-write of the file; the caller holds the config write lock. */
|
|
2632
|
+
async writeGlobal(config, opts) {
|
|
2633
|
+
const fallbackBase = this.fallbackBase;
|
|
2634
|
+
let staged = fallbackBase ? structuredClone(this.globalConfig) : null;
|
|
2635
|
+
try {
|
|
2636
|
+
await this.writeGlobalLayer(config, opts, (snapshot) => {
|
|
2637
|
+
if (fallbackBase) staged = structuredClone(snapshot);
|
|
2638
|
+
});
|
|
2639
|
+
} catch (error) {
|
|
2640
|
+
if (fallbackBase && staged && this.fallbackBase === fallbackBase) await this.rollBackTo(fallbackBase, staged, error instanceof RefusedSaveError ? error.key : void 0);
|
|
2641
|
+
throw error;
|
|
2642
|
+
}
|
|
2643
|
+
}
|
|
2644
|
+
/**
|
|
2645
|
+
* Undoes what a failed write staged: each top-level key (only `onlyKey` when the refusal named one) that differs
|
|
2646
|
+
* from `base` and still holds the value the write tried to save. A key another caller changed since is theirs and
|
|
2647
|
+
* is left alone, as are the sign-in and backend fields, which writers patch into the file directly.
|
|
2648
|
+
*/
|
|
2649
|
+
async rollBackTo(base, staged, onlyKey) {
|
|
2650
|
+
const current = this.globalConfig;
|
|
2651
|
+
if (!current) return;
|
|
2652
|
+
const from = base;
|
|
2653
|
+
const tried = staged;
|
|
2654
|
+
for (const key of /* @__PURE__ */ new Set([...Object.keys(from), ...Object.keys(current)])) {
|
|
2655
|
+
if (key === "auth" || key === "authByEnv" || key === "apiConfig") continue;
|
|
2656
|
+
if (onlyKey !== void 0 && key !== onlyKey) continue;
|
|
2657
|
+
const now = ownValue(current, key);
|
|
2658
|
+
if (isDeepStrictEqual(ownValue(from, key), now) || !isDeepStrictEqual(ownValue(tried, key), now)) continue;
|
|
2659
|
+
if (ownValue(from, key) === void 0) delete current[key];
|
|
2660
|
+
else current[key] = structuredClone(from[key]);
|
|
2661
|
+
}
|
|
2662
|
+
try {
|
|
2663
|
+
this.config = await this.computeMerged();
|
|
2664
|
+
} catch {}
|
|
2665
|
+
}
|
|
2666
|
+
async writeGlobalLayer(config, opts, onStaged) {
|
|
2667
|
+
const global = this.globalConfig;
|
|
2668
|
+
const authFields = opts?.authFields ?? (this.fallbackBase ? void 0 : await this.diskAuthFields());
|
|
2669
|
+
let explicitPatch;
|
|
2670
|
+
if (config) {
|
|
2671
|
+
const { auth, authByEnv, apiConfig, mcpServers, trustedTools, additionalDirectories, trustedProjects, trustedMcpDefinitions, tools, sandbox, ...rest } = config;
|
|
2672
|
+
if (!hasOwnKey(rest, "version")) {
|
|
2673
|
+
explicitPatch = { ...rest };
|
|
2674
|
+
if (!config.preferences) delete explicitPatch.preferences;
|
|
2675
|
+
if (!config.toolApiKeys) delete explicitPatch.toolApiKeys;
|
|
2676
|
+
}
|
|
2677
|
+
this.globalConfig = {
|
|
2678
|
+
...global,
|
|
2679
|
+
...rest,
|
|
2680
|
+
auth: global.auth,
|
|
2681
|
+
authByEnv: global.authByEnv,
|
|
2682
|
+
apiConfig: global.apiConfig,
|
|
2683
|
+
preferences: {
|
|
2684
|
+
...global.preferences,
|
|
2685
|
+
...config.preferences || {}
|
|
2686
|
+
},
|
|
2687
|
+
toolApiKeys: {
|
|
2688
|
+
...global.toolApiKeys,
|
|
2689
|
+
...config.toolApiKeys || {}
|
|
2690
|
+
},
|
|
2691
|
+
features: opts?.clearFeatures ? {} : this.mergeFeatures(await this.readDiskFeatures(), global.features, config.features ?? global.features)
|
|
2692
|
+
};
|
|
2693
|
+
} else this.globalConfig = {
|
|
2694
|
+
...global,
|
|
2695
|
+
features: opts?.clearFeatures ? {} : await this.readDiskFeatures()
|
|
2696
|
+
};
|
|
2697
|
+
if (this.fallbackBase) onStaged(structuredClone(this.globalConfig));
|
|
2698
|
+
if (!opts?.clearFeatures) this.globalConfig = await this.mergeModelFields(this.globalConfig, global, config);
|
|
2699
|
+
const staged = this.fallbackBase ? structuredClone(this.globalConfig) : this.globalConfig;
|
|
2700
|
+
onStaged(staged);
|
|
2701
|
+
const contents = this.fallbackBase ? await this.mergeOverInvalidConfig(this.fallbackBase, staged, opts?.authFields, explicitPatch) : {
|
|
2702
|
+
...this.globalConfig,
|
|
2703
|
+
...authFields
|
|
2704
|
+
};
|
|
2705
|
+
try {
|
|
2706
|
+
await this.writeConfigFile(JSON.stringify(contents, null, 2));
|
|
2707
|
+
} catch (error) {
|
|
2708
|
+
console.error("Failed to save config:", error);
|
|
2709
|
+
throw error;
|
|
2710
|
+
}
|
|
2711
|
+
if (this.fallbackBase) this.fallbackBase = staged;
|
|
2712
|
+
opts?.onCommit?.();
|
|
2713
|
+
try {
|
|
2714
|
+
await promises.chmod(this.configPath, 384);
|
|
2715
|
+
} catch (error) {
|
|
2716
|
+
console.warn(`Saved ${this.configPath}, but could not set its permissions to 0600: ${error instanceof Error ? error.message : String(error)}`);
|
|
2717
|
+
}
|
|
2718
|
+
try {
|
|
2719
|
+
await this.refreshMerged();
|
|
2720
|
+
} catch (error) {
|
|
2721
|
+
console.error("Failed to save config:", error);
|
|
2722
|
+
throw error;
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
/**
|
|
2726
|
+
* The file contents for a save while the snapshot stands in for a file that failed validation: the file's own
|
|
2727
|
+
* JSON, unknown and invalid keys included, with only what this process changed since `base` applied, so none of
|
|
2728
|
+
* the defaults behind the snapshot reach the file. The caller holds the config write lock.
|
|
2729
|
+
*/
|
|
2730
|
+
async mergeOverInvalidConfig(base, next, authFields, explicitPatch) {
|
|
2731
|
+
let text;
|
|
2732
|
+
let raw = null;
|
|
2733
|
+
try {
|
|
2734
|
+
text = await this.readConfigText();
|
|
2735
|
+
if (text !== null) raw = this.parseConfigText(text);
|
|
2736
|
+
} catch {
|
|
2737
|
+
text = "";
|
|
2738
|
+
}
|
|
2739
|
+
if (text === null) {
|
|
2740
|
+
this.fallbackBase = null;
|
|
2741
|
+
return {
|
|
2742
|
+
...next,
|
|
2743
|
+
...authFields ?? await this.diskAuthFields()
|
|
2744
|
+
};
|
|
2745
|
+
}
|
|
2746
|
+
if (!raw) throw this.invalidConfigError();
|
|
2747
|
+
const { auth: _baseAuth, authByEnv: _baseByEnv, apiConfig: _baseApi, ...from } = base;
|
|
2748
|
+
const { auth: _auth, authByEnv: _byEnv, apiConfig: _api, ...to } = next;
|
|
2749
|
+
const asJson = (value) => JSON.parse(JSON.stringify(value));
|
|
2750
|
+
let merged;
|
|
2751
|
+
try {
|
|
2752
|
+
merged = applyChanges(raw, asJson(from), asJson(to), explicitPatch ?? false);
|
|
2753
|
+
} catch (error) {
|
|
2754
|
+
if (error instanceof ShapeMismatchError) throw this.invalidConfigError(error.path[0]);
|
|
2755
|
+
throw error;
|
|
2756
|
+
}
|
|
2757
|
+
if (authFields) for (const key of [
|
|
2758
|
+
"auth",
|
|
2759
|
+
"authByEnv",
|
|
2760
|
+
"apiConfig"
|
|
2761
|
+
]) if (authFields[key] === void 0) delete merged[key];
|
|
2762
|
+
else merged[key] = authFields[key];
|
|
2763
|
+
return merged;
|
|
2764
|
+
}
|
|
2765
|
+
/** Rebuilds the merged view; on failure drops it, so the next load() rebuilds it from the file. */
|
|
2766
|
+
async refreshMerged() {
|
|
2767
|
+
try {
|
|
2768
|
+
this.config = await this.computeMerged();
|
|
2769
|
+
} catch (error) {
|
|
2770
|
+
this.config = null;
|
|
2771
|
+
throw error;
|
|
2772
|
+
}
|
|
2773
|
+
}
|
|
2774
|
+
invalidConfigError(key) {
|
|
2775
|
+
return new RefusedSaveError(`Could not save settings: ${this.configPath} failed validation, so it was left unchanged. Fix the file, or remove it to start over.`, key);
|
|
2776
|
+
}
|
|
2777
|
+
/**
|
|
2778
|
+
* While the snapshot stands in for a file that failed validation, applies `mutate` to the file's own JSON in place
|
|
2779
|
+
* of a save, then `change` (the same change, idempotent) to the snapshot and its base so a later save does not
|
|
2780
|
+
* apply it again. Returns false when not in that state or when there is no file, for the caller to save as usual.
|
|
2781
|
+
*/
|
|
2782
|
+
async patchInFallback(change, mutate) {
|
|
2783
|
+
if (!this.fallbackBase) return false;
|
|
2784
|
+
try {
|
|
2785
|
+
return await this.exclusive(async () => {
|
|
2786
|
+
if (!await this.withConfigWriteLock(() => this.patchConfigText(mutate, () => this.invalidConfigError()))) return false;
|
|
2787
|
+
if (this.fallbackBase) change(this.fallbackBase);
|
|
2788
|
+
if (this.globalConfig) change(this.globalConfig);
|
|
2789
|
+
await this.refreshMerged();
|
|
2790
|
+
return true;
|
|
2791
|
+
});
|
|
2792
|
+
} catch (error) {
|
|
2793
|
+
if (error instanceof ShapeMismatchError) throw this.invalidConfigError();
|
|
2794
|
+
throw error;
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
/**
|
|
2798
|
+
* Reset configuration to defaults
|
|
2799
|
+
*/
|
|
2800
|
+
async reset() {
|
|
2801
|
+
this.globalConfig = {
|
|
2802
|
+
...structuredClone(DEFAULT_CONFIG),
|
|
2803
|
+
userId: v4()
|
|
2804
|
+
};
|
|
2805
|
+
this.fallbackBase = null;
|
|
2806
|
+
this.projectTrusted = false;
|
|
2807
|
+
this.rawProjectConfig = null;
|
|
2808
|
+
this.rawProjectLocalConfig = null;
|
|
2809
|
+
this.rawMcpJsonServers = null;
|
|
2810
|
+
const g = this.globalConfig;
|
|
2811
|
+
await this.persistGlobal(void 0, {
|
|
2812
|
+
clearFeatures: true,
|
|
2813
|
+
authFields: {
|
|
2814
|
+
auth: g.auth,
|
|
2815
|
+
authByEnv: g.authByEnv,
|
|
2816
|
+
apiConfig: g.apiConfig
|
|
2817
|
+
}
|
|
2818
|
+
});
|
|
2819
|
+
return this.config;
|
|
2820
|
+
}
|
|
2821
|
+
/**
|
|
2822
|
+
* Get current configuration
|
|
2823
|
+
*/
|
|
2824
|
+
async get() {
|
|
2825
|
+
return this.load();
|
|
2826
|
+
}
|
|
2827
|
+
/**
|
|
2828
|
+
* Update a specific configuration value
|
|
2829
|
+
*/
|
|
2830
|
+
async update(updates) {
|
|
2831
|
+
await this.save(updates);
|
|
2832
|
+
}
|
|
2833
|
+
/**
|
|
2834
|
+
* Persist a sandbox config to the GLOBAL layer (the `/sandbox` handlers' path).
|
|
2835
|
+
* Sandbox is excluded from the generic `save()` allowlist so it flows only
|
|
2836
|
+
* through here - a merged-config save() can never launder a repo-tightened
|
|
2837
|
+
* sandbox into the user's global default.
|
|
2838
|
+
*/
|
|
2839
|
+
async saveSandboxConfig(sandbox) {
|
|
2840
|
+
await this.load();
|
|
2841
|
+
this.globalConfig.sandbox = structuredClone(sandbox);
|
|
2842
|
+
await this.save();
|
|
2843
|
+
}
|
|
2844
|
+
/**
|
|
2845
|
+
* Add MCP server configuration
|
|
2846
|
+
*/
|
|
2847
|
+
async addMcpServer(server) {
|
|
2848
|
+
await this.load();
|
|
2849
|
+
const upsert = (config) => {
|
|
2850
|
+
config.mcpServers = [...config.mcpServers.filter((s) => s.name !== server.name), structuredClone(server)];
|
|
2851
|
+
};
|
|
2852
|
+
upsert(this.globalConfig);
|
|
2853
|
+
if (await this.patchInFallback(upsert, (raw) => upsertRawMcpServer(raw, server))) return;
|
|
2854
|
+
await this.save();
|
|
2855
|
+
}
|
|
2856
|
+
/**
|
|
2857
|
+
* Remove MCP server configuration
|
|
2858
|
+
*/
|
|
2859
|
+
async removeMcpServer(name) {
|
|
2860
|
+
await this.load();
|
|
2861
|
+
const remove = (config) => {
|
|
2862
|
+
config.mcpServers = config.mcpServers.filter((s) => s.name !== name);
|
|
2863
|
+
};
|
|
2864
|
+
remove(this.globalConfig);
|
|
2865
|
+
if (await this.patchInFallback(remove, (raw) => removeRawMcpServer(raw, name))) return;
|
|
2866
|
+
await this.save();
|
|
2867
|
+
}
|
|
2868
|
+
/**
|
|
2869
|
+
* Enable/disable an MCP server saved in the user config. Rejects with McpToggleRefusedError naming the server's
|
|
2870
|
+
* source when the user config does not save it; `overriddenBy` names what decides whether it connects instead.
|
|
2871
|
+
*/
|
|
2872
|
+
async toggleMcpServer(name, enabled) {
|
|
2873
|
+
await this.load();
|
|
2874
|
+
const result = { overriddenBy: this.mcpToggleOverride(name) };
|
|
2875
|
+
const toggle = (config) => {
|
|
2876
|
+
const server = config.mcpServers.find((s) => s.name === name);
|
|
2877
|
+
if (server) server.enabled = enabled;
|
|
2878
|
+
};
|
|
2879
|
+
const toggleInFile = (raw) => {
|
|
2880
|
+
if (!setRawMcpServerEnabled(raw, name, enabled)) throw this.mcpServerNotSavedError(name);
|
|
2881
|
+
return true;
|
|
2882
|
+
};
|
|
2883
|
+
if (await this.patchInFallback(toggle, toggleInFile)) return result;
|
|
2884
|
+
const server = this.globalConfig.mcpServers.find((s) => s.name === name);
|
|
2885
|
+
if (!server) throw this.mcpServerNotSavedError(name);
|
|
2886
|
+
server.enabled = enabled;
|
|
2887
|
+
await this.save();
|
|
2888
|
+
return result;
|
|
2889
|
+
}
|
|
2890
|
+
mcpToggleOverride(name) {
|
|
2891
|
+
if (this.strictMcpConfig) return "strict-mcp-config";
|
|
2892
|
+
return this.injectedMcpNames.has(name) ? "mcp-config" : null;
|
|
2893
|
+
}
|
|
2894
|
+
/**
|
|
2895
|
+
* The MCP server `name` as enable/disable sees it: the user config's own entry when it saves one, read from the
|
|
2896
|
+
* file itself when that fails validation. A non-boolean `enabled` is undefined so a toggle repairs it.
|
|
2897
|
+
* Rejects servers from another source before the command decides whether the saved state already matches.
|
|
2898
|
+
*/
|
|
2899
|
+
async findMcpServer(name) {
|
|
2900
|
+
await this.load();
|
|
2901
|
+
const saved = this.globalConfig.mcpServers.find((s) => s.name === name);
|
|
2902
|
+
if (saved) return {
|
|
2903
|
+
enabled: saved.enabled,
|
|
2904
|
+
overriddenBy: this.mcpToggleOverride(name)
|
|
2905
|
+
};
|
|
2906
|
+
if (this.fallbackBase) {
|
|
2907
|
+
const text = await this.readConfigText();
|
|
2908
|
+
const raw = text === null ? null : this.parseConfigText(text);
|
|
2909
|
+
const entry = raw ? rawMcpServerEntry(raw, name) : void 0;
|
|
2910
|
+
if (entry) {
|
|
2911
|
+
const value = ownValue(entry, "enabled");
|
|
2912
|
+
return {
|
|
2913
|
+
enabled: value === void 0 ? true : typeof value === "boolean" ? value : void 0,
|
|
2914
|
+
overriddenBy: this.mcpToggleOverride(name)
|
|
2915
|
+
};
|
|
2916
|
+
}
|
|
2917
|
+
}
|
|
2918
|
+
if (this.injectedMcpNames.has(name) || this.projectMcpNames.has(name)) throw this.mcpServerNotSavedError(name);
|
|
2919
|
+
return null;
|
|
2920
|
+
}
|
|
2921
|
+
mcpServerNotSavedError(name) {
|
|
2922
|
+
if (this.injectedMcpNames.has(name)) return new McpToggleRefusedError(`MCP server "${name}" comes from --mcp-config, not ${this.configPath}; enable or disable it in that file.`);
|
|
2923
|
+
if (this.projectMcpNames.has(name)) return new McpToggleRefusedError(`MCP server "${name}" comes from this project's config, not ${this.configPath}; enable or disable it there.`);
|
|
2924
|
+
return new McpToggleRefusedError(`MCP server "${name}" was not found in ${this.configPath}.`);
|
|
2925
|
+
}
|
|
2926
|
+
/**
|
|
2927
|
+
* Add a tool to trusted tools list
|
|
2928
|
+
*/
|
|
2929
|
+
async trustTool(toolName) {
|
|
2930
|
+
await this.load();
|
|
2931
|
+
const g = this.globalConfig;
|
|
2932
|
+
if (!g.trustedTools) g.trustedTools = [];
|
|
2933
|
+
if (!g.trustedTools.includes(toolName)) {
|
|
2934
|
+
g.trustedTools.push(toolName);
|
|
2935
|
+
await this.save();
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
/**
|
|
2939
|
+
* Remove a tool from trusted tools list
|
|
2940
|
+
*/
|
|
2941
|
+
async untrustTool(toolName) {
|
|
2942
|
+
await this.load();
|
|
2943
|
+
const g = this.globalConfig;
|
|
2944
|
+
if (g.trustedTools) {
|
|
2945
|
+
const untrust = (config) => {
|
|
2946
|
+
config.trustedTools = (config.trustedTools || []).filter((t) => t !== toolName);
|
|
2947
|
+
};
|
|
2948
|
+
untrust(g);
|
|
2949
|
+
const revoke = (raw) => removeRawListItems(raw, "trustedTools", (t) => t === toolName);
|
|
2950
|
+
if (await this.patchInFallback(untrust, revoke)) return;
|
|
2951
|
+
await this.save();
|
|
2952
|
+
}
|
|
2953
|
+
}
|
|
2954
|
+
/**
|
|
2955
|
+
* Get list of trusted tools (merged effective view)
|
|
2956
|
+
*/
|
|
2957
|
+
async getTrustedTools() {
|
|
2958
|
+
return (await this.load()).trustedTools || [];
|
|
2959
|
+
}
|
|
2960
|
+
/**
|
|
2961
|
+
* Clear all trusted tools
|
|
2962
|
+
*/
|
|
2963
|
+
async clearTrustedTools() {
|
|
2964
|
+
await this.load();
|
|
2965
|
+
const clear = (config) => {
|
|
2966
|
+
config.trustedTools = [];
|
|
2967
|
+
};
|
|
2968
|
+
clear(this.globalConfig);
|
|
2969
|
+
const revokeAll = (raw) => removeRawListItems(raw, "trustedTools", () => true);
|
|
2970
|
+
if (await this.patchInFallback(clear, revokeAll)) return;
|
|
2971
|
+
await this.save();
|
|
2972
|
+
}
|
|
2973
|
+
/**
|
|
2974
|
+
* Get authentication tokens
|
|
2975
|
+
*/
|
|
2976
|
+
async getAuthTokens() {
|
|
2977
|
+
return (await this.load()).auth || null;
|
|
2978
|
+
}
|
|
2979
|
+
/**
|
|
2980
|
+
* Save the sign-in for this process's backend, leaving the rest of the file as another process may have left it.
|
|
2981
|
+
* With `expectedRefreshToken`, saves only while the saved sign-in still holds that token; resolves whether it saved.
|
|
2982
|
+
*/
|
|
2983
|
+
async setAuthTokens(tokens, expectedRefreshToken) {
|
|
2984
|
+
return this.saveAuthSlot(tokens, expectedRefreshToken);
|
|
2985
|
+
}
|
|
2986
|
+
/**
|
|
2987
|
+
* Clear the sign-in for this process's backend (logout), leaving other backends' sign-ins alone. With
|
|
2988
|
+
* `expectedRefreshToken`, clears only while the saved sign-in still holds that token, so a newer one is kept.
|
|
2989
|
+
* Resolves whether it cleared.
|
|
2990
|
+
*/
|
|
2991
|
+
async clearAuthTokens(expectedRefreshToken) {
|
|
2992
|
+
return this.saveAuthSlot(void 0, expectedRefreshToken);
|
|
2993
|
+
}
|
|
2994
|
+
/**
|
|
2995
|
+
* Write only this process's sign-in slot into the file as it is now: `auth` when the file's active backend
|
|
2996
|
+
* is this process's, otherwise `authByEnv[<this backend>]`. Another process's backend switch and sign-in survive.
|
|
2997
|
+
*/
|
|
2998
|
+
async saveAuthSlot(tokens, expectedRefreshToken) {
|
|
2999
|
+
await this.load();
|
|
3000
|
+
return this.lockedWrite(() => this.writeAuthSlot(tokens, expectedRefreshToken));
|
|
3001
|
+
}
|
|
3002
|
+
async writeAuthSlot(tokens, expectedRefreshToken) {
|
|
3003
|
+
const text = await this.readConfigText();
|
|
3004
|
+
if (text === null) {
|
|
3005
|
+
if (expectedRefreshToken !== void 0) return false;
|
|
3006
|
+
const g = this.globalConfig;
|
|
3007
|
+
await this.writeGlobal(void 0, {
|
|
3008
|
+
authFields: {
|
|
3009
|
+
auth: tokens,
|
|
3010
|
+
authByEnv: g.authByEnv,
|
|
3011
|
+
apiConfig: g.apiConfig
|
|
3012
|
+
},
|
|
3013
|
+
onCommit: () => {
|
|
3014
|
+
this.globalConfig.auth = tokens;
|
|
3015
|
+
}
|
|
3016
|
+
});
|
|
3017
|
+
return true;
|
|
3018
|
+
}
|
|
3019
|
+
const file = this.parseConfigText(text);
|
|
3020
|
+
if (!file) throw new Error(`Could not save the sign-in to ${this.configPath}: it does not hold a JSON object`);
|
|
3021
|
+
const myKey = this.envKey();
|
|
3022
|
+
const mySlotInAuth = this.fileEnvKey(file) === myKey;
|
|
3023
|
+
const byEnv = typeof file.authByEnv === "object" && file.authByEnv !== null && !Array.isArray(file.authByEnv) ? { ...file.authByEnv } : {};
|
|
3024
|
+
if (expectedRefreshToken !== void 0) {
|
|
3025
|
+
const held = mySlotInAuth ? file.auth : Object.prototype.hasOwnProperty.call(byEnv, myKey) ? byEnv[myKey] : void 0;
|
|
3026
|
+
if ((typeof held === "object" && held !== null ? held.refreshToken : void 0) !== expectedRefreshToken) return false;
|
|
3027
|
+
}
|
|
3028
|
+
if (mySlotInAuth) {
|
|
3029
|
+
if (tokens) file.auth = tokens;
|
|
3030
|
+
else delete file.auth;
|
|
3031
|
+
} else {
|
|
3032
|
+
if (tokens) byEnv[myKey] = tokens;
|
|
3033
|
+
else delete byEnv[myKey];
|
|
3034
|
+
file.authByEnv = byEnv;
|
|
3035
|
+
}
|
|
3036
|
+
await this.writeConfigFile(JSON.stringify(file, null, 2));
|
|
3037
|
+
this.globalConfig.auth = tokens;
|
|
3038
|
+
if (this.config) this.config.auth = tokens;
|
|
3039
|
+
return true;
|
|
3040
|
+
}
|
|
3041
|
+
envKey() {
|
|
3042
|
+
return normalizeEnvKey(this.globalConfig.apiConfig?.customUrl || getDefaultApiUrl());
|
|
3043
|
+
}
|
|
3044
|
+
fileEnvKey(file) {
|
|
3045
|
+
const apiConfig = file.apiConfig;
|
|
3046
|
+
return normalizeEnvKey(typeof apiConfig?.customUrl === "string" && apiConfig.customUrl ? apiConfig.customUrl : getDefaultApiUrl());
|
|
3047
|
+
}
|
|
3048
|
+
/** The config file's text, or null when there is none. Errors name the file and the error code only. */
|
|
3049
|
+
async readConfigText() {
|
|
3050
|
+
try {
|
|
3051
|
+
return await promises.readFile(this.configPath, "utf-8");
|
|
3052
|
+
} catch (error) {
|
|
3053
|
+
const code = error.code;
|
|
3054
|
+
if (code === "ENOENT") return null;
|
|
3055
|
+
throw new Error(`Could not read ${this.configPath}: ${code ?? "read failed"}`);
|
|
3056
|
+
}
|
|
3057
|
+
}
|
|
3058
|
+
/** The parsed config file, or null when it is not an object. Never echoes the file's bytes in an error. */
|
|
3059
|
+
parseConfigText(text) {
|
|
3060
|
+
let raw;
|
|
3061
|
+
try {
|
|
3062
|
+
raw = JSON.parse(text);
|
|
3063
|
+
} catch (error) {
|
|
3064
|
+
const position = error instanceof Error ? /position (\d+)/.exec(error.message)?.[1] : void 0;
|
|
3065
|
+
throw new Error(`Could not read ${this.configPath}: not valid JSON${position ? ` (at position ${position})` : ""}`);
|
|
3066
|
+
}
|
|
3067
|
+
return typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : null;
|
|
3068
|
+
}
|
|
3069
|
+
/**
|
|
3070
|
+
* The saved sign-in as the file holds it now, which another b4m process may have refreshed or cleared since
|
|
3071
|
+
* this store loaded; later reads return it too. The token refresh reads through this before it saves or clears.
|
|
3072
|
+
*/
|
|
3073
|
+
async reloadAuthTokens() {
|
|
3074
|
+
await this.load();
|
|
3075
|
+
return this.exclusive(async () => {
|
|
3076
|
+
if (!this.globalConfig) await this.load();
|
|
3077
|
+
const text = await this.readConfigText();
|
|
3078
|
+
const auth = text === null ? void 0 : this.authForEnv(text, this.envKey());
|
|
3079
|
+
this.globalConfig.auth = auth;
|
|
3080
|
+
if (this.config) this.config.auth = auth;
|
|
3081
|
+
return auth ?? null;
|
|
3082
|
+
});
|
|
3083
|
+
}
|
|
3084
|
+
/**
|
|
3085
|
+
* Run `work` holding the sign-in refresh lock shared by every b4m process using this config
|
|
3086
|
+
* directory. Waits at most `waitMs`, then rejects without running `work`. Rejects after `work` when another
|
|
3087
|
+
* process took the lock over meanwhile; a refresh guards its own save with a compare-and-set.
|
|
3088
|
+
*/
|
|
3089
|
+
async withRefreshLock(work, waitMs = REFRESH_LOCK_WAIT_MS) {
|
|
3090
|
+
return withLockDir(path.join(path.dirname(this.configPath), "auth-refresh.lock"), () => work(), {
|
|
3091
|
+
waitMs,
|
|
3092
|
+
staleMs: REFRESH_LOCK_STALE_MS,
|
|
3093
|
+
pollMs: REFRESH_LOCK_POLL_MS,
|
|
3094
|
+
heldMessage: "Another b4m process is still refreshing the sign-in"
|
|
3095
|
+
});
|
|
3096
|
+
}
|
|
3097
|
+
/** The sign-in `text` (the config file) holds for the environment keyed `envKey`, without echoing its bytes in errors. */
|
|
3098
|
+
authForEnv(text, envKey) {
|
|
3099
|
+
const file = this.parseConfigText(text);
|
|
3100
|
+
if (!file) return void 0;
|
|
3101
|
+
let candidate;
|
|
3102
|
+
if (this.fileEnvKey(file) === envKey) candidate = file.auth;
|
|
3103
|
+
else if (typeof file.authByEnv === "object" && file.authByEnv !== null && Object.prototype.hasOwnProperty.call(file.authByEnv, envKey)) candidate = file.authByEnv[envKey];
|
|
3104
|
+
if (candidate === void 0) return void 0;
|
|
3105
|
+
const parsed = AuthTokensSchema.safeParse(candidate);
|
|
3106
|
+
if (!parsed.success) throw new Error(`Could not read the saved sign-in from ${this.configPath}: it is not in the expected shape`);
|
|
3107
|
+
return parsed.data;
|
|
3108
|
+
}
|
|
3109
|
+
/**
|
|
3110
|
+
* Check if user is authenticated
|
|
3111
|
+
*/
|
|
3112
|
+
async isAuthenticated() {
|
|
3113
|
+
const tokens = await this.getAuthTokens();
|
|
3114
|
+
if (!tokens) return false;
|
|
3115
|
+
return new Date(tokens.expiresAt) > /* @__PURE__ */ new Date();
|
|
3116
|
+
}
|
|
3117
|
+
/**
|
|
3118
|
+
* Get API configuration
|
|
3119
|
+
*/
|
|
3120
|
+
async getApiConfig() {
|
|
3121
|
+
return (await this.load()).apiConfig;
|
|
3122
|
+
}
|
|
3123
|
+
/**
|
|
3124
|
+
* Set custom API URL for a self-hosted instance.
|
|
3125
|
+
* Pass null to reset to the build-time default service.
|
|
3126
|
+
*/
|
|
3127
|
+
async setCustomApiUrl(url) {
|
|
3128
|
+
await this.writeCustomApiUrl(url, false);
|
|
3129
|
+
}
|
|
3130
|
+
/**
|
|
3131
|
+
* Points the CLI at `url` (null: the build-time default service) and drops the active sign-in, which belongs to
|
|
3132
|
+
* the old origin, in the same write, so a failure never leaves the old backend's tokens next to the new URL.
|
|
3133
|
+
*/
|
|
3134
|
+
async setCustomApiUrlSignedOut(url) {
|
|
3135
|
+
await this.writeCustomApiUrl(url, true);
|
|
3136
|
+
}
|
|
3137
|
+
async writeCustomApiUrl(url, signOut) {
|
|
3138
|
+
await this.load();
|
|
3139
|
+
await this.lockedWrite(async () => {
|
|
3140
|
+
const apiConfig = url === null ? { endpointChosen: true } : {
|
|
3141
|
+
customUrl: url,
|
|
3142
|
+
endpointChosen: true
|
|
3143
|
+
};
|
|
3144
|
+
const disk = await this.diskAuthFields();
|
|
3145
|
+
await this.writeGlobal(void 0, {
|
|
3146
|
+
authFields: {
|
|
3147
|
+
...disk,
|
|
3148
|
+
apiConfig,
|
|
3149
|
+
...signOut ? { auth: void 0 } : {}
|
|
3150
|
+
},
|
|
3151
|
+
onCommit: () => {
|
|
3152
|
+
const g = this.globalConfig;
|
|
3153
|
+
g.apiConfig = apiConfig;
|
|
3154
|
+
if (signOut) g.auth = void 0;
|
|
3155
|
+
}
|
|
3156
|
+
});
|
|
3157
|
+
});
|
|
3158
|
+
}
|
|
3159
|
+
/** Record that a backend was chosen, so the first-run picker is not shown again. */
|
|
3160
|
+
async markEndpointChosen() {
|
|
3161
|
+
await this.load();
|
|
3162
|
+
if (this.globalConfig.apiConfig?.endpointChosen) return;
|
|
3163
|
+
await this.lockedWrite(async () => {
|
|
3164
|
+
const patched = await this.patchConfigText((raw) => {
|
|
3165
|
+
const onDisk = isJsonObject(raw.apiConfig) ? raw.apiConfig : {};
|
|
3166
|
+
if (onDisk.endpointChosen === true) return false;
|
|
3167
|
+
raw.apiConfig = {
|
|
3168
|
+
...onDisk,
|
|
3169
|
+
endpointChosen: true
|
|
3170
|
+
};
|
|
3171
|
+
return true;
|
|
3172
|
+
});
|
|
3173
|
+
const choose = () => {
|
|
3174
|
+
const g = this.globalConfig;
|
|
3175
|
+
g.apiConfig = {
|
|
3176
|
+
...g.apiConfig,
|
|
3177
|
+
endpointChosen: true
|
|
3178
|
+
};
|
|
3179
|
+
if (this.config) this.config.apiConfig = g.apiConfig;
|
|
3180
|
+
};
|
|
3181
|
+
if (patched) {
|
|
3182
|
+
choose();
|
|
3183
|
+
return;
|
|
3184
|
+
}
|
|
3185
|
+
const g = this.globalConfig;
|
|
3186
|
+
await this.writeGlobal(void 0, {
|
|
3187
|
+
authFields: {
|
|
3188
|
+
auth: g.auth,
|
|
3189
|
+
authByEnv: g.authByEnv,
|
|
3190
|
+
apiConfig: {
|
|
3191
|
+
...g.apiConfig,
|
|
3192
|
+
endpointChosen: true
|
|
3193
|
+
}
|
|
3194
|
+
},
|
|
3195
|
+
onCommit: choose
|
|
3196
|
+
});
|
|
3197
|
+
});
|
|
3198
|
+
}
|
|
3199
|
+
/**
|
|
3200
|
+
* Saves the launch auto-update choice by setting only `preferences.autoUpdate` in the raw file, without load()'s
|
|
3201
|
+
* schema pass, so a config this build cannot validate (one written by a newer b4m) keeps every other key. Rejects
|
|
3202
|
+
* when the file cannot be read or does not hold a JSON object.
|
|
3203
|
+
*/
|
|
3204
|
+
async saveAutoUpdatePreference(value) {
|
|
3205
|
+
await this.init();
|
|
3206
|
+
if (!await this.exclusive(() => this.withConfigWriteLock(() => this.patchConfigText((raw) => {
|
|
3207
|
+
const preferences = raw.preferences ?? {};
|
|
3208
|
+
if (!isJsonObject(preferences)) throw new Error(`Could not save the auto-update choice: preferences in ${this.configPath} is not an object`);
|
|
3209
|
+
raw.preferences = {
|
|
3210
|
+
...preferences,
|
|
3211
|
+
autoUpdate: value
|
|
3212
|
+
};
|
|
3213
|
+
return true;
|
|
3214
|
+
})))) {
|
|
3215
|
+
await this.save({ preferences: { autoUpdate: value } });
|
|
3216
|
+
return;
|
|
3217
|
+
}
|
|
3218
|
+
if (this.globalConfig) this.globalConfig.preferences.autoUpdate = value;
|
|
3219
|
+
if (this.config) this.config.preferences.autoUpdate = value;
|
|
3220
|
+
}
|
|
3221
|
+
/**
|
|
3222
|
+
* Applies `mutate` to the config file's raw JSON and writes it back when `mutate` returns true. The caller holds
|
|
3223
|
+
* the config write lock. Returns false when there is no file; rejects when it cannot be read or is not an object.
|
|
3224
|
+
*/
|
|
3225
|
+
async patchConfigText(mutate, notAnObject = () => /* @__PURE__ */ new Error(`Could not update ${this.configPath}: it does not hold a JSON object`)) {
|
|
3226
|
+
const text = await this.readConfigText();
|
|
3227
|
+
if (text === null) return false;
|
|
3228
|
+
const raw = this.parseConfigText(text);
|
|
3229
|
+
if (!raw) throw notAnObject();
|
|
3230
|
+
if (mutate(raw)) await this.writeConfigFile(JSON.stringify(raw, null, 2));
|
|
3231
|
+
return true;
|
|
3232
|
+
}
|
|
3233
|
+
/**
|
|
3234
|
+
* Switch the active API environment, caching auth tokens per-environment so
|
|
3235
|
+
* flipping between `--dev` and `--prod` doesn't force a re-login each time you
|
|
3236
|
+
* return to an environment you've already authenticated.
|
|
3237
|
+
*
|
|
3238
|
+
* Targets:
|
|
3239
|
+
* - 'prod' -> the build-time default service (clears customUrl)
|
|
3240
|
+
* - 'dev' -> local dev server (http://localhost:3000)
|
|
3241
|
+
* - { customUrl: '...' } -> arbitrary self-hosted URL
|
|
3242
|
+
*
|
|
3243
|
+
* Mutates the cached config in place and persists via `save()` (no argument)
|
|
3244
|
+
* so the write bypasses save()'s field-merge - `save(config)` would otherwise
|
|
3245
|
+
* preserve the previous `auth` and defeat the per-env swap.
|
|
3246
|
+
*/
|
|
3247
|
+
async switchApiEnvironment(target) {
|
|
3248
|
+
await this.load();
|
|
3249
|
+
let newUrl;
|
|
3250
|
+
let newApiConfig;
|
|
3251
|
+
if (target === "prod") {
|
|
3252
|
+
newUrl = getDefaultApiUrl();
|
|
3253
|
+
newApiConfig = { endpointChosen: true };
|
|
3254
|
+
} else if (target === "dev") {
|
|
3255
|
+
newUrl = LOCAL_DEV_URL;
|
|
3256
|
+
newApiConfig = {
|
|
3257
|
+
customUrl: LOCAL_DEV_URL,
|
|
3258
|
+
endpointChosen: true
|
|
3259
|
+
};
|
|
3260
|
+
} else {
|
|
3261
|
+
newUrl = target.customUrl;
|
|
3262
|
+
newApiConfig = {
|
|
3263
|
+
customUrl: target.customUrl,
|
|
3264
|
+
endpointChosen: true
|
|
3265
|
+
};
|
|
3266
|
+
}
|
|
3267
|
+
const envName = getEnvironmentName(newApiConfig);
|
|
3268
|
+
return this.lockedWrite(async () => {
|
|
3269
|
+
const g = this.globalConfig;
|
|
3270
|
+
const wasHere = normalizeEnvKey(g.apiConfig?.customUrl || getDefaultApiUrl()) === normalizeEnvKey(newUrl);
|
|
3271
|
+
const disk = await this.diskAuthFields();
|
|
3272
|
+
const auth = AuthTokensSchema.optional().safeParse(disk.auth);
|
|
3273
|
+
const authByEnv = z$1.record(z$1.string(), AuthTokensSchema).optional().safeParse(disk.authByEnv);
|
|
3274
|
+
if (!auth.success || !authByEnv.success) throw new Error(`Could not switch backend: the saved sign-in in ${this.configPath} is not in the expected shape`);
|
|
3275
|
+
const onDisk = ApiConfigSchema.optional().safeParse(disk.apiConfig);
|
|
3276
|
+
const diskApi = onDisk.success ? onDisk.data : void 0;
|
|
3277
|
+
const swap = swapActiveEnvAuth({
|
|
3278
|
+
auth: auth.data,
|
|
3279
|
+
authByEnv: authByEnv.data
|
|
3280
|
+
}, diskApi?.customUrl || getDefaultApiUrl(), newUrl);
|
|
3281
|
+
const apiConfig = swap.changed || !diskApi?.endpointChosen ? newApiConfig : diskApi;
|
|
3282
|
+
const nextAuthByEnv = swap.changed ? swap.authByEnv : authByEnv.data;
|
|
3283
|
+
const follow = () => {
|
|
3284
|
+
const next = this.globalConfig;
|
|
3285
|
+
next.apiConfig = apiConfig;
|
|
3286
|
+
next.authByEnv = nextAuthByEnv;
|
|
3287
|
+
next.auth = swap.auth;
|
|
3288
|
+
};
|
|
3289
|
+
if (swap.changed || !diskApi?.endpointChosen) await this.writeGlobal(void 0, {
|
|
3290
|
+
authFields: {
|
|
3291
|
+
auth: swap.auth,
|
|
3292
|
+
authByEnv: nextAuthByEnv,
|
|
3293
|
+
apiConfig
|
|
3294
|
+
},
|
|
3295
|
+
onCommit: follow
|
|
3296
|
+
});
|
|
3297
|
+
else {
|
|
3298
|
+
follow();
|
|
3299
|
+
await this.refreshMerged();
|
|
3300
|
+
}
|
|
3301
|
+
return {
|
|
3302
|
+
url: newUrl,
|
|
3303
|
+
envName,
|
|
3304
|
+
changed: !wasHere,
|
|
3305
|
+
authenticated: isAuthTokenValid(swap.auth)
|
|
3306
|
+
};
|
|
3307
|
+
});
|
|
3308
|
+
}
|
|
3309
|
+
/**
|
|
3310
|
+
* Get project config directory (if any)
|
|
3311
|
+
*/
|
|
3312
|
+
getProjectConfigDir() {
|
|
3313
|
+
return this.projectConfigDir;
|
|
3314
|
+
}
|
|
3315
|
+
/**
|
|
3316
|
+
* Initialize project config directory
|
|
3317
|
+
* Creates .bike4mind/ directory and ensures local.json is gitignored
|
|
3318
|
+
* Does NOT auto-create config.json (user creates that manually)
|
|
3319
|
+
*/
|
|
3320
|
+
async initProjectConfig() {
|
|
3321
|
+
const projectDir = this.projectConfigDir || findProjectConfigDir();
|
|
3322
|
+
if (!projectDir) return;
|
|
3323
|
+
const configDir = path.join(projectDir, ".bike4mind");
|
|
3324
|
+
await promises.mkdir(configDir, { recursive: true });
|
|
3325
|
+
await this.ensureGitignore(projectDir);
|
|
3326
|
+
}
|
|
3327
|
+
/**
|
|
3328
|
+
* Ensure .gitignore includes .bike4mind/local.json
|
|
3329
|
+
*/
|
|
3330
|
+
async ensureGitignore(projectDir) {
|
|
3331
|
+
const gitignorePath = path.join(projectDir, ".gitignore");
|
|
3332
|
+
const entryToAdd = ".bike4mind/local.json";
|
|
3333
|
+
try {
|
|
3334
|
+
let gitignoreContent = "";
|
|
3335
|
+
try {
|
|
3336
|
+
gitignoreContent = await promises.readFile(gitignorePath, "utf-8");
|
|
3337
|
+
} catch {}
|
|
3338
|
+
if (gitignoreContent.includes(entryToAdd)) return;
|
|
3339
|
+
const newContent = gitignoreContent.trim() + (gitignoreContent ? "\n" : "") + `\n# Bike4Mind local config (developer-specific)\n${entryToAdd}\n`;
|
|
3340
|
+
await promises.writeFile(gitignorePath, newContent, "utf-8");
|
|
3341
|
+
console.log(`✅ Added ${entryToAdd} to .gitignore`);
|
|
3342
|
+
} catch (error) {
|
|
3343
|
+
console.warn(`⚠️ Failed to update .gitignore:`, error);
|
|
3344
|
+
}
|
|
3345
|
+
}
|
|
3346
|
+
/**
|
|
3347
|
+
* Save project config to .bike4mind/config.json
|
|
3348
|
+
*/
|
|
3349
|
+
async saveProjectConfig(config, projectDir) {
|
|
3350
|
+
const targetDir = projectDir || this.projectConfigDir || process.cwd();
|
|
3351
|
+
const configPath = path.join(targetDir, ".bike4mind", "config.json");
|
|
3352
|
+
await promises.mkdir(path.dirname(configPath), { recursive: true });
|
|
3353
|
+
const validated = ProjectConfigSchema.parse(config);
|
|
3354
|
+
await promises.writeFile(configPath, JSON.stringify(validated, null, 2), "utf-8");
|
|
3355
|
+
console.log(`✅ Saved project config to: ${configPath}`);
|
|
3356
|
+
}
|
|
3357
|
+
/**
|
|
3358
|
+
* Save project-local config to .bike4mind/local.json
|
|
3359
|
+
*/
|
|
3360
|
+
async saveProjectLocalConfig(config, projectDir) {
|
|
3361
|
+
const targetDir = projectDir || this.projectConfigDir || process.cwd();
|
|
3362
|
+
const configPath = path.join(targetDir, ".bike4mind", "local.json");
|
|
3363
|
+
await promises.mkdir(path.dirname(configPath), { recursive: true });
|
|
3364
|
+
const validated = ProjectLocalConfigSchema.parse(config);
|
|
3365
|
+
await promises.writeFile(configPath, JSON.stringify(validated, null, 2), "utf-8");
|
|
3366
|
+
await promises.chmod(configPath, 384);
|
|
3367
|
+
console.log(`✅ Saved project-local config to: ${configPath}`);
|
|
3368
|
+
}
|
|
3369
|
+
/**
|
|
3370
|
+
* Load raw project config (without merging)
|
|
3371
|
+
*/
|
|
3372
|
+
async loadRawProjectConfig() {
|
|
3373
|
+
if (!this.projectConfigDir) return null;
|
|
3374
|
+
return loadProjectConfig(this.projectConfigDir);
|
|
3375
|
+
}
|
|
3376
|
+
/**
|
|
3377
|
+
* Load raw project-local config (without merging)
|
|
3378
|
+
*/
|
|
3379
|
+
async loadRawProjectLocalConfig() {
|
|
3380
|
+
if (!this.projectConfigDir) return null;
|
|
3381
|
+
return loadProjectLocalConfig(this.projectConfigDir);
|
|
3382
|
+
}
|
|
3383
|
+
/**
|
|
3384
|
+
* Add a directory to the allowed directories list
|
|
3385
|
+
* Persists to global config
|
|
3386
|
+
*/
|
|
3387
|
+
async addDirectory(dirPath) {
|
|
3388
|
+
await this.load();
|
|
3389
|
+
const g = this.globalConfig;
|
|
3390
|
+
if (!g.additionalDirectories) g.additionalDirectories = [];
|
|
3391
|
+
const resolvedPath = path.resolve(dirPath);
|
|
3392
|
+
if (!g.additionalDirectories.includes(resolvedPath)) {
|
|
3393
|
+
g.additionalDirectories.push(resolvedPath);
|
|
3394
|
+
await this.save();
|
|
3395
|
+
}
|
|
3396
|
+
}
|
|
3397
|
+
/**
|
|
3398
|
+
* Remove a directory from the allowed directories list
|
|
3399
|
+
*/
|
|
3400
|
+
async removeDirectory(dirPath) {
|
|
3401
|
+
await this.load();
|
|
3402
|
+
const g = this.globalConfig;
|
|
3403
|
+
if (g.additionalDirectories) {
|
|
3404
|
+
const resolvedPath = path.resolve(dirPath);
|
|
3405
|
+
const remove = (config) => {
|
|
3406
|
+
config.additionalDirectories = (config.additionalDirectories || []).filter((d) => path.resolve(d) !== resolvedPath);
|
|
3407
|
+
};
|
|
3408
|
+
remove(g);
|
|
3409
|
+
const removed = (d) => typeof d === "string" && path.resolve(d) === resolvedPath;
|
|
3410
|
+
const revoke = (raw) => removeRawListItems(raw, "additionalDirectories", removed);
|
|
3411
|
+
if (await this.patchInFallback(remove, revoke)) return;
|
|
3412
|
+
await this.save();
|
|
3413
|
+
}
|
|
3414
|
+
}
|
|
3415
|
+
/**
|
|
3416
|
+
* Get all additional directories (global config + trusted-project config).
|
|
3417
|
+
* Returns resolved absolute paths. Project-declared directories are included
|
|
3418
|
+
* ONLY when the project is trusted, and each must resolve inside the project
|
|
3419
|
+
* root (a repo cannot widen file access beyond its own tree).
|
|
3420
|
+
*/
|
|
3421
|
+
async getAdditionalDirectories() {
|
|
3422
|
+
await this.load();
|
|
3423
|
+
const g = this.globalConfig;
|
|
3424
|
+
const dirs = /* @__PURE__ */ new Set();
|
|
3425
|
+
if (g.additionalDirectories) for (const dir of g.additionalDirectories) dirs.add(path.resolve(dir));
|
|
3426
|
+
if (this.projectTrusted && this.rawProjectConfig?.additionalDirectories) {
|
|
3427
|
+
const projectRoot = this.projectRealPath || this.projectConfigDir;
|
|
3428
|
+
if (projectRoot) for (const dir of this.rawProjectConfig.additionalDirectories) {
|
|
3429
|
+
const real = await safeRealpath(path.resolve(projectRoot, dir));
|
|
3430
|
+
if (real && isWithin(projectRoot, real)) dirs.add(real);
|
|
3431
|
+
else logger.warn(`Ignoring project additionalDirectory outside project root: ${dir}`);
|
|
3432
|
+
}
|
|
3433
|
+
}
|
|
3434
|
+
return Array.from(dirs);
|
|
3435
|
+
}
|
|
3436
|
+
};
|
|
3437
|
+
//#endregion
|
|
3438
|
+
export { NotAuthenticatedError as C, sanitizeTerminalText as D, escapeTerminalControlChars as E, LOCAL_DEV_URL as S, parseApiUrl as T, getEnvironmentName as _, fingerprintMcpServer as a, AuthenticatedApiClient as b, ToolCatalog as c, sandboxedCommandArg as d, toolCategory as f, getDefaultApiUrl as g, getCreditsUrl as h, REFRESH_LOCK_WAIT_MS as i, commandTextOf as l, ApiEndpointUnconfiguredError as m, McpToggleRefusedError as n, extractCompactInstructions as o, writePathOf as p, REFRESH_LOCK_STALE_MS as r, loadContextFiles as s, ConfigStore as t, isReadOnlyTool as u, requireApiUrl as v, SessionRevokedError as w, DeviceFlowClient as x, resolveApiEndpoint as y };
|