@bike4mind/cli 4.0.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +86 -4
  2. package/bin/bike4mind-cli.mjs +249 -40
  3. package/bin/envFlags.d.mts +17 -0
  4. package/bin/envFlags.mjs +89 -0
  5. package/dist/{AgentHistoryStore-DgqmcVLN.mjs → AgentHistoryStore--J3sgO_-.mjs} +3794 -1368
  6. package/dist/{ApiClient-_JrM_xWw.mjs → ApiClient-CdO4Gamg.mjs} +22 -3
  7. package/dist/BubblewrapRuntime-3jAbC60G.mjs +157 -0
  8. package/dist/ConfigStore-CausUCzY.mjs +2 -0
  9. package/dist/ConfigStore-Dusy6glb.mjs +3364 -0
  10. package/dist/{ConfigStore-BwqsQ0U9.mjs → Logger-C1Wj6xla.mjs} +32672 -21643
  11. package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
  12. package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-CQwYq_uy.mjs} +26 -7
  13. package/dist/SandboxRuntimeAdapter-BsT2iLky.mjs +190 -0
  14. package/dist/SandboxRuntimeAdapter-Zg_0th7V.mjs +2 -0
  15. package/dist/SeatbeltRuntime-C2DEkrjy.mjs +194 -0
  16. package/dist/{WorkItemsClient-CERTDrhT.mjs → WorkItemsClient-CxNZaOmc.mjs} +1 -1
  17. package/dist/agents/defaults/review.md +8 -1
  18. package/dist/agents/defaults/test.md +8 -1
  19. package/dist/buildToolSearch-DOb7mx6F.mjs +417 -0
  20. package/dist/commands/acpCommand.mjs +25 -19
  21. package/dist/commands/apiCommand.mjs +3 -5
  22. package/dist/commands/doctorCommand.mjs +2 -2
  23. package/dist/commands/envCommand.mjs +1 -1
  24. package/dist/commands/headlessCommand.mjs +117 -36
  25. package/dist/commands/hostCommand.mjs +2344 -0
  26. package/dist/commands/mcpCommand.mjs +45 -30
  27. package/dist/commands/mirrorCommand.mjs +279 -0
  28. package/dist/commands/modelsCommand.mjs +1117 -0
  29. package/dist/commands/pluginCommand.mjs +9 -9
  30. package/dist/commands/skillsCommand.mjs +174 -29
  31. package/dist/commands/updateCommand.mjs +2 -2
  32. package/dist/curated-build.json +1 -0
  33. package/dist/dist-CbViwiS9.mjs +4739 -0
  34. package/dist/dist-Citbv0y0.mjs +7864 -0
  35. package/dist/fit-CVWDiavv.mjs +200 -0
  36. package/dist/index.mjs +853 -417
  37. package/dist/modelHub-BSB6qRFP.mjs +1963 -0
  38. package/dist/modelServers-BaegigV-.mjs +2465 -0
  39. package/dist/{package-CQaam4Dq.mjs → package-C9pfAdGF.mjs} +1 -1
  40. package/dist/{serve-CFxUhjml.mjs → serve-8wyGb8of.mjs} +595 -26
  41. package/dist/types-BFIvwByC.mjs +2 -0
  42. package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
  43. package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-BAKb8KWP.mjs} +7 -29
  44. package/package.json +16 -13
  45. package/dist/BubblewrapRuntime-5bLPTwEC.mjs +0 -72
  46. package/dist/SandboxRuntimeAdapter-BgLUVTJL.mjs +0 -57
  47. package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +0 -2
  48. package/dist/SeatbeltRuntime-C_Y8q8Mr.mjs +0 -124
  49. package/dist/buildToolSearch-D9GEK91u.mjs +0 -2351
  50. package/dist/dist-Ul2qwn5x.mjs +0 -624
  51. package/dist/types-I45lMh7Q.mjs +0 -2
@@ -1,4 +1,7 @@
1
1
  #!/usr/bin/env node
2
+ import { mkdtempSync, rmSync } from "fs";
3
+ import os from "os";
4
+ import path from "path";
2
5
  import http from "http";
3
6
  import { EventEmitter } from "events";
4
7
  import net from "net";
@@ -189,16 +192,79 @@ var HttpConnectProxy = class extends EventEmitter {
189
192
  }
190
193
  };
191
194
  //#endregion
