@codelia/runtime 0.1.90 → 0.1.93

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.
@@ -111,9 +111,21 @@ var resolveTuiConfig = async (workingDir) => {
111
111
  const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
112
112
  const effective = configRegistry.resolve([globalConfig, projectConfig]);
113
113
  return {
114
- theme: effective.tui?.theme
114
+ ...effective.tui?.theme ? { theme: effective.tui.theme } : {},
115
+ ...effective.tui?.color_scheme ? { color_scheme: effective.tui.color_scheme } : {},
116
+ ...effective.tui?.image_protocol ? { image_protocol: effective.tui.image_protocol } : {}
115
117
  };
116
118
  };
119
+ var resolveAgentsEnabled = async (workingDir) => {
120
+ const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
121
+ const effective = configRegistry.resolve([globalConfig, projectConfig]);
122
+ return effective.agents?.enabled ?? true;
123
+ };
124
+ var resolveAuthOAuthBrowser = async (workingDir) => {
125
+ const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
126
+ const effective = configRegistry.resolve([globalConfig, projectConfig]);
127
+ return effective.auth?.oauth_browser;
128
+ };
117
129
  var resolvePermissionsConfig = async (workingDir) => {
118
130
  const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
119
131
  const effective = configRegistry.resolve([globalConfig, projectConfig]);
@@ -294,7 +306,7 @@ var hasDefinedGroup = (group, value) => {
294
306
  case "permissions":
295
307
  return Array.isArray(value?.permissions?.allow) || Array.isArray(value?.permissions?.deny);
296
308
  case "tui":
297
- return typeof value?.tui?.theme === "string" && value.tui.theme.trim().length > 0;
309
+ return typeof value?.tui?.theme === "string" && value.tui.theme.trim().length > 0 || value?.tui?.color_scheme !== void 0 || value?.tui?.image_protocol !== void 0;
298
310
  default:
299
311
  return false;
300
312
  }
@@ -437,6 +449,8 @@ var sendNotificationAsync = async (state, notify) => {
437
449
  }
438
450
  await sendAsync(notify);
439
451
  };
452
+ var transportBackpressureEvents = 0;
453
+ var getTransportBackpressureEvents = () => transportBackpressureEvents;
440
454
  var send = (msg) => {
441
455
  const { payload, label } = serializeMessage(msg);
442
456
  const writable = process.stdout.write(payload, (error) => {
@@ -445,6 +459,7 @@ var send = (msg) => {
445
459
  }
446
460
  });
447
461
  if (!writable) {
462
+ transportBackpressureEvents += 1;
448
463
  debugLog(`transport.backpressure label=${label} bytes=${payload.length}`);
449
464
  }
450
465
  };
@@ -459,6 +474,7 @@ var sendAsync = async (msg) => new Promise((resolve) => {
459
474
  resolve();
460
475
  });
461
476
  if (!writable) {
477
+ transportBackpressureEvents += 1;
462
478
  debugLog(`transport.backpressure label=${label} bytes=${payload.length}`);
463
479
  }
464
480
  });
@@ -508,12 +524,12 @@ var sendRunContext = (state, runId, contextLeftPercent) => {
508
524
  })
509
525
  );
510
526
  };
511
- var sendRunDiagnostics = (state, params) => {
512
- sendNotification(state, notificationMessage("run.diagnostics", params));
513
- };
514
527
  var sendRunMetrics = (state, params) => {
515
528
  sendNotification(state, notificationMessage("run.metrics", params));
516
529
  };
530
+ var sendRunSummary = (state, params) => {
531
+ sendNotification(state, notificationMessage("run.summary", params));
532
+ };
517
533
 
518
534
  // src/rpc/protocol.ts
519
535
  var MAX_ISSUES = 10;
@@ -529,8 +545,18 @@ var schemaFor = (method, slot) => {
529
545
  throw new Error(`${method} is a notification without a result`);
530
546
  return spec.result;
531
547
  };