195
+ //#region src/sandbox/proxy/UnixSocketRelay.ts
196
+ /**
197
+ * Host-side unix socket that forwards each connection to the filtering proxy's loopback port.
198
+ * The Linux sandbox runs in a private network namespace, so this socket (bind-mounted into it,
199
+ * see BubblewrapRuntime) is its only route out.
200
+ */
201
+ var UnixSocketRelay = class {
202
+ constructor() {
203
+ this.listening = null;
204
+ this.activeSockets = /* @__PURE__ */ new Set();
205
+ }
206
+ async start(targetPort) {
207
+ if (this.listening) throw new Error("Proxy relay is already running");
208
+ const directory = mkdtempSync(path.join(os.tmpdir(), "b4m-proxy-"));
209
+ const socketPath = path.join(directory, "proxy.sock");
210
+ const removeDirectory = () => rmSync(directory, {
211
+ recursive: true,
212
+ force: true
213
+ });
214
+ const server = net.createServer((client) => {
215
+ const upstream = net.connect(targetPort, "127.0.0.1");
216
+ for (const socket of [client, upstream]) {
217
+ this.activeSockets.add(socket);
218
+ socket.on("close", () => this.activeSockets.delete(socket));
219
+ }
220
+ client.on("error", () => upstream.destroy());
221
+ upstream.on("error", () => client.destroy());
222
+ client.pipe(upstream).pipe(client);
223
+ });
224
+ try {
225
+ await new Promise((resolve, reject) => {
226
+ server.on("error", reject);
227
+ server.listen(socketPath, () => resolve());
228
+ });
229
+ } catch (error) {
230
+ removeDirectory();
231
+ throw error;
232
+ }
233
+ process.once("exit", removeDirectory);
234
+ this.listening = {
235
+ server,
236
+ socketPath,
237
+ removeDirectory
238
+ };
239
+ return socketPath;
240
+ }
241
+ async stop() {
242
+ if (!this.listening) return;
243
+ const { server, removeDirectory } = this.listening;
244
+ this.listening = null;
245
+ process.off("exit", removeDirectory);
246
+ for (const socket of this.activeSockets) socket.destroy();
247
+ this.activeSockets.clear();
248
+ await new Promise((resolve) => server.close(() => resolve()));
249
+ removeDirectory();
250
+ }
251
+ getSocketPath() {
252
+ return this.listening?.socketPath ?? null;
253
+ }
254
+ };
255
+ //#endregion
192
256
  //#region src/sandbox/proxy/ProxyManager.ts