548
+ var cachedProtocolAssertRaw;
549
+ var cachedProtocolAssertEnabled = false;
550
+ var isProtocolAssertEnabled = () => {
551
+ const raw = process.env.CODELIA_TEST_PROTOCOL_ASSERT;
552
+ if (raw !== cachedProtocolAssertRaw) {
553
+ cachedProtocolAssertRaw = raw;
554
+ cachedProtocolAssertEnabled = raw === "1";
555
+ }
556
+ return cachedProtocolAssertEnabled;
557
+ };
532
558
  var assertOutgoing = (method, slot, value) => {
533
- if (process.env.CODELIA_PROTOCOL_ASSERT !== "1") return;
559
+ if (!isProtocolAssertEnabled()) return;
534
560
  const result = schemaFor(method, slot).safeParse(value);
535
561
  if (!result.success)
536
562
  throw new Error(
@@ -671,14 +697,14 @@ var readBrowserMode = (value) => {
671
697
  return null;
672
698
  };
673
699
  var hasSshSession = (env) => !!env.SSH_CONNECTION || !!env.SSH_CLIENT || !!env.SSH_TTY;
674
- var resolveOAuthBrowserMode = (env = process.env) => {
675
- const configured = readBrowserMode(env.CODELIA_OAUTH_BROWSER);
700
+ var resolveOAuthBrowserMode = (configuredMode, env = process.env) => {
701
+ const configured = readBrowserMode(configuredMode);
676
702
  if (configured) {
677
703
  return configured;
678
704
  }
679
705
  return hasSshSession(env) ? "manual" : "auto";
680
706
  };
681
- var shouldAutoOpenOAuthBrowser = (env = process.env) => resolveOAuthBrowserMode(env) === "auto";
707
+ var shouldAutoOpenOAuthBrowser = (configuredMode, env = process.env) => resolveOAuthBrowserMode(configuredMode, env) === "auto";
682
708
  var parseCallbackParams = (input) => {
683
709
  const trimmed = input.trim();
684
710
  if (!trimmed) {
@@ -851,7 +877,7 @@ var OPENAI_OAUTH_ORIGINATOR = "codelia";
851
877
  var OPENAI_OAUTH_USER_AGENT = "codelia-cli";
852
878
  var HTML_SUCCESS = "<!doctype html><html><head><title>codelia - Authorization successful</title></head><body><h2>Authorization successful</h2><p>You can close this window.</p></body></html>";
853
879
  var HTML_ERROR = (message) => `<!doctype html><html><head><title>codelia - Authorization failed</title></head><body><h2>Authorization failed</h2><pre>${message}</pre></body></html>`;
854
- var clientId = () => process.env.CODELIA_OPENAI_OAUTH_CLIENT_ID ?? DEFAULT_CLIENT_ID;
880
+ var clientId = () => DEFAULT_CLIENT_ID;
855
881
  var oauthPort = () => readPositiveIntEnv("CODELIA_OPENAI_OAUTH_PORT", DEFAULT_PORT);
856
882
  var buildAuthorizeUrl = (redirectUri, pkce, state) => {
857
883
  const params = new URLSearchParams({
@@ -1075,11 +1101,8 @@ var DEFAULT_CLIENT_ID2 = "app_EMoamEEZ73f0CkXaXp7hrann";
1075
1101
  var ISSUER2 = "https://auth.openai.com";
1076
1102
  var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
1077
1103
  var DEFAULT_INTERVAL_SECONDS = 5;
1078
- var clientId2 = () => process.env.CODELIA_OPENAI_OAUTH_CLIENT_ID ?? DEFAULT_CLIENT_ID2;
1079
- var deviceCodeTimeoutMs = () => readPositiveIntEnv(
1080
- "CODELIA_OPENAI_DEVICE_CODE_TIMEOUT_MS",
1081
- DEFAULT_TIMEOUT_MS
1082
- );
1104
+ var clientId2 = () => DEFAULT_CLIENT_ID2;
1105
+ var deviceCodeTimeoutMs = () => DEFAULT_TIMEOUT_MS;
1083
1106
  var cancelledError = () => new Error("device code login cancelled");
1084
1107
  var sleep = (ms, signal) => new Promise((resolve, reject) => {
1085
1108
  if (signal?.aborted) {
@@ -1795,7 +1818,10 @@ var AuthResolver = class _AuthResolver {
1795
1818
  if (!supportsPick || !supportsPrompt) {
1796
1819
  throw new Error("UI does not support auth prompts");
1797
1820
  }
1798
- const prefersDeviceCode = resolveOAuthBrowserMode() === "manual";
1821
+ const configuredBrowser = await resolveAuthOAuthBrowser(
1822
+ this.state.runtimeWorkingDir ?? void 0
1823
+ ).catch(() => void 0);
1824
+ const prefersDeviceCode = resolveOAuthBrowserMode(configuredBrowser) === "manual";
1799
1825
  const pick = await requestUiPick(this.state, {
1800
1826
  title: "How would you like to connect OpenAI?",
1801
1827
  items: prefersDeviceCode ? [
@@ -1854,7 +1880,10 @@ var AuthResolver = class _AuthResolver {
1854
1880
  throw new Error("UI does not support device code confirmation");
1855
1881
  }
1856
1882
  const session = await createOpenAiDeviceCodeSession();
1857
- const shouldAutoOpen = shouldAutoOpenOAuthBrowser();
1883
+ const configuredBrowser = await resolveAuthOAuthBrowser(
1884
+ this.state.runtimeWorkingDir ?? void 0
1885
+ ).catch(() => void 0);
1886
+ const shouldAutoOpen = shouldAutoOpenOAuthBrowser(configuredBrowser);
1858
1887
  const confirm = await requestUiConfirm(this.state, {
1859
1888
  title: "OpenAI device code",
1860
1889
  message: [
@@ -1897,7 +1926,10 @@ var AuthResolver = class _AuthResolver {
1897
1926
  if (!supportsConfirm) {
1898
1927
  throw new Error("UI does not support OAuth confirmation");
1899
1928
  }
1900
- const shouldAutoOpen = shouldAutoOpenOAuthBrowser();
1929
+ const configuredBrowser = await resolveAuthOAuthBrowser(
1930
+ this.state.runtimeWorkingDir ?? void 0
1931
+ ).catch(() => void 0);
1932
+ const shouldAutoOpen = shouldAutoOpenOAuthBrowser(configuredBrowser);
1901
1933
  const canPasteCallback = !shouldAutoOpen && supportsPrompt;
1902
1934
  const session = await createOAuthSession({
1903
1935
  callbackMode: canPasteCallback ? "paste" : "server"
@@ -1984,15 +2016,15 @@ var AuthResolver = class _AuthResolver {
1984
2016
  // src/permissions/shell-backend.ts
1985
2017
  import { spawn as spawn4, spawnSync as spawnSync3 } from "child_process";
1986
2018
  import {
1987
- lstatSync as lstatSync9,
2019
+ lstatSync as lstatSync11,
1988
2020
  mkdirSync as mkdirSync2,
1989
- mkdtempSync as mkdtempSync2,
1990
- realpathSync as realpathSync8,
1991
- rmSync as rmSync2,
1992
- statSync as statSync5
2021
+ mkdtempSync as mkdtempSync3,
2022
+ realpathSync as realpathSync9,
2023
+ rmSync as rmSync3,
2024
+ statSync as statSync6
1993
2025
  } from "fs";
1994
- import os2 from "os";
1995
- import path13 from "path";
2026
+ import os3 from "os";
2027
+ import path14 from "path";
1996
2028
  import { resolveStoragePaths as resolveStoragePaths3 } from "@codelia/storage";
1997
2029
 
1998
2030
  // src/sandbox/file-mutation-helper.ts
@@ -2113,13 +2145,19 @@ import {
2113
2145
  lstatSync,
2114
2146
  openSync as openSync2,
2115
2147
  readdirSync,
2148
+ readlinkSync,
2116
2149
  readSync,
2117
2150
  realpathSync,
2118
2151
  statSync
2119
2152
  } from "fs";
2153
+ import os from "os";
2120
2154
  import path4 from "path";
2121
2155
  var isMissing = (error) => error.code === "ENOENT";
2122
2156
  var metadataPathSize = 16 * 1024;
2157
+ var gitConfigMaxBytes = 256 * 1024;
2158
+ var maxSymlinkHops = 64;
2159
+ var maxConfigDepth = 8;
2160
+ var maxConfigFiles = 32;
2123
2161
  var readPointer = (filename, prefix) => {
2124
2162
  const fd = openSync2(
2125
2163
  filename,
@@ -2221,6 +2259,7 @@ var eligibleObjectDirectory = (gitDirectory, commonDirectory, marker) => {
2221
2259
  };
2222
2260
  var discoverGitMetadata = (directories, includeObjectDirectories) => {
2223
2261
  const readOnlyPaths = /* @__PURE__ */ new Set();
2262
+ const repositories = [];
2224
2263
  const reservedMarkers = /* @__PURE__ */ new Set();
2225
2264
  const objectDirectories = /* @__PURE__ */ new Map();
2226
2265
  const hookAliases = /* @__PURE__ */ new Map();
@@ -2245,22 +2284,47 @@ var discoverGitMetadata = (directories, includeObjectDirectories) => {
2245
2284
  readOnlyPaths.add(actual);
2246
2285
  return actual;
2247
2286
  };
2287
+ const rootDirectory = directories[0];
2288
+ const verifyLinkedWorktree = (gitDirectory, commonDirectory, actualMarker) => {
2289
+ try {
2290
+ if (gitDirectory === commonDirectory) return false;
2291
+ if (path4.dirname(gitDirectory) !== path4.join(commonDirectory, "worktrees"))
2292
+ return false;
2293
+ const backPointer = readPointer(path4.join(gitDirectory, "gitdir"), "");
2294
+ const resolvedBack = path4.resolve(gitDirectory, backPointer);
2295
+ const backStat = lstatSync(resolvedBack);
2296
+ if (backStat.isSymbolicLink() || !backStat.isFile()) return false;
2297
+ return realpathSync(path4.dirname(resolvedBack)) === path4.dirname(actualMarker) && realpathSync(resolvedBack) === actualMarker;
2298
+ } catch {
2299
+ return false;
2300
+ }
2301
+ };
2248
2302
  for (const directory of new Set(directories)) {
2303
+ const fromRoot = directory === rootDirectory;
2249
2304
  const marker = findMarker(directory);
2250
2305
  const localMarker = path4.join(directory, ".git");
2251
2306
  if (marker !== localMarker) reservedMarkers.add(localMarker);
2252
2307
  if (!marker) continue;
2253
2308
  if (readOnlyPaths.has(marker)) continue;
2309
+ const isWorkspaceRootRepo = fromRoot && marker === localMarker;
2310
+ const markerLstat = lstatSync(marker);
2254
2311
  const actualMarker = realpathSync(marker);
2255
2312
  readOnlyPaths.add(marker);
2256
2313
  readOnlyPaths.add(actualMarker);
2257
2314
  const markerInfo = statSync(actualMarker);
2258
- const gitDirectory = markerInfo.isDirectory() ? actualMarker : addDirectory(
2259
- path4.resolve(
2315
+ const directoryEntries = [];
2316
+ let gitDirectory;
2317
+ if (markerInfo.isDirectory()) {
2318
+ gitDirectory = actualMarker;
2319
+ directoryEntries.push(marker, actualMarker);
2320
+ } else {
2321
+ const location = path4.resolve(
2260
2322
  path4.dirname(marker),
2261
2323
  readPointer(actualMarker, "gitdir: ")
2262
- )
2263
- );
2324
+ );
2325
+ gitDirectory = addDirectory(location);
2326
+ directoryEntries.push(location, gitDirectory);
2327
+ }
2264
2328
  if (!statSync(path4.join(gitDirectory, "HEAD")).isFile())
2265
2329
  throw new Error("invalid_git_metadata_directory");
2266
2330
  const commonPointer = path4.join(gitDirectory, "commondir");
@@ -2270,19 +2334,34 @@ var discoverGitMetadata = (directories, includeObjectDirectories) => {
2270
2334
  } catch (error) {
2271
2335
  if (!isMissing(error)) throw error;
2272
2336
  recordObjects(gitDirectory, gitDirectory, actualMarker);
2337
+ repositories.push({
2338
+ gitDirectory,
2339
+ commonDirectory: gitDirectory,
2340
+ worktreeRoot: path4.dirname(actualMarker),
2341
+ directoryEntries,
2342
+ writable: isWorkspaceRootRepo && markerLstat.isDirectory() && !markerLstat.isSymbolicLink()
2343
+ });
2273
2344
  continue;
2274
2345
  }
2275
2346
  readOnlyPaths.add(commonPointer);
2276
2347
  readOnlyPaths.add(common);
2277
- const commonDirectory = addDirectory(
2278
- path4.resolve(gitDirectory, readPointer(common, ""))
2279
- );
2348
+ const commonLocation = path4.resolve(gitDirectory, readPointer(common, ""));
2349
+ const commonDirectory = addDirectory(commonLocation);
2350
+ directoryEntries.push(commonLocation, commonDirectory);
2280
2351
  if (!statSync(path4.join(commonDirectory, "objects")).isDirectory())
2281
2352
  throw new Error("invalid_git_common_directory");
2282
2353
  recordObjects(gitDirectory, commonDirectory, actualMarker);
2354
+ repositories.push({
2355
+ gitDirectory,
2356
+ commonDirectory,
2357
+ worktreeRoot: path4.dirname(actualMarker),
2358
+ directoryEntries,
2359
+ writable: isWorkspaceRootRepo && markerLstat.isFile() && !markerLstat.isSymbolicLink() && verifyLinkedWorktree(gitDirectory, commonDirectory, actualMarker)
2360
+ });
2283
2361
  }
2284
2362
  return Object.freeze({
2285
2363
  readOnlyPaths: Object.freeze([...readOnlyPaths].sort()),
2364
+ repositories: Object.freeze(repositories),
2286
2365
  reservedMarkers: Object.freeze([...reservedMarkers].sort()),
2287
2366
  objectDirectories: Object.freeze([...objectDirectories.values()]),
2288
2367
  hookAliases: Object.freeze([...hookAliases.values()])
@@ -2297,17 +2376,402 @@ var resolveGitMetadata = (directories, includeObjectDirectories) => {
2297
2376
  };
2298
2377
  var gitMetadataPaths = (...directories) => resolveGitMetadata(directories, false);
2299
2378
  var gitMetadataWithObjectDirectories = (...directories) => resolveGitMetadata(directories, true);
2379
+ var joinPreservingDotDot = (base, target) => {
2380
+ if (path4.isAbsolute(target)) return target;
2381
+ const separator = process.platform === "win32" ? path4.sep : "/";
2382
+ const trimmedBase = base.length > 1 && base.endsWith(separator) ? base.slice(0, -1) : base;
2383
+ return `${trimmedBase}${separator}${target}`;
2384
+ };
2385
+ var traceSymlinkHops = (target) => {
2386
+ const rawAbsolute = path4.isAbsolute(target) ? target : joinPreservingDotDot(process.cwd(), target);
2387
+ const root = path4.parse(rawAbsolute).root;
2388
+ const collected = /* @__PURE__ */ new Set([target, path4.resolve(rawAbsolute)]);
2389
+ let resolvedParts = [];
2390
+ let queue = rawAbsolute.slice(root.length).split(process.platform === "win32" ? /[\\/]/u : "/").filter(Boolean);
2391
+ let hops = 0;
2392
+ while (queue.length > 0) {
2393
+ const part = queue.shift();
2394
+ if (part === ".") continue;
2395
+ if (part === "..") {
2396
+ resolvedParts.pop();
2397
+ continue;
2398
+ }
2399
+ const candidate = path4.join(root, ...resolvedParts, part);
2400
+ const stat = lstatSync(candidate, { throwIfNoEntry: false });
2401
+ if (!stat) {
2402
+ if (queue.some((entry) => entry === ".."))
2403
+ throw new Error("reserved_path_unresolved");
2404
+ resolvedParts.push(part, ...queue.filter((entry) => entry !== "."));
2405
+ queue = [];
2406
+ break;
2407
+ }
2408
+ if (stat.isSymbolicLink()) {
2409
+ if (path4.dirname(candidate) !== root) collected.add(candidate);
2410
+ if (++hops > maxSymlinkHops) throw new Error("symlink_chain_too_deep");
2411
+ const referent = readlinkSync(candidate);
2412
+ const referentParts = referent.split(process.platform === "win32" ? /[\\/]/u : "/").filter(Boolean);
2413
+ if (path4.isAbsolute(referent)) resolvedParts = [];
2414
+ queue = [...referentParts, ...queue];
2415
+ continue;
2416
+ }
2417
+ resolvedParts.push(part);
2418
+ }
2419
+ collected.add(path4.join(root, ...resolvedParts));
2420
+ return [...collected];
2421
+ };
2422
+ var readBoundedTextFile = (filename) => {
2423
+ let fd;
2424
+ try {
2425
+ fd = openSync2(filename, constants2.O_RDONLY | (constants2.O_NONBLOCK ?? 0));
2426
+ } catch (error) {
2427
+ if (isMissing(error)) return void 0;
2428
+ throw error;
2429
+ }
2430
+ try {
2431
+ const stat = fstatSync2(fd);
2432
+ if (!stat.isFile() || stat.size > gitConfigMaxBytes)
2433
+ throw new Error("unreadable_git_config");
2434
+ const bytes = Buffer.alloc(stat.size + 1);
2435
+ const length = readSync(fd, bytes, 0, bytes.length, 0);
2436
+ if (length !== stat.size || length > gitConfigMaxBytes)
2437
+ throw new Error("unreadable_git_config");
2438
+ return new TextDecoder("utf-8", { fatal: true }).decode(
2439
+ bytes.subarray(0, length)
2440
+ );
2441
+ } finally {
2442
+ closeSync2(fd);
2443
+ }
2444
+ };
2445
+ var parseGitConfigValue = (raw) => {
2446
+ let result = "";
2447
+ let inQuotes = false;
2448
+ let pendingSpace = "";
2449
+ let i = 0;
2450
+ while (i < raw.length && (raw[i] === " " || raw[i] === " ")) i++;
2451
+ for (; i < raw.length; i++) {
2452
+ const ch = raw[i];
2453
+ if (ch === "\\") {
2454
+ if (i + 1 >= raw.length) {
2455
+ throw new Error("unsupported_git_config_continuation");
2456
+ }
2457
+ const next = raw[++i];
2458
+ if (pendingSpace) {
2459
+ result += pendingSpace;
2460
+ pendingSpace = "";
2461
+ }
2462
+ if (next === "n") result += "\n";
2463
+ else if (next === "t") result += " ";
2464
+ else if (next === "b") result += "\b";
2465
+ else if (next === '"' || next === "\\") result += next;
2466
+ else throw new Error("unsupported_git_config_escape");
2467
+ continue;
2468
+ }
2469
+ if (ch === '"') {
2470
+ if (pendingSpace && !inQuotes) {
2471
+ result += pendingSpace;
2472
+ pendingSpace = "";
2473
+ }
2474
+ inQuotes = !inQuotes;
2475
+ continue;
2476
+ }
2477
+ if (!inQuotes && (ch === "#" || ch === ";")) break;
2478
+ if (!inQuotes && (ch === " " || ch === " ")) {
2479
+ pendingSpace += ch;
2480
+ continue;
2481
+ }
2482
+ if (pendingSpace) {
2483
+ result += pendingSpace;
2484
+ pendingSpace = "";
2485
+ }
2486
+ result += ch;
2487
+ }
2488
+ if (inQuotes) throw new Error("unterminated_git_config_quote");
2489
+ return result;
2490
+ };
2491
+ var parseIrrelevantLineContinuation = (raw, initialInQuotes = false) => {
2492
+ let inQuotes = initialInQuotes;
2493
+ for (let i = 0; i < raw.length; i++) {
2494
+ const ch = raw[i];
2495
+ if (ch === "\\") {
2496
+ if (i + 1 >= raw.length) {
2497
+ return { continues: true, inQuotes };
2498
+ }
2499
+ i++;
2500
+ continue;
2501
+ }
2502
+ if (ch === '"') {
2503
+ inQuotes = !inQuotes;
2504
+ continue;
2505
+ }
2506
+ if (!inQuotes && (ch === "#" || ch === ";")) {
2507
+ return { continues: false, inQuotes: false };
2508
+ }
2509
+ }
2510
+ return { continues: false, inQuotes: false };
2511
+ };
2512
+ var expandGitHome = (value) => {
2513
+ if (value === "~") return os.homedir();
2514
+ if (value.startsWith("~/")) return path4.join(os.homedir(), value.slice(2));
2515
+ return value;
2516
+ };
2517
+ var collectGitConfigProtectedPaths = (configPath, worktreeRoot, seen, depth) => {
2518
+ if (depth > maxConfigDepth || seen.size >= maxConfigFiles)
2519
+ throw new Error("git_config_include_limit");
2520
+ let canonicalConfig = configPath;
2521
+ try {
2522
+ canonicalConfig = realpathSync(configPath);
2523
+ } catch (error) {
2524
+ if (isMissing(error)) return [];
2525
+ throw error;
2526
+ }
2527
+ const openedConfigDir = path4.dirname(configPath);
2528
+ const seenKey = `${openedConfigDir}\0${canonicalConfig}`;
2529
+ if (seen.has(seenKey)) return [];
2530
+ seen.add(seenKey);
2531
+ const content = readBoundedTextFile(canonicalConfig);
2532
+ if (content === void 0) return [];
2533
+ const results = [];
2534
+ const recordReferencedDirective = (directiveSection, rawValue) => {
2535
+ const parsed = parseGitConfigValue(rawValue);
2536
+ if (!parsed) throw new Error("empty_git_config_path");
2537
+ const expanded = expandGitHome(parsed);
2538
+ if (directiveSection === "core") {
2539
+ const bases2 = /* @__PURE__ */ new Set([
2540
+ ...worktreeRoot ? [worktreeRoot] : [],
2541
+ openedConfigDir
2542
+ ]);
2543
+ for (const base of bases2) {
2544
+ results.push({
2545
+ path: path4.isAbsolute(expanded) ? expanded : joinPreservingDotDot(base, expanded),
2546
+ kind: "hooks"
2547
+ });
2548
+ }
2549
+ return;
2550
+ }
2551
+ const target = path4.isAbsolute(expanded) ? expanded : joinPreservingDotDot(openedConfigDir, expanded);
2552
+ results.push({ path: target, kind: "config" });
2553
+ results.push(
2554
+ ...collectGitConfigProtectedPaths(target, worktreeRoot, seen, depth + 1)
2555
+ );
2556
+ };
2557
+ let section = "";
2558
+ let continuingIrrelevantLine = false;
2559
+ let continuingIrrelevantQuotes = false;
2560
+ for (const rawLine of content.split(/\r?\n/u)) {
2561
+ const trimmed = rawLine.trim();
2562
+ if (continuingIrrelevantLine) {
2563
+ const state = parseIrrelevantLineContinuation(
2564
+ rawLine,
2565
+ continuingIrrelevantQuotes
2566
+ );
2567
+ continuingIrrelevantLine = state.continues;
2568
+ continuingIrrelevantQuotes = state.inQuotes;
2569
+ continue;
2570
+ }
2571
+ if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";"))
2572
+ continue;
2573
+ if (trimmed.startsWith("[")) {
2574
+ const header = /^\[([A-Za-z0-9-]+)(?:\s+"(?:[^"\\]|\\.)*"|\.[A-Za-z0-9.-]+)?\s*\](.*)$/u.exec(
2575
+ trimmed
2576
+ );
2577
+ if (!header) throw new Error("unsupported_git_config_section");
2578
+ section = header[1].toLowerCase();
2579
+ const rest = header[2].trim();
2580
+ if (!rest || rest.startsWith("#") || rest.startsWith(";")) continue;
2581
+ const eq2 = rest.indexOf("=");
2582
+ if (eq2 < 0) continue;
2583
+ const key2 = rest.slice(0, eq2).trim().toLowerCase();
2584
+ const rawValue2 = rest.slice(eq2 + 1);
2585
+ if ((section === "include" || section === "includeif") && key2 === "path" || section === "core" && key2 === "hookspath") {
2586
+ recordReferencedDirective(section, rawValue2);
2587
+ } else {
2588
+ const state = parseIrrelevantLineContinuation(rawValue2);
2589
+ continuingIrrelevantLine = state.continues;
2590
+ continuingIrrelevantQuotes = state.inQuotes;
2591
+ }
2592
+ continue;
2593
+ }
2594
+ const eq = rawLine.indexOf("=");
2595
+ if (eq < 0) {
2596
+ const bareKey = trimmed.replace(/[#;].*$/u, "").trim().toLowerCase();
2597
+ if ((section === "include" || section === "includeif") && bareKey === "path" || section === "core" && bareKey === "hookspath")
2598
+ throw new Error("empty_git_config_path");
2599
+ continue;
2600
+ }
2601
+ const key = rawLine.slice(0, eq).trim().toLowerCase();
2602
+ const rawValue = rawLine.slice(eq + 1);
2603
+ if ((section === "include" || section === "includeif") && key === "path" || section === "core" && key === "hookspath") {
2604
+ recordReferencedDirective(section, rawValue);
2605
+ } else {
2606
+ const state = parseIrrelevantLineContinuation(rawValue);
2607
+ continuingIrrelevantLine = state.continues;
2608
+ continuingIrrelevantQuotes = state.inQuotes;
2609
+ }
2610
+ }
2611
+ return results;
2612
+ };
2613
+ var externalGitConfigFiles = () => {
2614
+ const files = /* @__PURE__ */ new Set();
2615
+ const home = os.homedir();
2616
+ const xdgConfigHome = process.env.XDG_CONFIG_HOME && path4.isAbsolute(process.env.XDG_CONFIG_HOME) ? process.env.XDG_CONFIG_HOME : path4.join(home, ".config");
2617
+ if (process.env.GIT_CONFIG_GLOBAL) {
2618
+ files.add(process.env.GIT_CONFIG_GLOBAL);
2619
+ } else {
2620
+ files.add(path4.join(home, ".gitconfig"));
2621
+ files.add(path4.join(xdgConfigHome, "git", "config"));
2622
+ }
2623
+ if (process.env.GIT_CONFIG_NOSYSTEM !== "1") {
2624
+ files.add(process.env.GIT_CONFIG_SYSTEM || "/etc/gitconfig");
2625
+ }
2626
+ return [...files];
2627
+ };
2628
+ var gitWriteScope = (repositories) => {
2629
+ const writeRoots = /* @__PURE__ */ new Set();
2630
+ const readOnly = /* @__PURE__ */ new Set();
2631
+ const released = /* @__PURE__ */ new Set();
2632
+ for (const {
2633
+ gitDirectory,
2634
+ commonDirectory,
2635
+ worktreeRoot,
2636
+ directoryEntries,
2637
+ writable
2638
+ } of repositories) {
2639
+ if (!writable) continue;
2640
+ const repoReadOnly = /* @__PURE__ */ new Set();
2641
+ const addProtected = (entry) => {
2642
+ for (const hop of traceSymlinkHops(entry)) repoReadOnly.add(hop);
2643
+ };
2644
+ const protectHooksDirectory = (hooksPath) => {
2645
+ addProtected(hooksPath);
2646
+ let resolvedHooks;
2647
+ try {
2648
+ const real = realpathSync(hooksPath);
2649
+ if (statSync(real).isDirectory()) resolvedHooks = real;
2650
+ } catch (error) {
2651
+ if (!["ENOENT", "ENOTDIR", "ELOOP", "EACCES", "EPERM"].includes(
2652
+ error.code ?? ""
2653
+ ))
2654
+ throw error;
2655
+ }
2656
+ if (resolvedHooks) {
2657
+ for (const entry of readdirSync(resolvedHooks, {
2658
+ withFileTypes: true
2659
+ })) {
2660
+ if (entry.isSymbolicLink())
2661
+ addProtected(path4.join(resolvedHooks, entry.name));
2662
+ }
2663
+ }
2664
+ };
2665
+ try {
2666
+ const objectsDirectory = path4.join(commonDirectory, "objects");
2667
+ const objectsInfo = path4.join(objectsDirectory, "info");
2668
+ const configFiles = [
2669
+ path4.join(commonDirectory, "config"),
2670
+ path4.join(commonDirectory, "config.worktree"),
2671
+ path4.join(gitDirectory, "config.worktree")
2672
+ ];
2673
+ for (const entry of [
2674
+ ...configFiles,
2675
+ path4.join(commonDirectory, "hooks"),
2676
+ path4.join(commonDirectory, "commondir"),
2677
+ path4.join(gitDirectory, "commondir"),
2678
+ path4.join(gitDirectory, "gitdir"),
2679
+ ...gitObjectStoreConfigPaths(objectsDirectory),
2680
+ path4.join(commonDirectory, "remotes"),
2681
+ path4.join(commonDirectory, "branches"),
2682
+ path4.join(commonDirectory, "modules"),
2683
+ // Rebase/sequencer todo files can contain `exec <cmd>` lines that
2684
+ // execute during a later unconfined `git rebase --continue`.
2685
+ path4.join(commonDirectory, "rebase-merge"),
2686
+ path4.join(commonDirectory, "rebase-apply"),
2687
+ path4.join(commonDirectory, "sequencer"),
2688
+ path4.join(gitDirectory, "rebase-merge"),
2689
+ path4.join(gitDirectory, "rebase-apply"),
2690
+ path4.join(gitDirectory, "sequencer")
2691
+ ])
2692
+ addProtected(entry);
2693
+ if (lstatSync(objectsInfo, { throwIfNoEntry: false })?.isSymbolicLink()) {
2694
+ const hops = traceSymlinkHops(objectsInfo);
2695
+ for (const hop of hops) repoReadOnly.add(hop);
2696
+ const targetInfo = hops[hops.length - 1];
2697
+ if (targetInfo) {
2698
+ addProtected(path4.join(targetInfo, "alternates"));
2699
+ addProtected(path4.join(targetInfo, "http-alternates"));
2700
+ }
2701
+ }
2702
+ protectHooksDirectory(path4.join(commonDirectory, "hooks"));
2703
+ const siblingConfigs = [];
2704
+ const worktrees = path4.join(commonDirectory, "worktrees");
2705
+ if (lstatSync(worktrees, { throwIfNoEntry: false })?.isDirectory()) {
2706
+ for (const entry of readdirSync(worktrees, { withFileTypes: true })) {
2707
+ if (!entry.isDirectory()) continue;
2708
+ const siblingDir = path4.join(worktrees, entry.name);
2709
+ for (const name of [
2710
+ "gitdir",
2711
+ "commondir",
2712
+ "config.worktree",
2713
+ "rebase-merge",
2714
+ "rebase-apply",
2715
+ "sequencer"
2716
+ ])
2717
+ addProtected(path4.join(siblingDir, name));
2718
+ let siblingWorktreeRoot;
2719
+ try {
2720
+ const pointer = readPointer(path4.join(siblingDir, "gitdir"), "");
2721
+ siblingWorktreeRoot = path4.dirname(
2722
+ realpathSync(path4.resolve(siblingDir, pointer))
2723
+ );
2724
+ } catch {
2725
+ siblingWorktreeRoot = void 0;
2726
+ }
2727
+ siblingConfigs.push({
2728
+ file: path4.join(siblingDir, "config.worktree"),
2729
+ worktreeRoot: siblingWorktreeRoot
2730
+ });
2731
+ }
2732
+ }
2733
+ const seenConfigs = /* @__PURE__ */ new Set();
2734
+ const configSources = [
2735
+ ...configFiles.map((file) => ({ file, worktreeRoot })),
2736
+ ...siblingConfigs,
2737
+ ...externalGitConfigFiles().map((file) => ({ file, worktreeRoot }))
2738
+ ];
2739
+ for (const source of configSources) {
2740
+ for (const referenced of collectGitConfigProtectedPaths(
2741
+ source.file,
2742
+ source.worktreeRoot,
2743
+ seenConfigs,
2744
+ 0
2745
+ )) {
2746
+ if (referenced.kind === "hooks")
2747
+ protectHooksDirectory(referenced.path);
2748
+ else addProtected(referenced.path);
2749
+ }
2750
+ }
2751
+ writeRoots.add(gitDirectory);
2752
+ writeRoots.add(commonDirectory);
2753
+ for (const entry of directoryEntries) released.add(entry);
2754
+ for (const entry of repoReadOnly) readOnly.add(entry);
2755
+ } catch {
2756
+ }
2757
+ }
2758
+ return Object.freeze({
2759
+ writeRoots: Object.freeze([...writeRoots].sort()),
2760
+ readOnlyPaths: Object.freeze([...readOnly].sort()),
2761
+ releasedPaths: Object.freeze([...released].sort())
2762
+ });
2763
+ };
2300
2764
 
2301
2765
  // src/permissions/home-dot-paths.ts
2302
- import { readdirSync as readdirSync2, readlinkSync as readlinkSync2 } from "fs";
2303
- import os from "os";
2766
+ import { lstatSync as lstatSync3, readdirSync as readdirSync2, readlinkSync as readlinkSync3 } from "fs";
2767
+ import os2 from "os";
2304
2768
  import path6 from "path";
2305
2769
 
2306
2770
  // src/permissions/resource-paths.ts
2307
2771
  import {
2308
2772
  lstatSync as lstatSync2,
2309
2773
  opendirSync,
2310
- readlinkSync,
2774
+ readlinkSync as readlinkSync2,
2311
2775
  realpathSync as realpathSync2
2312
2776
  } from "fs";
2313
2777
  import path5 from "path";
@@ -2378,7 +2842,7 @@ function resolveReservedTarget(target, remaining = 64) {
2378
2842
  const canonicalParent = resolveReservedTarget(parent, remaining - 1);
2379
2843
  if (!lstatSync2(target, { throwIfNoEntry: false })?.isSymbolicLink())
2380
2844
  return path5.join(canonicalParent, path5.basename(target));
2381
- const referent = readlinkSync(target);
2845
+ const referent = readlinkSync2(target);
2382
2846
  let seenName = false;
2383
2847
  for (const part of referent.split(
2384
2848
  process.platform === "win32" ? /[\\/]/u : "/"
@@ -2395,7 +2859,7 @@ function resolveReservedTarget(target, remaining = 64) {
2395
2859
  }
2396
2860
 
2397
2861
  // src/permissions/home-dot-paths.ts
2398
- var homeDotDirectory = (writeRoots, home = os.homedir()) => {
2862
+ var homeDotDirectory = (writeRoots, home = os2.homedir()) => {
2399
2863
  if (!writeRoots.length) return void 0;
2400
2864
  const canonicalHome = resolveReservedTarget(home);
2401
2865
  return writeRoots.some(
@@ -2417,7 +2881,7 @@ var hasClosedHomeDotCycle = (home, start) => {
2417
2881
  seen.add(current);
2418
2882
  let link;
2419
2883
  try {
2420
- link = readlinkSync2(current);
2884
+ link = readlinkSync3(current);
2421
2885
  } catch {
2422
2886
  return false;
2423
2887
  }
@@ -2442,23 +2906,50 @@ var homeDotLinkTargets = (home) => readdirSync2(home, { withFileTypes: true }).f
2442
2906
  }
2443
2907
  });
2444
2908
  var isHomeWriteReserved = (home, target) => isHomeDotTarget(home, target) || homeDotLinkTargets(home).some((link) => resourceContainsPath(link, target));
2909
+ var MAX_HOME_DOT_ALIAS_ENTRIES = 8192;
2910
+ var hasHomeDotHardLinkAliases = (home) => {
2911
+ const pending = [];
2912
+ try {
2913
+ for (const entry of readdirSync2(home, { withFileTypes: true })) {
2914
+ if (!entry.name.startsWith(".") || entry.isSymbolicLink()) continue;
2915
+ pending.push(path6.join(home, entry.name));
2916
+ }
2917
+ const visited = /* @__PURE__ */ new Set();
2918
+ while (pending.length) {
2919
+ const current = pending.pop();
2920
+ if (!current || visited.has(current)) continue;
2921
+ visited.add(current);
2922
+ if (visited.size > MAX_HOME_DOT_ALIAS_ENTRIES) return true;
2923
+ const info = lstatSync3(current, { bigint: true });
2924
+ if (info.isSymbolicLink()) continue;
2925
+ if ((info.isFile() || info.isSocket() || info.isFIFO()) && info.nlink > 1n)
2926
+ return true;
2927
+ if (info.isDirectory()) {
2928
+ for (const child of readdirSync2(current)) {
2929
+ pending.push(path6.join(current, child));
2930
+ }
2931
+ }
2932
+ }
2933
+ return false;
2934
+ } catch {
2935
+ return true;
2936
+ }
2937
+ };
2445
2938
 
2446
- // src/permissions/linux-shell-backend.ts
2447
- import { spawn as spawn2, spawnSync } from "child_process";
2939
+ // src/permissions/linux-mxc-backend.ts
2448
2940
  import {
2449
2941
  accessSync as accessSync2,
2450
2942
  constants as constants4,
2451
- lstatSync as lstatSync5,
2452
- mkdirSync,
2943
+ lstatSync as lstatSync7,
2453
2944
  mkdtempSync,
2454
- readdirSync as readdirSync5,
2455
- readFileSync as readFileSync3,
2456
- realpathSync as realpathSync5,
2945
+ readdirSync as readdirSync6,
2946
+ readFileSync as readFileSync4,
2947
+ realpathSync as realpathSync6,
2457
2948
  rmSync,
2458
- statSync as statSync3,
2459
- writeFileSync
2949
+ statSync as statSync4
2460
2950
  } from "fs";
2461
- import path10 from "path";
2951
+ import { homedir } from "os";
2952
+ import path11 from "path";
2462
2953
 
2463
2954
  // src/permissions/linux-mountinfo.ts
2464
2955
  import { readFileSync as readFileSync2 } from "fs";
@@ -2545,21 +3036,283 @@ function executableMountSnapshot(file, dev, text = readFileSync2("/proc/self/mou
2545
3036
  ).map(({ line }) => line).join("\n");
2546
3037
  }
2547
3038
 
2548
- // src/permissions/protected-aliases.ts
3039
+ // src/permissions/mxc-launcher.ts
3040
+ import { spawn as spawn2, spawnSync } from "child_process";
2549
3041
  import {
2550
- lstatSync as lstatSync3,
3042
+ lstatSync as lstatSync4,
2551
3043
  readdirSync as readdirSync3,
2552
- realpathSync as realpathSync3
3044
+ readFileSync as readFileSync3,
3045
+ realpathSync as realpathSync3,
3046
+ statSync as statSync2
2553
3047
  } from "fs";
2554
3048
  import path8 from "path";
3049
+ import { fileURLToPath } from "url";
3050
+ var binaryName = "codelia-mxc-launcher";
3051
+ var MXC_PROTOCOL_VERSION = 3;
3052
+ var MAX_MXC_FRAME_BYTES = 256 * 1024;
3053
+ var supportedMxcPackages = /* @__PURE__ */ new Map([
3054
+ ["darwin-arm64", "@codelia/tui-darwin-arm64"],
3055
+ ["linux-x64", "@codelia/tui-linux-x64"],
3056
+ ["linux-arm64", "@codelia/tui-linux-arm64"]
3057
+ ]);
3058
+ var moduleDir = typeof __dirname === "string" ? __dirname : path8.dirname(fileURLToPath(import.meta.url));
3059
+ var helperCwd = () => process.platform === "darwin" ? "/private/tmp" : "/tmp";
3060
+ var packageVersion = (directory, name) => {
3061
+ try {
3062
+ const manifest = path8.join(directory, "package.json");
3063
+ const info = lstatSync4(manifest);
3064
+ if (!info.isFile() || info.size > 64 * 1024) return void 0;
3065
+ const parsed = JSON.parse(readFileSync3(manifest, "utf8"));
3066
+ return parsed.name === name && typeof parsed.version === "string" ? parsed.version : void 0;
3067
+ } catch {
3068
+ return void 0;
3069
+ }
3070
+ };
3071
+ var directoryId = (info) => `${info.dev}:${info.ino}`;
3072
+ var isTrustedCargoSubdir = (info, writableDirs, uid) => info.isDirectory() && !writableDirs.has(directoryId(info)) && (info.uid === uid || info.uid === 0n) && (info.mode & 0o022n) === 0n;
3073
+ var MAX_CARGO_LINK_SCAN_DEPTH = 6;
3074
+ var MAX_CARGO_LINK_SCAN_ENTRIES = 1e5;
3075
+ var SKIPPED_CARGO_SUBDIRS = /* @__PURE__ */ new Set([".fingerprint", "incremental"]);
3076
+ var accountsForCargoTargetLinks = (directory, launcherFile, info, writableDirs, uid) => {
3077
+ if (info.nlink === 1n) return true;
3078
+ const targetDir = path8.dirname(directory);
3079
+ const queue = [
3080
+ { dir: directory, depth: 0 }
3081
+ ];
3082
+ for (const sibling of ["build", "deps"]) {
3083
+ const root = path8.join(targetDir, sibling);
3084
+ const rootInfo = lstatSync4(root, { bigint: true, throwIfNoEntry: false });
3085
+ if (rootInfo && isTrustedCargoSubdir(rootInfo, writableDirs, uid)) {
3086
+ queue.push({ dir: root, depth: 0 });
3087
+ }
3088
+ }
3089
+ let accounted = 1n;
3090
+ let visited = 0;
3091
+ for (let head = 0; head < queue.length; head += 1) {
3092
+ const item = queue[head];
3093
+ if (!item || item.depth > MAX_CARGO_LINK_SCAN_DEPTH) continue;
3094
+ let names;
3095
+ try {
3096
+ names = readdirSync3(item.dir);
3097
+ } catch {
3098
+ continue;
3099
+ }
3100
+ names.sort((left, right) => {
3101
+ const leftPriority = left.includes("codelia") ? 0 : 1;
3102
+ const rightPriority = right.includes("codelia") ? 0 : 1;
3103
+ return leftPriority - rightPriority;
3104
+ });
3105
+ for (const name of names) {
3106
+ if (SKIPPED_CARGO_SUBDIRS.has(name)) continue;
3107
+ if (++visited > MAX_CARGO_LINK_SCAN_ENTRIES) return false;
3108
+ const entryPath = path8.join(item.dir, name);
3109
+ if (entryPath === launcherFile) continue;
3110
+ const child = lstatSync4(entryPath, {
3111
+ bigint: true,
3112
+ throwIfNoEntry: false
3113
+ });
3114
+ if (!child) continue;
3115
+ if (child.isFile() && child.dev === info.dev && child.ino === info.ino) {
3116
+ accounted += 1n;
3117
+ if (accounted === info.nlink) return true;
3118
+ } else if (item.depth < MAX_CARGO_LINK_SCAN_DEPTH && child.isDirectory() && isTrustedCargoSubdir(child, writableDirs, uid)) {
3119
+ queue.push({ dir: entryPath, depth: item.depth + 1 });
3120
+ }
3121
+ }
3122
+ }
3123
+ return accounted === info.nlink;
3124
+ };
3125
+ var trustedLauncher = (candidate, writableDirs, uid, protectedHome, allowCargoTargetLinks = false) => {
3126
+ try {
3127
+ const directory = realpathSync3(path8.dirname(candidate));
3128
+ const file = path8.join(directory, binaryName);
3129
+ const info = lstatSync4(file, { bigint: true });
3130
+ const linksAccounted = allowCargoTargetLinks ? accountsForCargoTargetLinks(directory, file, info, writableDirs, uid) : info.nlink === 1n;
3131
+ if (!info.isFile() || !linksAccounted || info.size === 0n || info.uid !== uid && info.uid !== 0n || (info.mode & 0o6022n) !== 0n || (info.mode & 0o100n) === 0n)
3132
+ return void 0;
3133
+ const protectedInHomeDot = protectedHome !== void 0 && isHomeDotTarget(protectedHome, directory);
3134
+ let current = directory;
3135
+ for (; ; ) {
3136
+ const parent = statSync2(current, { bigint: true });
3137
+ const systemSticky = parent.uid === 0n && (parent.mode & 0o1000n) !== 0n;
3138
+ const isWritableParent = writableDirs.has(directoryId(parent)) && !(protectedInHomeDot && current === protectedHome);
3139
+ if (!parent.isDirectory() || isWritableParent || parent.uid !== uid && parent.uid !== 0n || (parent.mode & 0o022n) !== 0n && !systemSticky)
3140
+ return void 0;
3141
+ const next = path8.dirname(current);
3142
+ if (next === current) break;
3143
+ current = next;
3144
+ }
3145
+ return {
3146
+ candidate,
3147
+ file,
3148
+ identity: `${directoryId(info)}:${info.size}:${info.ctimeNs}`
3149
+ };
3150
+ } catch {
3151
+ return void 0;
3152
+ }
3153
+ };
3154
+ var resolveMxcLauncher = (protection) => {
3155
+ const uid = process.geteuid?.();
3156
+ const packageName = supportedMxcPackages.get(
3157
+ `${process.platform}-${process.arch}`
3158
+ );
3159
+ if (!packageName || uid === void 0) return void 0;
3160
+ try {
3161
+ const mutable = new Set(
3162
+ [
3163
+ protection.root,
3164
+ ...protection.writeRoots,
3165
+ ...protection.gitWriteRoots ?? []
3166
+ ].map((root) => directoryId(statSync2(root, { bigint: true })))
3167
+ );
3168
+ const actualModule = realpathSync3(moduleDir);
3169
+ const projectPackage = path8.basename(actualModule) === "permissions" ? path8.resolve(actualModule, "../..") : path8.dirname(actualModule);
3170
+ const suffix = path8.join("packages", "runtime");
3171
+ if (projectPackage.endsWith(`${path8.sep}${suffix}`)) {
3172
+ const checkout = path8.resolve(projectPackage, "../..");
3173
+ const built = trustedLauncher(
3174
+ path8.join(checkout, "crates/mxc-launcher/target/release", binaryName),
3175
+ mutable,
3176
+ BigInt(uid),
3177
+ void 0,
3178
+ true
3179
+ );
3180
+ if (built) return built;
3181
+ }
3182
+ const version = packageVersion(projectPackage, "@codelia/runtime");
3183
+ if (!version) return void 0;
3184
+ const packagePath = path8.join("node_modules", ...packageName.split("/"));
3185
+ let directory = actualModule;
3186
+ for (; ; ) {
3187
+ const candidatePackage = path8.join(directory, packagePath);
3188
+ const installed = packageVersion(candidatePackage, packageName) === version ? trustedLauncher(
3189
+ path8.join(candidatePackage, "bin", binaryName),
3190
+ mutable,
3191
+ BigInt(uid),
3192
+ protection.homeDotDirectory
3193
+ ) : void 0;
3194
+ if (installed) return installed;
3195
+ const parent = path8.dirname(directory);
3196
+ if (parent === directory) return void 0;
3197
+ directory = parent;
3198
+ }
3199
+ } catch {
3200
+ return void 0;
3201
+ }
3202
+ };
3203
+ var probeMxcLauncher = (launcher, options) => spawnSync(
3204
+ launcher.file,
3205
+ ["--probe-v3", ...options?.bwrapPath ? [options.bwrapPath] : []],
3206
+ {
3207
+ cwd: helperCwd(),
3208
+ env: {},
3209
+ stdio: "ignore",
3210
+ // On Linux, MXC's internal `bwrap --version` probe uses a 5s deadline.
3211
+ timeout: process.platform === "linux" ? 6e3 : 2500,
3212
+ killSignal: "SIGKILL"
3213
+ }
3214
+ ).status === 0;
3215
+ var lifecycles = /* @__PURE__ */ new WeakMap();
3216
+ var mxcLifecycle = (child) => lifecycles.get(child);
3217
+ var launchMxc = (launcher, request, stdin) => {
3218
+ const frame = `${JSON.stringify({ version: MXC_PROTOCOL_VERSION, ...request })}
3219
+ `;
3220
+ if (Buffer.byteLength(frame) > MAX_MXC_FRAME_BYTES)
3221
+ throw new Error("sandbox_launch_failed");
3222
+ const child = spawn2(launcher.file, ["--run"], {
3223
+ cwd: helperCwd(),
3224
+ env: {},
3225
+ detached: true,
3226
+ stdio: [stdin === "pipe" ? "pipe" : "ignore", "pipe", "pipe", "pipe"]
3227
+ });
3228
+ const control2 = child.stdio[3];
3229
+ let pending = "";
3230
+ let accepted = false;
3231
+ let failed = false;
3232
+ let expectedExit;
3233
+ let deadline;
3234
+ let reportCompletion;
3235
+ const completed = new Promise((resolve) => {
3236
+ reportCompletion = resolve;
3237
+ });
3238
+ const boundCleanup = () => {
3239
+ deadline ??= setTimeout(() => {
3240
+ reportCompletion("unconfirmed");
3241
+ control2.destroy();
3242
+ child.stdin?.destroy();
3243
+ child.stdout.destroy();
3244
+ child.stderr.destroy();
3245
+ child.unref();
3246
+ }, 8e3);
3247
+ };
3248
+ const revoke = () => {
3249
+ if (!control2.writableEnded && !control2.destroyed) control2.end();
3250
+ boundCleanup();
3251
+ };
3252
+ const rejectReport = () => {
3253
+ failed = true;
3254
+ revoke();
3255
+ };
3256
+ control2.setEncoding("utf8");
3257
+ control2.on("error", rejectReport);
3258
+ control2.on("data", (chunk) => {
3259
+ if (failed) return;
3260
+ pending += chunk;
3261
+ if (pending.length > 256) return rejectReport();
3262
+ let newline = pending.indexOf("\n");
3263
+ while (newline !== -1) {
3264
+ try {
3265
+ const value = JSON.parse(pending.slice(0, newline));
3266
+ if (expectedExit !== void 0) return rejectReport();
3267
+ if (value.event === "started" && !accepted) accepted = true;
3268
+ else if (value.event === "cancelled") expectedExit = 143;
3269
+ else if (accepted && value.event === "finished" && Number.isInteger(value.exit_code) && value.exit_code >= 0 && value.exit_code <= 255)
3270
+ expectedExit = value.exit_code;
3271
+ else return rejectReport();
3272
+ } catch {
3273
+ return rejectReport();
3274
+ }
3275
+ pending = pending.slice(newline + 1);
3276
+ newline = pending.indexOf("\n");
3277
+ }
3278
+ });
3279
+ child.once("exit", boundCleanup);
3280
+ child.once("close", (code, signal) => {
3281
+ clearTimeout(deadline);
3282
+ reportCompletion(
3283
+ !failed && pending === "" && signal === null && code === expectedExit ? "clean" : "unconfirmed"
3284
+ );
3285
+ });
3286
+ lifecycles.set(child, { revoke, completed });
3287
+ control2.write(frame);
3288
+ return child;
3289
+ };
3290
+
3291
+ // src/permissions/protected-aliases.ts
3292
+ import {
3293
+ lstatSync as lstatSync5,
3294
+ readdirSync as readdirSync4,
3295
+ realpathSync as realpathSync4
3296
+ } from "fs";
3297
+ import path9 from "path";
2555
3298
  var maxEntries = 4096;
2556
3299
  var inode = (stat) => `${stat.dev}:${stat.ino}`;
2557
3300
  function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifiedHooks = []) {
2558
3301
  const pending = roots.map((entry) => {
2559
3302
  try {
2560
- return realpathSync3(entry);
3303
+ return realpathSync4(entry);
2561
3304
  } catch (error) {
2562
- if (error.code === "ENOENT") return entry;
3305
+ const code = error.code;
3306
+ if (code === "ENOENT") return entry;
3307
+ if (code === "EOPNOTSUPP" || code === "ENXIO") {
3308
+ const info = lstatSync5(entry, { throwIfNoEntry: false });
3309
+ if (info && !info.isSymbolicLink()) {
3310
+ return path9.join(
3311
+ realpathSync4(path9.dirname(entry)),
3312
+ path9.basename(entry)
3313
+ );
3314
+ }
3315
+ }
2563
3316
  throw error;
2564
3317
  }
2565
3318
  });
@@ -2573,7 +3326,7 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
2573
3326
  const target = hooks.get(file);
2574
3327
  if (!target) return false;
2575
3328
  try {
2576
- return realpathSync3(file) === target && lstatSync3(target).isFile();
3329
+ return realpathSync4(file) === target && lstatSync5(target).isFile();
2577
3330
  } catch {
2578
3331
  return false;
2579
3332
  }
@@ -2585,18 +3338,19 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
2585
3338
  if (visited.size > entryLimit)
2586
3339
  throw new Error("protected_alias_index_unavailable");
2587
3340
  try {
2588
- const metadata = lstatSync3(file, { bigint: true });
2589
- if (metadata.isFile() && metadata.nlink > 1n) yield inode(metadata);
3341
+ const metadata = lstatSync5(file, { bigint: true });
3342
+ if ((metadata.isFile() || metadata.isSocket() || metadata.isFIFO()) && metadata.nlink > 1n)
3343
+ yield inode(metadata);
2590
3344
  if (metadata.isSymbolicLink() && ignored.size) {
2591
3345
  if (verifiedHook(file)) continue;
2592
3346
  pending.push(...ignored);
2593
3347
  ignored.clear();
2594
3348
  } else if (metadata.isDirectory()) {
2595
- const children = readdirSync3(file);
3349
+ const children = readdirSync4(file);
2596
3350
  if (children.length + pending.length + visited.size > entryLimit)
2597
3351
  throw new Error("protected_alias_index_unavailable");
2598
3352
  for (const name of children) {
2599
- const child = path8.join(file, name);
3353
+ const child = path9.join(file, name);
2600
3354
  if (!ignored.has(child)) pending.push(child);
2601
3355
  }
2602
3356
  }
@@ -2870,29 +3624,29 @@ var analyzeShell = (invocation) => {
2870
3624
  import {
2871
3625
  accessSync,
2872
3626
  constants as constants3,
2873
- lstatSync as lstatSync4,
2874
- readdirSync as readdirSync4,
2875
- readlinkSync as readlinkSync3,
2876
- realpathSync as realpathSync4,
2877
- statSync as statSync2
3627
+ lstatSync as lstatSync6,
3628
+ readdirSync as readdirSync5,
3629
+ readlinkSync as readlinkSync4,
3630
+ realpathSync as realpathSync5,
3631
+ statSync as statSync3
2878
3632
  } from "fs";
2879
- import path9 from "path";
2880
- var shellBinPaths = (override) => Object.freeze((override ?? process.env.PATH ?? "").split(path9.delimiter));
2881
- var shellPathForLaunch = (binPaths) => (binPaths ?? shellBinPaths()).join(path9.delimiter);
3633
+ import path10 from "path";
3634
+ var shellBinPaths = (override) => Object.freeze((override ?? process.env.PATH ?? "").split(path10.delimiter));
3635
+ var shellPathForLaunch = (binPaths) => (binPaths ?? shellBinPaths()).join(path10.delimiter);
2882
3636
  var resolveShellExecutable = (name, paths, cwd = process.cwd()) => {
2883
- if (!name || name.includes("\0") || !path9.isAbsolute(name) && (name.includes("/") || process.platform === "win32" && name.includes("\\")))
3637
+ if (!name || name.includes("\0") || !path10.isAbsolute(name) && (name.includes("/") || process.platform === "win32" && name.includes("\\")))
2884
3638
  throw new Error("invalid_executable");
2885
- const executable = process.platform === "win32" && !path9.extname(name) ? `${name}.exe` : name;
2886
- const candidates = path9.isAbsolute(executable) ? [executable] : paths.map((entry) => {
3639
+ const executable = process.platform === "win32" && !path10.extname(name) ? `${name}.exe` : name;
3640
+ const candidates = path10.isAbsolute(executable) ? [executable] : paths.map((entry) => {
2887
3641
  const directory = process.platform === "win32" && entry.startsWith('"') && entry.endsWith('"') ? entry.slice(1, -1) : entry;
2888
- const resolved = path9.isAbsolute(directory) ? directory : `${cwd}${path9.sep}${directory || "."}`;
2889
- return `${resolved}${path9.sep}${executable}`;
3642
+ const resolved = path10.isAbsolute(directory) ? directory : `${cwd}${path10.sep}${directory || "."}`;
3643
+ return `${resolved}${path10.sep}${executable}`;
2890
3644
  });
2891
3645
  for (const candidate of candidates) {
2892
3646
  try {
2893
3647
  accessSync(candidate, constants3.X_OK);
2894
- const actual = realpathSync4(candidate);
2895
- if (statSync2(actual).isFile()) return actual;
3648
+ const actual = realpathSync5(candidate);
3649
+ if (statSync3(actual).isFile()) return actual;
2896
3650
  } catch {
2897
3651
  }
2898
3652
  }
@@ -2906,11 +3660,11 @@ var inspectBashPath = (candidate, policy) => {
2906
3660
  while (components.length) {
2907
3661
  const component = components.shift();
2908
3662
  if (!component || component === ".") continue;
2909
- const name = path9.join(current, component);
3663
+ const name = path10.join(current, component);
2910
3664
  const restriction = policy(name);
2911
3665
  if (restriction === "unbound") throw new Error("unbound_shell_path");
2912
3666
  masked ||= restriction === "masked";
2913
- const entry = lstatSync4(name, { throwIfNoEntry: false });
3667
+ const entry = lstatSync6(name, { throwIfNoEntry: false });
2914
3668
  if (!entry) return void 0;
2915
3669
  if (!entry.isSymbolicLink()) {
2916
3670
  if (components.length && !entry.isDirectory()) return void 0;
@@ -2918,27 +3672,27 @@ var inspectBashPath = (candidate, policy) => {
2918
3672
  continue;
2919
3673
  }
2920
3674
  if (++links > 40) throw new Error("unbound_shell_path");
2921
- const destination = readlinkSync3(name);
2922
- if (path9.isAbsolute(destination)) current = "/";
3675
+ const destination = readlinkSync4(name);
3676
+ if (path10.isAbsolute(destination)) current = "/";
2923
3677
  components = [...destination.split("/"), ...components];
2924
3678
  }
2925
3679
  return { file: current, masked };
2926
3680
  };
2927
3681
  var bindBashCommand = (name, paths, policy, acceptShared = () => false) => {
2928
- const absolute = path9.isAbsolute(name);
3682
+ const absolute = path10.isAbsolute(name);
2929
3683
  try {
2930
3684
  for (const directory of absolute ? [""] : paths) {
2931
- if (!absolute && (!path9.isAbsolute(directory) || directory.split("/").includes("..")))
3685
+ if (!absolute && (!path10.isAbsolute(directory) || directory.split("/").includes("..")))
2932
3686
  return void 0;
2933
3687
  const inspected = inspectBashPath(
2934
3688
  absolute ? name : `${directory}/${name}`,
2935
3689
  policy
2936
3690
  );
2937
3691
  if (!inspected) continue;
2938
- const executable = realpathSync4(inspected.file);
3692
+ const executable = realpathSync5(inspected.file);
2939
3693
  const restriction = policy(executable);
2940
3694
  if (restriction === "unbound") return void 0;
2941
- const info = statSync2(executable, { bigint: true });
3695
+ const info = statSync3(executable, { bigint: true });
2942
3696
  if (!info.isFile()) continue;
2943
3697
  if (info.nlink !== 1n && !acceptShared(executable, info))
2944
3698
  return void 0;
@@ -2961,11 +3715,11 @@ var bindBashCommand = (name, paths, policy, acceptShared = () => false) => {
2961
3715
  };
2962
3716
  function bindKnownSystemExecutable(program, paths, policy, directArgv) {
2963
3717
  if (process.platform === "win32") return void 0;
2964
- const name = path9.basename(program);
3718
+ const name = path10.basename(program);
2965
3719
  const known = new Set(
2966
3720
  [`/usr/bin/${name}`, `/bin/${name}`].flatMap((entry) => {
2967
3721
  try {
2968
- return [realpathSync4(entry)];
3722
+ return [realpathSync5(entry)];
2969
3723
  } catch {
2970
3724
  return [];
2971
3725
  }
@@ -2987,22 +3741,22 @@ var isRootControlledSharedExecutable = (file, info) => {
2987
3741
  var sameLinkMetadata = (left, right) => left.dev === right.dev && left.ino === right.ino && left.nlink === right.nlink && left.mode === right.mode && left.uid === right.uid && left.gid === right.gid && left.size === right.size && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
2988
3742
  function areAllExecutableLinksOutsideRestrictedPaths(file, info, policy) {
2989
3743
  try {
2990
- const parent = path9.dirname(file);
2991
- if (policy(parent) || realpathSync4(parent) !== parent) return false;
2992
- const directory = lstatSync4(parent, { bigint: true });
2993
- const executable = lstatSync4(file, { bigint: true });
3744
+ const parent = path10.dirname(file);
3745
+ if (policy(parent) || realpathSync5(parent) !== parent) return false;
3746
+ const directory = lstatSync6(parent, { bigint: true });
3747
+ const executable = lstatSync6(file, { bigint: true });
2994
3748
  if (!directory.isDirectory() || !executable.isFile() || !sameLinkMetadata(executable, info) || executable.nlink < 2n)
2995
3749
  return false;
2996
3750
  const mounts = process.platform === "linux" ? executableMountSnapshot(file, executable.dev) : void 0;
2997
3751
  let links = 0n;
2998
3752
  let foundExecutable = false;
2999
- const entries = readdirSync4(parent, { encoding: "buffer" });
3753
+ const entries = readdirSync5(parent, { encoding: "buffer" });
3000
3754
  if (entries.length > 4096) return false;
3001
3755
  for (const entry of entries) {
3002
3756
  const name = entry.toString();
3003
3757
  if (!Buffer.from(name).equals(entry)) return false;
3004
- const peer = path9.join(parent, name);
3005
- const peerInfo = lstatSync4(peer, { bigint: true });
3758
+ const peer = path10.join(parent, name);
3759
+ const peerInfo = lstatSync6(peer, { bigint: true });
3006
3760
  if (peerInfo.dev !== executable.dev || peerInfo.ino !== executable.ino)
3007
3761
  continue;
3008
3762
  if (!peerInfo.isFile() || policy(peer) || !sameLinkMetadata(executable, peerInfo))
@@ -3010,47 +3764,445 @@ function areAllExecutableLinksOutsideRestrictedPaths(file, info, policy) {
3010
3764
  foundExecutable ||= peer === file;
3011
3765
  links++;
3012
3766
  }
3013
- return foundExecutable && links === executable.nlink && realpathSync4(parent) === parent && sameLinkMetadata(directory, lstatSync4(parent, { bigint: true })) && sameLinkMetadata(executable, lstatSync4(file, { bigint: true })) && (mounts === void 0 || executableMountSnapshot(file, executable.dev) === mounts);
3014
- } catch {
3015
- return false;
3016
- }
3017
- }
3018
- var notWritable = (file) => {
3019
- try {
3020
- accessSync(file, constants3.W_OK);
3021
- return false;
3022
- } catch (error) {
3023
- return ["EACCES", "EPERM", "EROFS"].includes(
3024
- error.code ?? ""
3025
- );
3767
+ return foundExecutable && links === executable.nlink && realpathSync5(parent) === parent && sameLinkMetadata(directory, lstatSync6(parent, { bigint: true })) && sameLinkMetadata(executable, lstatSync6(file, { bigint: true })) && (mounts === void 0 || executableMountSnapshot(file, executable.dev) === mounts);
3768
+ } catch {
3769
+ return false;
3770
+ }
3771
+ }
3772
+ var notWritable = (file) => {
3773
+ try {
3774
+ accessSync(file, constants3.W_OK);
3775
+ return false;
3776
+ } catch (error) {
3777
+ return ["EACCES", "EPERM", "EROFS"].includes(
3778
+ error.code ?? ""
3779
+ );
3780
+ }
3781
+ };
3782
+
3783
+ // src/permissions/linux-mxc-backend.ts
3784
+ var within2 = (root, name) => root === "/" || root === name || name.startsWith(`${root}/`);
3785
+ var virtualRoots = ["/proc", "/dev", "/sys", "/run", "/var/run"];
3786
+ var MAX_FILESYSTEM_SPEC_BYTES = MAX_MXC_FRAME_BYTES - 16 * 1024;
3787
+ var baselineReadOnlyRoots = [
3788
+ "/bin",
3789
+ "/sbin",
3790
+ "/lib",
3791
+ "/lib32",
3792
+ "/lib64",
3793
+ "/libx32",
3794
+ "/usr/bin",
3795
+ "/usr/sbin",
3796
+ "/usr/lib",
3797
+ "/usr/lib32",
3798
+ "/usr/lib64",
3799
+ "/usr/libx32",
3800
+ "/usr/libexec",
3801
+ "/usr/share",
3802
+ "/etc"
3803
+ ];
3804
+ var DEFAULT_LINUX_MXC_READABLE_ROOTS = [
3805
+ "/home",
3806
+ "/opt",
3807
+ "/srv",
3808
+ "/mnt",
3809
+ "/media",
3810
+ "/nix/store",
3811
+ "/usr/local",
3812
+ "/usr/include",
3813
+ "/var/cache"
3814
+ ];
3815
+ var disallowedExtraReadRoots = /* @__PURE__ */ new Set(["/", "/tmp", ...virtualRoots]);
3816
+ var BWRAP_CANDIDATES = [
3817
+ "/usr/bin/bwrap",
3818
+ "/bin/bwrap",
3819
+ "/usr/local/bin/bwrap",
3820
+ "/run/current-system/sw/bin/bwrap"
3821
+ ];
3822
+ var SYSTEM_SH_CANDIDATES = ["/usr/bin/sh", "/bin/sh"];
3823
+ var resolveManagedLinuxTool = (candidates, options) => {
3824
+ for (const candidate of candidates) {
3825
+ const present = lstatSync7(candidate, { throwIfNoEntry: false }) !== void 0;
3826
+ if (!present) continue;
3827
+ try {
3828
+ const resolved = realpathSync6(candidate);
3829
+ if (options?.expectedBasename && path11.basename(resolved) !== options.expectedBasename) {
3830
+ if (options.firstPresentMustBeTrusted) return void 0;
3831
+ continue;
3832
+ }
3833
+ const fileInfo = statSync4(resolved, { bigint: true });
3834
+ if (!fileInfo.isFile() || fileInfo.uid !== 0n || (fileInfo.mode & 0o022n) !== 0n || (fileInfo.mode & 0o111n) === 0n) {
3835
+ if (options?.firstPresentMustBeTrusted) return void 0;
3836
+ continue;
3837
+ }
3838
+ accessSync2(resolved, constants4.X_OK);
3839
+ let trusted = true;
3840
+ let current = path11.dirname(resolved);
3841
+ for (; ; ) {
3842
+ const info = statSync4(current, { bigint: true });
3843
+ if (!info.isDirectory() || info.uid !== 0n || (info.mode & 0o022n) !== 0n) {
3844
+ trusted = false;
3845
+ break;
3846
+ }
3847
+ const parent = path11.dirname(current);
3848
+ if (parent === current) break;
3849
+ current = parent;
3850
+ }
3851
+ if (!trusted) {
3852
+ if (options?.firstPresentMustBeTrusted) return void 0;
3853
+ continue;
3854
+ }
3855
+ return {
3856
+ candidate,
3857
+ file: resolved,
3858
+ identity: `${fileInfo.dev}:${fileInfo.ino}:${fileInfo.size}:${fileInfo.ctimeNs}`
3859
+ };
3860
+ } catch {
3861
+ if (options?.firstPresentMustBeTrusted) return void 0;
3862
+ }
3863
+ }
3864
+ return void 0;
3865
+ };
3866
+ var resolveLinuxBwrap = () => process.platform === "linux" ? resolveManagedLinuxTool(BWRAP_CANDIDATES, { expectedBasename: "bwrap" }) : void 0;
3867
+ var resolveLinuxSystemSh = () => process.platform === "linux" ? resolveManagedLinuxTool(SYSTEM_SH_CANDIDATES, {
3868
+ // Container PATH searches /usr/bin before /bin, so an untrusted
3869
+ // /usr/bin/sh must fail closed instead of falling back to /bin/sh.
3870
+ firstPresentMustBeTrusted: true
3871
+ }) : void 0;
3872
+ var linuxMxcManagedToolPaths = () => {
3873
+ if (process.platform !== "linux") return [];
3874
+ const bwrap = resolveLinuxBwrap();
3875
+ const sh = resolveLinuxSystemSh();
3876
+ return [
3877
+ ...new Set(
3878
+ [bwrap, sh].flatMap((tool) => tool ? [tool.candidate, tool.file] : [])
3879
+ )
3880
+ ];
3881
+ };
3882
+ var deniedPathsFor = (policy) => {
3883
+ const paths = /* @__PURE__ */ new Set();
3884
+ for (const item of policy.protectedPaths) {
3885
+ if (!path11.isAbsolute(item) || item !== path11.normalize(item) || item === "/")
3886
+ throw new Error("invalid_protected_path");
3887
+ if (item === "/dev") continue;
3888
+ let resolved;
3889
+ try {
3890
+ resolved = realpathSync6(item);
3891
+ } catch (error) {
3892
+ const code = error.code;
3893
+ if (code === "ENOENT") {
3894
+ resolved = item;
3895
+ } else if (code === "EOPNOTSUPP" || code === "ENXIO") {
3896
+ const linfo = lstatSync7(item, { throwIfNoEntry: false });
3897
+ if (linfo && !linfo.isSymbolicLink() && (linfo.isSocket() || linfo.isFIFO())) {
3898
+ resolved = path11.join(
3899
+ realpathSync6(path11.dirname(item)),
3900
+ path11.basename(item)
3901
+ );
3902
+ } else {
3903
+ throw error;
3904
+ }
3905
+ } else {
3906
+ throw error;
3907
+ }
3908
+ }
3909
+ if (resolved === "/") throw new Error("invalid_protected_path");
3910
+ paths.add(item);
3911
+ paths.add(resolved);
3912
+ }
3913
+ const selected = [];
3914
+ for (const item of [...paths].sort((a, b) => a.length - b.length)) {
3915
+ if (!selected.some((mask) => within2(mask, item))) selected.push(item);
3916
+ }
3917
+ for (const target of selected) {
3918
+ const info = statSync4(target, { throwIfNoEntry: false });
3919
+ if (!info) throw new Error("missing_protected_mountpoint");
3920
+ if (!info.isDirectory() && !info.isFile() && !info.isSocket() && !info.isFIFO())
3921
+ throw new Error("unsupported_protected_mountpoint");
3922
+ }
3923
+ return selected;
3924
+ };
3925
+ var readOnlyMount = (entry, projectedHome) => {
3926
+ try {
3927
+ if (realpathSync6(entry) !== entry)
3928
+ throw new Error("unbound_read_only_path");
3929
+ return entry;
3930
+ } catch (error) {
3931
+ if (error.code !== "ENOENT" || !projectedHome || !within2(projectedHome, entry) || resolveReservedTarget(entry) !== entry)
3932
+ throw error;
3933
+ }
3934
+ let parent = path11.dirname(entry);
3935
+ while (within2(projectedHome, parent)) {
3936
+ const info = lstatSync7(parent, { throwIfNoEntry: false });
3937
+ if (info) {
3938
+ if (info.isDirectory() && realpathSync6(parent) === parent) return parent;
3939
+ break;
3940
+ }
3941
+ if (parent === projectedHome) break;
3942
+ parent = path11.dirname(parent);
3943
+ }
3944
+ throw new Error("unbound_read_only_path");
3945
+ };
3946
+ var existingReadableDirectory = (candidate, requireCanonical = false) => {
3947
+ if (!path11.isAbsolute(candidate)) return void 0;
3948
+ try {
3949
+ const linfo = lstatSync7(candidate, { throwIfNoEntry: false });
3950
+ if (!linfo) return void 0;
3951
+ if (requireCanonical && linfo.isSymbolicLink()) return void 0;
3952
+ const resolved = realpathSync6(candidate);
3953
+ if (requireCanonical && resolved !== candidate) return void 0;
3954
+ const info = statSync4(resolved, { throwIfNoEntry: false });
3955
+ if (!info?.isDirectory()) return void 0;
3956
+ accessSync2(resolved, constants4.R_OK);
3957
+ return resolved;
3958
+ } catch {
3959
+ return void 0;
3960
+ }
3961
+ };
3962
+ var buildLinuxMxcFilesystemPolicy = (policy, scratch, options = {}) => {
3963
+ if (policy.profile === "full-access" || policy.profile === "investigation" && policy.writeRoots.length || policy.gitWriteRoots?.length || policy.gitProtectedPaths?.length)
3964
+ throw new Error("unsupported_protection");
3965
+ if (!path11.isAbsolute(scratch) || scratch !== path11.normalize(scratch) || scratch === "/" || virtualRoots.some((name) => within2(name, scratch)))
3966
+ throw new Error("invalid_scratch_root");
3967
+ if (!options.skipScratchStat && (realpathSync6(scratch) !== scratch || !statSync4(scratch).isDirectory()))
3968
+ throw new Error("invalid_scratch_root");
3969
+ const deniedPaths = deniedPathsFor(policy);
3970
+ if (deniedPaths.some((mask) => within2(mask, scratch)))
3971
+ throw new Error("invalid_scratch_root");
3972
+ const readOnly = policy.readOnlyPaths ?? [];
3973
+ const home = policy.homeDotDirectory;
3974
+ const projectedHome = home && policy.writeRoots.includes(home) ? home : void 0;
3975
+ const protectedTargets = [...deniedPaths, ...readOnly];
3976
+ const covered = (target) => protectedTargets.some((entry) => within2(entry, target));
3977
+ const writableRoots = /* @__PURE__ */ new Set();
3978
+ for (const root of policy.writeRoots) {
3979
+ if (home && root !== home && (within2(root, home) || resourceContainsPath(root, home)))
3980
+ throw new Error("unsupported_home_write_root");
3981
+ if (root === "/" || root === "/tmp" || realpathSync6(root) !== root || !statSync4(root).isDirectory() || virtualRoots.some((name) => within2(name, root)))
3982
+ throw new Error("invalid_write_root");
3983
+ if (within2(scratch, root)) continue;
3984
+ if (deniedPaths.some((mask) => within2(mask, root)))
3985
+ throw new Error("invalid_write_root");
3986
+ if (readOnly.some((entry) => within2(entry, root))) continue;
3987
+ if (root !== home) writableRoots.add(root);
3988
+ }
3989
+ const explicitReadOnly = /* @__PURE__ */ new Set();
3990
+ if (projectedHome) {
3991
+ explicitReadOnly.add(projectedHome);
3992
+ for (const name of readdirSync6(projectedHome)) {
3993
+ const child = path11.join(projectedHome, name);
3994
+ if (child === scratch || isHomeDotTarget(projectedHome, child, "linux") || covered(child))
3995
+ continue;
3996
+ const info = lstatSync7(child, { throwIfNoEntry: false });
3997
+ if ((info?.isDirectory() || info?.isFile()) && realpathSync6(child) === child)
3998
+ writableRoots.add(child);
3999
+ }
4000
+ }
4001
+ const readOnlyMounts = /* @__PURE__ */ new Set();
4002
+ const proposedRoots = [...writableRoots];
4003
+ for (const entry of [...readOnly].sort((a, b) => a.length - b.length)) {
4004
+ if (!deniedPaths.some((mask) => within2(mask, entry)) && proposedRoots.some((root) => within2(root, entry)) && ![...readOnlyMounts].some((mount) => within2(mount, entry))) {
4005
+ readOnlyMounts.add(readOnlyMount(entry, projectedHome));
4006
+ }
4007
+ }
4008
+ protectedTargets.push(...readOnlyMounts);
4009
+ for (const root of writableRoots) {
4010
+ if (covered(root)) writableRoots.delete(root);
4011
+ }
4012
+ const writeRoots = [...writableRoots];
4013
+ const anchors = /* @__PURE__ */ new Set();
4014
+ for (const entry of [...readOnlyMounts, ...deniedPaths]) {
4015
+ let parent = path11.dirname(entry);
4016
+ while (writeRoots.some((root) => root !== parent && within2(root, parent))) {
4017
+ if (!writableRoots.has(parent) && !covered(parent)) anchors.add(parent);
4018
+ parent = path11.dirname(parent);
4019
+ }
4020
+ }
4021
+ for (const anchor of anchors) {
4022
+ const info = statSync4(anchor, { throwIfNoEntry: false });
4023
+ if (!info) {
4024
+ anchors.delete(anchor);
4025
+ continue;
4026
+ }
4027
+ if (!info.isDirectory() || realpathSync6(anchor) !== anchor)
4028
+ throw new Error("unbound_protected_ancestor");
4029
+ }
4030
+ const readwritePaths = [
4031
+ .../* @__PURE__ */ new Set([scratch, ...writeRoots, ...anchors])
4032
+ ].sort((a, b) => a.length - b.length || a.localeCompare(b));
4033
+ const readOnlyPaths = /* @__PURE__ */ new Set();
4034
+ for (const dir of options.readableRoots ?? DEFAULT_LINUX_MXC_READABLE_ROOTS) {
4035
+ const canonical = existingReadableDirectory(dir, true);
4036
+ if (!canonical) continue;
4037
+ if (disallowedExtraReadRoots.has(canonical) || virtualRoots.some((name) => within2(name, canonical)) || deniedPaths.some((mask) => within2(mask, canonical)) || readwritePaths.some((rw) => within2(rw, canonical)))
4038
+ continue;
4039
+ readOnlyPaths.add(canonical);
4040
+ }
4041
+ for (const entry of explicitReadOnly) {
4042
+ if (!deniedPaths.some((mask) => within2(mask, entry))) {
4043
+ readOnlyPaths.add(entry);
4044
+ }
4045
+ }
4046
+ for (const entry of readOnlyMounts) {
4047
+ if (writeRoots.some((root) => within2(root, entry))) {
4048
+ readOnlyPaths.add(entry);
4049
+ }
4050
+ }
4051
+ const extraReadableCandidates = [
4052
+ policy.root,
4053
+ policy.cwd,
4054
+ options.homeDir ?? homedir(),
4055
+ ...Object.values(policy.toolchainHomes ?? {}).filter(
4056
+ (value) => typeof value === "string" && value.length > 0
4057
+ ),
4058
+ ...policy.binPaths ?? []
4059
+ ];
4060
+ for (const candidate of extraReadableCandidates) {
4061
+ const canonical = existingReadableDirectory(candidate, false);
4062
+ if (!canonical) continue;
4063
+ if (disallowedExtraReadRoots.has(canonical) || virtualRoots.some((name) => within2(name, canonical)) || baselineReadOnlyRoots.some((base) => within2(base, canonical)) || deniedPaths.some((mask) => within2(mask, canonical)) || readwritePaths.some((rw) => within2(rw, canonical)) || [...readOnlyPaths].some((ro) => within2(ro, canonical)))
4064
+ continue;
4065
+ readOnlyPaths.add(canonical);
4066
+ }
4067
+ const spec = {
4068
+ readwrite_paths: readwritePaths,
4069
+ readonly_paths: [...readOnlyPaths].sort(
4070
+ (a, b) => a.length - b.length || a.localeCompare(b)
4071
+ ),
4072
+ denied_paths: [...deniedPaths].sort(
4073
+ (a, b) => a.length - b.length || a.localeCompare(b)
4074
+ )
4075
+ };
4076
+ if (Buffer.byteLength(JSON.stringify(spec)) > MAX_FILESYSTEM_SPEC_BYTES)
4077
+ throw new Error("filesystem_policy_too_large");
4078
+ return spec;
4079
+ };
4080
+ var release = (root) => {
4081
+ try {
4082
+ rmSync(root, { recursive: true, force: true });
4083
+ } catch {
4084
+ }
4085
+ };
4086
+ var LinuxMxcBackend = class {
4087
+ supportsReadOnlyPaths = true;
4088
+ supportsHomeDotProtection = true;
4089
+ supportsCommandBinding = true;
4090
+ exactLaunchBindingId = "codelia.linux.mxc/v1";
4091
+ verifiedProbeKey;
4092
+ validatePolicy(policy, scratch, skipScratchStat) {
4093
+ const spec = buildLinuxMxcFilesystemPolicy(policy, scratch, {
4094
+ skipScratchStat
4095
+ });
4096
+ if (findProtectedAliases(policy.protectedAliasPaths ?? policy.protectedPaths).size > 0)
4097
+ throw new Error("protected_file_has_alias");
4098
+ const readOnly = policy.readOnlyPaths ?? [];
4099
+ if (policy.writeRoots.length && hasReadOnlyAliases(policy.readOnlyAliasPaths ?? readOnly))
4100
+ throw new Error("read_only_file_has_alias");
4101
+ if (policy.homeDotDirectory && policy.writeRoots.includes(policy.homeDotDirectory) && hasHomeDotHardLinkAliases(policy.homeDotDirectory))
4102
+ throw new Error("home_dot_file_has_alias");
4103
+ checkLinuxMountTopology(readFileSync4("/proc/self/mountinfo", "utf8"));
4104
+ return spec;
4105
+ }
4106
+ supports(policy) {
4107
+ if (process.platform !== "linux" || process.getuid?.() === 0) return false;
4108
+ try {
4109
+ this.validatePolicy(policy, "/tmp/codelia-mxc-probe", true);
4110
+ const helper = resolveMxcLauncher(policy);
4111
+ const bwrap = resolveLinuxBwrap();
4112
+ const sh = resolveLinuxSystemSh();
4113
+ if (!helper || !bwrap || !sh) return false;
4114
+ const probeKey = `${helper.identity}|${bwrap.identity}|${sh.identity}`;
4115
+ if (this.verifiedProbeKey === probeKey) return true;
4116
+ if (!probeMxcLauncher(helper, { bwrapPath: bwrap.file })) return false;
4117
+ this.verifiedProbeKey = probeKey;
4118
+ return true;
4119
+ } catch {
4120
+ return false;
4121
+ }
4122
+ }
4123
+ supportsLaunchBinding(candidate) {
4124
+ return candidate.rule.template === "bun-typecheck/v1";
4125
+ }
4126
+ supportsExactLaunchBinding(_candidate) {
4127
+ return true;
4128
+ }
4129
+ launch(invocation, policy) {
4130
+ if (!this.supports(policy)) throw new Error("sandbox_unavailable");
4131
+ const scratch = realpathSync6(mkdtempSync("/tmp/codelia-mxc-"));
4132
+ const cleanup = () => release(scratch);
4133
+ try {
4134
+ const filesystem = this.validatePolicy(policy, scratch, false);
4135
+ const helper = resolveMxcLauncher(policy);
4136
+ const bwrap = resolveLinuxBwrap();
4137
+ const sh = resolveLinuxSystemSh();
4138
+ if (!helper || !bwrap || !sh || `${helper.identity}|${bwrap.identity}|${sh.identity}` !== this.verifiedProbeKey)
4139
+ throw new Error("sandbox_unavailable");
4140
+ const child = launchMxc(
4141
+ helper,
4142
+ {
4143
+ executable: invocation.executable,
4144
+ args: shellInvocationArgs(invocation),
4145
+ cwd: policy.cwd,
4146
+ filesystem,
4147
+ bwrap_path: bwrap.file,
4148
+ scratch,
4149
+ path: shellPathForLaunch(policy.binPaths),
4150
+ home: homedir(),
4151
+ cargo_home: policy.toolchainHomes?.CARGO_HOME,
4152
+ rustup_home: policy.toolchainHomes?.RUSTUP_HOME
4153
+ },
4154
+ policy.stdin
4155
+ );
4156
+ child.once("close", cleanup);
4157
+ return child;
4158
+ } catch (error) {
4159
+ cleanup();
4160
+ throw error;
4161
+ }
3026
4162
  }
3027
4163
  };
3028
4164
 
3029
4165
  // src/permissions/linux-shell-backend.ts
3030
- var within2 = (root, name) => root === "/" || root === name || name.startsWith(`${root}/`);
3031
- var virtualRoots = ["/proc", "/dev", "/sys"];
4166
+ import { spawn as spawn3, spawnSync as spawnSync2 } from "child_process";
4167
+ import {
4168
+ accessSync as accessSync3,
4169
+ constants as constants5,
4170
+ lstatSync as lstatSync8,
4171
+ mkdirSync,
4172
+ mkdtempSync as mkdtempSync2,
4173
+ readdirSync as readdirSync7,
4174
+ readFileSync as readFileSync5,
4175
+ realpathSync as realpathSync7,
4176
+ rmSync as rmSync2,
4177
+ statSync as statSync5,
4178
+ writeFileSync
4179
+ } from "fs";
4180
+ import { homedir as homedir2 } from "os";
4181
+ import path12 from "path";
4182
+ var within3 = (root, name) => root === "/" || root === name || name.startsWith(`${root}/`);
4183
+ var virtualRoots2 = ["/proc", "/dev", "/sys"];
3032
4184
  var managedTool = (name) => {
3033
- const resolved = realpathSync5(name);
4185
+ const resolved = realpathSync7(name);
3034
4186
  let current = resolved;
3035
4187
  for (; ; ) {
3036
- const info = statSync3(current);
4188
+ const info = statSync5(current);
3037
4189
  if (info.uid !== 0 || (info.mode & 18) !== 0)
3038
4190
  throw new Error("untrusted_sandbox_installation");
3039
4191
  if (current === resolved && (!info.isFile() || (info.mode & 73) === 0))
3040
4192
  throw new Error("sandbox_executable_unavailable");
3041
4193
  if (current === "/") return resolved;
3042
- current = path10.dirname(current);
4194
+ current = path12.dirname(current);
3043
4195
  }
3044
4196
  };
3045
4197
  var masksFor = (policy) => {
3046
4198
  const paths = /* @__PURE__ */ new Set();
3047
4199
  for (const item of [...policy.protectedPaths, "/run"]) {
3048
- if (!path10.isAbsolute(item) || item !== path10.normalize(item) || item === "/")
4200
+ if (!path12.isAbsolute(item) || item !== path12.normalize(item) || item === "/")
3049
4201
  throw new Error("invalid_protected_path");
3050
4202
  if (item === "/dev") continue;
3051
4203
  let resolved;
3052
4204
  try {
3053
- resolved = realpathSync5(item);
4205
+ resolved = realpathSync7(item);
3054
4206
  } catch (error) {
3055
4207
  if (error.code !== "ENOENT") throw error;
3056
4208
  resolved = item;
@@ -3061,34 +4213,34 @@ var masksFor = (policy) => {
3061
4213
  }
3062
4214
  const selected = [];
3063
4215
  for (const item of [...paths].sort((a, b) => a.length - b.length)) {
3064
- if (!selected.some((mask) => within2(mask, item))) selected.push(item);
4216
+ if (!selected.some((mask) => within3(mask, item))) selected.push(item);
3065
4217
  }
3066
4218
  return selected;
3067
4219
  };
3068
- var readOnlyMount = (entry, projectedHome) => {
4220
+ var readOnlyMount2 = (entry, projectedHome) => {
3069
4221
  try {
3070
- if (realpathSync5(entry) !== entry)
4222
+ if (realpathSync7(entry) !== entry)
3071
4223
  throw new Error("unbound_read_only_path");
3072
4224
  return entry;
3073
4225
  } catch (error) {
3074
- if (error.code !== "ENOENT" || !projectedHome || !within2(projectedHome, entry) || resolveReservedTarget(entry) !== entry)
4226
+ if (error.code !== "ENOENT" || !projectedHome || !within3(projectedHome, entry) || resolveReservedTarget(entry) !== entry)
3075
4227
  throw error;
3076
4228
  }
3077
- let parent = path10.dirname(entry);
3078
- while (within2(projectedHome, parent)) {
3079
- const info = lstatSync5(parent, { throwIfNoEntry: false });
4229
+ let parent = path12.dirname(entry);
4230
+ while (within3(projectedHome, parent)) {
4231
+ const info = lstatSync8(parent, { throwIfNoEntry: false });
3080
4232
  if (info) {
3081
- if (info.isDirectory() && realpathSync5(parent) === parent) return parent;
4233
+ if (info.isDirectory() && realpathSync7(parent) === parent) return parent;
3082
4234
  break;
3083
4235
  }
3084
4236
  if (parent === projectedHome) break;
3085
- parent = path10.dirname(parent);
4237
+ parent = path12.dirname(parent);
3086
4238
  }
3087
4239
  throw new Error("unbound_read_only_path");
3088
4240
  };
3089
4241
  var linuxRunscMountArgs = (policy, state, masks) => {
3090
4242
  const mountpoints = masks.map((target) => {
3091
- const info = statSync3(target, { throwIfNoEntry: false });
4243
+ const info = statSync5(target, { throwIfNoEntry: false });
3092
4244
  if (!info) throw new Error("missing_protected_mountpoint");
3093
4245
  if (!info.isDirectory() && !info.isFile())
3094
4246
  throw new Error("unsupported_protected_mountpoint");
@@ -3101,37 +4253,37 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3101
4253
  const home = policy.homeDotDirectory;
3102
4254
  const projectedHome = home && policy.writeRoots.includes(home) ? home : void 0;
3103
4255
  const protectedTargets = [...masks, ...readOnly];
3104
- const covered = (target) => protectedTargets.some((entry) => within2(entry, target));
4256
+ const covered = (target) => protectedTargets.some((entry) => within3(entry, target));
3105
4257
  const writableRoots = /* @__PURE__ */ new Set();
3106
4258
  const flags = ["--ro-bind", "/", "/", "--ro-bind", "/tmp", "/tmp"];
3107
4259
  for (const root of policy.writeRoots) {
3108
- if (home && root !== home && (within2(root, home) || resourceContainsPath(root, home)))
4260
+ if (home && root !== home && (within3(root, home) || resourceContainsPath(root, home)))
3109
4261
  throw new Error("unsupported_home_write_root");
3110
- if (root === "/" || realpathSync5(root) !== root || !statSync3(root).isDirectory() || virtualRoots.some((name) => within2(name, root)))
4262
+ if (root === "/" || realpathSync7(root) !== root || !statSync5(root).isDirectory() || virtualRoots2.some((name) => within3(name, root)))
3111
4263
  throw new Error("invalid_write_root");
3112
- if (within2(state, root)) continue;
3113
- if (masks.some((mask) => within2(mask, root)))
4264
+ if (within3(state, root)) continue;
4265
+ if (masks.some((mask) => within3(mask, root)))
3114
4266
  throw new Error("invalid_write_root");
3115
- if (readOnly.some((entry) => within2(entry, root))) continue;
4267
+ if (readOnly.some((entry) => within3(entry, root))) continue;
3116
4268
  if (root !== home) writableRoots.add(root);
3117
4269
  }
3118
4270
  if (projectedHome) {
3119
4271
  if (projectedHome !== "/tmp")
3120
4272
  flags.push("--ro-bind", projectedHome, projectedHome);
3121
- for (const name of readdirSync5(projectedHome)) {
3122
- const child = path10.join(projectedHome, name);
4273
+ for (const name of readdirSync7(projectedHome)) {
4274
+ const child = path12.join(projectedHome, name);
3123
4275
  if (child === state || isHomeDotTarget(projectedHome, child, "linux") || covered(child))
3124
4276
  continue;
3125
- const info = lstatSync5(child, { throwIfNoEntry: false });
3126
- if ((info?.isDirectory() || info?.isFile()) && realpathSync5(child) === child)
4277
+ const info = lstatSync8(child, { throwIfNoEntry: false });
4278
+ if ((info?.isDirectory() || info?.isFile()) && realpathSync7(child) === child)
3127
4279
  writableRoots.add(child);
3128
4280
  }
3129
4281
  }
3130
4282
  const readOnlyMounts = /* @__PURE__ */ new Set();
3131
4283
  const proposedRoots = [...writableRoots];
3132
4284
  for (const entry of [...readOnly].sort((a, b) => a.length - b.length)) {
3133
- if (!masks.some((mask) => within2(mask, entry)) && proposedRoots.some((root) => within2(root, entry)) && ![...readOnlyMounts].some((mount) => within2(mount, entry))) {
3134
- readOnlyMounts.add(readOnlyMount(entry, projectedHome));
4285
+ if (!masks.some((mask) => within3(mask, entry)) && proposedRoots.some((root) => within3(root, entry)) && ![...readOnlyMounts].some((mount) => within3(mount, entry))) {
4286
+ readOnlyMounts.add(readOnlyMount2(entry, projectedHome));
3135
4287
  }
3136
4288
  }
3137
4289
  protectedTargets.push(...readOnlyMounts);
@@ -3141,19 +4293,19 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3141
4293
  const writeRoots = [...writableRoots];
3142
4294
  const anchors = /* @__PURE__ */ new Set();
3143
4295
  for (const entry of [...readOnlyMounts, ...masks]) {
3144
- let parent = path10.dirname(entry);
3145
- while (writeRoots.some((root) => root !== parent && within2(root, parent))) {
4296
+ let parent = path12.dirname(entry);
4297
+ while (writeRoots.some((root) => root !== parent && within3(root, parent))) {
3146
4298
  if (!writableRoots.has(parent) && !covered(parent)) anchors.add(parent);
3147
- parent = path10.dirname(parent);
4299
+ parent = path12.dirname(parent);
3148
4300
  }
3149
4301
  }
3150
4302
  for (const anchor of anchors) {
3151
- const info = statSync3(anchor, { throwIfNoEntry: false });
4303
+ const info = statSync5(anchor, { throwIfNoEntry: false });
3152
4304
  if (!info) {
3153
4305
  anchors.delete(anchor);
3154
4306
  continue;
3155
4307
  }
3156
- if (!info.isDirectory() || realpathSync5(anchor) !== anchor)
4308
+ if (!info.isDirectory() || realpathSync7(anchor) !== anchor)
3157
4309
  throw new Error("unbound_protected_ancestor");
3158
4310
  }
3159
4311
  for (const root of [...writeRoots, ...anchors].sort(
@@ -3161,7 +4313,7 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3161
4313
  ))
3162
4314
  flags.push("--bind", root, root);
3163
4315
  for (const entry of [...readOnlyMounts].sort((a, b) => a.length - b.length)) {
3164
- if (!writeRoots.some((root) => within2(root, entry))) continue;
4316
+ if (!writeRoots.some((root) => within3(root, entry))) continue;
3165
4317
  flags.push("--ro-bind", entry, entry);
3166
4318
  }
3167
4319
  for (const { target, placeholder } of mountpoints)
@@ -3170,7 +4322,7 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3170
4322
  return flags;
3171
4323
  };
3172
4324
  var prepare = (policy, state, runsc, unshare) => {
3173
- if (policy.profile === "full-access" || policy.profile === "investigation" && policy.writeRoots.length)
4325
+ if (policy.profile === "full-access" || policy.profile === "investigation" && policy.writeRoots.length || policy.gitWriteRoots?.length || policy.gitProtectedPaths?.length)
3174
4326
  throw new Error("unsupported_protection");
3175
4327
  const masks = masksFor(policy);
3176
4328
  if (findProtectedAliases(policy.protectedAliasPaths ?? policy.protectedPaths).size)
@@ -3178,7 +4330,9 @@ var prepare = (policy, state, runsc, unshare) => {
3178
4330
  const readOnly = policy.readOnlyPaths ?? [];
3179
4331
  if (policy.writeRoots.length && hasReadOnlyAliases(policy.readOnlyAliasPaths ?? readOnly))
3180
4332
  throw new Error("read_only_file_has_alias");
3181
- checkLinuxMountTopology(readFileSync3("/proc/self/mountinfo", "utf8"));
4333
+ if (policy.homeDotDirectory && policy.writeRoots.includes(policy.homeDotDirectory) && hasHomeDotHardLinkAliases(policy.homeDotDirectory))
4334
+ throw new Error("home_dot_file_has_alias");
4335
+ checkLinuxMountTopology(readFileSync5("/proc/self/mountinfo", "utf8"));
3182
4336
  return [
3183
4337
  "--pdeathsig",
3184
4338
  "KILL",
@@ -3207,9 +4361,11 @@ var prepare = (policy, state, runsc, unshare) => {
3207
4361
  "ALL",
3208
4362
  "--clearenv",
3209
4363
  ...linuxRunscMountArgs(policy, state, masks),
4364
+ // The login home stays read-only outside existing grants; caches and
4365
+ // temporary files use the private state directory.
3210
4366
  "--setenv",
3211
4367
  "HOME",
3212
- state,
4368
+ homedir2(),
3213
4369
  "--setenv",
3214
4370
  "TMPDIR",
3215
4371
  state,
@@ -3232,16 +4388,16 @@ var prepare = (policy, state, runsc, unshare) => {
3232
4388
  "--"
3233
4389
  ];
3234
4390
  };
3235
- var release = (root) => rmSync(root, { recursive: true, force: true });
4391
+ var release2 = (root) => rmSync2(root, { recursive: true, force: true });
3236
4392
  var allocate = () => {
3237
- const root = mkdtempSync("/tmp/codelia-runsc-");
4393
+ const root = mkdtempSync2("/tmp/codelia-runsc-");
3238
4394
  try {
3239
4395
  mkdirSync(`${root}/runsc`, { mode: 448 });
3240
4396
  mkdirSync(`${root}/empty-dir`, { mode: 320 });
3241
4397
  writeFileSync(`${root}/empty-file`, "", { flag: "wx", mode: 256 });
3242
4398
  return root;
3243
4399
  } catch (error) {
3244
- release(root);
4400
+ release2(root);
3245
4401
  throw error;
3246
4402
  }
3247
4403
  };
@@ -3264,10 +4420,10 @@ var LinuxRunscBackend = class {
3264
4420
  for (const candidate of ["/usr/local/bin/runsc", "/usr/bin/runsc"]) {
3265
4421
  try {
3266
4422
  const runsc = managedTool(candidate);
3267
- const sidecars = path10.join(path10.dirname(runsc), "gvisor-bin");
3268
- accessSync2(path10.join(sidecars, "gvisor_sentry"), constants4.X_OK);
3269
- for (const executable of readdirSync5(sidecars)) {
3270
- managedTool(path10.join(sidecars, executable));
4423
+ const sidecars = path12.join(path12.dirname(runsc), "gvisor-bin");
4424
+ accessSync3(path12.join(sidecars, "gvisor_sentry"), constants5.X_OK);
4425
+ for (const executable of readdirSync7(sidecars)) {
4426
+ managedTool(path12.join(sidecars, executable));
3271
4427
  }
3272
4428
  this.tools = { setpriv, unshare, runsc };
3273
4429
  return this.tools;
@@ -3294,7 +4450,7 @@ var LinuxRunscBackend = class {
3294
4450
  }
3295
4451
  state = allocate();
3296
4452
  const args = prepare(policy, state, launcher.runsc, launcher.unshare);
3297
- const probe = spawnSync(launcher.setpriv, [...args, "/usr/bin/true"], {
4453
+ const probe = spawnSync2(launcher.setpriv, [...args, "/usr/bin/true"], {
3298
4454
  env: { PATH: "/usr/bin:/bin" },
3299
4455
  stdio: "ignore",
3300
4456
  timeout: 8e3,
@@ -3307,7 +4463,7 @@ var LinuxRunscBackend = class {
3307
4463
  } catch {
3308
4464
  return false;
3309
4465
  } finally {
3310
- if (state) release(state);
4466
+ if (state) release2(state);
3311
4467
  }
3312
4468
  }
3313
4469
  supportsLaunchBinding(candidate) {
@@ -3320,11 +4476,11 @@ var LinuxRunscBackend = class {
3320
4476
  launch(invocation, policy) {
3321
4477
  if (!this.supports(policy)) throw new Error("sandbox_unavailable");
3322
4478
  const state = allocate();
3323
- const cleanup = () => release(state);
4479
+ const cleanup = () => release2(state);
3324
4480
  try {
3325
4481
  const tools = this.resolveTools();
3326
4482
  const args = prepare(policy, state, tools.runsc, tools.unshare);
3327
- const child = spawn2(
4483
+ const child = spawn3(
3328
4484
  tools.setpriv,
3329
4485
  [...args, invocation.executable, ...shellInvocationArgs(invocation)],
3330
4486
  {
@@ -3343,194 +4499,21 @@ var LinuxRunscBackend = class {
3343
4499
  }
3344
4500
  };
3345
4501
 
3346
- // src/permissions/mxc-launcher.ts
3347
- import { spawn as spawn3, spawnSync as spawnSync2 } from "child_process";
3348
- import { lstatSync as lstatSync6, readFileSync as readFileSync4, realpathSync as realpathSync6, statSync as statSync4 } from "fs";
3349
- import path11 from "path";
3350
- import { fileURLToPath } from "url";
3351
- var binaryName = "codelia-mxc-launcher";
3352
- var packagePath = path11.join("node_modules", "@codelia", "tui-darwin-arm64");
3353
- var moduleDir = typeof __dirname === "string" ? __dirname : path11.dirname(fileURLToPath(import.meta.url));
3354
- var packageVersion = (directory, name) => {
3355
- try {
3356
- const manifest = path11.join(directory, "package.json");
3357
- const info = lstatSync6(manifest);
3358
- if (!info.isFile() || info.size > 64 * 1024) return void 0;
3359
- const parsed = JSON.parse(readFileSync4(manifest, "utf8"));
3360
- return parsed.name === name && typeof parsed.version === "string" ? parsed.version : void 0;
3361
- } catch {
3362
- return void 0;
3363
- }
3364
- };
3365
- var directoryId = (info) => `${info.dev}:${info.ino}`;
3366
- var trustedLauncher = (candidate, writableDirs, uid, protectedHome) => {
3367
- try {
3368
- const directory = realpathSync6(path11.dirname(candidate));
3369
- const file = path11.join(directory, binaryName);
3370
- const info = lstatSync6(file, { bigint: true });
3371
- if (!info.isFile() || info.nlink !== 1n || info.size === 0n || info.uid !== uid && info.uid !== 0n || (info.mode & 0o6022n) !== 0n || (info.mode & 0o100n) === 0n)
3372
- return void 0;
3373
- const protectedInHomeDot = protectedHome !== void 0 && isHomeDotTarget(protectedHome, directory);
3374
- let current = directory;
3375
- for (; ; ) {
3376
- const parent = statSync4(current, { bigint: true });
3377
- const systemSticky = parent.uid === 0n && (parent.mode & 0o1000n) !== 0n;
3378
- const isWritableParent = writableDirs.has(directoryId(parent)) && !(protectedInHomeDot && current === protectedHome);
3379
- if (!parent.isDirectory() || isWritableParent || parent.uid !== uid && parent.uid !== 0n || (parent.mode & 0o022n) !== 0n && !systemSticky)
3380
- return void 0;
3381
- const next = path11.dirname(current);
3382
- if (next === current) break;
3383
- current = next;
3384
- }
3385
- return {
3386
- candidate,
3387
- file,
3388
- identity: `${directoryId(info)}:${info.size}:${info.ctimeNs}`
3389
- };
3390
- } catch {
3391
- return void 0;
3392
- }
3393
- };
3394
- var resolveMxcLauncher = (protection) => {
3395
- const uid = process.geteuid?.();
3396
- if (process.platform !== "darwin" || process.arch !== "arm64" || uid === void 0)
3397
- return void 0;
3398
- try {
3399
- const mutable = new Set(
3400
- [protection.root, ...protection.writeRoots].map(
3401
- (root) => directoryId(statSync4(root, { bigint: true }))
3402
- )
3403
- );
3404
- const actualModule = realpathSync6(moduleDir);
3405
- const projectPackage = path11.basename(actualModule) === "permissions" ? path11.resolve(actualModule, "../..") : path11.dirname(actualModule);
3406
- const suffix = path11.join("packages", "runtime");
3407
- if (projectPackage.endsWith(`${path11.sep}${suffix}`)) {
3408
- const checkout = path11.resolve(projectPackage, "../..");
3409
- const built = trustedLauncher(
3410
- path11.join(checkout, "crates/mxc-launcher/target/release", binaryName),
3411
- mutable,
3412
- BigInt(uid)
3413
- );
3414
- if (built) return built;
3415
- }
3416
- const version = packageVersion(projectPackage, "@codelia/runtime");
3417
- if (!version) return void 0;
3418
- let directory = actualModule;
3419
- for (; ; ) {
3420
- const candidatePackage = path11.join(directory, packagePath);
3421
- const installed = packageVersion(candidatePackage, "@codelia/tui-darwin-arm64") === version ? trustedLauncher(
3422
- path11.join(candidatePackage, "bin", binaryName),
3423
- mutable,
3424
- BigInt(uid),
3425
- protection.homeDotDirectory
3426
- ) : void 0;
3427
- if (installed) return installed;
3428
- const parent = path11.dirname(directory);
3429
- if (parent === directory) return void 0;
3430
- directory = parent;
3431
- }
3432
- } catch {
3433
- return void 0;
3434
- }
3435
- };
3436
- var probeMxcLauncher = (launcher) => spawnSync2(launcher.file, ["--probe"], {
3437
- cwd: "/private/tmp",
3438
- env: {},
3439
- stdio: "ignore",
3440
- timeout: 2500,
3441
- killSignal: "SIGKILL"
3442
- }).status === 0;
3443
- var lifecycles = /* @__PURE__ */ new WeakMap();
3444
- var mxcLifecycle = (child) => lifecycles.get(child);
3445
- var launchMxc = (launcher, request, stdin) => {
3446
- const frame = `${JSON.stringify({ version: 1, ...request })}
3447
- `;
3448
- if (Buffer.byteLength(frame) > 256 * 1024)
3449
- throw new Error("sandbox_launch_failed");
3450
- const child = spawn3(launcher.file, ["--run"], {
3451
- cwd: "/private/tmp",
3452
- env: {},
3453
- detached: true,
3454
- stdio: [stdin === "pipe" ? "pipe" : "ignore", "pipe", "pipe", "pipe"]
3455
- });
3456
- const control2 = child.stdio[3];
3457
- let pending = "";
3458
- let accepted = false;
3459
- let failed = false;
3460
- let expectedExit;
3461
- let deadline;
3462
- let reportCompletion;
3463
- const completed = new Promise((resolve) => {
3464
- reportCompletion = resolve;
3465
- });
3466
- const boundCleanup = () => {
3467
- deadline ??= setTimeout(() => {
3468
- reportCompletion("unconfirmed");
3469
- control2.destroy();
3470
- child.stdin?.destroy();
3471
- child.stdout.destroy();
3472
- child.stderr.destroy();
3473
- child.unref();
3474
- }, 8e3);
3475
- };
3476
- const revoke = () => {
3477
- if (!control2.writableEnded && !control2.destroyed) control2.end();
3478
- boundCleanup();
3479
- };
3480
- const rejectReport = () => {
3481
- failed = true;
3482
- revoke();
3483
- };
3484
- control2.setEncoding("utf8");
3485
- control2.on("error", rejectReport);
3486
- control2.on("data", (chunk) => {
3487
- if (failed) return;
3488
- pending += chunk;
3489
- if (pending.length > 256) return rejectReport();
3490
- let newline = pending.indexOf("\n");
3491
- while (newline !== -1) {
3492
- try {
3493
- const value = JSON.parse(pending.slice(0, newline));
3494
- if (expectedExit !== void 0) return rejectReport();
3495
- if (value.event === "started" && !accepted) accepted = true;
3496
- else if (value.event === "cancelled") expectedExit = 143;
3497
- else if (accepted && value.event === "finished" && Number.isInteger(value.exit_code) && value.exit_code >= 0 && value.exit_code <= 255)
3498
- expectedExit = value.exit_code;
3499
- else return rejectReport();
3500
- } catch {
3501
- return rejectReport();
3502
- }
3503
- pending = pending.slice(newline + 1);
3504
- newline = pending.indexOf("\n");
3505
- }
3506
- });
3507
- child.once("exit", boundCleanup);
3508
- child.once("close", (code, signal) => {
3509
- clearTimeout(deadline);
3510
- reportCompletion(
3511
- !failed && pending === "" && signal === null && code === expectedExit ? "clean" : "unconfirmed"
3512
- );
3513
- });
3514
- lifecycles.set(child, { revoke, completed });
3515
- control2.write(frame);
3516
- return child;
3517
- };
3518
-
3519
4502
  // src/permissions/system-bash.ts
3520
4503
  import {
3521
- accessSync as accessSync3,
3522
- constants as constants5,
3523
- lstatSync as lstatSync7,
3524
- readlinkSync as readlinkSync4
4504
+ accessSync as accessSync4,
4505
+ constants as constants6,
4506
+ lstatSync as lstatSync9,
4507
+ readlinkSync as readlinkSync5
3525
4508
  } from "fs";
3526
4509
  import { posix } from "path";
3527
4510
  var conventional = ["/bin/bash", "/usr/bin/bash"];
3528
4511
  var nixSystemBash = "/run/current-system/sw/bin/bash";
3529
4512
  var nixStoreBash = /^\/nix\/store\/[^/]+\/bin\/bash$/u;
3530
4513
  var hostEntries = {
3531
- stat: (name) => lstatSync7(name, { throwIfNoEntry: false }),
3532
- readLink: readlinkSync4,
3533
- canExecute: (name) => accessSync3(name, constants5.X_OK)
4514
+ stat: (name) => lstatSync9(name, { throwIfNoEntry: false }),
4515
+ readLink: readlinkSync5,
4516
+ canExecute: (name) => accessSync4(name, constants6.X_OK)
3534
4517
  };
3535
4518
  var trustedDirectory = (name, entry) => entry.uid === 0 && entry.isDirectory() && ((entry.mode & 18) === 0 || // Nix builders can create new store entries in a sticky store. They
3536
4519
  // cannot replace the existing root-owned links and outputs we use.
@@ -3577,23 +4560,23 @@ var resolveSystemBash = (platform = process.platform, entries = hostEntries) =>
3577
4560
  };
3578
4561
 
3579
4562
  // src/permissions/workspace-config-paths.ts
3580
- import { lstatSync as lstatSync8, opendirSync as opendirSync2, readlinkSync as readlinkSync5, realpathSync as realpathSync7 } from "fs";
3581
- import path12 from "path";
4563
+ import { lstatSync as lstatSync10, opendirSync as opendirSync2, readlinkSync as readlinkSync6, realpathSync as realpathSync8 } from "fs";
4564
+ import path13 from "path";
3582
4565
  import { resolveStoragePaths as resolveStoragePaths2 } from "@codelia/storage";
3583
4566
  var confinedAutoLaunchDirectoryName = "confined-auto-launch";
3584
- var isWorkspaceConfigName = (root, target) => resourceContainsPath(path12.dirname(resolveProjectConfigPath(root)), target);
4567
+ var isWorkspaceConfigName = (root, target) => resourceContainsPath(path13.dirname(resolveProjectConfigPath(root)), target);
3585
4568
  var missing2 = (error) => error.code === "ENOENT";
3586
4569
  function resolveConfigTarget(target, remaining = 64) {
3587
4570
  if (!remaining) throw new Error("workspace_config_path_unresolved");
3588
4571
  try {
3589
- return realpathSync7(target);
4572
+ return realpathSync8(target);
3590
4573
  } catch (error) {
3591
- const parent = path12.dirname(target);
4574
+ const parent = path13.dirname(target);
3592
4575
  if (!missing2(error) || parent === target) throw error;
3593
4576
  const canonicalParent = resolveConfigTarget(parent, remaining - 1);
3594
- if (!lstatSync8(target, { throwIfNoEntry: false })?.isSymbolicLink())
3595
- return path12.join(canonicalParent, path12.basename(target));
3596
- const referent = readlinkSync5(target);
4577
+ if (!lstatSync10(target, { throwIfNoEntry: false })?.isSymbolicLink())
4578
+ return path13.join(canonicalParent, path13.basename(target));
4579
+ const referent = readlinkSync6(target);
3597
4580
  let seenName = false;
3598
4581
  for (const part of referent.split(
3599
4582
  process.platform === "win32" ? /[\\/]/u : "/"
@@ -3603,14 +4586,14 @@ function resolveConfigTarget(target, remaining = 64) {
3603
4586
  if (part && part !== "." && part !== "..") seenName = true;
3604
4587
  }
3605
4588
  return resolveConfigTarget(
3606
- path12.resolve(canonicalParent, referent),
4589
+ path13.resolve(canonicalParent, referent),
3607
4590
  remaining - 1
3608
4591
  );
3609
4592
  }
3610
4593
  }
3611
4594
  var workspaceConfigProtection = (root) => {
3612
4595
  const config = resolveProjectConfigPath(root);
3613
- const directory = path12.dirname(config);
4596
+ const directory = path13.dirname(config);
3614
4597
  const readOnlyPaths = /* @__PURE__ */ new Set([directory]);
3615
4598
  const readOnlyAliasPaths = /* @__PURE__ */ new Set();
3616
4599
  const reserveTarget = (file) => {
@@ -3618,12 +4601,12 @@ var workspaceConfigProtection = (root) => {
3618
4601
  readOnlyPaths.add(target);
3619
4602
  readOnlyAliasPaths.add(target);
3620
4603
  };
3621
- if (lstatSync8(directory, { throwIfNoEntry: false })) {
4604
+ if (lstatSync10(directory, { throwIfNoEntry: false })) {
3622
4605
  const canonical = resolveConfigTarget(directory);
3623
4606
  readOnlyPaths.add(canonical);
3624
- if (lstatSync8(canonical, { throwIfNoEntry: false })?.isDirectory()) {
3625
- const file = path12.join(canonical, path12.basename(config));
3626
- if (lstatSync8(file, { throwIfNoEntry: false })) reserveTarget(file);
4607
+ if (lstatSync10(canonical, { throwIfNoEntry: false })?.isDirectory()) {
4608
+ const file = path13.join(canonical, path13.basename(config));
4609
+ if (lstatSync10(file, { throwIfNoEntry: false })) reserveTarget(file);
3627
4610
  const storage = resolveStoragePaths2();
3628
4611
  const globalStorage = [
3629
4612
  resolveStoragePaths2({ layout: "home" }).root,
@@ -3631,24 +4614,24 @@ var workspaceConfigProtection = (root) => {
3631
4614
  storage.configDir
3632
4615
  ].some((entry) => {
3633
4616
  try {
3634
- return realpathSync7(entry) === canonical;
4617
+ return realpathSync8(entry) === canonical;
3635
4618
  } catch (error) {
3636
4619
  if (!missing2(error)) throw error;
3637
4620
  return false;
3638
4621
  }
3639
4622
  });
3640
4623
  if (!globalStorage) {
3641
- const worktrees = path12.join(canonical, "worktrees");
4624
+ const worktrees = path13.join(canonical, "worktrees");
3642
4625
  const pending = [canonical];
3643
4626
  for (const current of pending) {
3644
4627
  const children = opendirSync2(current);
3645
4628
  try {
3646
4629
  for (let entry = children.readSync(); entry; entry = children.readSync()) {
3647
- const target = path12.join(current, entry.name);
4630
+ const target = path13.join(current, entry.name);
3648
4631
  if (target === file || target === worktrees) continue;
3649
4632
  if (entry.isSymbolicLink()) reserveTarget(target);
3650
4633
  else if (entry.isDirectory()) pending.push(target);
3651
- else if (entry.isFile() && (lstatSync8(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
4634
+ else if (entry.isFile() && (lstatSync10(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
3652
4635
  readOnlyAliasPaths.add(target);
3653
4636
  }
3654
4637
  } finally {
@@ -3686,11 +4669,11 @@ var platformShellSource = (source) => {
3686
4669
  return fixedBash(source, executable);
3687
4670
  }
3688
4671
  const systemRoot = process.env.SystemRoot;
3689
- if (!systemRoot || !path13.isAbsolute(systemRoot))
4672
+ if (!systemRoot || !path14.isAbsolute(systemRoot))
3690
4673
  throw new Error("windows_system_directory_unavailable");
3691
4674
  return Object.freeze({
3692
4675
  kind: "source",
3693
- executable: path13.join(
4676
+ executable: path14.join(
3694
4677
  systemRoot,
3695
4678
  "System32",
3696
4679
  "WindowsPowerShell",
@@ -3709,27 +4692,27 @@ var platformShellSource = (source) => {
3709
4692
  };
3710
4693
  var realOrLexical = (value) => {
3711
4694
  try {
3712
- return realpathSync8(value);
4695
+ return realpathSync9(value);
3713
4696
  } catch {
3714
- return path13.resolve(value);
4697
+ return path14.resolve(value);
3715
4698
  }
3716
4699
  };
3717
4700
  var resolvePolicyPath = (target) => {
3718
- const absolute = path13.resolve(target);
4701
+ const absolute = path14.resolve(target);
3719
4702
  try {
3720
- return realpathSync8(absolute);
4703
+ return realpathSync9(absolute);
3721
4704
  } catch (error) {
3722
- const parent = path13.dirname(absolute);
4705
+ const parent = path14.dirname(absolute);
3723
4706
  if (error.code !== "ENOENT" || parent === absolute)
3724
4707
  throw error;
3725
- if (lstatSync9(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
4708
+ if (lstatSync11(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
3726
4709
  throw error;
3727
- return path13.join(resolvePolicyPath(parent), path13.basename(absolute));
4710
+ return path14.join(resolvePolicyPath(parent), path14.basename(absolute));
3728
4711
  }
3729
4712
  };
3730
4713
  var canonicalPolicyPaths = (paths) => Object.freeze([
3731
4714
  ...new Set(
3732
- paths.flatMap((entry) => [path13.resolve(entry), resolvePolicyPath(entry)])
4715
+ paths.flatMap((entry) => [path14.resolve(entry), resolvePolicyPath(entry)])
3733
4716
  )
3734
4717
  ]);
3735
4718
  var runtimeReadOnlyPaths = () => {
@@ -3749,12 +4732,12 @@ var runtimeProtectedCredentialPaths = () => {
3749
4732
  mkdirSync2(storage.credentialsDir, { recursive: true, mode: 448 });
3750
4733
  targets.push(storage.credentialsDir);
3751
4734
  } catch {
3752
- if (lstatSync9(storage.credentialsDir, { throwIfNoEntry: false })) {
4735
+ if (lstatSync11(storage.credentialsDir, { throwIfNoEntry: false })) {
3753
4736
  targets.push(storage.credentialsDir);
3754
4737
  }
3755
4738
  }
3756
4739
  for (const legacy of [storage.legacyAuthFile, storage.legacyMcpAuthFile]) {
3757
- if (lstatSync9(legacy, { throwIfNoEntry: false })) {
4740
+ if (lstatSync11(legacy, { throwIfNoEntry: false })) {
3758
4741
  targets.push(legacy);
3759
4742
  }
3760
4743
  }
@@ -3770,8 +4753,8 @@ var runtimeProtectedCredentialPaths = () => {
3770
4753
  var runtimeAuthorityAliasPaths = () => {
3771
4754
  const storage = resolveStoragePaths3();
3772
4755
  const databasePaths = [
3773
- path13.join(storage.configDir, ".projects-policy-lock.sqlite"),
3774
- path13.join(storage.sessionsDir, "state.db")
4756
+ path14.join(storage.configDir, ".projects-policy-lock.sqlite"),
4757
+ path14.join(storage.sessionsDir, "state.db")
3775
4758
  ];
3776
4759
  return canonicalPolicyPaths([
3777
4760
  resolveConfigPath(),
@@ -3781,15 +4764,22 @@ var runtimeAuthorityAliasPaths = () => {
3781
4764
  "launch-approvals",
3782
4765
  "auto-review.json",
3783
4766
  confinedAutoLaunchDirectoryName
3784
- ].map((entry) => path13.join(storage.configDir, entry)),
4767
+ ].map((entry) => path14.join(storage.configDir, entry)),
3785
4768
  ...databasePaths.flatMap(
3786
4769
  (file) => ["", "-wal", "-shm", "-journal"].map((suffix) => `${file}${suffix}`)
3787
4770
  )
3788
4771
  ]);
3789
4772
  };
3790
4773
  var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectories = [], sandboxMode = "workspace-write", allowSharedGitObjects = false, extraReadOnlyPaths = [], homeScope = {}) => {
3791
- const discover = allowSharedGitObjects && sandboxMode === "workspace-write" ? gitMetadataWithObjectDirectories : gitMetadataPaths;
3792
- const { readOnlyPaths, reservedMarkers, objectDirectories, hookAliases } = discover(root, ...relatedDirectories);
4774
+ const discover = allowSharedGitObjects && sandboxMode === "workspace-write" && !homeScope.gitWrites ? gitMetadataWithObjectDirectories : gitMetadataPaths;
4775
+ const metadata = discover(root, ...relatedDirectories);
4776
+ const { reservedMarkers, objectDirectories, hookAliases } = metadata;
4777
+ const gitScope = homeScope.gitWrites ? gitWriteScope(metadata.repositories) : void 0;
4778
+ const released = new Set(gitScope?.releasedPaths ?? []);
4779
+ const readOnlyPaths = gitScope ? [
4780
+ ...metadata.readOnlyPaths.filter((entry) => !released.has(entry)),
4781
+ ...gitScope.readOnlyPaths
4782
+ ] : metadata.readOnlyPaths;
3793
4783
  const protectedPaths = canonicalPolicyPaths([
3794
4784
  ...extraProtectedPaths,
3795
4785
  ...runtimeProtectedCredentialPaths()
@@ -3815,14 +4805,23 @@ var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectorie
3815
4805
  const objectDirectoriesWithSharedFiles = objectDirectories.filter(
3816
4806
  (directory) => {
3817
4807
  const overlaps = (other) => resourceContainsPath(other, directory.path) || resourceContainsPath(directory.path, other);
3818
- const commonDirectory = path13.dirname(directory.path);
4808
+ const commonDirectory = path14.dirname(directory.path);
3819
4809
  return !strongerPaths.some(overlaps) && !readOnlyPaths.some(
3820
4810
  (other) => overlaps(other) && realOrLexical(other) !== commonDirectory
3821
4811
  );
3822
4812
  }
3823
4813
  );
4814
+ const gitWriteRoots = (gitScope?.writeRoots ?? []).filter(
4815
+ (directory) => directory !== path14.parse(directory).root && !(homeScope.writeRoots ?? []).some((root2) => isWithin(root2, directory)) && !strongerPaths.some(
4816
+ (entry) => isWithin(entry, directory) || isWithin(directory, entry)
4817
+ )
4818
+ );
3824
4819
  return {
3825
4820
  ...protectedHome ? { homeDotDirectory: protectedHome } : {},
4821
+ ...gitScope && gitScope.releasedPaths.length > 0 ? {
4822
+ ...gitWriteRoots.length ? { gitWriteRoots } : {},
4823
+ gitProtectedPaths: gitScope.readOnlyPaths
4824
+ } : {},
3826
4825
  protectedPaths,
3827
4826
  protectedAliasPaths: protectedPaths,
3828
4827
  readOnlyPaths: Object.freeze(
@@ -3859,26 +4858,48 @@ var protectedSeatbeltAncestors = (base) => {
3859
4858
  ...base.readOnlyPaths ?? [],
3860
4859
  ...base.homeDotDirectory ? [base.homeDotDirectory] : []
3861
4860
  ]) {
3862
- for (let child = protectedPath, parent = path13.dirname(child); parent !== child; child = parent, parent = path13.dirname(child)) {
3863
- if (base.writeRoots.some((root) => isWithin(root, parent)))
4861
+ for (let child = protectedPath, parent = path14.dirname(child); parent !== child; child = parent, parent = path14.dirname(child)) {
4862
+ if ([...base.writeRoots, ...base.gitWriteRoots ?? []].some(
4863
+ (root) => isWithin(root, parent)
4864
+ ))
4865
+ parents.add(parent);
4866
+ }
4867
+ }
4868
+ return [...parents];
4869
+ };
4870
+ var absentProtectedSeatbeltAncestors = (base) => {
4871
+ const gitProtected = base.gitProtectedPaths ?? [];
4872
+ if (!gitProtected.length) return [];
4873
+ const writableRoots = [...base.writeRoots, ...base.gitWriteRoots ?? []];
4874
+ const parents = /* @__PURE__ */ new Set();
4875
+ for (const protectedPath of gitProtected) {
4876
+ for (let child = protectedPath, parent = path14.dirname(child); parent !== child; child = parent, parent = path14.dirname(child)) {
4877
+ if (writableRoots.some((root) => isWithin(root, parent)) && !lstatSync11(parent, { throwIfNoEntry: false }))
3864
4878
  parents.add(parent);
3865
4879
  }
3866
4880
  }
3867
4881
  return [...parents];
3868
4882
  };
3869
4883
  var literal = (entry) => `(literal ${sbplString(entry)})`;
4884
+ var pseudoTerminalRules = `(allow pseudo-tty)
4885
+ (allow file-read* file-write* file-ioctl (literal "/dev/ptmx"))
4886
+ (allow file-read* file-write*
4887
+ (require-all (regex #"^/dev/ttys[0-9]+$") (extension "com.apple.sandbox.pty")))
4888
+ (allow file-ioctl (regex #"^/dev/ttys[0-9]+$"))`;
3870
4889
  var seatbeltProfile = (base, scratch, mutation) => {
3871
4890
  const deviceAndIpcPaths = ["/dev", "/private/var/run"];
3872
- const ancestors = protectedSeatbeltAncestors({
4891
+ const ancestorList = protectedSeatbeltAncestors({
3873
4892
  ...base,
3874
4893
  protectedPaths: [...base.protectedPaths, ...deviceAndIpcPaths]
3875
- }).map(literal).join(" ");
4894
+ });
4895
+ const ancestors = ancestorList.map(literal).join(" ");
4896
+ const absentAncestors = absentProtectedSeatbeltAncestors(base).map(literal).join(" ");
3876
4897
  const home = base.homeDotDirectory;
3877
- const homeRule = home ? `(deny file-write* (prefix ${sbplString(`${path13.join(home, "/")}.`)}) ${subpaths([path13.join(home, "Library")])})` : "";
4898
+ const homeRule = home ? `(deny file-write* (prefix ${sbplString(`${path14.join(home, "/")}.`)}) ${subpaths([path14.join(home, "Library")])})` : "";
3878
4899
  const approvedHomeDotRoots = !mutation && home ? base.writeRoots.filter(
3879
4900
  (root) => root !== home && isHomeDotTarget(home, root)
3880
4901
  ) : [];
3881
- const writeTrees = mutation ? [scratch] : [scratch, ...base.writeRoots];
4902
+ const writeTrees = mutation ? [scratch] : [scratch, ...base.writeRoots, ...base.gitWriteRoots ?? []];
3882
4903
  const fixedWriteRules = mutation && [
3883
4904
  mutation.directories.length ? `(allow file-write-create ${mutation.directories.map(literal).join(" ")})` : "",
3884
4905
  mutation.destination ? `(allow file-write-create file-write-data file-write-mode ${literal(mutation.destination)})` : "",
@@ -3898,17 +4919,19 @@ ${fixedWriteRules ?? ""}
3898
4919
  (allow file-read* (literal "/dev/null") (literal "/dev/zero")
3899
4920
  (literal "/dev/random") (literal "/dev/urandom"))
3900
4921
  (allow file-write-data (literal "/dev/null"))
4922
+ ${mutation ? "" : pseudoTerminalRules}
3901
4923
  ${homeRule}
3902
4924
  ${approvedHomeDotRoots.length ? `(allow file-write* ${subpaths(approvedHomeDotRoots)})` : ""}
3903
4925
  ${base.protectedPaths.length ? `(deny file-read* file-write* ${subpaths(base.protectedPaths)})` : ""}
3904
4926
  ${base.readOnlyPaths?.length ? `(deny file-write* ${subpaths(base.readOnlyPaths)})` : ""}
3905
4927
  ${ancestors ? `(deny file-write-unlink ${ancestors})` : ""}
4928
+ ${absentAncestors ? `(deny file-write-create ${absentAncestors})` : ""}
3906
4929
  (deny network*)
3907
4930
  (deny file-write-setugid)
3908
4931
  `;
3909
4932
  };
3910
4933
  var sandboxExec = "/usr/bin/sandbox-exec";
3911
- var macAdditionalWriteLauncherPaths = (protection) => {
4934
+ var mxcAdditionalWriteLauncherPaths = (protection) => {
3912
4935
  const baseline = resolveMxcLauncher({
3913
4936
  ...protection,
3914
4937
  writeRoots: [protection.root],
@@ -3916,11 +4939,12 @@ var macAdditionalWriteLauncherPaths = (protection) => {
3916
4939
  });
3917
4940
  const selected = resolveMxcLauncher(protection);
3918
4941
  return [
3919
- ...new Set(
3920
- [baseline, selected].flatMap(
4942
+ .../* @__PURE__ */ new Set([
4943
+ ...[baseline, selected].flatMap(
3921
4944
  (launcher) => launcher ? [launcher.candidate, launcher.file] : []
3922
- )
3923
- )
4945
+ ),
4946
+ ...linuxMxcManagedToolPaths()
4947
+ ])
3924
4948
  ];
3925
4949
  };
3926
4950
  var MacSeatbeltBackend = class {
@@ -3930,6 +4954,7 @@ var MacSeatbeltBackend = class {
3930
4954
  launcher;
3931
4955
  supportsReadOnlyPaths = true;
3932
4956
  supportsHomeDotProtection = true;
4957
+ supportsAbsentPathDenial = true;
3933
4958
  supportsCommandBinding = true;
3934
4959
  available;
3935
4960
  mxcProbe;
@@ -3946,7 +4971,7 @@ var MacSeatbeltBackend = class {
3946
4971
  return false;
3947
4972
  try {
3948
4973
  if (mutation && (protection.profile !== "development" || protection.stdin !== "pipe" || [...mutation.directories, mutation.destination, mutation.source].some(
3949
- (entry) => entry !== void 0 && (!path13.isAbsolute(entry) || path13.normalize(entry) !== entry || !protection.writeRoots.some(
4974
+ (entry) => entry !== void 0 && (!path14.isAbsolute(entry) || path14.normalize(entry) !== entry || !protection.writeRoots.some(
3950
4975
  (root) => entry !== root && isWithin(root, entry)
3951
4976
  ))
3952
4977
  )))
@@ -4031,12 +5056,12 @@ var MacSeatbeltBackend = class {
4031
5056
  launchWithPolicy(invocation, protection, mutation) {
4032
5057
  if (!(mutation ? this.supportsPolicy(protection, mutation) : this.supports(protection)))
4033
5058
  throw new Error("sandbox_unavailable");
4034
- const scratch = realpathSync8(
4035
- mkdtempSync2(path13.join(os2.tmpdir(), "codelia-shell-"))
5059
+ const scratch = realpathSync9(
5060
+ mkdtempSync3(path14.join(os3.tmpdir(), "codelia-shell-"))
4036
5061
  );
4037
5062
  const cleanup = () => {
4038
5063
  try {
4039
- rmSync2(scratch, { recursive: true, force: true });
5064
+ rmSync3(scratch, { recursive: true, force: true });
4040
5065
  } catch {
4041
5066
  }
4042
5067
  };
@@ -4056,6 +5081,7 @@ var MacSeatbeltBackend = class {
4056
5081
  profile,
4057
5082
  scratch,
4058
5083
  path: shellPathForLaunch(protection.binPaths),
5084
+ home: os3.homedir(),
4059
5085
  cargo_home: protection.toolchainHomes?.CARGO_HOME,
4060
5086
  rustup_home: protection.toolchainHomes?.RUSTUP_HOME
4061
5087
  },
@@ -4072,7 +5098,7 @@ var MacSeatbeltBackend = class {
4072
5098
  env: {
4073
5099
  PATH: shellPathForLaunch(protection.binPaths),
4074
5100
  LANG: "C",
4075
- HOME: scratch,
5101
+ HOME: os3.homedir(),
4076
5102
  TMPDIR: scratch,
4077
5103
  XDG_CACHE_HOME: scratch,
4078
5104
  GIT_OPTIONAL_LOCKS: "0",
@@ -4095,6 +5121,39 @@ var MacSeatbeltBackend = class {
4095
5121
  }
4096
5122
  };
4097
5123
  var createMacMxcShellBackend = () => new MacSeatbeltBackend("mxc");
5124
+ var createLinuxMxcShellBackend = () => new LinuxMxcBackend();
5125
+ var SCRUBBED_LOGIN_ENV_KEYS = /* @__PURE__ */ new Set([
5126
+ "BASH_ENV",
5127
+ "ENV",
5128
+ "SHELLOPTS",
5129
+ "BASHOPTS",
5130
+ "PS4",
5131
+ "PROMPT_COMMAND",
5132
+ "CDPATH",
5133
+ "GLOBIGNORE",
5134
+ "FPATH",
5135
+ "ZDOTDIR",
5136
+ "IFS",
5137
+ "NODE_OPTIONS",
5138
+ "PYTHONSTARTUP",
5139
+ "PERL5OPT",
5140
+ "RUBYOPT",
5141
+ "LD_PRELOAD",
5142
+ "LD_LIBRARY_PATH",
5143
+ "DYLD_INSERT_LIBRARIES",
5144
+ "DYLD_LIBRARY_PATH",
5145
+ "DYLD_FRAMEWORK_PATH"
5146
+ ]);
5147
+ var loginUserEnvironment = (sourceEnv = process.env) => {
5148
+ const env = {};
5149
+ for (const [key, value] of Object.entries(sourceEnv)) {
5150
+ if (value === void 0) continue;
5151
+ if (SCRUBBED_LOGIN_ENV_KEYS.has(key) || key.startsWith("BASH_FUNC_") || key.startsWith("LD_") || key.startsWith("DYLD_"))
5152
+ continue;
5153
+ env[key] = value;
5154
+ }
5155
+ return env;
5156
+ };
4098
5157
  var UserShellBackend = class {
4099
5158
  supportsCommandBinding = true;
4100
5159
  supports(protection) {
@@ -4108,16 +5167,17 @@ var UserShellBackend = class {
4108
5167
  shell: false,
4109
5168
  windowsHide: true,
4110
5169
  env: {
5170
+ ...loginUserEnvironment(),
4111
5171
  PATH: shellPathForLaunch(protection.binPaths),
4112
- HOME: os2.homedir(),
4113
- TMPDIR: os2.tmpdir(),
5172
+ HOME: os3.homedir(),
5173
+ TMPDIR: os3.tmpdir(),
4114
5174
  LANG: "C",
4115
5175
  ...protection.toolchainHomes,
4116
5176
  ...process.platform === "win32" && {
4117
5177
  SystemRoot: process.env.SystemRoot,
4118
- USERPROFILE: os2.homedir(),
4119
- TEMP: os2.tmpdir(),
4120
- TMP: os2.tmpdir()
5178
+ USERPROFILE: os3.homedir(),
5179
+ TEMP: os3.tmpdir(),
5180
+ TMP: os3.tmpdir()
4121
5181
  }
4122
5182
  },
4123
5183
  stdio: [protection.stdin === "pipe" ? "pipe" : "ignore", "pipe", "pipe"]
@@ -4126,18 +5186,24 @@ var UserShellBackend = class {
4126
5186
  };
4127
5187
  var standardMacBackend;
4128
5188
  var explicitMacMxcBackend;
4129
- var standardLinuxBackend;
5189
+ var standardLinuxMxcBackend;
5190
+ var fallbackLinuxRunscBackend;
4130
5191
  var selectProtectedShellBackend = ({
4131
5192
  platform = process.platform,
4132
5193
  allowStandard,
4133
5194
  adapter,
4134
- macBackend = "seatbelt"
5195
+ macBackend = "seatbelt",
5196
+ linuxBackend = "mxc"
4135
5197
  }) => {
4136
5198
  if (adapter) return adapter;
4137
5199
  if (!allowStandard) return void 0;
4138
5200
  if (platform === "linux") {
4139
- standardLinuxBackend ??= new LinuxRunscBackend();
4140
- return standardLinuxBackend;
5201
+ if (linuxBackend === "gvisor") {
5202
+ fallbackLinuxRunscBackend ??= new LinuxRunscBackend();
5203
+ return fallbackLinuxRunscBackend;
5204
+ }
5205
+ standardLinuxMxcBackend ??= new LinuxMxcBackend();
5206
+ return standardLinuxMxcBackend;
4141
5207
  }
4142
5208
  if (platform === "darwin") {
4143
5209
  if (macBackend === "mxc") {
@@ -4150,7 +5216,7 @@ var selectProtectedShellBackend = ({
4150
5216
  return void 0;
4151
5217
  };
4152
5218
  var directoryIdentity = (directory) => {
4153
- const stat = statSync5(directory, { bigint: true });
5219
+ const stat = statSync6(directory, { bigint: true });
4154
5220
  if (!stat.isDirectory()) throw new Error("invalid_working_directory");
4155
5221
  return `${stat.dev}:${stat.ino}`;
4156
5222
  };
@@ -4178,6 +5244,7 @@ import {
4178
5244
  ZAI_DEFAULT_MODEL,
4179
5245
  ZAI_REASONING_EFFORT_MODELS
4180
5246
  } from "@codelia/core";
5247
+ import { isDebugEnabled as isDebugEnabled2 } from "@codelia/logger";
4181
5248
  import { ModelMetadataServiceImpl } from "@codelia/model-metadata";
4182
5249
  import { StoragePathServiceImpl as StoragePathServiceImpl2 } from "@codelia/storage";
4183
5250
 
@@ -4712,17 +5779,12 @@ var requireApiKeyAuth = (provider, auth) => {
4712
5779
  }
4713
5780
  return auth.api_key;
4714
5781
  };
4715
- var envTruthy = (value) => {
4716
- if (!value) return false;
4717
- const normalized = value.trim().toLowerCase();
4718
- return normalized === "1" || normalized === "true";
4719
- };
4720
5782
  var buildOpenAiClientOptions = (getOpenAiAccessToken, auth, log2) => {
4721
5783
  if (auth.method === "api_key") {
4722
5784
  return { apiKey: auth.api_key };
4723
5785
  }
4724
5786
  let accountId = auth.oauth.account_id;
4725
- const enableDebugHttp = envTruthy(process.env.CODELIA_DEBUG);
5787
+ const enableDebugHttp = isDebugEnabled2();
4726
5788
  const apiKey = async () => {
4727
5789
  if (!getOpenAiAccessToken) {
4728
5790
  throw new Error("OpenAI OAuth token refresh is unavailable");
@@ -5088,10 +6150,10 @@ var createRuntimeModel = async ({
5088
6150
 
5089
6151
  // src/runtime-state.ts
5090
6152
  import crypto from "crypto";
5091
- import { realpathSync as realpathSync9 } from "fs";
6153
+ import { realpathSync as realpathSync10 } from "fs";
5092
6154
 
5093
6155
  // src/environment.ts
5094
- import path14 from "path";
6156
+ import path15 from "path";
5095
6157
  import {
5096
6158
  parseSandboxMode
5097
6159
  } from "@codelia/shared-types";
@@ -5104,7 +6166,7 @@ var cloneContract = (contract) => ({
5104
6166
  persistence: { ...contract.persistence },
5105
6167
  events: { ...contract.events }
5106
6168
  });
5107
- var defaultWorkspaceRoot = () => process.env.CODELIA_SANDBOX_ROOT ? path14.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
6169
+ var defaultWorkspaceRoot = () => process.env.CODELIA_SANDBOX_ROOT ? path15.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
5108
6170
  var runtimeEnvironmentPresets = {
5109
6171
  "tui-local": {
5110
6172
  workspace: {
@@ -5229,11 +6291,11 @@ var resolveRuntimeEnvironment = (options = {}) => {
5229
6291
  if (contract.workspace.sandboxMode !== void 0 && !parseSandboxMode(contract.workspace.sandboxMode))
5230
6292
  throw new Error("Invalid workspace.sandboxMode");
5231
6293
  if (contract.workspace.filesystem === "enabled" || contract.workspace.process === "runtime") {
5232
- contract.workspace.root = path14.resolve(
6294
+ contract.workspace.root = path15.resolve(
5233
6295
  contract.workspace.root ?? defaultWorkspaceRoot()
5234
6296
  );
5235
6297
  } else if (contract.workspace.root) {
5236
- contract.workspace.root = path14.resolve(contract.workspace.root);
6298
+ contract.workspace.root = path15.resolve(contract.workspace.root);
5237
6299
  }
5238
6300
  rejectContract(
5239
6301
  contract.workspace.filesystem === "disabled" && (contract.context.projectInstructions === "from-workspace" || contract.context.skills === "from-config" || contract.context.executionEnvironment === "from-config" || contract.tools.builtin === "full-coding-agent" || contract.tools.mcp === "from-config"),
@@ -5345,9 +6407,6 @@ var resolveRuntimeSandboxMode = async (environment, input = {}) => {
5345
6407
  const modeFlag = readFlag(args, "--sandbox-mode");
5346
6408
  if (modeFlag !== void 0)
5347
6409
  return parseMode(modeFlag, "--sandbox-mode", "cli", false);
5348
- const legacyFlag = readFlag(args, "--approval-mode");
5349
- if (legacyFlag !== void 0)
5350
- return parseMode(legacyFlag, "--approval-mode", "cli", true);
5351
6410
  if (env.CODELIA_SANDBOX_MODE !== void 0)
5352
6411
  return parseMode(
5353
6412
  env.CODELIA_SANDBOX_MODE,
@@ -5355,13 +6414,6 @@ var resolveRuntimeSandboxMode = async (environment, input = {}) => {
5355
6414
  "env",
5356
6415
  false
5357
6416
  );
5358
- if (env.CODELIA_APPROVAL_MODE !== void 0)
5359
- return parseMode(
5360
- env.CODELIA_APPROVAL_MODE,
5361
- "CODELIA_APPROVAL_MODE",
5362
- "env",
5363
- true
5364
- );
5365
6417
  const store = input.store ?? new ProjectsPolicyStore();
5366
6418
  const projectKey = await fs3.realpath(root).catch((error) => {
5367
6419
  if (error.code !== "ENOENT") throw error;
@@ -5383,6 +6435,213 @@ var resolveRuntimeSandboxMode = async (environment, input = {}) => {
5383
6435
  return defaultSandboxMode;
5384
6436
  };
5385
6437
 
6438
+ // src/telemetry.ts
6439
+ var MAX_RECENT_CALLS = 64;
6440
+ var MAX_RECENT_TOOLS = 64;
6441
+ var cloneModelUsage = (entry) => ({
6442
+ ...entry
6443
+ });
6444
+ var createEmptyTelemetrySummary = () => ({
6445
+ total_calls: 0,
6446
+ total_tokens: 0,
6447
+ total_input_tokens: 0,
6448
+ total_output_tokens: 0,
6449
+ total_output_reasoning_tokens: 0,
6450
+ total_cached_input_tokens: 0,
6451
+ total_cache_creation_tokens: 0,
6452
+ total_input_image_tokens: 0,
6453
+ cache_hit_calls: 0,
6454
+ cache_miss_calls: 0,
6455
+ cache_unknown_calls: 0,
6456
+ total_cost_usd: null,
6457
+ retry_count: 0,
6458
+ retry_wait_ms: 0,
6459
+ tool_calls: 0,
6460
+ tool_errors: 0,
6461
+ tool_exec_ms: 0,
6462
+ tool_approval_wait_ms: 0,
6463
+ compaction_count: 0,
6464
+ compaction_duration_ms: 0,
6465
+ by_model: {}
6466
+ });
6467
+ var cloneTelemetrySummary = (summary) => ({
6468
+ ...summary,
6469
+ by_model: Object.fromEntries(
6470
+ Object.entries(summary.by_model).map(([model, entry]) => [
6471
+ model,
6472
+ cloneModelUsage(entry)
6473
+ ])
6474
+ )
6475
+ });
6476
+ var applyCallToSummary = (summary, call) => {
6477
+ const usage = call.usage ?? null;
6478
+ const inputTokens = usage?.input_tokens ?? 0;
6479
+ const outputTokens = usage?.output_tokens ?? 0;
6480
+ const reasoningTokens = usage?.output_reasoning_tokens ?? 0;
6481
+ const cachedTokens = usage?.input_cached_tokens ?? 0;
6482
+ const cacheCreationTokens = usage?.input_cache_creation_tokens ?? 0;
6483
+ const imageTokens = usage?.input_image_tokens ?? 0;
6484
+ const totalTokens = usage?.total_tokens ?? 0;
6485
+ const hitState = call.cache?.hit_state ?? (typeof usage?.input_cached_tokens === "number" ? cachedTokens > 0 ? "hit" : "miss" : "unknown");
6486
+ const validCost = typeof call.cost_usd === "number" && Number.isFinite(call.cost_usd) && call.cost_usd >= 0 ? call.cost_usd : null;
6487
+ summary.total_calls += 1;
6488
+ summary.total_tokens += totalTokens;
6489
+ summary.total_input_tokens += inputTokens;
6490
+ summary.total_output_tokens += outputTokens;
6491
+ summary.total_output_reasoning_tokens += reasoningTokens;
6492
+ summary.total_cached_input_tokens += cachedTokens;
6493
+ summary.total_cache_creation_tokens += cacheCreationTokens;
6494
+ summary.total_input_image_tokens += imageTokens;
6495
+ if (hitState === "hit") summary.cache_hit_calls += 1;
6496
+ else if (hitState === "miss") summary.cache_miss_calls += 1;
6497
+ else summary.cache_unknown_calls += 1;
6498
+ if (validCost !== null) {
6499
+ summary.total_cost_usd = (summary.total_cost_usd ?? 0) + validCost;
6500
+ }
6501
+ const modelKey = call.model ?? "unknown";
6502
+ const existing = summary.by_model[modelKey];
6503
+ if (!existing) {
6504
+ summary.by_model[modelKey] = {
6505
+ calls: 1,
6506
+ input_tokens: inputTokens,
6507
+ output_tokens: outputTokens,
6508
+ output_reasoning_tokens: reasoningTokens,
6509
+ cached_input_tokens: cachedTokens,
6510
+ cache_creation_tokens: cacheCreationTokens,
6511
+ input_image_tokens: imageTokens,
6512
+ cache_hit_calls: hitState === "hit" ? 1 : 0,
6513
+ cache_miss_calls: hitState === "miss" ? 1 : 0,
6514
+ cache_unknown_calls: hitState === "unknown" ? 1 : 0,
6515
+ total_tokens: totalTokens,
6516
+ cost_usd: validCost
6517
+ };
6518
+ } else {
6519
+ existing.calls += 1;
6520
+ existing.input_tokens += inputTokens;
6521
+ existing.output_tokens += outputTokens;
6522
+ existing.output_reasoning_tokens += reasoningTokens;
6523
+ existing.cached_input_tokens += cachedTokens;
6524
+ existing.cache_creation_tokens += cacheCreationTokens;
6525
+ existing.input_image_tokens += imageTokens;
6526
+ if (hitState === "hit") existing.cache_hit_calls += 1;
6527
+ else if (hitState === "miss") existing.cache_miss_calls += 1;
6528
+ else existing.cache_unknown_calls += 1;
6529
+ existing.total_tokens += totalTokens;
6530
+ if (validCost !== null) {
6531
+ existing.cost_usd = (existing.cost_usd ?? 0) + validCost;
6532
+ }
6533
+ }
6534
+ };
6535
+ var applyToolToSummary = (summary, record) => {
6536
+ summary.tool_calls += 1;
6537
+ if (record.status === "error") {
6538
+ summary.tool_errors += 1;
6539
+ }
6540
+ summary.tool_exec_ms += Math.max(
6541
+ 0,
6542
+ record.exec_duration_ms ?? record.duration_ms
6543
+ );
6544
+ summary.tool_approval_wait_ms += Math.max(0, record.approval_wait_ms ?? 0);
6545
+ };
6546
+ var applyRetryToSummary = (summary, delayMs) => {
6547
+ summary.retry_count += 1;
6548
+ summary.retry_wait_ms += Math.max(0, Math.round(delayMs));
6549
+ };
6550
+ var applyCompactionToSummary = (summary, durationMs) => {
6551
+ summary.compaction_count += 1;
6552
+ summary.compaction_duration_ms += Math.max(0, durationMs);
6553
+ };
6554
+ var RuntimeTelemetryStore = class {
6555
+ sessionSummary = createEmptyTelemetrySummary();
6556
+ currentRunId = null;
6557
+ currentRunSummary = null;
6558
+ recentCalls = [];
6559
+ recentTools = [];
6560
+ startupPhases = [];
6561
+ agentInitPhases = [];
6562
+ resetSession() {
6563
+ this.sessionSummary = createEmptyTelemetrySummary();
6564
+ this.currentRunId = null;
6565
+ this.currentRunSummary = null;
6566
+ this.recentCalls.length = 0;
6567
+ this.recentTools.length = 0;
6568
+ }
6569
+ beginRun(runId) {
6570
+ this.currentRunId = runId;
6571
+ this.currentRunSummary = createEmptyTelemetrySummary();
6572
+ }
6573
+ recordLlmCall(call) {
6574
+ applyCallToSummary(this.sessionSummary, call);
6575
+ if (this.currentRunId === call.run_id && this.currentRunSummary) {
6576
+ applyCallToSummary(this.currentRunSummary, call);
6577
+ }
6578
+ const { session: _session, ...callRecord } = call;
6579
+ this.recentCalls.push(callRecord);
6580
+ if (this.recentCalls.length > MAX_RECENT_CALLS) {
6581
+ this.recentCalls.shift();
6582
+ }
6583
+ }
6584
+ recordToolComplete(record) {
6585
+ applyToolToSummary(this.sessionSummary, record);
6586
+ if (this.currentRunId === record.run_id && this.currentRunSummary) {
6587
+ applyToolToSummary(this.currentRunSummary, record);
6588
+ }
6589
+ this.recentTools.push(record);
6590
+ if (this.recentTools.length > MAX_RECENT_TOOLS) {
6591
+ this.recentTools.shift();
6592
+ }
6593
+ }
6594
+ recordRetry(runId, delayMs) {
6595
+ applyRetryToSummary(this.sessionSummary, delayMs);
6596
+ if (this.currentRunId === runId && this.currentRunSummary) {
6597
+ applyRetryToSummary(this.currentRunSummary, delayMs);
6598
+ }
6599
+ }
6600
+ recordRetryWait(runId, waitMs) {
6601
+ const rounded = Math.max(0, Math.round(waitMs));
6602
+ this.sessionSummary.retry_wait_ms += rounded;
6603
+ if (this.currentRunId === runId && this.currentRunSummary) {
6604
+ this.currentRunSummary.retry_wait_ms += rounded;
6605
+ }
6606
+ }
6607
+ recordCompaction(runId, durationMs) {
6608
+ applyCompactionToSummary(this.sessionSummary, durationMs);
6609
+ if (this.currentRunId === runId && this.currentRunSummary) {
6610
+ applyCompactionToSummary(this.currentRunSummary, durationMs);
6611
+ }
6612
+ }
6613
+ recordStartupPhase(name, durationMs) {
6614
+ this.startupPhases.push({
6615
+ name,
6616
+ duration_ms: Math.max(0, Math.round(durationMs))
6617
+ });
6618
+ }
6619
+ setAgentInitPhases(phases) {
6620
+ this.agentInitPhases = phases.map((phase) => ({
6621
+ name: phase.name,
6622
+ duration_ms: Math.max(0, Math.round(phase.duration_ms))
6623
+ }));
6624
+ }
6625
+ getSessionSummary() {
6626
+ return cloneTelemetrySummary(this.sessionSummary);
6627
+ }
6628
+ getRunSummary() {
6629
+ return this.currentRunSummary ? cloneTelemetrySummary(this.currentRunSummary) : null;
6630
+ }
6631
+ getRecentCalls() {
6632
+ return this.recentCalls.slice();
6633
+ }
6634
+ getRecentTools() {
6635
+ return this.recentTools.slice();
6636
+ }
6637
+ getStartupPhases() {
6638
+ return this.startupPhases.slice();
6639
+ }
6640
+ getAgentInitPhases() {
6641
+ return this.agentInitPhases.slice();
6642
+ }
6643
+ };
6644
+
5386
6645
  // src/runtime-state.ts
5387
6646
  var RuntimeState = class {
5388
6647
  attachments;
@@ -5473,7 +6732,7 @@ var RuntimeState = class {
5473
6732
  if (scope === "workspace") {
5474
6733
  const root = this.runtimeSandboxRoot ?? this.runtimeWorkingDir;
5475
6734
  return JSON.stringify([
5476
- root === null ? null : realpathSync9(root),
6735
+ root === null ? null : realpathSync10(root),
5477
6736
  this.sandboxMode.value,
5478
6737
  connection,
5479
6738
  authority
@@ -5515,6 +6774,7 @@ var RuntimeState = class {
5515
6774
  set sessionId(value) {
5516
6775
  if (value === this.boundSessionId) return;
5517
6776
  this.boundSessionId = value;
6777
+ this.telemetry.resetSession();
5518
6778
  this.receiptOwner.abort();
5519
6779
  this.receiptOwner = new AbortController();
5520
6780
  this.signalApprovalChange();
@@ -5578,7 +6838,7 @@ var RuntimeState = class {
5578
6838
  currentModelName = null;
5579
6839
  currentModelSource = null;
5580
6840
  sessionModelOverride = null;
5581
- diagnosticsEnabled = false;
6841
+ telemetry = new RuntimeTelemetryStore();
5582
6842
  setRuntimeEnvironment(options) {
5583
6843
  this.effectiveEnvironment = resolveRuntimeEnvironment(options);
5584
6844
  const value = this.effectiveEnvironment.workspace.sandboxMode;
@@ -5783,7 +7043,7 @@ var RuntimeState = class {
5783
7043
  };
5784
7044
 
5785
7045
  // src/subagents/bootstrap.ts
5786
- import path15 from "path";
7046
+ import path16 from "path";
5787
7047
  import { sandboxModes } from "@codelia/shared-types";
5788
7048
  import { z as z3 } from "zod";
5789
7049
 
@@ -5857,8 +7117,8 @@ var subagentBootstrapSchema = z3.object({
5857
7117
  version: z3.literal(1),
5858
7118
  task_id: z3.string().uuid(),
5859
7119
  prompt: z3.string().min(1).max(32768),
5860
- workspace_root: z3.string().refine(path15.isAbsolute),
5861
- protected_paths: z3.array(z3.string().refine(path15.isAbsolute)).optional(),
7120
+ workspace_root: z3.string().refine(path16.isAbsolute),
7121
+ protected_paths: z3.array(z3.string().refine(path16.isAbsolute)).optional(),
5862
7122
  lineage: z3.object({
5863
7123
  name: subagentNameSchema.optional(),
5864
7124
  tree_id: z3.string().min(1),
@@ -6780,19 +8040,19 @@ var redactSubagentJson = (value, secrets = []) => JSON.parse(
6780
8040
 
6781
8041
  // src/subagents/read-tools.ts
6782
8042
  import { promises as fs6 } from "fs";
6783
- import path18 from "path";
8043
+ import path19 from "path";
6784
8044
  import { defineTool } from "@codelia/core";
6785
8045
  import { z as z5 } from "zod";
6786
8046
 
6787
8047
  // src/sandbox/context.ts
6788
8048
  import crypto3 from "crypto";
6789
8049
  import {
6790
- constants as constants6,
8050
+ constants as constants7,
6791
8051
  promises as fs4,
6792
- lstatSync as lstatSync10,
6793
- realpathSync as realpathSync10
8052
+ lstatSync as lstatSync12,
8053
+ realpathSync as realpathSync11
6794
8054
  } from "fs";
6795
- import path16 from "path";
8055
+ import path17 from "path";
6796
8056
  var SecurityError = class extends Error {
6797
8057
  constructor(message) {
6798
8058
  super(message);
@@ -6802,22 +8062,22 @@ var SecurityError = class extends Error {
6802
8062
  var identity = (info) => `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
6803
8063
  var directoryIdentity2 = (stat) => `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
6804
8064
  var selectMissingFile = (entry) => {
6805
- let parent = path16.dirname(entry.target);
8065
+ let parent = path17.dirname(entry.target);
6806
8066
  for (; ; ) {
6807
8067
  try {
6808
- const stat = lstatSync10(parent, { bigint: true });
6809
- if (!stat.isDirectory() || realpathSync10(parent) !== parent)
8068
+ const stat = lstatSync12(parent, { bigint: true });
8069
+ if (!stat.isDirectory() || realpathSync11(parent) !== parent)
6810
8070
  throw new SecurityError("Expected a canonical parent directory");
6811
8071
  return Object.freeze({
6812
8072
  ...entry,
6813
8073
  identity: null,
6814
8074
  parent,
6815
8075
  parentIdentity: directoryIdentity2(stat),
6816
- tail: path16.relative(parent, entry.target)
8076
+ tail: path17.relative(parent, entry.target)
6817
8077
  });
6818
8078
  } catch (error) {
6819
8079
  if (error.code !== "ENOENT") throw error;
6820
- const ancestor = path16.dirname(parent);
8080
+ const ancestor = path17.dirname(parent);
6821
8081
  if (ancestor === parent) throw error;
6822
8082
  parent = ancestor;
6823
8083
  }
@@ -6825,15 +8085,15 @@ var selectMissingFile = (entry) => {
6825
8085
  };
6826
8086
  var missingDestinationCurrent = (selection) => {
6827
8087
  try {
6828
- const segments = selection.tail.split(path16.sep);
8088
+ const segments = selection.tail.split(path17.sep);
6829
8089
  if (segments.some(
6830
8090
  (segment) => !segment || segment === "." || segment === ".."
6831
- ) || path16.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
8091
+ ) || path17.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
6832
8092
  return false;
6833
8093
  let current = selection.parent;
6834
8094
  for (const [index, segment] of segments.entries()) {
6835
- current = path16.join(current, segment);
6836
- const stat = lstatSync10(current);
8095
+ current = path17.join(current, segment);
8096
+ const stat = lstatSync12(current);
6837
8097
  if (index === segments.length - 1 || !stat.isDirectory()) return false;
6838
8098
  }
6839
8099
  return false;
@@ -6843,8 +8103,8 @@ var missingDestinationCurrent = (selection) => {
6843
8103
  };
6844
8104
  var directoryBindingCurrent = (selection) => {
6845
8105
  try {
6846
- const stat = lstatSync10(selection.parent, { bigint: true });
6847
- return stat.isDirectory() && directoryIdentity2(stat) === selection.parentIdentity && realpathSync10(selection.parent) === selection.parent;
8106
+ const stat = lstatSync12(selection.parent, { bigint: true });
8107
+ return stat.isDirectory() && directoryIdentity2(stat) === selection.parentIdentity && realpathSync11(selection.parent) === selection.parent;
6848
8108
  } catch {
6849
8109
  return false;
6850
8110
  }
@@ -6878,7 +8138,7 @@ var SandboxContext = class _SandboxContext {
6878
8138
  }
6879
8139
  static async create(rootDir, options = {}) {
6880
8140
  const sessionId = crypto3.randomUUID().slice(0, 8);
6881
- const root = rootDir ? path16.resolve(rootDir) : process.cwd();
8141
+ const root = rootDir ? path17.resolve(rootDir) : process.cwd();
6882
8142
  if (options.sandboxMode !== "readonly")
6883
8143
  await fs4.mkdir(root, { recursive: true });
6884
8144
  const directory = options.protectResources ? await fs4.realpath(root) : root;
@@ -6903,7 +8163,7 @@ var SandboxContext = class _SandboxContext {
6903
8163
  resolvePath(targetPath, access = "write") {
6904
8164
  if (access === "write" && this.sandboxMode === "readonly")
6905
8165
  throw new SecurityError("Sandbox mode is readonly");
6906
- const resolved = path16.isAbsolute(targetPath) ? path16.resolve(targetPath) : path16.resolve(this.workingDir, targetPath);
8166
+ const resolved = path17.isAbsolute(targetPath) ? path17.resolve(targetPath) : path17.resolve(this.workingDir, targetPath);
6907
8167
  if (this.protectedPaths) return this.resolveProtectedPath(resolved, access);
6908
8168
  if (this.approvalMode === "full-access") {
6909
8169
  return resolved;
@@ -6921,12 +8181,12 @@ var SandboxContext = class _SandboxContext {
6921
8181
  selectFile(operand, access, directoryEntry = false) {
6922
8182
  const target = this.resolvePath(operand, access);
6923
8183
  if (directoryEntry) {
6924
- const lexical = path16.resolve(this.workingDir, operand);
6925
- const name = path16.join(
6926
- resolvePolicyPath(path16.dirname(lexical)),
6927
- path16.basename(lexical)
8184
+ const lexical = path17.resolve(this.workingDir, operand);
8185
+ const name = path17.join(
8186
+ resolvePolicyPath(path17.dirname(lexical)),
8187
+ path17.basename(lexical)
6928
8188
  );
6929
- if (target !== name || lstatSync10(name, { throwIfNoEntry: false })?.isSymbolicLink())
8189
+ if (target !== name || lstatSync12(name, { throwIfNoEntry: false })?.isSymbolicLink())
6930
8190
  throw new SecurityError(
6931
8191
  "Patch deletion and move require a regular directory entry without a symbolic link"
6932
8192
  );
@@ -6938,7 +8198,7 @@ var SandboxContext = class _SandboxContext {
6938
8198
  ...directoryEntry ? { directoryEntry: true } : {}
6939
8199
  };
6940
8200
  try {
6941
- const info = lstatSync10(target, { bigint: true });
8201
+ const info = lstatSync12(target, { bigint: true });
6942
8202
  if (!info.isFile())
6943
8203
  throw new SecurityError("Expected a regular file for this operation");
6944
8204
  return Object.freeze({
@@ -6986,7 +8246,7 @@ var SandboxContext = class _SandboxContext {
6986
8246
  error.code = "ENOENT";
6987
8247
  throw error;
6988
8248
  }
6989
- const flags = (mode === "read" ? constants6.O_RDONLY : constants6.O_RDWR) | (constants6.O_NOFOLLOW ?? 0) | (constants6.O_NONBLOCK ?? 0);
8249
+ const flags = (mode === "read" ? constants7.O_RDONLY : constants7.O_RDWR) | (constants7.O_NOFOLLOW ?? 0) | (constants7.O_NONBLOCK ?? 0);
6990
8250
  const handle = await fs4.open(selected.target, flags);
6991
8251
  try {
6992
8252
  const opened = await handle.stat({ bigint: true });
@@ -7080,7 +8340,7 @@ var SandboxContext = class _SandboxContext {
7080
8340
  writeProtection(target, alias = false) {
7081
8341
  const { readOnlyPaths } = gitMetadataPaths(
7082
8342
  this.rootDir,
7083
- path16.dirname(target)
8343
+ path17.dirname(target)
7084
8344
  );
7085
8345
  const projectConfig = workspaceConfigProtection(this.rootDir);
7086
8346
  return [
@@ -7112,16 +8372,16 @@ var SandboxContext = class _SandboxContext {
7112
8372
  let probe = resolved;
7113
8373
  for (; ; ) {
7114
8374
  try {
7115
- const actual = realpathSync10(probe);
7116
- const target = path16.resolve(actual, path16.relative(probe, resolved));
8375
+ const actual = realpathSync11(probe);
8376
+ const target = path17.resolve(actual, path17.relative(probe, resolved));
7117
8377
  rejectProtected(target);
7118
8378
  if (target !== resolved) rejectWrite(target);
7119
8379
  if (probe === resolved) {
7120
- const stat = lstatSync10(target);
8380
+ const stat = lstatSync12(target);
7121
8381
  if (!stat.isFile() && !stat.isDirectory())
7122
8382
  throw new SecurityError("Unsupported file type");
7123
8383
  if (stat.isFile() && stat.nlink > 1) {
7124
- const inode2 = lstatSync10(target, { bigint: true });
8384
+ const inode2 = lstatSync12(target, { bigint: true });
7125
8385
  if (isProtectedAlias(inode2, protectedPaths))
7126
8386
  throw new SecurityError("Path aliases a protected file");
7127
8387
  if (access === "write" && this.isReadOnlyAlias(inode2, target))
@@ -7131,10 +8391,10 @@ var SandboxContext = class _SandboxContext {
7131
8391
  return target;
7132
8392
  } catch (error) {
7133
8393
  if (error.code !== "ENOENT") throw error;
7134
- const ancestor = path16.dirname(probe);
8394
+ const ancestor = path17.dirname(probe);
7135
8395
  if (ancestor === probe) throw error;
7136
8396
  try {
7137
- if (lstatSync10(probe).isSymbolicLink())
8397
+ if (lstatSync12(probe).isSymbolicLink())
7138
8398
  throw new SecurityError("Path contains a dangling symlink");
7139
8399
  } catch (entryError) {
7140
8400
  if (entryError.code !== "ENOENT")
@@ -7180,8 +8440,8 @@ var appendReadMetadata = (output, content) => `${output}
7180
8440
  [read_metadata] content_sha256=${hashUtf8Content(content)}`;
7181
8441
 
7182
8442
  // src/subagents/workspace-files.ts
7183
- import { constants as constants7, promises as fs5 } from "fs";
7184
- import path17 from "path";
8443
+ import { constants as constants8, promises as fs5 } from "fs";
8444
+ import path18 from "path";
7185
8445
  var MAX_CHILD_FILE_BYTES = 4 * 1024 * 1024;
7186
8446
  var readContent = async (handle) => {
7187
8447
  const buffer = Buffer.alloc(MAX_CHILD_FILE_BYTES + 1);
@@ -7208,15 +8468,15 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7208
8468
  );
7209
8469
  const blocked = (target) => protectedPaths.some((entry) => resourceContainsPath(entry, target));
7210
8470
  const resolve = async (name, allowMissing = false) => {
7211
- const candidate = path17.resolve(root, name);
8471
+ const candidate = path18.resolve(root, name);
7212
8472
  if (blocked(candidate))
7213
8473
  throw new Error("Path is protected by the resource policy");
7214
- const relative = path17.relative(root, candidate);
7215
- if (relative === ".." || relative.startsWith(`..${path17.sep}`) || path17.isAbsolute(relative))
8474
+ const relative = path18.relative(root, candidate);
8475
+ if (relative === ".." || relative.startsWith(`..${path18.sep}`) || path18.isAbsolute(relative))
7216
8476
  throw new Error("Path outside delegated workspace");
7217
8477
  let part = root;
7218
- for (const segment of relative.split(path17.sep).filter(Boolean)) {
7219
- part = path17.join(part, segment);
8478
+ for (const segment of relative.split(path18.sep).filter(Boolean)) {
8479
+ part = path18.join(part, segment);
7220
8480
  try {
7221
8481
  if ((await fs5.lstat(part)).isSymbolicLink())
7222
8482
  throw new Error(
@@ -7256,7 +8516,7 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7256
8516
  const file = await resolve(name, expected === "missing");
7257
8517
  const repositoryReadOnly = gitMetadataPaths(
7258
8518
  root,
7259
- path17.dirname(file)
8519
+ path18.dirname(file)
7260
8520
  ).readOnlyPaths;
7261
8521
  const projectConfig = workspaceConfigProtection(root);
7262
8522
  if (homeDotDirectory2 && isHomeWriteReserved(homeDotDirectory2, file) || isWorkspaceConfigName(root, file) || [
@@ -7279,12 +8539,12 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7279
8539
  if (approval && expected === "missing")
7280
8540
  throw new Error("File already exists");
7281
8541
  if (expected === "missing") {
7282
- await fs5.mkdir(path17.dirname(file), { recursive: true });
8542
+ await fs5.mkdir(path18.dirname(file), { recursive: true });
7283
8543
  await resolve(name, true);
7284
8544
  }
7285
8545
  const handle = await fs5.open(
7286
8546
  file,
7287
- expected === "missing" ? "wx" : constants7.O_RDWR | (constants7.O_NOFOLLOW ?? 0)
8547
+ expected === "missing" ? "wx" : constants8.O_RDWR | (constants8.O_NOFOLLOW ?? 0)
7288
8548
  );
7289
8549
  try {
7290
8550
  const stat = await handle.stat({ bigint: true });
@@ -7328,16 +8588,16 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7328
8588
  };
7329
8589
  const update = async (name, expected, transform, signal, approval) => {
7330
8590
  const previous = pendingUpdate;
7331
- let release2;
8591
+ let release3;
7332
8592
  pendingUpdate = new Promise((done) => {
7333
- release2 = done;
8593
+ release3 = done;
7334
8594
  });
7335
8595
  try {
7336
8596
  await previous;
7337
8597
  signal?.throwIfAborted();
7338
8598
  return await updateFile(name, expected, transform, approval);
7339
8599
  } finally {
7340
- release2();
8600
+ release3();
7341
8601
  }
7342
8602
  };
7343
8603
  return { resolve, read, selectRead, update, blocked };
@@ -7388,17 +8648,17 @@ var createSubagentReadTools = (root, protectedPaths, options = {}) => {
7388
8648
  signal?.throwIfAborted();
7389
8649
  const dir = pending.shift();
7390
8650
  if (!dir) break;
7391
- const entries = await fs6.opendir(await resolve(path18.relative(root2, dir)));
8651
+ const entries = await fs6.opendir(await resolve(path19.relative(root2, dir)));
7392
8652
  for await (const entry of entries) {
7393
8653
  if (entry.isSymbolicLink() || entry.name === ".git" || entry.name === "node_modules")
7394
8654
  continue;
7395
- const child = path18.join(dir, entry.name);
8655
+ const child = path19.join(dir, entry.name);
7396
8656
  if (blocked(child)) continue;
7397
8657
  if (entry.isDirectory()) {
7398
8658
  if (pending.length >= 2e3) return { paths, truncated: true };
7399
8659
  pending.push(child);
7400
8660
  } else if (entry.isFile()) {
7401
- const name = path18.relative(root2, child);
8661
+ const name = path19.relative(root2, child);
7402
8662
  const selected = await selectRead(name, sandbox).catch(
7403
8663
  () => void 0
7404
8664
  );
@@ -7900,6 +9160,8 @@ export {
7900
9160
  resolveModelConfig,
7901
9161
  resolveSubagentConfig,
7902
9162
  resolveTuiConfig,
9163
+ resolveAgentsEnabled,
9164
+ resolveAuthOAuthBrowser,
7903
9165
  resolvePermissionsConfig,
7904
9166
  resolveSkillsConfig,
7905
9167
  resolveExecutionEnvironmentConfig,
@@ -7915,13 +9177,14 @@ export {
7915
9177
  withRpcResponseContext,
7916
9178
  hasRpcResponse,
7917
9179
  sendNotificationAsync,
9180
+ getTransportBackpressureEvents,
7918
9181
  send,
7919
9182
  sendError,
7920
9183
  sendAgentEvent,
7921
9184
  sendRunStatus,
7922
9185
  sendRunContext,
7923
- sendRunDiagnostics,
7924
9186
  sendRunMetrics,
9187
+ sendRunSummary,
7925
9188
  parseRequestParams,
7926
9189
  parseUiNotificationParams,
7927
9190
  sendRequestResult,
@@ -7957,12 +9220,14 @@ export {
7957
9220
  isSimpleAndChain,
7958
9221
  analyzeShell,
7959
9222
  fixedFileMutation,
9223
+ isProtectedAlias,
7960
9224
  shellBinPaths,
7961
9225
  resolveShellExecutable,
7962
9226
  bindBashCommand,
7963
9227
  bindKnownSystemExecutable,
7964
9228
  isRootControlledSharedExecutable,
7965
9229
  areAllExecutableLinksOutsideRestrictedPaths,
9230
+ LinuxMxcBackend,
7966
9231
  resolveSystemBash,
7967
9232
  confinedAutoLaunchDirectoryName,
7968
9233
  supportsProtectedShell,
@@ -7971,9 +9236,10 @@ export {
7971
9236
  canonicalPolicyPaths,
7972
9237
  runtimeReadOnlyPaths,
7973
9238
  workspacePathProtection,
7974
- macAdditionalWriteLauncherPaths,
9239
+ mxcAdditionalWriteLauncherPaths,
7975
9240
  MacSeatbeltBackend,
7976
9241
  createMacMxcShellBackend,
9242
+ createLinuxMxcShellBackend,
7977
9243
  UserShellBackend,
7978
9244
  selectProtectedShellBackend,
7979
9245
  directoryIdentity,