193
257
  var ProxyManager = class {
194
- constructor(networkConfig) {
258
+ constructor(networkConfig, options = {}) {
195
259
  this.proxy = null;
260
+ this.relay = null;
196
261
  this.eventHandlers = /* @__PURE__ */ new Set();
197
262
  this.startPromise = null;
198
263
  this.networkConfig = {
199
264
  ...networkConfig,
200
265
  allowedDomains: [...networkConfig.allowedDomains]
201
266
  };
267
+ this.unixSocket = options.unixSocket === true;
202
268
  }
203
269
  /**
204
270
  * Update the live enabled flag so a runtime toggle takes effect on the next
@@ -222,10 +288,22 @@ var ProxyManager = class {
222
288
  this.proxy.on("proxy-event", (event) => {
223
289
  for (const handler of this.eventHandlers) handler(event);
224
290
  });
225
- await this.proxy.start();
291
+ const port = await this.proxy.start();
292
+ if (!this.unixSocket) return;
293
+ const relay = new UnixSocketRelay();
294
+ try {
295
+ await relay.start(port);
296
+ } catch (error) {
297
+ await this.proxy.stop();
298
+ this.proxy = null;
299
+ throw error;
300
+ }
301
+ this.relay = relay;
226
302
  }
227
303
  async stop() {
228
304
  if (this.startPromise) await this.startPromise.catch(() => {});
305
+ await this.relay?.stop();
306
+ this.relay = null;
229
307
  if (!this.proxy) return;
230
308
  await this.proxy.stop();
231
309
  this.proxy = null;
@@ -246,7 +324,10 @@ var ProxyManager = class {
246
324
  HTTPS_PROXY: proxyUrl,
247
325
  https_proxy: proxyUrl,
248
326
  NO_PROXY: noProxy,
249
- no_proxy: noProxy
327
+ no_proxy: noProxy,
328
+ ALL_PROXY: proxyUrl,
329
+ all_proxy: proxyUrl,
330
+ NODE_USE_ENV_PROXY: "1"
250
331
  };
251
332
  }
252
333
  addAllowedDomain(domain) {
@@ -264,6 +345,10 @@ var ProxyManager = class {
264
345
  getPort() {
265
346
  return this.proxy?.getPort() ?? null;
266
347
  }
348
+ /** Host path of the proxy's unix socket, or null when the manager was not asked for one. */
349
+ getSocketPath() {
350
+ return this.relay?.getSocketPath() ?? null;
351
+ }
267
352
  /**
268
353
  * Subscribe to proxy events. Returns an unsubscribe function.
269
354
  */
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { t as DEFAULT_SANDBOX_CONFIG } from "./types-F61_hxmG.mjs";
2
+ import { t as DEFAULT_SANDBOX_CONFIG } from "./types-CxrzVXel.mjs";
3
+ import { c as resolveSandboxPath } from "./SandboxRuntimeAdapter-BsT2iLky.mjs";
4
+ import path from "path";
3
5
  //#region src/sandbox/SandboxOrchestrator.ts
4
6
  var SandboxOrchestrator = class {
5
7
  constructor(config, runtime, proxyManager) {
@@ -11,6 +13,16 @@ var SandboxOrchestrator = class {
11
13
  };
12
14
  this.violationStore = null;
13
15
  this.config = structuredClone(config ?? DEFAULT_SANDBOX_CONFIG);
16
+ const fsConfig = this.config.filesystem;
17
+ fsConfig.deniedPaths = [.../* @__PURE__ */ new Set([...DEFAULT_SANDBOX_CONFIG.filesystem.deniedPaths, ...fsConfig.deniedPaths])];
18
+ const deniedPaths = fsConfig.deniedPaths.map(resolveSandboxPath);
19
+ fsConfig.allowedReadPaths = fsConfig.allowedReadPaths.filter((allowedPath) => {
20
+ const resolvedAllowedPath = resolveSandboxPath(allowedPath);
21
+ return !deniedPaths.some((deniedPath) => {
22
+ const relativePath = path.relative(deniedPath, resolvedAllowedPath);
23
+ return relativePath === "" || !relativePath.startsWith(`..${path.sep}`) && relativePath !== ".." && !path.isAbsolute(relativePath);
24
+ });
25
+ });
14
26
  this.runtime = runtime ?? null;
15
27
  this.proxyManager = proxyManager ?? null;
16
28
  }
@@ -23,7 +35,7 @@ var SandboxOrchestrator = class {
23
35
  * 3. If runtime is not available -> unsandboxed with warning
24
36
  * 4. Otherwise -> sandbox the command
25
37
  */
26
- shouldSandbox(command, cwd) {
38
+ shouldSandbox(command, cwd, validateWorkingDirectory) {
27
39
  if (!this.config.enabled || this.config.mode === "disabled") return {
28
40
  type: "unsandboxed",
29
41
  requiresPermission: true
@@ -45,14 +57,24 @@ var SandboxOrchestrator = class {
45
57
  requiresPermission: true,
46
58
  reason: "Sandbox runtime not available on this platform"
47
59
  };
60
+ const workingDirectoryError = validateWorkingDirectory?.(cwd);
61
+ if (workingDirectoryError) return {
62
+ type: "blocked",
63
+ reason: workingDirectoryError
64
+ };
48
65
  const proxyEnv = this.proxyManager?.getProxyEnv() ?? {};
66
+ const proxyPort = this.config.network.enabled && this.proxyManager?.isRunning() ? this.proxyManager.getPort() : null;
67
+ const proxySocketPath = proxyPort !== null ? this.proxyManager?.getSocketPath() : null;
49
68
  return {
50
69
  type: "sandbox",
51
70
  wrappedCommand: this.runtime.wrapCommand({
52
71
  command,
53
72
  cwd,
54
73
  filesystemConfig: this.config.filesystem,
55
- networkEnabled: this.config.network.enabled && (this.proxyManager?.isRunning() ?? false),
74
+ networkEnabled: proxyPort !== null,
75
+ ...proxyPort !== null && { proxyPort },
76
+ ...proxySocketPath && { proxySocketPath },
77
+ allowContainerSockets: this.config.allowContainerSockets === true,
56
78
  env: proxyEnv,
57
79
  ...this.runtime.platform === "linux" && this.config.platform.linux.seccompProfile && { seccompProfile: this.config.platform.linux.seccompProfile }
58
80
  })
@@ -84,10 +106,7 @@ var SandboxOrchestrator = class {
84
106
  * proxy in lockstep - this is the SINGLE lifecycle owner. Fail-closed: when
85
107
  * enabling, the proxy must be running afterwards or the flag stays false. The
86
108
  * flag is not trusted on its own either - shouldSandbox additionally gates on
87
- * proxyManager.isRunning(), so a stale network.enabled left by any other path
88
- * can never hand the runtime raw egress. Note the proxy only filters clients
89
- * that honor HTTP(S)_PROXY; raw sockets (`curl --noproxy`, `nc`) still egress
90
- * when network is on, so allowedDomains binds proxy-aware traffic only.
109
+ * proxyManager.isRunning().
91
110
  * Returns whether network is enabled on return. Does not persist - caller saves.
92
111
  */
93
112
  async setNetworkEnabled(enabled) {
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env node
2
+ import { accessSync, constants, lstatSync, readFileSync, realpathSync } from "fs";
3
+ import os from "os";
4
+ import path from "path";
5
+ //#region src/sandbox/runtime/SandboxRuntimeAdapter.ts
6
+ /**
7
+ * Abstract sandbox runtime adapter with platform detection and factory.
8
+ */
9
+ /** Docker, Podman, Colima, Lima, Rancher Desktop and OrbStack API sockets, or the directories holding them. */
10
+ function getContainerSocketPaths() {
11
+ const home = os.homedir();
12
+ const env = process.env;
13
+ const entries = [
14
+ {
15
+ path: "/var/run/docker.sock",
16
+ directory: false
17
+ },
18
+ {
19
+ path: "/run/docker.sock",
20
+ directory: false
21
+ },
22
+ {
23
+ path: "/run/podman",
24
+ directory: true
25
+ },
26
+ {
27
+ path: path.join(home, ".docker"),
28
+ directory: true
29
+ },
30
+ {
31
+ path: path.join(home, "Library", "Containers", "com.docker.docker", "Data"),
32
+ directory: true
33
+ },
34
+ {
35
+ path: path.join(home, ".colima"),
36
+ directory: true
37
+ },
38
+ {
39
+ path: path.join(home, ".lima"),
40
+ directory: true
41
+ },
42
+ {
43
+ path: path.join(home, ".rd"),
44
+ directory: true
45
+ },
46
+ {
47
+ path: path.join(home, ".orbstack"),
48
+ directory: true
49
+ },
50
+ {
51
+ path: path.join(home, ".local", "share", "containers"),
52
+ directory: true
53
+ },
54
+ {
55
+ path: path.join(os.tmpdir(), "podman"),
56
+ directory: true
57
+ }
58
+ ];
59
+ const addIfAbsolute = (p, directory) => {
60
+ if (p && path.isAbsolute(p)) entries.push({
61
+ path: p,
62
+ directory
63
+ });
64
+ };
65
+ if (env.XDG_RUNTIME_DIR && path.isAbsolute(env.XDG_RUNTIME_DIR)) {
66
+ addIfAbsolute(path.join(env.XDG_RUNTIME_DIR, "docker.sock"), false);
67
+ addIfAbsolute(path.join(env.XDG_RUNTIME_DIR, "podman"), true);
68
+ }
69
+ for (const host of [env.DOCKER_HOST, env.CONTAINER_HOST]) if (host?.startsWith("unix://")) addIfAbsolute(host.slice(7), false);
70
+ addIfAbsolute(env.COLIMA_HOME, true);
71
+ addIfAbsolute(env.LIMA_HOME, true);
72
+ const configHome = env.XDG_CONFIG_HOME && path.isAbsolute(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : path.join(home, ".config");
73
+ addIfAbsolute(path.join(configHome, "colima"), true);
74
+ return entries;
75
+ }
76
+ /** Rejects anything but a TCP port number before it is written into a profile or relay script. */
77
+ function assertProxyPort(port) {
78
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid sandbox proxy port: ${port}`);
79
+ }
80
+ /**
81
+ * Detect the current platform.
82
+ * Returns null if the platform is not supported for sandboxing.
83
+ */
84
+ function detectPlatform() {
85
+ const platform = os.platform();
86
+ if (platform === "darwin") return "darwin";
87
+ if (platform === "linux") return "linux";
88
+ return null;
89
+ }
90
+ /**
91
+ * Check if a binary exists on the system PATH.
92
+ * Uses pure filesystem checks instead of shell execution to avoid command injection.
93
+ */
94
+ function isBinaryAvailable(binary) {
95
+ const pathDirs = (process.env.PATH || "").split(path.delimiter);
96
+ for (const dir of pathDirs) try {
97
+ accessSync(path.join(dir, binary), constants.X_OK);
98
+ return true;
99
+ } catch {}
100
+ return false;
101
+ }
102
+ /**
103
+ * Expand environment variables ($HOME, $USER) in a path string.
104
+ */
105
+ function expandPath(pathStr) {
106
+ return pathStr.replace(/\$HOME/g, os.homedir()).replace(/\$USER/g, os.userInfo().username).replace(/~\//g, `${os.homedir()}/`);
107
+ }
108
+ /** Paths under cwd that stay read-only inside the writable working directory. */
109
+ function getProtectedWorkspacePaths(cwd) {
110
+ const git = findGitEntry(cwd);
111
+ const repositoryRoot = path.dirname(git);
112
+ const protectedPaths = /* @__PURE__ */ new Set([
113
+ path.join(cwd, ".git"),
114
+ path.join(cwd, ".bike4mind"),
115
+ git,
116
+ path.join(repositoryRoot, ".bike4mind")
117
+ ]);
118
+ let ancestor = cwd;
119
+ while (path.dirname(ancestor) !== ancestor) {
120
+ if ([".git", ".bike4mind"].includes(path.basename(ancestor))) protectedPaths.add(ancestor);
121
+ ancestor = path.dirname(ancestor);
122
+ }
123
+ const gitDirectory = readMetadataFile(git)?.match(/^gitdir:\s*(.+)\s*$/)?.[1];
124
+ if (gitDirectory) {
125
+ const metadataPath = path.resolve(repositoryRoot, gitDirectory.trim());
126
+ protectedPaths.add(metadataPath);
127
+ const commonDirectory = readMetadataFile(path.join(metadataPath, "commondir"))?.trim();
128
+ if (commonDirectory) protectedPaths.add(path.resolve(metadataPath, commonDirectory));
129
+ }
130
+ for (const protectedPath of [...protectedPaths]) protectedPaths.add(resolveSandboxPath(protectedPath));
131
+ return [...protectedPaths];
132
+ }
133
+ function findGitEntry(cwd) {
134
+ let directory = cwd;
135
+ while (true) {
136
+ const gitPath = path.join(directory, ".git");
137
+ try {
138
+ lstatSync(gitPath);
139
+ return gitPath;
140
+ } catch (error) {
141
+ if (!(error instanceof Error && "code" in error && ["ENOENT", "ENOTDIR"].includes(String(error.code)))) throw error;
142
+ }
143
+ const parentDirectory = path.dirname(directory);
144
+ if (parentDirectory === directory) return path.join(cwd, ".git");
145
+ directory = parentDirectory;
146
+ }
147
+ }
148
+ function readMetadataFile(filePath) {
149
+ try {
150
+ return readFileSync(filePath, "utf8");
151
+ } catch (error) {
152
+ if (error instanceof Error && "code" in error && [
153
+ "ENOENT",
154
+ "ENOTDIR",
155
+ "EISDIR"
156
+ ].includes(String(error.code))) return;
157
+ throw error;
158
+ }
159
+ }
160
+ /** Resolve aliases so sensitive symlinks are protected at their actual target. */
161
+ function resolveSandboxPath(pathString) {
162
+ const expandedPath = path.resolve(expandPath(pathString));
163
+ try {
164
+ return realpathSync(expandedPath);
165
+ } catch (error) {
166
+ if (error instanceof Error && "code" in error && ["ENOENT", "ENOTDIR"].includes(String(error.code))) {
167
+ const parentPath = path.dirname(expandedPath);
168
+ return parentPath === expandedPath ? expandedPath : path.join(resolveSandboxPath(parentPath), path.basename(expandedPath));
169
+ }
170
+ throw error;
171
+ }
172
+ }
173
+ /**
174
+ * Factory function to create the appropriate sandbox runtime for the current platform.
175
+ * Returns null if the platform is unsupported or the runtime binary is not available.
176
+ */
177
+ async function createSandboxRuntime() {
178
+ const platform = detectPlatform();
179
+ if (!platform) return null;
180
+ if (platform === "darwin") {
181
+ const { SeatbeltRuntime } = await import("./SeatbeltRuntime-C2DEkrjy.mjs");
182
+ const runtime = new SeatbeltRuntime();
183
+ return runtime.isAvailable() ? runtime : null;
184
+ }
185
+ const { BubblewrapRuntime } = await import("./BubblewrapRuntime-3jAbC60G.mjs");
186
+ const runtime = new BubblewrapRuntime();
187
+ return runtime.isAvailable() ? runtime : null;
188
+ }
189
+ //#endregion
190
+ export { getContainerSocketPaths as a, resolveSandboxPath as c, expandPath as i, createSandboxRuntime as n, getProtectedWorkspacePaths as o, detectPlatform as r, isBinaryAvailable as s, assertProxyPort as t };
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export { t as assertProxyPort, n as createSandboxRuntime, r as detectPlatform, i as expandPath, a as getContainerSocketPaths, o as getProtectedWorkspacePaths, s as isBinaryAvailable, c as resolveSandboxPath } from "./SandboxRuntimeAdapter-BsT2iLky.mjs";
@@ -0,0 +1,194 @@
1
+ #!/usr/bin/env node
2
+ import { t as logger } from "./Logger-C1Wj6xla.mjs";
3
+ import { a as getContainerSocketPaths, c as resolveSandboxPath, o as getProtectedWorkspacePaths, s as isBinaryAvailable, t as assertProxyPort } from "./SandboxRuntimeAdapter-BsT2iLky.mjs";
4
+ import { mkdtempSync, writeFileSync } from "fs";
5
+ import os from "os";
6
+ import path from "path";
7
+ //#region src/sandbox/runtime/SeatbeltRuntime.ts
8
+ /**
9
+ * macOS Seatbelt (sandbox-exec) runtime implementation.
10
+ *
11
+ * Generates dynamic Seatbelt profiles to restrict filesystem access.
12
+ * Uses Apple's Sandbox framework via the `sandbox-exec` CLI tool.
13
+ */
14
+ /**
15
+ * Escape a path for use in a Seatbelt profile.
16
+ *
17
+ * Seatbelt profiles use S-expression (Scheme-like) syntax where paths are
18
+ * enclosed in quoted strings. Only two characters need escaping:
19
+ * - Backslash (\): Must be doubled to prevent interpreting the next char as special.
20
+ * - Double quote ("): Must be escaped to prevent closing the string prematurely.
21
+ *
22
+ * Scheme syntax characters like (, ), and ; do NOT need escaping because they
23
+ * are only special at the expression parsing level. Inside a quoted string,
24
+ * they are treated as literal characters and cannot inject directives.
25
+ */
26
+ function escapeSeatbeltPath(p) {
27
+ return p.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
28
+ }
29
+ const MDNS_RESPONDER_SOCKET = "/private/var/run/mDNSResponder";
30
+ const DEVICE_WRITE_ALLOWS = [
31
+ "(allow file-write-data (literal \"/dev/null\"))",
32
+ "(allow file-write-data (literal \"/dev/zero\"))",
33
+ "(allow file-write-data (literal \"/dev/dtracehelper\"))",
34
+ "(allow file-write-data (subpath \"/dev/fd\"))"
35
+ ];
36
+ /** Unresolvable paths keep their rule at the unresolved location instead of failing profile generation. */
37
+ function resolveProfilePath(p) {
38
+ try {
39
+ return resolveSandboxPath(p);
40
+ } catch (error) {
41
+ if (error instanceof Error && "code" in error && [
42
+ "EACCES",
43
+ "ELOOP",
44
+ "EPERM"
45
+ ].includes(String(error.code))) {
46
+ logger.debug(`Sandbox: using unresolved profile path ${p}: ${error.code}`);
47
+ return p;
48
+ }
49
+ throw error;
50
+ }
51
+ }
52
+ /**
53
+ * Seatbelt matches a socket connect against the fully resolved path, so a symlink like
54
+ * /var/run/docker.sock is denied at its current target, resolved each time a profile is built.
55
+ * The write denies stop a socket in a writable directory from being renamed to an unlisted path,
56
+ * directly or by renaming one of its parent directories.
57
+ */
58
+ function containerSocketDenies() {
59
+ const network = /* @__PURE__ */ new Set();
60
+ const fileWrite = /* @__PURE__ */ new Set();
61
+ for (const entry of getContainerSocketPaths()) {
62
+ const resolvedParent = path.join(resolveProfilePath(path.dirname(entry.path)), path.basename(entry.path));
63
+ for (const candidate of [resolvedParent, resolveProfilePath(entry.path)]) {
64
+ const filter = entry.directory ? "subpath" : "path-literal";
65
+ const escaped = escapeSeatbeltPath(candidate);
66
+ network.add(`(deny network-outbound (remote unix-socket (${filter} "${escaped}")))`);
67
+ fileWrite.add(`(deny file-write* (${filter} "${escaped}"))`);
68
+ for (let dir = path.dirname(candidate); dir !== path.dirname(dir); dir = path.dirname(dir)) fileWrite.add(`(deny file-write* (path-literal "${escapeSeatbeltPath(dir)}"))`);
69
+ }
70
+ }
71
+ return {
72
+ network: [...network],
73
+ fileWrite: [...fileWrite]
74
+ };
75
+ }
76
+ var SeatbeltRuntime = class {
77
+ constructor() {
78
+ this.platform = "darwin";
79
+ this.name = "seatbelt";
80
+ }
81
+ isAvailable() {
82
+ return isBinaryAvailable("sandbox-exec");
83
+ }
84
+ /**
85
+ * Generate a Seatbelt profile string from the filesystem config.
86
+ *
87
+ * Strategy:
88
+ * - Start with (allow default) to permit most operations
89
+ * - Deny all file writes globally
90
+ * - Allow file writes only to the working directory
91
+ * - Deny all access to explicitly denied paths
92
+ * - Allow read access to explicitly allowed paths
93
+ */
94
+ generateProfile(options) {
95
+ const { cwd, filesystemConfig } = options;
96
+ const expandedDenied = filesystemConfig.deniedPaths.map(resolveSandboxPath);
97
+ const expandedAllowed = filesystemConfig.allowedReadPaths.map(resolveSandboxPath);
98
+ const containerDenies = options.allowContainerSockets ? null : containerSocketDenies();
99
+ const lines = [
100
+ "(version 1)",
101
+ "",
102
+ "; Start with permissive defaults (process exec, network, sysctl, etc.)",
103
+ "(allow default)",
104
+ ""
105
+ ];
106
+ lines.push("; Deny all network, then re-allow local unix sockets except the DNS resolver");
107
+ lines.push("(deny network*)");
108
+ lines.push("(allow network-outbound (remote unix-socket))");
109
+ lines.push("(allow network-inbound (local unix-socket))");
110
+ lines.push("(allow network-bind (local unix-socket))");
111
+ lines.push(`(deny network-outbound (remote unix-socket (path-literal "${MDNS_RESPONDER_SOCKET}")))`);
112
+ if (options.networkEnabled && options.proxyPort !== void 0) {
113
+ assertProxyPort(options.proxyPort);
114
+ lines.push("; Allow outbound loopback to the filtering proxy only");
115
+ lines.push("(allow network-bind (local ip \"localhost:*\"))");
116
+ lines.push("(allow network-inbound (local ip \"localhost:*\"))");
117
+ lines.push(`(allow network-outbound (remote ip "localhost:${options.proxyPort}"))`);
118
+ }
119
+ if (containerDenies) {
120
+ lines.push("; Keep container engine sockets out of reach");
121
+ lines.push(...containerDenies.network);
122
+ }
123
+ lines.push("");
124
+ if (filesystemConfig.writeOnlyToWorkingDir) {
125
+ lines.push("; Deny all file writes globally");
126
+ lines.push("(deny file-write*)");
127
+ lines.push("");
128
+ const writable = (p) => [.../* @__PURE__ */ new Set([p, resolveProfilePath(p)])];
129
+ lines.push("; Allow writes to working directory");
130
+ for (const p of writable(cwd)) lines.push(`(allow file-write* (subpath "${escapeSeatbeltPath(p)}"))`);
131
+ lines.push("");
132
+ lines.push("; Allow writes to temp directories");
133
+ lines.push(`(allow file-write* (subpath "/tmp"))`);
134
+ lines.push(`(allow file-write* (subpath "/private/tmp"))`);
135
+ for (const p of writable(os.tmpdir())) lines.push(`(allow file-write* (subpath "${escapeSeatbeltPath(p)}"))`);
136
+ lines.push("");
137
+ lines.push("; Allow writes to standard device files");
138
+ lines.push(...DEVICE_WRITE_ALLOWS);
139
+ lines.push("");
140
+ }
141
+ lines.push("; Keep protected workspace paths read-only");
142
+ for (const protectedPath of getProtectedWorkspacePaths(cwd)) lines.push(`(deny file-write* (subpath "${escapeSeatbeltPath(protectedPath)}"))`);
143
+ lines.push("");
144
+ if (containerDenies) {
145
+ lines.push("; Keep container engine sockets where they are");
146
+ lines.push(...containerDenies.fileWrite, "");
147
+ }
148
+ if (expandedAllowed.length > 0) {
149
+ lines.push("; Explicitly allowed read paths");
150
+ for (const allowedPath of expandedAllowed) lines.push(`(allow file-read* (subpath "${escapeSeatbeltPath(allowedPath)}"))`);
151
+ lines.push("");
152
+ }
153
+ if (expandedDenied.length > 0) {
154
+ lines.push("; Deny access to sensitive paths");
155
+ for (const deniedPath of expandedDenied) lines.push(`(deny file-read* file-write* (subpath "${escapeSeatbeltPath(deniedPath)}"))`);
156
+ lines.push("");
157
+ }
158
+ return lines.join("\n");
159
+ }
160
+ wrapCommand(options) {
161
+ try {
162
+ const profile = this.generateProfile(options);
163
+ const tmpDir = mkdtempSync(path.join(os.tmpdir(), "b4m-sandbox-"));
164
+ const profilePath = path.join(tmpDir, "sandbox.sb");
165
+ writeFileSync(profilePath, profile, "utf-8");
166
+ const args = [
167
+ "-f",
168
+ profilePath,
169
+ "bash",
170
+ "-c",
171
+ options.command
172
+ ];
173
+ const envEntries = Object.entries(options.env ?? {});
174
+ const envPrefix = envEntries.length > 0 ? envEntries.map(([k, v]) => `${k}=${shellEscape(v)}`).join(" ") + " " : "";
175
+ return {
176
+ executable: "sandbox-exec",
177
+ args,
178
+ env: options.env ?? {},
179
+ commandString: `${envPrefix}sandbox-exec -f ${profilePath} bash -c ${shellEscape(options.command)}`,
180
+ cleanupPaths: [profilePath, tmpDir]
181
+ };
182
+ } catch (err) {
183
+ throw new Error(`Failed to create sandbox profile: ${err instanceof Error ? err.message : String(err)}`);
184
+ }
185
+ }
186
+ };
187
+ /**
188
+ * Shell-escape a string for safe embedding in a command.
189
+ */
190
+ function shellEscape(str) {
191
+ return `'${str.replace(/'/g, "'\\''")}'`;
192
+ }
193
+ //#endregion
194
+ export { SeatbeltRuntime };
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { Vt as tokenEstimateMultiplier } from "./ConfigStore-BwqsQ0U9.mjs";
2
+ import { Bt as tokenEstimateMultiplier } from "./Logger-C1Wj6xla.mjs";
3
3
  import { v4 } from "uuid";
4
4
  import { get_encoding } from "tiktoken";
5
5
  //#region ../../b4m-core/utils/dist/calibratedTokenizer.mjs
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  description: Code quality analysis and review
3
- model: claude-sonnet-4-5-20250929
3
+ model: claude-sonnet-5-5
4
4
  allowed-tools:
5
5
  - file_read
6
6
  - grep_search
@@ -25,6 +25,7 @@ shared-context:
25
25
  You are a code review specialist. Your job is to analyze code quality and identify issues.
26
26
 
27
27
  ## Focus Areas
28
+
28
29
  - Code quality and best practices
29
30
  - Potential bugs and edge cases
30
31
  - Performance considerations
@@ -32,24 +33,30 @@ You are a code review specialist. Your job is to analyze code quality and identi
32
33
  - Maintainability and readability
33
34
 
34
35
  ## Review Process
36
+
35
37
  1. Understand the context and purpose of the code
36
38
  2. Check for common issues (error handling, edge cases, null checks)
37
39
  3. Verify consistent patterns with rest of codebase
38
40
  4. Look for security concerns (injection, XSS, etc.)
39
41
 
40
42
  ## Output Format
43
+
41
44
  Provide actionable feedback:
42
45
 
43
46
  ### Critical Issues
47
+
44
48
  - [file:line] Description of issue and why it matters
45
49
 
46
50
  ### Suggestions
51
+
47
52
  - [file:line] Improvement suggestion
48
53
 
49
54
  ### Positive Observations
55
+
50
56
  - What's done well (optional)
51
57
 
52
58
  ## Iteration Budget
59
+
53
60
  You have **$MAX_ITERATIONS iterations** for this task (thoroughness: $THOROUGHNESS). Plan your tool usage to complete within this budget. Prioritize the most impactful actions first.
54
61
 
55
62
  Be specific with file paths and line numbers. Focus on actionable feedback.