@codelia/runtime 0.1.90 → 0.1.91

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.
@@ -1984,15 +1984,15 @@ var AuthResolver = class _AuthResolver {
1984
1984
  // src/permissions/shell-backend.ts
1985
1985
  import { spawn as spawn4, spawnSync as spawnSync3 } from "child_process";
1986
1986
  import {
1987
- lstatSync as lstatSync9,
1987
+ lstatSync as lstatSync11,
1988
1988
  mkdirSync as mkdirSync2,
1989
- mkdtempSync as mkdtempSync2,
1990
- realpathSync as realpathSync8,
1991
- rmSync as rmSync2,
1992
- statSync as statSync5
1989
+ mkdtempSync as mkdtempSync3,
1990
+ realpathSync as realpathSync9,
1991
+ rmSync as rmSync3,
1992
+ statSync as statSync6
1993
1993
  } from "fs";
1994
- import os2 from "os";
1995
- import path13 from "path";
1994
+ import os3 from "os";
1995
+ import path14 from "path";
1996
1996
  import { resolveStoragePaths as resolveStoragePaths3 } from "@codelia/storage";
1997
1997
 
1998
1998
  // src/sandbox/file-mutation-helper.ts
@@ -2113,13 +2113,19 @@ import {
2113
2113
  lstatSync,
2114
2114
  openSync as openSync2,
2115
2115
  readdirSync,
2116
+ readlinkSync,
2116
2117
  readSync,
2117
2118
  realpathSync,
2118
2119
  statSync
2119
2120
  } from "fs";
2121
+ import os from "os";
2120
2122
  import path4 from "path";
2121
2123
  var isMissing = (error) => error.code === "ENOENT";
2122
2124
  var metadataPathSize = 16 * 1024;
2125
+ var gitConfigMaxBytes = 256 * 1024;
2126
+ var maxSymlinkHops = 64;
2127
+ var maxConfigDepth = 8;
2128
+ var maxConfigFiles = 32;
2123
2129
  var readPointer = (filename, prefix) => {
2124
2130
  const fd = openSync2(
2125
2131
  filename,
@@ -2221,6 +2227,7 @@ var eligibleObjectDirectory = (gitDirectory, commonDirectory, marker) => {
2221
2227
  };
2222
2228
  var discoverGitMetadata = (directories, includeObjectDirectories) => {
2223
2229
  const readOnlyPaths = /* @__PURE__ */ new Set();
2230
+ const repositories = [];
2224
2231
  const reservedMarkers = /* @__PURE__ */ new Set();
2225
2232
  const objectDirectories = /* @__PURE__ */ new Map();
2226
2233
  const hookAliases = /* @__PURE__ */ new Map();
@@ -2245,22 +2252,47 @@ var discoverGitMetadata = (directories, includeObjectDirectories) => {
2245
2252
  readOnlyPaths.add(actual);
2246
2253
  return actual;
2247
2254
  };
2255
+ const rootDirectory = directories[0];
2256
+ const verifyLinkedWorktree = (gitDirectory, commonDirectory, actualMarker) => {
2257
+ try {
2258
+ if (gitDirectory === commonDirectory) return false;
2259
+ if (path4.dirname(gitDirectory) !== path4.join(commonDirectory, "worktrees"))
2260
+ return false;
2261
+ const backPointer = readPointer(path4.join(gitDirectory, "gitdir"), "");
2262
+ const resolvedBack = path4.resolve(gitDirectory, backPointer);
2263
+ const backStat = lstatSync(resolvedBack);
2264
+ if (backStat.isSymbolicLink() || !backStat.isFile()) return false;
2265
+ return realpathSync(path4.dirname(resolvedBack)) === path4.dirname(actualMarker) && realpathSync(resolvedBack) === actualMarker;
2266
+ } catch {
2267
+ return false;
2268
+ }
2269
+ };
2248
2270
  for (const directory of new Set(directories)) {
2271
+ const fromRoot = directory === rootDirectory;
2249
2272
  const marker = findMarker(directory);
2250
2273
  const localMarker = path4.join(directory, ".git");
2251
2274
  if (marker !== localMarker) reservedMarkers.add(localMarker);
2252
2275
  if (!marker) continue;
2253
2276
  if (readOnlyPaths.has(marker)) continue;
2277
+ const isWorkspaceRootRepo = fromRoot && marker === localMarker;
2278
+ const markerLstat = lstatSync(marker);
2254
2279
  const actualMarker = realpathSync(marker);
2255
2280
  readOnlyPaths.add(marker);
2256
2281
  readOnlyPaths.add(actualMarker);
2257
2282
  const markerInfo = statSync(actualMarker);
2258
- const gitDirectory = markerInfo.isDirectory() ? actualMarker : addDirectory(
2259
- path4.resolve(
2283
+ const directoryEntries = [];
2284
+ let gitDirectory;
2285
+ if (markerInfo.isDirectory()) {
2286
+ gitDirectory = actualMarker;
2287
+ directoryEntries.push(marker, actualMarker);
2288
+ } else {
2289
+ const location = path4.resolve(
2260
2290
  path4.dirname(marker),
2261
2291
  readPointer(actualMarker, "gitdir: ")
2262
- )
2263
- );
2292
+ );
2293
+ gitDirectory = addDirectory(location);
2294
+ directoryEntries.push(location, gitDirectory);
2295
+ }
2264
2296
  if (!statSync(path4.join(gitDirectory, "HEAD")).isFile())
2265
2297
  throw new Error("invalid_git_metadata_directory");
2266
2298
  const commonPointer = path4.join(gitDirectory, "commondir");
@@ -2270,19 +2302,34 @@ var discoverGitMetadata = (directories, includeObjectDirectories) => {
2270
2302
  } catch (error) {
2271
2303
  if (!isMissing(error)) throw error;
2272
2304
  recordObjects(gitDirectory, gitDirectory, actualMarker);
2305
+ repositories.push({
2306
+ gitDirectory,
2307
+ commonDirectory: gitDirectory,
2308
+ worktreeRoot: path4.dirname(actualMarker),
2309
+ directoryEntries,
2310
+ writable: isWorkspaceRootRepo && markerLstat.isDirectory() && !markerLstat.isSymbolicLink()
2311
+ });
2273
2312
  continue;
2274
2313
  }
2275
2314
  readOnlyPaths.add(commonPointer);
2276
2315
  readOnlyPaths.add(common);
2277
- const commonDirectory = addDirectory(
2278
- path4.resolve(gitDirectory, readPointer(common, ""))
2279
- );
2316
+ const commonLocation = path4.resolve(gitDirectory, readPointer(common, ""));
2317
+ const commonDirectory = addDirectory(commonLocation);
2318
+ directoryEntries.push(commonLocation, commonDirectory);
2280
2319
  if (!statSync(path4.join(commonDirectory, "objects")).isDirectory())
2281
2320
  throw new Error("invalid_git_common_directory");
2282
2321
  recordObjects(gitDirectory, commonDirectory, actualMarker);
2322
+ repositories.push({
2323
+ gitDirectory,
2324
+ commonDirectory,
2325
+ worktreeRoot: path4.dirname(actualMarker),
2326
+ directoryEntries,
2327
+ writable: isWorkspaceRootRepo && markerLstat.isFile() && !markerLstat.isSymbolicLink() && verifyLinkedWorktree(gitDirectory, commonDirectory, actualMarker)
2328
+ });
2283
2329
  }
2284
2330
  return Object.freeze({
2285
2331
  readOnlyPaths: Object.freeze([...readOnlyPaths].sort()),
2332
+ repositories: Object.freeze(repositories),
2286
2333
  reservedMarkers: Object.freeze([...reservedMarkers].sort()),
2287
2334
  objectDirectories: Object.freeze([...objectDirectories.values()]),
2288
2335
  hookAliases: Object.freeze([...hookAliases.values()])
@@ -2297,17 +2344,402 @@ var resolveGitMetadata = (directories, includeObjectDirectories) => {
2297
2344
  };
2298
2345
  var gitMetadataPaths = (...directories) => resolveGitMetadata(directories, false);
2299
2346
  var gitMetadataWithObjectDirectories = (...directories) => resolveGitMetadata(directories, true);
2347
+ var joinPreservingDotDot = (base, target) => {
2348
+ if (path4.isAbsolute(target)) return target;
2349
+ const separator = process.platform === "win32" ? path4.sep : "/";
2350
+ const trimmedBase = base.length > 1 && base.endsWith(separator) ? base.slice(0, -1) : base;
2351
+ return `${trimmedBase}${separator}${target}`;
2352
+ };
2353
+ var traceSymlinkHops = (target) => {
2354
+ const rawAbsolute = path4.isAbsolute(target) ? target : joinPreservingDotDot(process.cwd(), target);
2355
+ const root = path4.parse(rawAbsolute).root;
2356
+ const collected = /* @__PURE__ */ new Set([target, path4.resolve(rawAbsolute)]);
2357
+ let resolvedParts = [];
2358
+ let queue = rawAbsolute.slice(root.length).split(process.platform === "win32" ? /[\\/]/u : "/").filter(Boolean);
2359
+ let hops = 0;
2360
+ while (queue.length > 0) {
2361
+ const part = queue.shift();
2362
+ if (part === ".") continue;
2363
+ if (part === "..") {
2364
+ resolvedParts.pop();
2365
+ continue;
2366
+ }
2367
+ const candidate = path4.join(root, ...resolvedParts, part);
2368
+ const stat = lstatSync(candidate, { throwIfNoEntry: false });
2369
+ if (!stat) {
2370
+ if (queue.some((entry) => entry === ".."))
2371
+ throw new Error("reserved_path_unresolved");
2372
+ resolvedParts.push(part, ...queue.filter((entry) => entry !== "."));
2373
+ queue = [];
2374
+ break;
2375
+ }
2376
+ if (stat.isSymbolicLink()) {
2377
+ if (path4.dirname(candidate) !== root) collected.add(candidate);
2378
+ if (++hops > maxSymlinkHops) throw new Error("symlink_chain_too_deep");
2379
+ const referent = readlinkSync(candidate);
2380
+ const referentParts = referent.split(process.platform === "win32" ? /[\\/]/u : "/").filter(Boolean);
2381
+ if (path4.isAbsolute(referent)) resolvedParts = [];
2382
+ queue = [...referentParts, ...queue];
2383
+ continue;
2384
+ }
2385
+ resolvedParts.push(part);
2386
+ }
2387
+ collected.add(path4.join(root, ...resolvedParts));
2388
+ return [...collected];
2389
+ };
2390
+ var readBoundedTextFile = (filename) => {
2391
+ let fd;
2392
+ try {
2393
+ fd = openSync2(filename, constants2.O_RDONLY | (constants2.O_NONBLOCK ?? 0));
2394
+ } catch (error) {
2395
+ if (isMissing(error)) return void 0;
2396
+ throw error;
2397
+ }
2398
+ try {
2399
+ const stat = fstatSync2(fd);
2400
+ if (!stat.isFile() || stat.size > gitConfigMaxBytes)
2401
+ throw new Error("unreadable_git_config");
2402
+ const bytes = Buffer.alloc(stat.size + 1);
2403
+ const length = readSync(fd, bytes, 0, bytes.length, 0);
2404
+ if (length !== stat.size || length > gitConfigMaxBytes)
2405
+ throw new Error("unreadable_git_config");
2406
+ return new TextDecoder("utf-8", { fatal: true }).decode(
2407
+ bytes.subarray(0, length)
2408
+ );
2409
+ } finally {
2410
+ closeSync2(fd);
2411
+ }
2412
+ };
2413
+ var parseGitConfigValue = (raw) => {
2414
+ let result = "";
2415
+ let inQuotes = false;
2416
+ let pendingSpace = "";
2417
+ let i = 0;
2418
+ while (i < raw.length && (raw[i] === " " || raw[i] === " ")) i++;
2419
+ for (; i < raw.length; i++) {
2420
+ const ch = raw[i];
2421
+ if (ch === "\\") {
2422
+ if (i + 1 >= raw.length) {
2423
+ throw new Error("unsupported_git_config_continuation");
2424
+ }
2425
+ const next = raw[++i];
2426
+ if (pendingSpace) {
2427
+ result += pendingSpace;
2428
+ pendingSpace = "";
2429
+ }
2430
+ if (next === "n") result += "\n";
2431
+ else if (next === "t") result += " ";
2432
+ else if (next === "b") result += "\b";
2433
+ else if (next === '"' || next === "\\") result += next;
2434
+ else throw new Error("unsupported_git_config_escape");
2435
+ continue;
2436
+ }
2437
+ if (ch === '"') {
2438
+ if (pendingSpace && !inQuotes) {
2439
+ result += pendingSpace;
2440
+ pendingSpace = "";
2441
+ }
2442
+ inQuotes = !inQuotes;
2443
+ continue;
2444
+ }
2445
+ if (!inQuotes && (ch === "#" || ch === ";")) break;
2446
+ if (!inQuotes && (ch === " " || ch === " ")) {
2447
+ pendingSpace += ch;
2448
+ continue;
2449
+ }
2450
+ if (pendingSpace) {
2451
+ result += pendingSpace;
2452
+ pendingSpace = "";
2453
+ }
2454
+ result += ch;
2455
+ }
2456
+ if (inQuotes) throw new Error("unterminated_git_config_quote");
2457
+ return result;
2458
+ };
2459
+ var parseIrrelevantLineContinuation = (raw, initialInQuotes = false) => {
2460
+ let inQuotes = initialInQuotes;
2461
+ for (let i = 0; i < raw.length; i++) {
2462
+ const ch = raw[i];
2463
+ if (ch === "\\") {
2464
+ if (i + 1 >= raw.length) {
2465
+ return { continues: true, inQuotes };
2466
+ }
2467
+ i++;
2468
+ continue;
2469
+ }
2470
+ if (ch === '"') {
2471
+ inQuotes = !inQuotes;
2472
+ continue;
2473
+ }
2474
+ if (!inQuotes && (ch === "#" || ch === ";")) {
2475
+ return { continues: false, inQuotes: false };
2476
+ }
2477
+ }
2478
+ return { continues: false, inQuotes: false };
2479
+ };
2480
+ var expandGitHome = (value) => {
2481
+ if (value === "~") return os.homedir();
2482
+ if (value.startsWith("~/")) return path4.join(os.homedir(), value.slice(2));
2483
+ return value;
2484
+ };
2485
+ var collectGitConfigProtectedPaths = (configPath, worktreeRoot, seen, depth) => {
2486
+ if (depth > maxConfigDepth || seen.size >= maxConfigFiles)
2487
+ throw new Error("git_config_include_limit");
2488
+ let canonicalConfig = configPath;
2489
+ try {
2490
+ canonicalConfig = realpathSync(configPath);
2491
+ } catch (error) {
2492
+ if (isMissing(error)) return [];
2493
+ throw error;
2494
+ }
2495
+ const openedConfigDir = path4.dirname(configPath);
2496
+ const seenKey = `${openedConfigDir}\0${canonicalConfig}`;
2497
+ if (seen.has(seenKey)) return [];
2498
+ seen.add(seenKey);
2499
+ const content = readBoundedTextFile(canonicalConfig);
2500
+ if (content === void 0) return [];
2501
+ const results = [];
2502
+ const recordReferencedDirective = (directiveSection, rawValue) => {
2503
+ const parsed = parseGitConfigValue(rawValue);
2504
+ if (!parsed) throw new Error("empty_git_config_path");
2505
+ const expanded = expandGitHome(parsed);
2506
+ if (directiveSection === "core") {
2507
+ const bases2 = /* @__PURE__ */ new Set([
2508
+ ...worktreeRoot ? [worktreeRoot] : [],
2509
+ openedConfigDir
2510
+ ]);
2511
+ for (const base of bases2) {
2512
+ results.push({
2513
+ path: path4.isAbsolute(expanded) ? expanded : joinPreservingDotDot(base, expanded),
2514
+ kind: "hooks"
2515
+ });
2516
+ }
2517
+ return;
2518
+ }
2519
+ const target = path4.isAbsolute(expanded) ? expanded : joinPreservingDotDot(openedConfigDir, expanded);
2520
+ results.push({ path: target, kind: "config" });
2521
+ results.push(
2522
+ ...collectGitConfigProtectedPaths(target, worktreeRoot, seen, depth + 1)
2523
+ );
2524
+ };
2525
+ let section = "";
2526
+ let continuingIrrelevantLine = false;
2527
+ let continuingIrrelevantQuotes = false;
2528
+ for (const rawLine of content.split(/\r?\n/u)) {
2529
+ const trimmed = rawLine.trim();
2530
+ if (continuingIrrelevantLine) {
2531
+ const state = parseIrrelevantLineContinuation(
2532
+ rawLine,
2533
+ continuingIrrelevantQuotes
2534
+ );
2535
+ continuingIrrelevantLine = state.continues;
2536
+ continuingIrrelevantQuotes = state.inQuotes;
2537
+ continue;
2538
+ }
2539
+ if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";"))
2540
+ continue;
2541
+ if (trimmed.startsWith("[")) {
2542
+ const header = /^\[([A-Za-z0-9-]+)(?:\s+"(?:[^"\\]|\\.)*"|\.[A-Za-z0-9.-]+)?\s*\](.*)$/u.exec(
2543
+ trimmed
2544
+ );
2545
+ if (!header) throw new Error("unsupported_git_config_section");
2546
+ section = header[1].toLowerCase();
2547
+ const rest = header[2].trim();
2548
+ if (!rest || rest.startsWith("#") || rest.startsWith(";")) continue;
2549
+ const eq2 = rest.indexOf("=");
2550
+ if (eq2 < 0) continue;
2551
+ const key2 = rest.slice(0, eq2).trim().toLowerCase();
2552
+ const rawValue2 = rest.slice(eq2 + 1);
2553
+ if ((section === "include" || section === "includeif") && key2 === "path" || section === "core" && key2 === "hookspath") {
2554
+ recordReferencedDirective(section, rawValue2);
2555
+ } else {
2556
+ const state = parseIrrelevantLineContinuation(rawValue2);
2557
+ continuingIrrelevantLine = state.continues;
2558
+ continuingIrrelevantQuotes = state.inQuotes;
2559
+ }
2560
+ continue;
2561
+ }
2562
+ const eq = rawLine.indexOf("=");
2563
+ if (eq < 0) {
2564
+ const bareKey = trimmed.replace(/[#;].*$/u, "").trim().toLowerCase();
2565
+ if ((section === "include" || section === "includeif") && bareKey === "path" || section === "core" && bareKey === "hookspath")
2566
+ throw new Error("empty_git_config_path");
2567
+ continue;
2568
+ }
2569
+ const key = rawLine.slice(0, eq).trim().toLowerCase();
2570
+ const rawValue = rawLine.slice(eq + 1);
2571
+ if ((section === "include" || section === "includeif") && key === "path" || section === "core" && key === "hookspath") {
2572
+ recordReferencedDirective(section, rawValue);
2573
+ } else {
2574
+ const state = parseIrrelevantLineContinuation(rawValue);
2575
+ continuingIrrelevantLine = state.continues;
2576
+ continuingIrrelevantQuotes = state.inQuotes;
2577
+ }
2578
+ }
2579
+ return results;
2580
+ };
2581
+ var externalGitConfigFiles = () => {
2582
+ const files = /* @__PURE__ */ new Set();
2583
+ const home = os.homedir();
2584
+ const xdgConfigHome = process.env.XDG_CONFIG_HOME && path4.isAbsolute(process.env.XDG_CONFIG_HOME) ? process.env.XDG_CONFIG_HOME : path4.join(home, ".config");
2585
+ if (process.env.GIT_CONFIG_GLOBAL) {
2586
+ files.add(process.env.GIT_CONFIG_GLOBAL);
2587
+ } else {
2588
+ files.add(path4.join(home, ".gitconfig"));
2589
+ files.add(path4.join(xdgConfigHome, "git", "config"));
2590
+ }
2591
+ if (process.env.GIT_CONFIG_NOSYSTEM !== "1") {
2592
+ files.add(process.env.GIT_CONFIG_SYSTEM || "/etc/gitconfig");
2593
+ }
2594
+ return [...files];
2595
+ };
2596
+ var gitWriteScope = (repositories) => {
2597
+ const writeRoots = /* @__PURE__ */ new Set();
2598
+ const readOnly = /* @__PURE__ */ new Set();
2599
+ const released = /* @__PURE__ */ new Set();
2600
+ for (const {
2601
+ gitDirectory,
2602
+ commonDirectory,
2603
+ worktreeRoot,
2604
+ directoryEntries,
2605
+ writable
2606
+ } of repositories) {
2607
+ if (!writable) continue;
2608
+ const repoReadOnly = /* @__PURE__ */ new Set();
2609
+ const addProtected = (entry) => {
2610
+ for (const hop of traceSymlinkHops(entry)) repoReadOnly.add(hop);
2611
+ };
2612
+ const protectHooksDirectory = (hooksPath) => {
2613
+ addProtected(hooksPath);
2614
+ let resolvedHooks;
2615
+ try {
2616
+ const real = realpathSync(hooksPath);
2617
+ if (statSync(real).isDirectory()) resolvedHooks = real;
2618
+ } catch (error) {
2619
+ if (!["ENOENT", "ENOTDIR", "ELOOP", "EACCES", "EPERM"].includes(
2620
+ error.code ?? ""
2621
+ ))
2622
+ throw error;
2623
+ }
2624
+ if (resolvedHooks) {
2625
+ for (const entry of readdirSync(resolvedHooks, {
2626
+ withFileTypes: true
2627
+ })) {
2628
+ if (entry.isSymbolicLink())
2629
+ addProtected(path4.join(resolvedHooks, entry.name));
2630
+ }
2631
+ }
2632
+ };
2633
+ try {
2634
+ const objectsDirectory = path4.join(commonDirectory, "objects");
2635
+ const objectsInfo = path4.join(objectsDirectory, "info");
2636
+ const configFiles = [
2637
+ path4.join(commonDirectory, "config"),
2638
+ path4.join(commonDirectory, "config.worktree"),
2639
+ path4.join(gitDirectory, "config.worktree")
2640
+ ];
2641
+ for (const entry of [
2642
+ ...configFiles,
2643
+ path4.join(commonDirectory, "hooks"),
2644
+ path4.join(commonDirectory, "commondir"),
2645
+ path4.join(gitDirectory, "commondir"),
2646
+ path4.join(gitDirectory, "gitdir"),
2647
+ ...gitObjectStoreConfigPaths(objectsDirectory),
2648
+ path4.join(commonDirectory, "remotes"),
2649
+ path4.join(commonDirectory, "branches"),
2650
+ path4.join(commonDirectory, "modules"),
2651
+ // Rebase/sequencer todo files can contain `exec <cmd>` lines that
2652
+ // execute during a later unconfined `git rebase --continue`.
2653
+ path4.join(commonDirectory, "rebase-merge"),
2654
+ path4.join(commonDirectory, "rebase-apply"),
2655
+ path4.join(commonDirectory, "sequencer"),
2656
+ path4.join(gitDirectory, "rebase-merge"),
2657
+ path4.join(gitDirectory, "rebase-apply"),
2658
+ path4.join(gitDirectory, "sequencer")
2659
+ ])
2660
+ addProtected(entry);
2661
+ if (lstatSync(objectsInfo, { throwIfNoEntry: false })?.isSymbolicLink()) {
2662
+ const hops = traceSymlinkHops(objectsInfo);
2663
+ for (const hop of hops) repoReadOnly.add(hop);
2664
+ const targetInfo = hops[hops.length - 1];
2665
+ if (targetInfo) {
2666
+ addProtected(path4.join(targetInfo, "alternates"));
2667
+ addProtected(path4.join(targetInfo, "http-alternates"));
2668
+ }
2669
+ }
2670
+ protectHooksDirectory(path4.join(commonDirectory, "hooks"));
2671
+ const siblingConfigs = [];
2672
+ const worktrees = path4.join(commonDirectory, "worktrees");
2673
+ if (lstatSync(worktrees, { throwIfNoEntry: false })?.isDirectory()) {
2674
+ for (const entry of readdirSync(worktrees, { withFileTypes: true })) {
2675
+ if (!entry.isDirectory()) continue;
2676
+ const siblingDir = path4.join(worktrees, entry.name);
2677
+ for (const name of [
2678
+ "gitdir",
2679
+ "commondir",
2680
+ "config.worktree",
2681
+ "rebase-merge",
2682
+ "rebase-apply",
2683
+ "sequencer"
2684
+ ])
2685
+ addProtected(path4.join(siblingDir, name));
2686
+ let siblingWorktreeRoot;
2687
+ try {
2688
+ const pointer = readPointer(path4.join(siblingDir, "gitdir"), "");
2689
+ siblingWorktreeRoot = path4.dirname(
2690
+ realpathSync(path4.resolve(siblingDir, pointer))
2691
+ );
2692
+ } catch {
2693
+ siblingWorktreeRoot = void 0;
2694
+ }
2695
+ siblingConfigs.push({
2696
+ file: path4.join(siblingDir, "config.worktree"),
2697
+ worktreeRoot: siblingWorktreeRoot
2698
+ });
2699
+ }
2700
+ }
2701
+ const seenConfigs = /* @__PURE__ */ new Set();
2702
+ const configSources = [
2703
+ ...configFiles.map((file) => ({ file, worktreeRoot })),
2704
+ ...siblingConfigs,
2705
+ ...externalGitConfigFiles().map((file) => ({ file, worktreeRoot }))
2706
+ ];
2707
+ for (const source of configSources) {
2708
+ for (const referenced of collectGitConfigProtectedPaths(
2709
+ source.file,
2710
+ source.worktreeRoot,
2711
+ seenConfigs,
2712
+ 0
2713
+ )) {
2714
+ if (referenced.kind === "hooks")
2715
+ protectHooksDirectory(referenced.path);
2716
+ else addProtected(referenced.path);
2717
+ }
2718
+ }
2719
+ writeRoots.add(gitDirectory);
2720
+ writeRoots.add(commonDirectory);
2721
+ for (const entry of directoryEntries) released.add(entry);
2722
+ for (const entry of repoReadOnly) readOnly.add(entry);
2723
+ } catch {
2724
+ }
2725
+ }
2726
+ return Object.freeze({
2727
+ writeRoots: Object.freeze([...writeRoots].sort()),
2728
+ readOnlyPaths: Object.freeze([...readOnly].sort()),
2729
+ releasedPaths: Object.freeze([...released].sort())
2730
+ });
2731
+ };
2300
2732
 
2301
2733
  // src/permissions/home-dot-paths.ts
2302
- import { readdirSync as readdirSync2, readlinkSync as readlinkSync2 } from "fs";
2303
- import os from "os";
2734
+ import { lstatSync as lstatSync3, readdirSync as readdirSync2, readlinkSync as readlinkSync3 } from "fs";
2735
+ import os2 from "os";
2304
2736
  import path6 from "path";
2305
2737
 
2306
2738
  // src/permissions/resource-paths.ts
2307
2739
  import {
2308
2740
  lstatSync as lstatSync2,
2309
2741
  opendirSync,
2310
- readlinkSync,
2742
+ readlinkSync as readlinkSync2,
2311
2743
  realpathSync as realpathSync2
2312
2744
  } from "fs";
2313
2745
  import path5 from "path";
@@ -2378,7 +2810,7 @@ function resolveReservedTarget(target, remaining = 64) {
2378
2810
  const canonicalParent = resolveReservedTarget(parent, remaining - 1);
2379
2811
  if (!lstatSync2(target, { throwIfNoEntry: false })?.isSymbolicLink())
2380
2812
  return path5.join(canonicalParent, path5.basename(target));
2381
- const referent = readlinkSync(target);
2813
+ const referent = readlinkSync2(target);
2382
2814
  let seenName = false;
2383
2815
  for (const part of referent.split(
2384
2816
  process.platform === "win32" ? /[\\/]/u : "/"
@@ -2395,7 +2827,7 @@ function resolveReservedTarget(target, remaining = 64) {
2395
2827
  }
2396
2828
 
2397
2829
  // src/permissions/home-dot-paths.ts
2398
- var homeDotDirectory = (writeRoots, home = os.homedir()) => {
2830
+ var homeDotDirectory = (writeRoots, home = os2.homedir()) => {
2399
2831
  if (!writeRoots.length) return void 0;
2400
2832
  const canonicalHome = resolveReservedTarget(home);
2401
2833
  return writeRoots.some(
@@ -2417,7 +2849,7 @@ var hasClosedHomeDotCycle = (home, start) => {
2417
2849
  seen.add(current);
2418
2850
  let link;
2419
2851
  try {
2420
- link = readlinkSync2(current);
2852
+ link = readlinkSync3(current);
2421
2853
  } catch {
2422
2854
  return false;
2423
2855
  }
@@ -2442,23 +2874,50 @@ var homeDotLinkTargets = (home) => readdirSync2(home, { withFileTypes: true }).f
2442
2874
  }
2443
2875
  });
2444
2876
  var isHomeWriteReserved = (home, target) => isHomeDotTarget(home, target) || homeDotLinkTargets(home).some((link) => resourceContainsPath(link, target));
2877
+ var MAX_HOME_DOT_ALIAS_ENTRIES = 8192;
2878
+ var hasHomeDotHardLinkAliases = (home) => {
2879
+ const pending = [];
2880
+ try {
2881
+ for (const entry of readdirSync2(home, { withFileTypes: true })) {
2882
+ if (!entry.name.startsWith(".") || entry.isSymbolicLink()) continue;
2883
+ pending.push(path6.join(home, entry.name));
2884
+ }
2885
+ const visited = /* @__PURE__ */ new Set();
2886
+ while (pending.length) {
2887
+ const current = pending.pop();
2888
+ if (!current || visited.has(current)) continue;
2889
+ visited.add(current);
2890
+ if (visited.size > MAX_HOME_DOT_ALIAS_ENTRIES) return true;
2891
+ const info = lstatSync3(current, { bigint: true });
2892
+ if (info.isSymbolicLink()) continue;
2893
+ if ((info.isFile() || info.isSocket() || info.isFIFO()) && info.nlink > 1n)
2894
+ return true;
2895
+ if (info.isDirectory()) {
2896
+ for (const child of readdirSync2(current)) {
2897
+ pending.push(path6.join(current, child));
2898
+ }
2899
+ }
2900
+ }
2901
+ return false;
2902
+ } catch {
2903
+ return true;
2904
+ }
2905
+ };
2445
2906
 
2446
- // src/permissions/linux-shell-backend.ts
2447
- import { spawn as spawn2, spawnSync } from "child_process";
2907
+ // src/permissions/linux-mxc-backend.ts
2448
2908
  import {
2449
2909
  accessSync as accessSync2,
2450
2910
  constants as constants4,
2451
- lstatSync as lstatSync5,
2452
- mkdirSync,
2911
+ lstatSync as lstatSync7,
2453
2912
  mkdtempSync,
2454
- readdirSync as readdirSync5,
2455
- readFileSync as readFileSync3,
2456
- realpathSync as realpathSync5,
2913
+ readdirSync as readdirSync6,
2914
+ readFileSync as readFileSync4,
2915
+ realpathSync as realpathSync6,
2457
2916
  rmSync,
2458
- statSync as statSync3,
2459
- writeFileSync
2917
+ statSync as statSync4
2460
2918
  } from "fs";
2461
- import path10 from "path";
2919
+ import { homedir } from "os";
2920
+ import path11 from "path";
2462
2921
 
2463
2922
  // src/permissions/linux-mountinfo.ts
2464
2923
  import { readFileSync as readFileSync2 } from "fs";
@@ -2545,21 +3004,283 @@ function executableMountSnapshot(file, dev, text = readFileSync2("/proc/self/mou
2545
3004
  ).map(({ line }) => line).join("\n");
2546
3005
  }
2547
3006
 
2548
- // src/permissions/protected-aliases.ts
3007
+ // src/permissions/mxc-launcher.ts
3008
+ import { spawn as spawn2, spawnSync } from "child_process";
2549
3009
  import {
2550
- lstatSync as lstatSync3,
3010
+ lstatSync as lstatSync4,
2551
3011
  readdirSync as readdirSync3,
2552
- realpathSync as realpathSync3
3012
+ readFileSync as readFileSync3,
3013
+ realpathSync as realpathSync3,
3014
+ statSync as statSync2
2553
3015
  } from "fs";
2554
3016
  import path8 from "path";
3017
+ import { fileURLToPath } from "url";
3018
+ var binaryName = "codelia-mxc-launcher";
3019
+ var MXC_PROTOCOL_VERSION = 3;
3020
+ var MAX_MXC_FRAME_BYTES = 256 * 1024;
3021
+ var supportedMxcPackages = /* @__PURE__ */ new Map([
3022
+ ["darwin-arm64", "@codelia/tui-darwin-arm64"],
3023
+ ["linux-x64", "@codelia/tui-linux-x64"],
3024
+ ["linux-arm64", "@codelia/tui-linux-arm64"]
3025
+ ]);
3026
+ var moduleDir = typeof __dirname === "string" ? __dirname : path8.dirname(fileURLToPath(import.meta.url));
3027
+ var helperCwd = () => process.platform === "darwin" ? "/private/tmp" : "/tmp";
3028
+ var packageVersion = (directory, name) => {
3029
+ try {
3030
+ const manifest = path8.join(directory, "package.json");
3031
+ const info = lstatSync4(manifest);
3032
+ if (!info.isFile() || info.size > 64 * 1024) return void 0;
3033
+ const parsed = JSON.parse(readFileSync3(manifest, "utf8"));
3034
+ return parsed.name === name && typeof parsed.version === "string" ? parsed.version : void 0;
3035
+ } catch {
3036
+ return void 0;
3037
+ }
3038
+ };
3039
+ var directoryId = (info) => `${info.dev}:${info.ino}`;
3040
+ var isTrustedCargoSubdir = (info, writableDirs, uid) => info.isDirectory() && !writableDirs.has(directoryId(info)) && (info.uid === uid || info.uid === 0n) && (info.mode & 0o022n) === 0n;
3041
+ var MAX_CARGO_LINK_SCAN_DEPTH = 6;
3042
+ var MAX_CARGO_LINK_SCAN_ENTRIES = 1e5;
3043
+ var SKIPPED_CARGO_SUBDIRS = /* @__PURE__ */ new Set([".fingerprint", "incremental"]);
3044
+ var accountsForCargoTargetLinks = (directory, launcherFile, info, writableDirs, uid) => {
3045
+ if (info.nlink === 1n) return true;
3046
+ const targetDir = path8.dirname(directory);
3047
+ const queue = [
3048
+ { dir: directory, depth: 0 }
3049
+ ];
3050
+ for (const sibling of ["build", "deps"]) {
3051
+ const root = path8.join(targetDir, sibling);
3052
+ const rootInfo = lstatSync4(root, { bigint: true, throwIfNoEntry: false });
3053
+ if (rootInfo && isTrustedCargoSubdir(rootInfo, writableDirs, uid)) {
3054
+ queue.push({ dir: root, depth: 0 });
3055
+ }
3056
+ }
3057
+ let accounted = 1n;
3058
+ let visited = 0;
3059
+ for (let head = 0; head < queue.length; head += 1) {
3060
+ const item = queue[head];
3061
+ if (!item || item.depth > MAX_CARGO_LINK_SCAN_DEPTH) continue;
3062
+ let names;
3063
+ try {
3064
+ names = readdirSync3(item.dir);
3065
+ } catch {
3066
+ continue;
3067
+ }
3068
+ names.sort((left, right) => {
3069
+ const leftPriority = left.includes("codelia") ? 0 : 1;
3070
+ const rightPriority = right.includes("codelia") ? 0 : 1;
3071
+ return leftPriority - rightPriority;
3072
+ });
3073
+ for (const name of names) {
3074
+ if (SKIPPED_CARGO_SUBDIRS.has(name)) continue;
3075
+ if (++visited > MAX_CARGO_LINK_SCAN_ENTRIES) return false;
3076
+ const entryPath = path8.join(item.dir, name);
3077
+ if (entryPath === launcherFile) continue;
3078
+ const child = lstatSync4(entryPath, {
3079
+ bigint: true,
3080
+ throwIfNoEntry: false
3081
+ });
3082
+ if (!child) continue;
3083
+ if (child.isFile() && child.dev === info.dev && child.ino === info.ino) {
3084
+ accounted += 1n;
3085
+ if (accounted === info.nlink) return true;
3086
+ } else if (item.depth < MAX_CARGO_LINK_SCAN_DEPTH && child.isDirectory() && isTrustedCargoSubdir(child, writableDirs, uid)) {
3087
+ queue.push({ dir: entryPath, depth: item.depth + 1 });
3088
+ }
3089
+ }
3090
+ }
3091
+ return accounted === info.nlink;
3092
+ };
3093
+ var trustedLauncher = (candidate, writableDirs, uid, protectedHome, allowCargoTargetLinks = false) => {
3094
+ try {
3095
+ const directory = realpathSync3(path8.dirname(candidate));
3096
+ const file = path8.join(directory, binaryName);
3097
+ const info = lstatSync4(file, { bigint: true });
3098
+ const linksAccounted = allowCargoTargetLinks ? accountsForCargoTargetLinks(directory, file, info, writableDirs, uid) : info.nlink === 1n;
3099
+ if (!info.isFile() || !linksAccounted || info.size === 0n || info.uid !== uid && info.uid !== 0n || (info.mode & 0o6022n) !== 0n || (info.mode & 0o100n) === 0n)
3100
+ return void 0;
3101
+ const protectedInHomeDot = protectedHome !== void 0 && isHomeDotTarget(protectedHome, directory);
3102
+ let current = directory;
3103
+ for (; ; ) {
3104
+ const parent = statSync2(current, { bigint: true });
3105
+ const systemSticky = parent.uid === 0n && (parent.mode & 0o1000n) !== 0n;
3106
+ const isWritableParent = writableDirs.has(directoryId(parent)) && !(protectedInHomeDot && current === protectedHome);
3107
+ if (!parent.isDirectory() || isWritableParent || parent.uid !== uid && parent.uid !== 0n || (parent.mode & 0o022n) !== 0n && !systemSticky)
3108
+ return void 0;
3109
+ const next = path8.dirname(current);
3110
+ if (next === current) break;
3111
+ current = next;
3112
+ }
3113
+ return {
3114
+ candidate,
3115
+ file,
3116
+ identity: `${directoryId(info)}:${info.size}:${info.ctimeNs}`
3117
+ };
3118
+ } catch {
3119
+ return void 0;
3120
+ }
3121
+ };
3122
+ var resolveMxcLauncher = (protection) => {
3123
+ const uid = process.geteuid?.();
3124
+ const packageName = supportedMxcPackages.get(
3125
+ `${process.platform}-${process.arch}`
3126
+ );
3127
+ if (!packageName || uid === void 0) return void 0;
3128
+ try {
3129
+ const mutable = new Set(
3130
+ [
3131
+ protection.root,
3132
+ ...protection.writeRoots,
3133
+ ...protection.gitWriteRoots ?? []
3134
+ ].map((root) => directoryId(statSync2(root, { bigint: true })))
3135
+ );
3136
+ const actualModule = realpathSync3(moduleDir);
3137
+ const projectPackage = path8.basename(actualModule) === "permissions" ? path8.resolve(actualModule, "../..") : path8.dirname(actualModule);
3138
+ const suffix = path8.join("packages", "runtime");
3139
+ if (projectPackage.endsWith(`${path8.sep}${suffix}`)) {
3140
+ const checkout = path8.resolve(projectPackage, "../..");
3141
+ const built = trustedLauncher(
3142
+ path8.join(checkout, "crates/mxc-launcher/target/release", binaryName),
3143
+ mutable,
3144
+ BigInt(uid),
3145
+ void 0,
3146
+ true
3147
+ );
3148
+ if (built) return built;
3149
+ }
3150
+ const version = packageVersion(projectPackage, "@codelia/runtime");
3151
+ if (!version) return void 0;
3152
+ const packagePath = path8.join("node_modules", ...packageName.split("/"));
3153
+ let directory = actualModule;
3154
+ for (; ; ) {
3155
+ const candidatePackage = path8.join(directory, packagePath);
3156
+ const installed = packageVersion(candidatePackage, packageName) === version ? trustedLauncher(
3157
+ path8.join(candidatePackage, "bin", binaryName),
3158
+ mutable,
3159
+ BigInt(uid),
3160
+ protection.homeDotDirectory
3161
+ ) : void 0;
3162
+ if (installed) return installed;
3163
+ const parent = path8.dirname(directory);
3164
+ if (parent === directory) return void 0;
3165
+ directory = parent;
3166
+ }
3167
+ } catch {
3168
+ return void 0;
3169
+ }
3170
+ };
3171
+ var probeMxcLauncher = (launcher, options) => spawnSync(
3172
+ launcher.file,
3173
+ ["--probe-v3", ...options?.bwrapPath ? [options.bwrapPath] : []],
3174
+ {
3175
+ cwd: helperCwd(),
3176
+ env: {},
3177
+ stdio: "ignore",
3178
+ // On Linux, MXC's internal `bwrap --version` probe uses a 5s deadline.
3179
+ timeout: process.platform === "linux" ? 6e3 : 2500,
3180
+ killSignal: "SIGKILL"
3181
+ }
3182
+ ).status === 0;
3183
+ var lifecycles = /* @__PURE__ */ new WeakMap();
3184
+ var mxcLifecycle = (child) => lifecycles.get(child);
3185
+ var launchMxc = (launcher, request, stdin) => {
3186
+ const frame = `${JSON.stringify({ version: MXC_PROTOCOL_VERSION, ...request })}
3187
+ `;
3188
+ if (Buffer.byteLength(frame) > MAX_MXC_FRAME_BYTES)
3189
+ throw new Error("sandbox_launch_failed");
3190
+ const child = spawn2(launcher.file, ["--run"], {
3191
+ cwd: helperCwd(),
3192
+ env: {},
3193
+ detached: true,
3194
+ stdio: [stdin === "pipe" ? "pipe" : "ignore", "pipe", "pipe", "pipe"]
3195
+ });
3196
+ const control2 = child.stdio[3];
3197
+ let pending = "";
3198
+ let accepted = false;
3199
+ let failed = false;
3200
+ let expectedExit;
3201
+ let deadline;
3202
+ let reportCompletion;
3203
+ const completed = new Promise((resolve) => {
3204
+ reportCompletion = resolve;
3205
+ });
3206
+ const boundCleanup = () => {
3207
+ deadline ??= setTimeout(() => {
3208
+ reportCompletion("unconfirmed");
3209
+ control2.destroy();
3210
+ child.stdin?.destroy();
3211
+ child.stdout.destroy();
3212
+ child.stderr.destroy();
3213
+ child.unref();
3214
+ }, 8e3);
3215
+ };
3216
+ const revoke = () => {
3217
+ if (!control2.writableEnded && !control2.destroyed) control2.end();
3218
+ boundCleanup();
3219
+ };
3220
+ const rejectReport = () => {
3221
+ failed = true;
3222
+ revoke();
3223
+ };
3224
+ control2.setEncoding("utf8");
3225
+ control2.on("error", rejectReport);
3226
+ control2.on("data", (chunk) => {
3227
+ if (failed) return;
3228
+ pending += chunk;
3229
+ if (pending.length > 256) return rejectReport();
3230
+ let newline = pending.indexOf("\n");
3231
+ while (newline !== -1) {
3232
+ try {
3233
+ const value = JSON.parse(pending.slice(0, newline));
3234
+ if (expectedExit !== void 0) return rejectReport();
3235
+ if (value.event === "started" && !accepted) accepted = true;
3236
+ else if (value.event === "cancelled") expectedExit = 143;
3237
+ else if (accepted && value.event === "finished" && Number.isInteger(value.exit_code) && value.exit_code >= 0 && value.exit_code <= 255)
3238
+ expectedExit = value.exit_code;
3239
+ else return rejectReport();
3240
+ } catch {
3241
+ return rejectReport();
3242
+ }
3243
+ pending = pending.slice(newline + 1);
3244
+ newline = pending.indexOf("\n");
3245
+ }
3246
+ });
3247
+ child.once("exit", boundCleanup);
3248
+ child.once("close", (code, signal) => {
3249
+ clearTimeout(deadline);
3250
+ reportCompletion(
3251
+ !failed && pending === "" && signal === null && code === expectedExit ? "clean" : "unconfirmed"
3252
+ );
3253
+ });
3254
+ lifecycles.set(child, { revoke, completed });
3255
+ control2.write(frame);
3256
+ return child;
3257
+ };
3258
+
3259
+ // src/permissions/protected-aliases.ts
3260
+ import {
3261
+ lstatSync as lstatSync5,
3262
+ readdirSync as readdirSync4,
3263
+ realpathSync as realpathSync4
3264
+ } from "fs";
3265
+ import path9 from "path";
2555
3266
  var maxEntries = 4096;
2556
3267
  var inode = (stat) => `${stat.dev}:${stat.ino}`;
2557
3268
  function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifiedHooks = []) {
2558
3269
  const pending = roots.map((entry) => {
2559
3270
  try {
2560
- return realpathSync3(entry);
3271
+ return realpathSync4(entry);
2561
3272
  } catch (error) {
2562
- if (error.code === "ENOENT") return entry;
3273
+ const code = error.code;
3274
+ if (code === "ENOENT") return entry;
3275
+ if (code === "EOPNOTSUPP" || code === "ENXIO") {
3276
+ const info = lstatSync5(entry, { throwIfNoEntry: false });
3277
+ if (info && !info.isSymbolicLink()) {
3278
+ return path9.join(
3279
+ realpathSync4(path9.dirname(entry)),
3280
+ path9.basename(entry)
3281
+ );
3282
+ }
3283
+ }
2563
3284
  throw error;
2564
3285
  }
2565
3286
  });
@@ -2573,7 +3294,7 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
2573
3294
  const target = hooks.get(file);
2574
3295
  if (!target) return false;
2575
3296
  try {
2576
- return realpathSync3(file) === target && lstatSync3(target).isFile();
3297
+ return realpathSync4(file) === target && lstatSync5(target).isFile();
2577
3298
  } catch {
2578
3299
  return false;
2579
3300
  }
@@ -2585,18 +3306,19 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
2585
3306
  if (visited.size > entryLimit)
2586
3307
  throw new Error("protected_alias_index_unavailable");
2587
3308
  try {
2588
- const metadata = lstatSync3(file, { bigint: true });
2589
- if (metadata.isFile() && metadata.nlink > 1n) yield inode(metadata);
3309
+ const metadata = lstatSync5(file, { bigint: true });
3310
+ if ((metadata.isFile() || metadata.isSocket() || metadata.isFIFO()) && metadata.nlink > 1n)
3311
+ yield inode(metadata);
2590
3312
  if (metadata.isSymbolicLink() && ignored.size) {
2591
3313
  if (verifiedHook(file)) continue;
2592
3314
  pending.push(...ignored);
2593
3315
  ignored.clear();
2594
3316
  } else if (metadata.isDirectory()) {
2595
- const children = readdirSync3(file);
3317
+ const children = readdirSync4(file);
2596
3318
  if (children.length + pending.length + visited.size > entryLimit)
2597
3319
  throw new Error("protected_alias_index_unavailable");
2598
3320
  for (const name of children) {
2599
- const child = path8.join(file, name);
3321
+ const child = path9.join(file, name);
2600
3322
  if (!ignored.has(child)) pending.push(child);
2601
3323
  }
2602
3324
  }
@@ -2870,29 +3592,29 @@ var analyzeShell = (invocation) => {
2870
3592
  import {
2871
3593
  accessSync,
2872
3594
  constants as constants3,
2873
- lstatSync as lstatSync4,
2874
- readdirSync as readdirSync4,
2875
- readlinkSync as readlinkSync3,
2876
- realpathSync as realpathSync4,
2877
- statSync as statSync2
3595
+ lstatSync as lstatSync6,
3596
+ readdirSync as readdirSync5,
3597
+ readlinkSync as readlinkSync4,
3598
+ realpathSync as realpathSync5,
3599
+ statSync as statSync3
2878
3600
  } 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);
3601
+ import path10 from "path";
3602
+ var shellBinPaths = (override) => Object.freeze((override ?? process.env.PATH ?? "").split(path10.delimiter));
3603
+ var shellPathForLaunch = (binPaths) => (binPaths ?? shellBinPaths()).join(path10.delimiter);
2882
3604
  var resolveShellExecutable = (name, paths, cwd = process.cwd()) => {
2883
- if (!name || name.includes("\0") || !path9.isAbsolute(name) && (name.includes("/") || process.platform === "win32" && name.includes("\\")))
3605
+ if (!name || name.includes("\0") || !path10.isAbsolute(name) && (name.includes("/") || process.platform === "win32" && name.includes("\\")))
2884
3606
  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) => {
3607
+ const executable = process.platform === "win32" && !path10.extname(name) ? `${name}.exe` : name;
3608
+ const candidates = path10.isAbsolute(executable) ? [executable] : paths.map((entry) => {
2887
3609
  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}`;
3610
+ const resolved = path10.isAbsolute(directory) ? directory : `${cwd}${path10.sep}${directory || "."}`;
3611
+ return `${resolved}${path10.sep}${executable}`;
2890
3612
  });
2891
3613
  for (const candidate of candidates) {
2892
3614
  try {
2893
3615
  accessSync(candidate, constants3.X_OK);
2894
- const actual = realpathSync4(candidate);
2895
- if (statSync2(actual).isFile()) return actual;
3616
+ const actual = realpathSync5(candidate);
3617
+ if (statSync3(actual).isFile()) return actual;
2896
3618
  } catch {
2897
3619
  }
2898
3620
  }
@@ -2906,11 +3628,11 @@ var inspectBashPath = (candidate, policy) => {
2906
3628
  while (components.length) {
2907
3629
  const component = components.shift();
2908
3630
  if (!component || component === ".") continue;
2909
- const name = path9.join(current, component);
3631
+ const name = path10.join(current, component);
2910
3632
  const restriction = policy(name);
2911
3633
  if (restriction === "unbound") throw new Error("unbound_shell_path");
2912
3634
  masked ||= restriction === "masked";
2913
- const entry = lstatSync4(name, { throwIfNoEntry: false });
3635
+ const entry = lstatSync6(name, { throwIfNoEntry: false });
2914
3636
  if (!entry) return void 0;
2915
3637
  if (!entry.isSymbolicLink()) {
2916
3638
  if (components.length && !entry.isDirectory()) return void 0;
@@ -2918,27 +3640,27 @@ var inspectBashPath = (candidate, policy) => {
2918
3640
  continue;
2919
3641
  }
2920
3642
  if (++links > 40) throw new Error("unbound_shell_path");
2921
- const destination = readlinkSync3(name);
2922
- if (path9.isAbsolute(destination)) current = "/";
3643
+ const destination = readlinkSync4(name);
3644
+ if (path10.isAbsolute(destination)) current = "/";
2923
3645
  components = [...destination.split("/"), ...components];
2924
3646
  }
2925
3647
  return { file: current, masked };
2926
3648
  };
2927
3649
  var bindBashCommand = (name, paths, policy, acceptShared = () => false) => {
2928
- const absolute = path9.isAbsolute(name);
3650
+ const absolute = path10.isAbsolute(name);
2929
3651
  try {
2930
3652
  for (const directory of absolute ? [""] : paths) {
2931
- if (!absolute && (!path9.isAbsolute(directory) || directory.split("/").includes("..")))
3653
+ if (!absolute && (!path10.isAbsolute(directory) || directory.split("/").includes("..")))
2932
3654
  return void 0;
2933
3655
  const inspected = inspectBashPath(
2934
3656
  absolute ? name : `${directory}/${name}`,
2935
3657
  policy
2936
3658
  );
2937
3659
  if (!inspected) continue;
2938
- const executable = realpathSync4(inspected.file);
3660
+ const executable = realpathSync5(inspected.file);
2939
3661
  const restriction = policy(executable);
2940
3662
  if (restriction === "unbound") return void 0;
2941
- const info = statSync2(executable, { bigint: true });
3663
+ const info = statSync3(executable, { bigint: true });
2942
3664
  if (!info.isFile()) continue;
2943
3665
  if (info.nlink !== 1n && !acceptShared(executable, info))
2944
3666
  return void 0;
@@ -2961,11 +3683,11 @@ var bindBashCommand = (name, paths, policy, acceptShared = () => false) => {
2961
3683
  };
2962
3684
  function bindKnownSystemExecutable(program, paths, policy, directArgv) {
2963
3685
  if (process.platform === "win32") return void 0;
2964
- const name = path9.basename(program);
3686
+ const name = path10.basename(program);
2965
3687
  const known = new Set(
2966
3688
  [`/usr/bin/${name}`, `/bin/${name}`].flatMap((entry) => {
2967
3689
  try {
2968
- return [realpathSync4(entry)];
3690
+ return [realpathSync5(entry)];
2969
3691
  } catch {
2970
3692
  return [];
2971
3693
  }
@@ -2984,73 +3706,471 @@ var isRootControlledSharedExecutable = (file, info) => {
2984
3706
  const uid = process.getuid?.();
2985
3707
  return uid !== void 0 && uid !== 0 && uid === process.geteuid?.() && info.uid === 0n && (info.mode & 0o022n) === 0n && notWritable(file);
2986
3708
  };
2987
- 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
- function areAllExecutableLinksOutsideRestrictedPaths(file, info, policy) {
3709
+ 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;
3710
+ function areAllExecutableLinksOutsideRestrictedPaths(file, info, policy) {
3711
+ try {
3712
+ const parent = path10.dirname(file);
3713
+ if (policy(parent) || realpathSync5(parent) !== parent) return false;
3714
+ const directory = lstatSync6(parent, { bigint: true });
3715
+ const executable = lstatSync6(file, { bigint: true });
3716
+ if (!directory.isDirectory() || !executable.isFile() || !sameLinkMetadata(executable, info) || executable.nlink < 2n)
3717
+ return false;
3718
+ const mounts = process.platform === "linux" ? executableMountSnapshot(file, executable.dev) : void 0;
3719
+ let links = 0n;
3720
+ let foundExecutable = false;
3721
+ const entries = readdirSync5(parent, { encoding: "buffer" });
3722
+ if (entries.length > 4096) return false;
3723
+ for (const entry of entries) {
3724
+ const name = entry.toString();
3725
+ if (!Buffer.from(name).equals(entry)) return false;
3726
+ const peer = path10.join(parent, name);
3727
+ const peerInfo = lstatSync6(peer, { bigint: true });
3728
+ if (peerInfo.dev !== executable.dev || peerInfo.ino !== executable.ino)
3729
+ continue;
3730
+ if (!peerInfo.isFile() || policy(peer) || !sameLinkMetadata(executable, peerInfo))
3731
+ return false;
3732
+ foundExecutable ||= peer === file;
3733
+ links++;
3734
+ }
3735
+ 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);
3736
+ } catch {
3737
+ return false;
3738
+ }
3739
+ }
3740
+ var notWritable = (file) => {
3741
+ try {
3742
+ accessSync(file, constants3.W_OK);
3743
+ return false;
3744
+ } catch (error) {
3745
+ return ["EACCES", "EPERM", "EROFS"].includes(
3746
+ error.code ?? ""
3747
+ );
3748
+ }
3749
+ };
3750
+
3751
+ // src/permissions/linux-mxc-backend.ts
3752
+ var within2 = (root, name) => root === "/" || root === name || name.startsWith(`${root}/`);
3753
+ var virtualRoots = ["/proc", "/dev", "/sys", "/run", "/var/run"];
3754
+ var MAX_FILESYSTEM_SPEC_BYTES = MAX_MXC_FRAME_BYTES - 16 * 1024;
3755
+ var baselineReadOnlyRoots = [
3756
+ "/bin",
3757
+ "/sbin",
3758
+ "/lib",
3759
+ "/lib32",
3760
+ "/lib64",
3761
+ "/libx32",
3762
+ "/usr/bin",
3763
+ "/usr/sbin",
3764
+ "/usr/lib",
3765
+ "/usr/lib32",
3766
+ "/usr/lib64",
3767
+ "/usr/libx32",
3768
+ "/usr/libexec",
3769
+ "/usr/share",
3770
+ "/etc"
3771
+ ];
3772
+ var DEFAULT_LINUX_MXC_READABLE_ROOTS = [
3773
+ "/home",
3774
+ "/opt",
3775
+ "/srv",
3776
+ "/mnt",
3777
+ "/media",
3778
+ "/nix/store",
3779
+ "/usr/local",
3780
+ "/usr/include",
3781
+ "/var/cache"
3782
+ ];
3783
+ var disallowedExtraReadRoots = /* @__PURE__ */ new Set(["/", "/tmp", ...virtualRoots]);
3784
+ var BWRAP_CANDIDATES = [
3785
+ "/usr/bin/bwrap",
3786
+ "/bin/bwrap",
3787
+ "/usr/local/bin/bwrap",
3788
+ "/run/current-system/sw/bin/bwrap"
3789
+ ];
3790
+ var SYSTEM_SH_CANDIDATES = ["/usr/bin/sh", "/bin/sh"];
3791
+ var resolveManagedLinuxTool = (candidates, options) => {
3792
+ for (const candidate of candidates) {
3793
+ const present = lstatSync7(candidate, { throwIfNoEntry: false }) !== void 0;
3794
+ if (!present) continue;
3795
+ try {
3796
+ const resolved = realpathSync6(candidate);
3797
+ if (options?.expectedBasename && path11.basename(resolved) !== options.expectedBasename) {
3798
+ if (options.firstPresentMustBeTrusted) return void 0;
3799
+ continue;
3800
+ }
3801
+ const fileInfo = statSync4(resolved, { bigint: true });
3802
+ if (!fileInfo.isFile() || fileInfo.uid !== 0n || (fileInfo.mode & 0o022n) !== 0n || (fileInfo.mode & 0o111n) === 0n) {
3803
+ if (options?.firstPresentMustBeTrusted) return void 0;
3804
+ continue;
3805
+ }
3806
+ accessSync2(resolved, constants4.X_OK);
3807
+ let trusted = true;
3808
+ let current = path11.dirname(resolved);
3809
+ for (; ; ) {
3810
+ const info = statSync4(current, { bigint: true });
3811
+ if (!info.isDirectory() || info.uid !== 0n || (info.mode & 0o022n) !== 0n) {
3812
+ trusted = false;
3813
+ break;
3814
+ }
3815
+ const parent = path11.dirname(current);
3816
+ if (parent === current) break;
3817
+ current = parent;
3818
+ }
3819
+ if (!trusted) {
3820
+ if (options?.firstPresentMustBeTrusted) return void 0;
3821
+ continue;
3822
+ }
3823
+ return {
3824
+ candidate,
3825
+ file: resolved,
3826
+ identity: `${fileInfo.dev}:${fileInfo.ino}:${fileInfo.size}:${fileInfo.ctimeNs}`
3827
+ };
3828
+ } catch {
3829
+ if (options?.firstPresentMustBeTrusted) return void 0;
3830
+ }
3831
+ }
3832
+ return void 0;
3833
+ };
3834
+ var resolveLinuxBwrap = () => process.platform === "linux" ? resolveManagedLinuxTool(BWRAP_CANDIDATES, { expectedBasename: "bwrap" }) : void 0;
3835
+ var resolveLinuxSystemSh = () => process.platform === "linux" ? resolveManagedLinuxTool(SYSTEM_SH_CANDIDATES, {
3836
+ // Container PATH searches /usr/bin before /bin, so an untrusted
3837
+ // /usr/bin/sh must fail closed instead of falling back to /bin/sh.
3838
+ firstPresentMustBeTrusted: true
3839
+ }) : void 0;
3840
+ var linuxMxcManagedToolPaths = () => {
3841
+ if (process.platform !== "linux") return [];
3842
+ const bwrap = resolveLinuxBwrap();
3843
+ const sh = resolveLinuxSystemSh();
3844
+ return [
3845
+ ...new Set(
3846
+ [bwrap, sh].flatMap((tool) => tool ? [tool.candidate, tool.file] : [])
3847
+ )
3848
+ ];
3849
+ };
3850
+ var deniedPathsFor = (policy) => {
3851
+ const paths = /* @__PURE__ */ new Set();
3852
+ for (const item of policy.protectedPaths) {
3853
+ if (!path11.isAbsolute(item) || item !== path11.normalize(item) || item === "/")
3854
+ throw new Error("invalid_protected_path");
3855
+ if (item === "/dev") continue;
3856
+ let resolved;
3857
+ try {
3858
+ resolved = realpathSync6(item);
3859
+ } catch (error) {
3860
+ const code = error.code;
3861
+ if (code === "ENOENT") {
3862
+ resolved = item;
3863
+ } else if (code === "EOPNOTSUPP" || code === "ENXIO") {
3864
+ const linfo = lstatSync7(item, { throwIfNoEntry: false });
3865
+ if (linfo && !linfo.isSymbolicLink() && (linfo.isSocket() || linfo.isFIFO())) {
3866
+ resolved = path11.join(
3867
+ realpathSync6(path11.dirname(item)),
3868
+ path11.basename(item)
3869
+ );
3870
+ } else {
3871
+ throw error;
3872
+ }
3873
+ } else {
3874
+ throw error;
3875
+ }
3876
+ }
3877
+ if (resolved === "/") throw new Error("invalid_protected_path");
3878
+ paths.add(item);
3879
+ paths.add(resolved);
3880
+ }
3881
+ const selected = [];
3882
+ for (const item of [...paths].sort((a, b) => a.length - b.length)) {
3883
+ if (!selected.some((mask) => within2(mask, item))) selected.push(item);
3884
+ }
3885
+ for (const target of selected) {
3886
+ const info = statSync4(target, { throwIfNoEntry: false });
3887
+ if (!info) throw new Error("missing_protected_mountpoint");
3888
+ if (!info.isDirectory() && !info.isFile() && !info.isSocket() && !info.isFIFO())
3889
+ throw new Error("unsupported_protected_mountpoint");
3890
+ }
3891
+ return selected;
3892
+ };
3893
+ var readOnlyMount = (entry, projectedHome) => {
3894
+ try {
3895
+ if (realpathSync6(entry) !== entry)
3896
+ throw new Error("unbound_read_only_path");
3897
+ return entry;
3898
+ } catch (error) {
3899
+ if (error.code !== "ENOENT" || !projectedHome || !within2(projectedHome, entry) || resolveReservedTarget(entry) !== entry)
3900
+ throw error;
3901
+ }
3902
+ let parent = path11.dirname(entry);
3903
+ while (within2(projectedHome, parent)) {
3904
+ const info = lstatSync7(parent, { throwIfNoEntry: false });
3905
+ if (info) {
3906
+ if (info.isDirectory() && realpathSync6(parent) === parent) return parent;
3907
+ break;
3908
+ }
3909
+ if (parent === projectedHome) break;
3910
+ parent = path11.dirname(parent);
3911
+ }
3912
+ throw new Error("unbound_read_only_path");
3913
+ };
3914
+ var existingReadableDirectory = (candidate, requireCanonical = false) => {
3915
+ if (!path11.isAbsolute(candidate)) return void 0;
3916
+ try {
3917
+ const linfo = lstatSync7(candidate, { throwIfNoEntry: false });
3918
+ if (!linfo) return void 0;
3919
+ if (requireCanonical && linfo.isSymbolicLink()) return void 0;
3920
+ const resolved = realpathSync6(candidate);
3921
+ if (requireCanonical && resolved !== candidate) return void 0;
3922
+ const info = statSync4(resolved, { throwIfNoEntry: false });
3923
+ if (!info?.isDirectory()) return void 0;
3924
+ accessSync2(resolved, constants4.R_OK);
3925
+ return resolved;
3926
+ } catch {
3927
+ return void 0;
3928
+ }
3929
+ };
3930
+ var buildLinuxMxcFilesystemPolicy = (policy, scratch, options = {}) => {
3931
+ if (policy.profile === "full-access" || policy.profile === "investigation" && policy.writeRoots.length || policy.gitWriteRoots?.length || policy.gitProtectedPaths?.length)
3932
+ throw new Error("unsupported_protection");
3933
+ if (!path11.isAbsolute(scratch) || scratch !== path11.normalize(scratch) || scratch === "/" || virtualRoots.some((name) => within2(name, scratch)))
3934
+ throw new Error("invalid_scratch_root");
3935
+ if (!options.skipScratchStat && (realpathSync6(scratch) !== scratch || !statSync4(scratch).isDirectory()))
3936
+ throw new Error("invalid_scratch_root");
3937
+ const deniedPaths = deniedPathsFor(policy);
3938
+ if (deniedPaths.some((mask) => within2(mask, scratch)))
3939
+ throw new Error("invalid_scratch_root");
3940
+ const readOnly = policy.readOnlyPaths ?? [];
3941
+ const home = policy.homeDotDirectory;
3942
+ const projectedHome = home && policy.writeRoots.includes(home) ? home : void 0;
3943
+ const protectedTargets = [...deniedPaths, ...readOnly];
3944
+ const covered = (target) => protectedTargets.some((entry) => within2(entry, target));
3945
+ const writableRoots = /* @__PURE__ */ new Set();
3946
+ for (const root of policy.writeRoots) {
3947
+ if (home && root !== home && (within2(root, home) || resourceContainsPath(root, home)))
3948
+ throw new Error("unsupported_home_write_root");
3949
+ if (root === "/" || root === "/tmp" || realpathSync6(root) !== root || !statSync4(root).isDirectory() || virtualRoots.some((name) => within2(name, root)))
3950
+ throw new Error("invalid_write_root");
3951
+ if (within2(scratch, root)) continue;
3952
+ if (deniedPaths.some((mask) => within2(mask, root)))
3953
+ throw new Error("invalid_write_root");
3954
+ if (readOnly.some((entry) => within2(entry, root))) continue;
3955
+ if (root !== home) writableRoots.add(root);
3956
+ }
3957
+ const explicitReadOnly = /* @__PURE__ */ new Set();
3958
+ if (projectedHome) {
3959
+ explicitReadOnly.add(projectedHome);
3960
+ for (const name of readdirSync6(projectedHome)) {
3961
+ const child = path11.join(projectedHome, name);
3962
+ if (child === scratch || isHomeDotTarget(projectedHome, child, "linux") || covered(child))
3963
+ continue;
3964
+ const info = lstatSync7(child, { throwIfNoEntry: false });
3965
+ if ((info?.isDirectory() || info?.isFile()) && realpathSync6(child) === child)
3966
+ writableRoots.add(child);
3967
+ }
3968
+ }
3969
+ const readOnlyMounts = /* @__PURE__ */ new Set();
3970
+ const proposedRoots = [...writableRoots];
3971
+ for (const entry of [...readOnly].sort((a, b) => a.length - b.length)) {
3972
+ if (!deniedPaths.some((mask) => within2(mask, entry)) && proposedRoots.some((root) => within2(root, entry)) && ![...readOnlyMounts].some((mount) => within2(mount, entry))) {
3973
+ readOnlyMounts.add(readOnlyMount(entry, projectedHome));
3974
+ }
3975
+ }
3976
+ protectedTargets.push(...readOnlyMounts);
3977
+ for (const root of writableRoots) {
3978
+ if (covered(root)) writableRoots.delete(root);
3979
+ }
3980
+ const writeRoots = [...writableRoots];
3981
+ const anchors = /* @__PURE__ */ new Set();
3982
+ for (const entry of [...readOnlyMounts, ...deniedPaths]) {
3983
+ let parent = path11.dirname(entry);
3984
+ while (writeRoots.some((root) => root !== parent && within2(root, parent))) {
3985
+ if (!writableRoots.has(parent) && !covered(parent)) anchors.add(parent);
3986
+ parent = path11.dirname(parent);
3987
+ }
3988
+ }
3989
+ for (const anchor of anchors) {
3990
+ const info = statSync4(anchor, { throwIfNoEntry: false });
3991
+ if (!info) {
3992
+ anchors.delete(anchor);
3993
+ continue;
3994
+ }
3995
+ if (!info.isDirectory() || realpathSync6(anchor) !== anchor)
3996
+ throw new Error("unbound_protected_ancestor");
3997
+ }
3998
+ const readwritePaths = [
3999
+ .../* @__PURE__ */ new Set([scratch, ...writeRoots, ...anchors])
4000
+ ].sort((a, b) => a.length - b.length || a.localeCompare(b));
4001
+ const readOnlyPaths = /* @__PURE__ */ new Set();
4002
+ for (const dir of options.readableRoots ?? DEFAULT_LINUX_MXC_READABLE_ROOTS) {
4003
+ const canonical = existingReadableDirectory(dir, true);
4004
+ if (!canonical) continue;
4005
+ if (disallowedExtraReadRoots.has(canonical) || virtualRoots.some((name) => within2(name, canonical)) || deniedPaths.some((mask) => within2(mask, canonical)) || readwritePaths.some((rw) => within2(rw, canonical)))
4006
+ continue;
4007
+ readOnlyPaths.add(canonical);
4008
+ }
4009
+ for (const entry of explicitReadOnly) {
4010
+ if (!deniedPaths.some((mask) => within2(mask, entry))) {
4011
+ readOnlyPaths.add(entry);
4012
+ }
4013
+ }
4014
+ for (const entry of readOnlyMounts) {
4015
+ if (writeRoots.some((root) => within2(root, entry))) {
4016
+ readOnlyPaths.add(entry);
4017
+ }
4018
+ }
4019
+ const extraReadableCandidates = [
4020
+ policy.root,
4021
+ policy.cwd,
4022
+ options.homeDir ?? homedir(),
4023
+ ...Object.values(policy.toolchainHomes ?? {}).filter(
4024
+ (value) => typeof value === "string" && value.length > 0
4025
+ ),
4026
+ ...policy.binPaths ?? []
4027
+ ];
4028
+ for (const candidate of extraReadableCandidates) {
4029
+ const canonical = existingReadableDirectory(candidate, false);
4030
+ if (!canonical) continue;
4031
+ 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)))
4032
+ continue;
4033
+ readOnlyPaths.add(canonical);
4034
+ }
4035
+ const spec = {
4036
+ readwrite_paths: readwritePaths,
4037
+ readonly_paths: [...readOnlyPaths].sort(
4038
+ (a, b) => a.length - b.length || a.localeCompare(b)
4039
+ ),
4040
+ denied_paths: [...deniedPaths].sort(
4041
+ (a, b) => a.length - b.length || a.localeCompare(b)
4042
+ )
4043
+ };
4044
+ if (Buffer.byteLength(JSON.stringify(spec)) > MAX_FILESYSTEM_SPEC_BYTES)
4045
+ throw new Error("filesystem_policy_too_large");
4046
+ return spec;
4047
+ };
4048
+ var release = (root) => {
2989
4049
  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 });
2994
- if (!directory.isDirectory() || !executable.isFile() || !sameLinkMetadata(executable, info) || executable.nlink < 2n)
4050
+ rmSync(root, { recursive: true, force: true });
4051
+ } catch {
4052
+ }
4053
+ };
4054
+ var LinuxMxcBackend = class {
4055
+ supportsReadOnlyPaths = true;
4056
+ supportsHomeDotProtection = true;
4057
+ supportsCommandBinding = true;
4058
+ exactLaunchBindingId = "codelia.linux.mxc/v1";
4059
+ verifiedProbeKey;
4060
+ validatePolicy(policy, scratch, skipScratchStat) {
4061
+ const spec = buildLinuxMxcFilesystemPolicy(policy, scratch, {
4062
+ skipScratchStat
4063
+ });
4064
+ if (findProtectedAliases(policy.protectedAliasPaths ?? policy.protectedPaths).size > 0)
4065
+ throw new Error("protected_file_has_alias");
4066
+ const readOnly = policy.readOnlyPaths ?? [];
4067
+ if (policy.writeRoots.length && hasReadOnlyAliases(policy.readOnlyAliasPaths ?? readOnly))
4068
+ throw new Error("read_only_file_has_alias");
4069
+ if (policy.homeDotDirectory && policy.writeRoots.includes(policy.homeDotDirectory) && hasHomeDotHardLinkAliases(policy.homeDotDirectory))
4070
+ throw new Error("home_dot_file_has_alias");
4071
+ checkLinuxMountTopology(readFileSync4("/proc/self/mountinfo", "utf8"));
4072
+ return spec;
4073
+ }
4074
+ supports(policy) {
4075
+ if (process.platform !== "linux" || process.getuid?.() === 0) return false;
4076
+ try {
4077
+ this.validatePolicy(policy, "/tmp/codelia-mxc-probe", true);
4078
+ const helper = resolveMxcLauncher(policy);
4079
+ const bwrap = resolveLinuxBwrap();
4080
+ const sh = resolveLinuxSystemSh();
4081
+ if (!helper || !bwrap || !sh) return false;
4082
+ const probeKey = `${helper.identity}|${bwrap.identity}|${sh.identity}`;
4083
+ if (this.verifiedProbeKey === probeKey) return true;
4084
+ if (!probeMxcLauncher(helper, { bwrapPath: bwrap.file })) return false;
4085
+ this.verifiedProbeKey = probeKey;
4086
+ return true;
4087
+ } catch {
2995
4088
  return false;
2996
- const mounts = process.platform === "linux" ? executableMountSnapshot(file, executable.dev) : void 0;
2997
- let links = 0n;
2998
- let foundExecutable = false;
2999
- const entries = readdirSync4(parent, { encoding: "buffer" });
3000
- if (entries.length > 4096) return false;
3001
- for (const entry of entries) {
3002
- const name = entry.toString();
3003
- if (!Buffer.from(name).equals(entry)) return false;
3004
- const peer = path9.join(parent, name);
3005
- const peerInfo = lstatSync4(peer, { bigint: true });
3006
- if (peerInfo.dev !== executable.dev || peerInfo.ino !== executable.ino)
3007
- continue;
3008
- if (!peerInfo.isFile() || policy(peer) || !sameLinkMetadata(executable, peerInfo))
3009
- return false;
3010
- foundExecutable ||= peer === file;
3011
- links++;
3012
4089
  }
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
4090
  }
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
- );
4091
+ supportsLaunchBinding(candidate) {
4092
+ return candidate.rule.template === "bun-typecheck/v1";
4093
+ }
4094
+ supportsExactLaunchBinding(_candidate) {
4095
+ return true;
4096
+ }
4097
+ launch(invocation, policy) {
4098
+ if (!this.supports(policy)) throw new Error("sandbox_unavailable");
4099
+ const scratch = realpathSync6(mkdtempSync("/tmp/codelia-mxc-"));
4100
+ const cleanup = () => release(scratch);
4101
+ try {
4102
+ const filesystem = this.validatePolicy(policy, scratch, false);
4103
+ const helper = resolveMxcLauncher(policy);
4104
+ const bwrap = resolveLinuxBwrap();
4105
+ const sh = resolveLinuxSystemSh();
4106
+ if (!helper || !bwrap || !sh || `${helper.identity}|${bwrap.identity}|${sh.identity}` !== this.verifiedProbeKey)
4107
+ throw new Error("sandbox_unavailable");
4108
+ const child = launchMxc(
4109
+ helper,
4110
+ {
4111
+ executable: invocation.executable,
4112
+ args: shellInvocationArgs(invocation),
4113
+ cwd: policy.cwd,
4114
+ filesystem,
4115
+ bwrap_path: bwrap.file,
4116
+ scratch,
4117
+ path: shellPathForLaunch(policy.binPaths),
4118
+ home: homedir(),
4119
+ cargo_home: policy.toolchainHomes?.CARGO_HOME,
4120
+ rustup_home: policy.toolchainHomes?.RUSTUP_HOME
4121
+ },
4122
+ policy.stdin
4123
+ );
4124
+ child.once("close", cleanup);
4125
+ return child;
4126
+ } catch (error) {
4127
+ cleanup();
4128
+ throw error;
4129
+ }
3026
4130
  }
3027
4131
  };
3028
4132
 
3029
4133
  // src/permissions/linux-shell-backend.ts
3030
- var within2 = (root, name) => root === "/" || root === name || name.startsWith(`${root}/`);
3031
- var virtualRoots = ["/proc", "/dev", "/sys"];
4134
+ import { spawn as spawn3, spawnSync as spawnSync2 } from "child_process";
4135
+ import {
4136
+ accessSync as accessSync3,
4137
+ constants as constants5,
4138
+ lstatSync as lstatSync8,
4139
+ mkdirSync,
4140
+ mkdtempSync as mkdtempSync2,
4141
+ readdirSync as readdirSync7,
4142
+ readFileSync as readFileSync5,
4143
+ realpathSync as realpathSync7,
4144
+ rmSync as rmSync2,
4145
+ statSync as statSync5,
4146
+ writeFileSync
4147
+ } from "fs";
4148
+ import { homedir as homedir2 } from "os";
4149
+ import path12 from "path";
4150
+ var within3 = (root, name) => root === "/" || root === name || name.startsWith(`${root}/`);
4151
+ var virtualRoots2 = ["/proc", "/dev", "/sys"];
3032
4152
  var managedTool = (name) => {
3033
- const resolved = realpathSync5(name);
4153
+ const resolved = realpathSync7(name);
3034
4154
  let current = resolved;
3035
4155
  for (; ; ) {
3036
- const info = statSync3(current);
4156
+ const info = statSync5(current);
3037
4157
  if (info.uid !== 0 || (info.mode & 18) !== 0)
3038
4158
  throw new Error("untrusted_sandbox_installation");
3039
4159
  if (current === resolved && (!info.isFile() || (info.mode & 73) === 0))
3040
4160
  throw new Error("sandbox_executable_unavailable");
3041
4161
  if (current === "/") return resolved;
3042
- current = path10.dirname(current);
4162
+ current = path12.dirname(current);
3043
4163
  }
3044
4164
  };
3045
4165
  var masksFor = (policy) => {
3046
4166
  const paths = /* @__PURE__ */ new Set();
3047
4167
  for (const item of [...policy.protectedPaths, "/run"]) {
3048
- if (!path10.isAbsolute(item) || item !== path10.normalize(item) || item === "/")
4168
+ if (!path12.isAbsolute(item) || item !== path12.normalize(item) || item === "/")
3049
4169
  throw new Error("invalid_protected_path");
3050
4170
  if (item === "/dev") continue;
3051
4171
  let resolved;
3052
4172
  try {
3053
- resolved = realpathSync5(item);
4173
+ resolved = realpathSync7(item);
3054
4174
  } catch (error) {
3055
4175
  if (error.code !== "ENOENT") throw error;
3056
4176
  resolved = item;
@@ -3061,34 +4181,34 @@ var masksFor = (policy) => {
3061
4181
  }
3062
4182
  const selected = [];
3063
4183
  for (const item of [...paths].sort((a, b) => a.length - b.length)) {
3064
- if (!selected.some((mask) => within2(mask, item))) selected.push(item);
4184
+ if (!selected.some((mask) => within3(mask, item))) selected.push(item);
3065
4185
  }
3066
4186
  return selected;
3067
4187
  };
3068
- var readOnlyMount = (entry, projectedHome) => {
4188
+ var readOnlyMount2 = (entry, projectedHome) => {
3069
4189
  try {
3070
- if (realpathSync5(entry) !== entry)
4190
+ if (realpathSync7(entry) !== entry)
3071
4191
  throw new Error("unbound_read_only_path");
3072
4192
  return entry;
3073
4193
  } catch (error) {
3074
- if (error.code !== "ENOENT" || !projectedHome || !within2(projectedHome, entry) || resolveReservedTarget(entry) !== entry)
4194
+ if (error.code !== "ENOENT" || !projectedHome || !within3(projectedHome, entry) || resolveReservedTarget(entry) !== entry)
3075
4195
  throw error;
3076
4196
  }
3077
- let parent = path10.dirname(entry);
3078
- while (within2(projectedHome, parent)) {
3079
- const info = lstatSync5(parent, { throwIfNoEntry: false });
4197
+ let parent = path12.dirname(entry);
4198
+ while (within3(projectedHome, parent)) {
4199
+ const info = lstatSync8(parent, { throwIfNoEntry: false });
3080
4200
  if (info) {
3081
- if (info.isDirectory() && realpathSync5(parent) === parent) return parent;
4201
+ if (info.isDirectory() && realpathSync7(parent) === parent) return parent;
3082
4202
  break;
3083
4203
  }
3084
4204
  if (parent === projectedHome) break;
3085
- parent = path10.dirname(parent);
4205
+ parent = path12.dirname(parent);
3086
4206
  }
3087
4207
  throw new Error("unbound_read_only_path");
3088
4208
  };
3089
4209
  var linuxRunscMountArgs = (policy, state, masks) => {
3090
4210
  const mountpoints = masks.map((target) => {
3091
- const info = statSync3(target, { throwIfNoEntry: false });
4211
+ const info = statSync5(target, { throwIfNoEntry: false });
3092
4212
  if (!info) throw new Error("missing_protected_mountpoint");
3093
4213
  if (!info.isDirectory() && !info.isFile())
3094
4214
  throw new Error("unsupported_protected_mountpoint");
@@ -3101,37 +4221,37 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3101
4221
  const home = policy.homeDotDirectory;
3102
4222
  const projectedHome = home && policy.writeRoots.includes(home) ? home : void 0;
3103
4223
  const protectedTargets = [...masks, ...readOnly];
3104
- const covered = (target) => protectedTargets.some((entry) => within2(entry, target));
4224
+ const covered = (target) => protectedTargets.some((entry) => within3(entry, target));
3105
4225
  const writableRoots = /* @__PURE__ */ new Set();
3106
4226
  const flags = ["--ro-bind", "/", "/", "--ro-bind", "/tmp", "/tmp"];
3107
4227
  for (const root of policy.writeRoots) {
3108
- if (home && root !== home && (within2(root, home) || resourceContainsPath(root, home)))
4228
+ if (home && root !== home && (within3(root, home) || resourceContainsPath(root, home)))
3109
4229
  throw new Error("unsupported_home_write_root");
3110
- if (root === "/" || realpathSync5(root) !== root || !statSync3(root).isDirectory() || virtualRoots.some((name) => within2(name, root)))
4230
+ if (root === "/" || realpathSync7(root) !== root || !statSync5(root).isDirectory() || virtualRoots2.some((name) => within3(name, root)))
3111
4231
  throw new Error("invalid_write_root");
3112
- if (within2(state, root)) continue;
3113
- if (masks.some((mask) => within2(mask, root)))
4232
+ if (within3(state, root)) continue;
4233
+ if (masks.some((mask) => within3(mask, root)))
3114
4234
  throw new Error("invalid_write_root");
3115
- if (readOnly.some((entry) => within2(entry, root))) continue;
4235
+ if (readOnly.some((entry) => within3(entry, root))) continue;
3116
4236
  if (root !== home) writableRoots.add(root);
3117
4237
  }
3118
4238
  if (projectedHome) {
3119
4239
  if (projectedHome !== "/tmp")
3120
4240
  flags.push("--ro-bind", projectedHome, projectedHome);
3121
- for (const name of readdirSync5(projectedHome)) {
3122
- const child = path10.join(projectedHome, name);
4241
+ for (const name of readdirSync7(projectedHome)) {
4242
+ const child = path12.join(projectedHome, name);
3123
4243
  if (child === state || isHomeDotTarget(projectedHome, child, "linux") || covered(child))
3124
4244
  continue;
3125
- const info = lstatSync5(child, { throwIfNoEntry: false });
3126
- if ((info?.isDirectory() || info?.isFile()) && realpathSync5(child) === child)
4245
+ const info = lstatSync8(child, { throwIfNoEntry: false });
4246
+ if ((info?.isDirectory() || info?.isFile()) && realpathSync7(child) === child)
3127
4247
  writableRoots.add(child);
3128
4248
  }
3129
4249
  }
3130
4250
  const readOnlyMounts = /* @__PURE__ */ new Set();
3131
4251
  const proposedRoots = [...writableRoots];
3132
4252
  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));
4253
+ if (!masks.some((mask) => within3(mask, entry)) && proposedRoots.some((root) => within3(root, entry)) && ![...readOnlyMounts].some((mount) => within3(mount, entry))) {
4254
+ readOnlyMounts.add(readOnlyMount2(entry, projectedHome));
3135
4255
  }
3136
4256
  }
3137
4257
  protectedTargets.push(...readOnlyMounts);
@@ -3141,19 +4261,19 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3141
4261
  const writeRoots = [...writableRoots];
3142
4262
  const anchors = /* @__PURE__ */ new Set();
3143
4263
  for (const entry of [...readOnlyMounts, ...masks]) {
3144
- let parent = path10.dirname(entry);
3145
- while (writeRoots.some((root) => root !== parent && within2(root, parent))) {
4264
+ let parent = path12.dirname(entry);
4265
+ while (writeRoots.some((root) => root !== parent && within3(root, parent))) {
3146
4266
  if (!writableRoots.has(parent) && !covered(parent)) anchors.add(parent);
3147
- parent = path10.dirname(parent);
4267
+ parent = path12.dirname(parent);
3148
4268
  }
3149
4269
  }
3150
4270
  for (const anchor of anchors) {
3151
- const info = statSync3(anchor, { throwIfNoEntry: false });
4271
+ const info = statSync5(anchor, { throwIfNoEntry: false });
3152
4272
  if (!info) {
3153
4273
  anchors.delete(anchor);
3154
4274
  continue;
3155
4275
  }
3156
- if (!info.isDirectory() || realpathSync5(anchor) !== anchor)
4276
+ if (!info.isDirectory() || realpathSync7(anchor) !== anchor)
3157
4277
  throw new Error("unbound_protected_ancestor");
3158
4278
  }
3159
4279
  for (const root of [...writeRoots, ...anchors].sort(
@@ -3161,7 +4281,7 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3161
4281
  ))
3162
4282
  flags.push("--bind", root, root);
3163
4283
  for (const entry of [...readOnlyMounts].sort((a, b) => a.length - b.length)) {
3164
- if (!writeRoots.some((root) => within2(root, entry))) continue;
4284
+ if (!writeRoots.some((root) => within3(root, entry))) continue;
3165
4285
  flags.push("--ro-bind", entry, entry);
3166
4286
  }
3167
4287
  for (const { target, placeholder } of mountpoints)
@@ -3170,7 +4290,7 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3170
4290
  return flags;
3171
4291
  };
3172
4292
  var prepare = (policy, state, runsc, unshare) => {
3173
- if (policy.profile === "full-access" || policy.profile === "investigation" && policy.writeRoots.length)
4293
+ if (policy.profile === "full-access" || policy.profile === "investigation" && policy.writeRoots.length || policy.gitWriteRoots?.length || policy.gitProtectedPaths?.length)
3174
4294
  throw new Error("unsupported_protection");
3175
4295
  const masks = masksFor(policy);
3176
4296
  if (findProtectedAliases(policy.protectedAliasPaths ?? policy.protectedPaths).size)
@@ -3178,7 +4298,9 @@ var prepare = (policy, state, runsc, unshare) => {
3178
4298
  const readOnly = policy.readOnlyPaths ?? [];
3179
4299
  if (policy.writeRoots.length && hasReadOnlyAliases(policy.readOnlyAliasPaths ?? readOnly))
3180
4300
  throw new Error("read_only_file_has_alias");
3181
- checkLinuxMountTopology(readFileSync3("/proc/self/mountinfo", "utf8"));
4301
+ if (policy.homeDotDirectory && policy.writeRoots.includes(policy.homeDotDirectory) && hasHomeDotHardLinkAliases(policy.homeDotDirectory))
4302
+ throw new Error("home_dot_file_has_alias");
4303
+ checkLinuxMountTopology(readFileSync5("/proc/self/mountinfo", "utf8"));
3182
4304
  return [
3183
4305
  "--pdeathsig",
3184
4306
  "KILL",
@@ -3207,9 +4329,11 @@ var prepare = (policy, state, runsc, unshare) => {
3207
4329
  "ALL",
3208
4330
  "--clearenv",
3209
4331
  ...linuxRunscMountArgs(policy, state, masks),
4332
+ // The login home stays read-only outside existing grants; caches and
4333
+ // temporary files use the private state directory.
3210
4334
  "--setenv",
3211
4335
  "HOME",
3212
- state,
4336
+ homedir2(),
3213
4337
  "--setenv",
3214
4338
  "TMPDIR",
3215
4339
  state,
@@ -3232,16 +4356,16 @@ var prepare = (policy, state, runsc, unshare) => {
3232
4356
  "--"
3233
4357
  ];
3234
4358
  };
3235
- var release = (root) => rmSync(root, { recursive: true, force: true });
4359
+ var release2 = (root) => rmSync2(root, { recursive: true, force: true });
3236
4360
  var allocate = () => {
3237
- const root = mkdtempSync("/tmp/codelia-runsc-");
4361
+ const root = mkdtempSync2("/tmp/codelia-runsc-");
3238
4362
  try {
3239
4363
  mkdirSync(`${root}/runsc`, { mode: 448 });
3240
4364
  mkdirSync(`${root}/empty-dir`, { mode: 320 });
3241
4365
  writeFileSync(`${root}/empty-file`, "", { flag: "wx", mode: 256 });
3242
4366
  return root;
3243
4367
  } catch (error) {
3244
- release(root);
4368
+ release2(root);
3245
4369
  throw error;
3246
4370
  }
3247
4371
  };
@@ -3264,10 +4388,10 @@ var LinuxRunscBackend = class {
3264
4388
  for (const candidate of ["/usr/local/bin/runsc", "/usr/bin/runsc"]) {
3265
4389
  try {
3266
4390
  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));
4391
+ const sidecars = path12.join(path12.dirname(runsc), "gvisor-bin");
4392
+ accessSync3(path12.join(sidecars, "gvisor_sentry"), constants5.X_OK);
4393
+ for (const executable of readdirSync7(sidecars)) {
4394
+ managedTool(path12.join(sidecars, executable));
3271
4395
  }
3272
4396
  this.tools = { setpriv, unshare, runsc };
3273
4397
  return this.tools;
@@ -3294,7 +4418,7 @@ var LinuxRunscBackend = class {
3294
4418
  }
3295
4419
  state = allocate();
3296
4420
  const args = prepare(policy, state, launcher.runsc, launcher.unshare);
3297
- const probe = spawnSync(launcher.setpriv, [...args, "/usr/bin/true"], {
4421
+ const probe = spawnSync2(launcher.setpriv, [...args, "/usr/bin/true"], {
3298
4422
  env: { PATH: "/usr/bin:/bin" },
3299
4423
  stdio: "ignore",
3300
4424
  timeout: 8e3,
@@ -3307,7 +4431,7 @@ var LinuxRunscBackend = class {
3307
4431
  } catch {
3308
4432
  return false;
3309
4433
  } finally {
3310
- if (state) release(state);
4434
+ if (state) release2(state);
3311
4435
  }
3312
4436
  }
3313
4437
  supportsLaunchBinding(candidate) {
@@ -3320,11 +4444,11 @@ var LinuxRunscBackend = class {
3320
4444
  launch(invocation, policy) {
3321
4445
  if (!this.supports(policy)) throw new Error("sandbox_unavailable");
3322
4446
  const state = allocate();
3323
- const cleanup = () => release(state);
4447
+ const cleanup = () => release2(state);
3324
4448
  try {
3325
4449
  const tools = this.resolveTools();
3326
4450
  const args = prepare(policy, state, tools.runsc, tools.unshare);
3327
- const child = spawn2(
4451
+ const child = spawn3(
3328
4452
  tools.setpriv,
3329
4453
  [...args, invocation.executable, ...shellInvocationArgs(invocation)],
3330
4454
  {
@@ -3343,194 +4467,21 @@ var LinuxRunscBackend = class {
3343
4467
  }
3344
4468
  };
3345
4469
 
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
4470
  // src/permissions/system-bash.ts
3520
4471
  import {
3521
- accessSync as accessSync3,
3522
- constants as constants5,
3523
- lstatSync as lstatSync7,
3524
- readlinkSync as readlinkSync4
4472
+ accessSync as accessSync4,
4473
+ constants as constants6,
4474
+ lstatSync as lstatSync9,
4475
+ readlinkSync as readlinkSync5
3525
4476
  } from "fs";
3526
4477
  import { posix } from "path";
3527
4478
  var conventional = ["/bin/bash", "/usr/bin/bash"];
3528
4479
  var nixSystemBash = "/run/current-system/sw/bin/bash";
3529
4480
  var nixStoreBash = /^\/nix\/store\/[^/]+\/bin\/bash$/u;
3530
4481
  var hostEntries = {
3531
- stat: (name) => lstatSync7(name, { throwIfNoEntry: false }),
3532
- readLink: readlinkSync4,
3533
- canExecute: (name) => accessSync3(name, constants5.X_OK)
4482
+ stat: (name) => lstatSync9(name, { throwIfNoEntry: false }),
4483
+ readLink: readlinkSync5,
4484
+ canExecute: (name) => accessSync4(name, constants6.X_OK)
3534
4485
  };
3535
4486
  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
4487
  // cannot replace the existing root-owned links and outputs we use.
@@ -3577,23 +4528,23 @@ var resolveSystemBash = (platform = process.platform, entries = hostEntries) =>
3577
4528
  };
3578
4529
 
3579
4530
  // 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";
4531
+ import { lstatSync as lstatSync10, opendirSync as opendirSync2, readlinkSync as readlinkSync6, realpathSync as realpathSync8 } from "fs";
4532
+ import path13 from "path";
3582
4533
  import { resolveStoragePaths as resolveStoragePaths2 } from "@codelia/storage";
3583
4534
  var confinedAutoLaunchDirectoryName = "confined-auto-launch";
3584
- var isWorkspaceConfigName = (root, target) => resourceContainsPath(path12.dirname(resolveProjectConfigPath(root)), target);
4535
+ var isWorkspaceConfigName = (root, target) => resourceContainsPath(path13.dirname(resolveProjectConfigPath(root)), target);
3585
4536
  var missing2 = (error) => error.code === "ENOENT";
3586
4537
  function resolveConfigTarget(target, remaining = 64) {
3587
4538
  if (!remaining) throw new Error("workspace_config_path_unresolved");
3588
4539
  try {
3589
- return realpathSync7(target);
4540
+ return realpathSync8(target);
3590
4541
  } catch (error) {
3591
- const parent = path12.dirname(target);
4542
+ const parent = path13.dirname(target);
3592
4543
  if (!missing2(error) || parent === target) throw error;
3593
4544
  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);
4545
+ if (!lstatSync10(target, { throwIfNoEntry: false })?.isSymbolicLink())
4546
+ return path13.join(canonicalParent, path13.basename(target));
4547
+ const referent = readlinkSync6(target);
3597
4548
  let seenName = false;
3598
4549
  for (const part of referent.split(
3599
4550
  process.platform === "win32" ? /[\\/]/u : "/"
@@ -3603,14 +4554,14 @@ function resolveConfigTarget(target, remaining = 64) {
3603
4554
  if (part && part !== "." && part !== "..") seenName = true;
3604
4555
  }
3605
4556
  return resolveConfigTarget(
3606
- path12.resolve(canonicalParent, referent),
4557
+ path13.resolve(canonicalParent, referent),
3607
4558
  remaining - 1
3608
4559
  );
3609
4560
  }
3610
4561
  }
3611
4562
  var workspaceConfigProtection = (root) => {
3612
4563
  const config = resolveProjectConfigPath(root);
3613
- const directory = path12.dirname(config);
4564
+ const directory = path13.dirname(config);
3614
4565
  const readOnlyPaths = /* @__PURE__ */ new Set([directory]);
3615
4566
  const readOnlyAliasPaths = /* @__PURE__ */ new Set();
3616
4567
  const reserveTarget = (file) => {
@@ -3618,12 +4569,12 @@ var workspaceConfigProtection = (root) => {
3618
4569
  readOnlyPaths.add(target);
3619
4570
  readOnlyAliasPaths.add(target);
3620
4571
  };
3621
- if (lstatSync8(directory, { throwIfNoEntry: false })) {
4572
+ if (lstatSync10(directory, { throwIfNoEntry: false })) {
3622
4573
  const canonical = resolveConfigTarget(directory);
3623
4574
  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);
4575
+ if (lstatSync10(canonical, { throwIfNoEntry: false })?.isDirectory()) {
4576
+ const file = path13.join(canonical, path13.basename(config));
4577
+ if (lstatSync10(file, { throwIfNoEntry: false })) reserveTarget(file);
3627
4578
  const storage = resolveStoragePaths2();
3628
4579
  const globalStorage = [
3629
4580
  resolveStoragePaths2({ layout: "home" }).root,
@@ -3631,24 +4582,24 @@ var workspaceConfigProtection = (root) => {
3631
4582
  storage.configDir
3632
4583
  ].some((entry) => {
3633
4584
  try {
3634
- return realpathSync7(entry) === canonical;
4585
+ return realpathSync8(entry) === canonical;
3635
4586
  } catch (error) {
3636
4587
  if (!missing2(error)) throw error;
3637
4588
  return false;
3638
4589
  }
3639
4590
  });
3640
4591
  if (!globalStorage) {
3641
- const worktrees = path12.join(canonical, "worktrees");
4592
+ const worktrees = path13.join(canonical, "worktrees");
3642
4593
  const pending = [canonical];
3643
4594
  for (const current of pending) {
3644
4595
  const children = opendirSync2(current);
3645
4596
  try {
3646
4597
  for (let entry = children.readSync(); entry; entry = children.readSync()) {
3647
- const target = path12.join(current, entry.name);
4598
+ const target = path13.join(current, entry.name);
3648
4599
  if (target === file || target === worktrees) continue;
3649
4600
  if (entry.isSymbolicLink()) reserveTarget(target);
3650
4601
  else if (entry.isDirectory()) pending.push(target);
3651
- else if (entry.isFile() && (lstatSync8(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
4602
+ else if (entry.isFile() && (lstatSync10(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
3652
4603
  readOnlyAliasPaths.add(target);
3653
4604
  }
3654
4605
  } finally {
@@ -3686,11 +4637,11 @@ var platformShellSource = (source) => {
3686
4637
  return fixedBash(source, executable);
3687
4638
  }
3688
4639
  const systemRoot = process.env.SystemRoot;
3689
- if (!systemRoot || !path13.isAbsolute(systemRoot))
4640
+ if (!systemRoot || !path14.isAbsolute(systemRoot))
3690
4641
  throw new Error("windows_system_directory_unavailable");
3691
4642
  return Object.freeze({
3692
4643
  kind: "source",
3693
- executable: path13.join(
4644
+ executable: path14.join(
3694
4645
  systemRoot,
3695
4646
  "System32",
3696
4647
  "WindowsPowerShell",
@@ -3709,27 +4660,27 @@ var platformShellSource = (source) => {
3709
4660
  };
3710
4661
  var realOrLexical = (value) => {
3711
4662
  try {
3712
- return realpathSync8(value);
4663
+ return realpathSync9(value);
3713
4664
  } catch {
3714
- return path13.resolve(value);
4665
+ return path14.resolve(value);
3715
4666
  }
3716
4667
  };
3717
4668
  var resolvePolicyPath = (target) => {
3718
- const absolute = path13.resolve(target);
4669
+ const absolute = path14.resolve(target);
3719
4670
  try {
3720
- return realpathSync8(absolute);
4671
+ return realpathSync9(absolute);
3721
4672
  } catch (error) {
3722
- const parent = path13.dirname(absolute);
4673
+ const parent = path14.dirname(absolute);
3723
4674
  if (error.code !== "ENOENT" || parent === absolute)
3724
4675
  throw error;
3725
- if (lstatSync9(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
4676
+ if (lstatSync11(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
3726
4677
  throw error;
3727
- return path13.join(resolvePolicyPath(parent), path13.basename(absolute));
4678
+ return path14.join(resolvePolicyPath(parent), path14.basename(absolute));
3728
4679
  }
3729
4680
  };
3730
4681
  var canonicalPolicyPaths = (paths) => Object.freeze([
3731
4682
  ...new Set(
3732
- paths.flatMap((entry) => [path13.resolve(entry), resolvePolicyPath(entry)])
4683
+ paths.flatMap((entry) => [path14.resolve(entry), resolvePolicyPath(entry)])
3733
4684
  )
3734
4685
  ]);
3735
4686
  var runtimeReadOnlyPaths = () => {
@@ -3749,12 +4700,12 @@ var runtimeProtectedCredentialPaths = () => {
3749
4700
  mkdirSync2(storage.credentialsDir, { recursive: true, mode: 448 });
3750
4701
  targets.push(storage.credentialsDir);
3751
4702
  } catch {
3752
- if (lstatSync9(storage.credentialsDir, { throwIfNoEntry: false })) {
4703
+ if (lstatSync11(storage.credentialsDir, { throwIfNoEntry: false })) {
3753
4704
  targets.push(storage.credentialsDir);
3754
4705
  }
3755
4706
  }
3756
4707
  for (const legacy of [storage.legacyAuthFile, storage.legacyMcpAuthFile]) {
3757
- if (lstatSync9(legacy, { throwIfNoEntry: false })) {
4708
+ if (lstatSync11(legacy, { throwIfNoEntry: false })) {
3758
4709
  targets.push(legacy);
3759
4710
  }
3760
4711
  }
@@ -3770,8 +4721,8 @@ var runtimeProtectedCredentialPaths = () => {
3770
4721
  var runtimeAuthorityAliasPaths = () => {
3771
4722
  const storage = resolveStoragePaths3();
3772
4723
  const databasePaths = [
3773
- path13.join(storage.configDir, ".projects-policy-lock.sqlite"),
3774
- path13.join(storage.sessionsDir, "state.db")
4724
+ path14.join(storage.configDir, ".projects-policy-lock.sqlite"),
4725
+ path14.join(storage.sessionsDir, "state.db")
3775
4726
  ];
3776
4727
  return canonicalPolicyPaths([
3777
4728
  resolveConfigPath(),
@@ -3781,15 +4732,22 @@ var runtimeAuthorityAliasPaths = () => {
3781
4732
  "launch-approvals",
3782
4733
  "auto-review.json",
3783
4734
  confinedAutoLaunchDirectoryName
3784
- ].map((entry) => path13.join(storage.configDir, entry)),
4735
+ ].map((entry) => path14.join(storage.configDir, entry)),
3785
4736
  ...databasePaths.flatMap(
3786
4737
  (file) => ["", "-wal", "-shm", "-journal"].map((suffix) => `${file}${suffix}`)
3787
4738
  )
3788
4739
  ]);
3789
4740
  };
3790
4741
  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);
4742
+ const discover = allowSharedGitObjects && sandboxMode === "workspace-write" && !homeScope.gitWrites ? gitMetadataWithObjectDirectories : gitMetadataPaths;
4743
+ const metadata = discover(root, ...relatedDirectories);
4744
+ const { reservedMarkers, objectDirectories, hookAliases } = metadata;
4745
+ const gitScope = homeScope.gitWrites ? gitWriteScope(metadata.repositories) : void 0;
4746
+ const released = new Set(gitScope?.releasedPaths ?? []);
4747
+ const readOnlyPaths = gitScope ? [
4748
+ ...metadata.readOnlyPaths.filter((entry) => !released.has(entry)),
4749
+ ...gitScope.readOnlyPaths
4750
+ ] : metadata.readOnlyPaths;
3793
4751
  const protectedPaths = canonicalPolicyPaths([
3794
4752
  ...extraProtectedPaths,
3795
4753
  ...runtimeProtectedCredentialPaths()
@@ -3815,14 +4773,23 @@ var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectorie
3815
4773
  const objectDirectoriesWithSharedFiles = objectDirectories.filter(
3816
4774
  (directory) => {
3817
4775
  const overlaps = (other) => resourceContainsPath(other, directory.path) || resourceContainsPath(directory.path, other);
3818
- const commonDirectory = path13.dirname(directory.path);
4776
+ const commonDirectory = path14.dirname(directory.path);
3819
4777
  return !strongerPaths.some(overlaps) && !readOnlyPaths.some(
3820
4778
  (other) => overlaps(other) && realOrLexical(other) !== commonDirectory
3821
4779
  );
3822
4780
  }
3823
4781
  );
4782
+ const gitWriteRoots = (gitScope?.writeRoots ?? []).filter(
4783
+ (directory) => directory !== path14.parse(directory).root && !(homeScope.writeRoots ?? []).some((root2) => isWithin(root2, directory)) && !strongerPaths.some(
4784
+ (entry) => isWithin(entry, directory) || isWithin(directory, entry)
4785
+ )
4786
+ );
3824
4787
  return {
3825
4788
  ...protectedHome ? { homeDotDirectory: protectedHome } : {},
4789
+ ...gitScope && gitScope.releasedPaths.length > 0 ? {
4790
+ ...gitWriteRoots.length ? { gitWriteRoots } : {},
4791
+ gitProtectedPaths: gitScope.readOnlyPaths
4792
+ } : {},
3826
4793
  protectedPaths,
3827
4794
  protectedAliasPaths: protectedPaths,
3828
4795
  readOnlyPaths: Object.freeze(
@@ -3859,26 +4826,48 @@ var protectedSeatbeltAncestors = (base) => {
3859
4826
  ...base.readOnlyPaths ?? [],
3860
4827
  ...base.homeDotDirectory ? [base.homeDotDirectory] : []
3861
4828
  ]) {
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)))
4829
+ for (let child = protectedPath, parent = path14.dirname(child); parent !== child; child = parent, parent = path14.dirname(child)) {
4830
+ if ([...base.writeRoots, ...base.gitWriteRoots ?? []].some(
4831
+ (root) => isWithin(root, parent)
4832
+ ))
4833
+ parents.add(parent);
4834
+ }
4835
+ }
4836
+ return [...parents];
4837
+ };
4838
+ var absentProtectedSeatbeltAncestors = (base) => {
4839
+ const gitProtected = base.gitProtectedPaths ?? [];
4840
+ if (!gitProtected.length) return [];
4841
+ const writableRoots = [...base.writeRoots, ...base.gitWriteRoots ?? []];
4842
+ const parents = /* @__PURE__ */ new Set();
4843
+ for (const protectedPath of gitProtected) {
4844
+ for (let child = protectedPath, parent = path14.dirname(child); parent !== child; child = parent, parent = path14.dirname(child)) {
4845
+ if (writableRoots.some((root) => isWithin(root, parent)) && !lstatSync11(parent, { throwIfNoEntry: false }))
3864
4846
  parents.add(parent);
3865
4847
  }
3866
4848
  }
3867
4849
  return [...parents];
3868
4850
  };
3869
4851
  var literal = (entry) => `(literal ${sbplString(entry)})`;
4852
+ var pseudoTerminalRules = `(allow pseudo-tty)
4853
+ (allow file-read* file-write* file-ioctl (literal "/dev/ptmx"))
4854
+ (allow file-read* file-write*
4855
+ (require-all (regex #"^/dev/ttys[0-9]+$") (extension "com.apple.sandbox.pty")))
4856
+ (allow file-ioctl (regex #"^/dev/ttys[0-9]+$"))`;
3870
4857
  var seatbeltProfile = (base, scratch, mutation) => {
3871
4858
  const deviceAndIpcPaths = ["/dev", "/private/var/run"];
3872
- const ancestors = protectedSeatbeltAncestors({
4859
+ const ancestorList = protectedSeatbeltAncestors({
3873
4860
  ...base,
3874
4861
  protectedPaths: [...base.protectedPaths, ...deviceAndIpcPaths]
3875
- }).map(literal).join(" ");
4862
+ });
4863
+ const ancestors = ancestorList.map(literal).join(" ");
4864
+ const absentAncestors = absentProtectedSeatbeltAncestors(base).map(literal).join(" ");
3876
4865
  const home = base.homeDotDirectory;
3877
- const homeRule = home ? `(deny file-write* (prefix ${sbplString(`${path13.join(home, "/")}.`)}) ${subpaths([path13.join(home, "Library")])})` : "";
4866
+ const homeRule = home ? `(deny file-write* (prefix ${sbplString(`${path14.join(home, "/")}.`)}) ${subpaths([path14.join(home, "Library")])})` : "";
3878
4867
  const approvedHomeDotRoots = !mutation && home ? base.writeRoots.filter(
3879
4868
  (root) => root !== home && isHomeDotTarget(home, root)
3880
4869
  ) : [];
3881
- const writeTrees = mutation ? [scratch] : [scratch, ...base.writeRoots];
4870
+ const writeTrees = mutation ? [scratch] : [scratch, ...base.writeRoots, ...base.gitWriteRoots ?? []];
3882
4871
  const fixedWriteRules = mutation && [
3883
4872
  mutation.directories.length ? `(allow file-write-create ${mutation.directories.map(literal).join(" ")})` : "",
3884
4873
  mutation.destination ? `(allow file-write-create file-write-data file-write-mode ${literal(mutation.destination)})` : "",
@@ -3898,17 +4887,19 @@ ${fixedWriteRules ?? ""}
3898
4887
  (allow file-read* (literal "/dev/null") (literal "/dev/zero")
3899
4888
  (literal "/dev/random") (literal "/dev/urandom"))
3900
4889
  (allow file-write-data (literal "/dev/null"))
4890
+ ${mutation ? "" : pseudoTerminalRules}
3901
4891
  ${homeRule}
3902
4892
  ${approvedHomeDotRoots.length ? `(allow file-write* ${subpaths(approvedHomeDotRoots)})` : ""}
3903
4893
  ${base.protectedPaths.length ? `(deny file-read* file-write* ${subpaths(base.protectedPaths)})` : ""}
3904
4894
  ${base.readOnlyPaths?.length ? `(deny file-write* ${subpaths(base.readOnlyPaths)})` : ""}
3905
4895
  ${ancestors ? `(deny file-write-unlink ${ancestors})` : ""}
4896
+ ${absentAncestors ? `(deny file-write-create ${absentAncestors})` : ""}
3906
4897
  (deny network*)
3907
4898
  (deny file-write-setugid)
3908
4899
  `;
3909
4900
  };
3910
4901
  var sandboxExec = "/usr/bin/sandbox-exec";
3911
- var macAdditionalWriteLauncherPaths = (protection) => {
4902
+ var mxcAdditionalWriteLauncherPaths = (protection) => {
3912
4903
  const baseline = resolveMxcLauncher({
3913
4904
  ...protection,
3914
4905
  writeRoots: [protection.root],
@@ -3916,11 +4907,12 @@ var macAdditionalWriteLauncherPaths = (protection) => {
3916
4907
  });
3917
4908
  const selected = resolveMxcLauncher(protection);
3918
4909
  return [
3919
- ...new Set(
3920
- [baseline, selected].flatMap(
4910
+ .../* @__PURE__ */ new Set([
4911
+ ...[baseline, selected].flatMap(
3921
4912
  (launcher) => launcher ? [launcher.candidate, launcher.file] : []
3922
- )
3923
- )
4913
+ ),
4914
+ ...linuxMxcManagedToolPaths()
4915
+ ])
3924
4916
  ];
3925
4917
  };
3926
4918
  var MacSeatbeltBackend = class {
@@ -3930,6 +4922,7 @@ var MacSeatbeltBackend = class {
3930
4922
  launcher;
3931
4923
  supportsReadOnlyPaths = true;
3932
4924
  supportsHomeDotProtection = true;
4925
+ supportsAbsentPathDenial = true;
3933
4926
  supportsCommandBinding = true;
3934
4927
  available;
3935
4928
  mxcProbe;
@@ -3946,7 +4939,7 @@ var MacSeatbeltBackend = class {
3946
4939
  return false;
3947
4940
  try {
3948
4941
  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(
4942
+ (entry) => entry !== void 0 && (!path14.isAbsolute(entry) || path14.normalize(entry) !== entry || !protection.writeRoots.some(
3950
4943
  (root) => entry !== root && isWithin(root, entry)
3951
4944
  ))
3952
4945
  )))
@@ -4031,12 +5024,12 @@ var MacSeatbeltBackend = class {
4031
5024
  launchWithPolicy(invocation, protection, mutation) {
4032
5025
  if (!(mutation ? this.supportsPolicy(protection, mutation) : this.supports(protection)))
4033
5026
  throw new Error("sandbox_unavailable");
4034
- const scratch = realpathSync8(
4035
- mkdtempSync2(path13.join(os2.tmpdir(), "codelia-shell-"))
5027
+ const scratch = realpathSync9(
5028
+ mkdtempSync3(path14.join(os3.tmpdir(), "codelia-shell-"))
4036
5029
  );
4037
5030
  const cleanup = () => {
4038
5031
  try {
4039
- rmSync2(scratch, { recursive: true, force: true });
5032
+ rmSync3(scratch, { recursive: true, force: true });
4040
5033
  } catch {
4041
5034
  }
4042
5035
  };
@@ -4056,6 +5049,7 @@ var MacSeatbeltBackend = class {
4056
5049
  profile,
4057
5050
  scratch,
4058
5051
  path: shellPathForLaunch(protection.binPaths),
5052
+ home: os3.homedir(),
4059
5053
  cargo_home: protection.toolchainHomes?.CARGO_HOME,
4060
5054
  rustup_home: protection.toolchainHomes?.RUSTUP_HOME
4061
5055
  },
@@ -4072,7 +5066,7 @@ var MacSeatbeltBackend = class {
4072
5066
  env: {
4073
5067
  PATH: shellPathForLaunch(protection.binPaths),
4074
5068
  LANG: "C",
4075
- HOME: scratch,
5069
+ HOME: os3.homedir(),
4076
5070
  TMPDIR: scratch,
4077
5071
  XDG_CACHE_HOME: scratch,
4078
5072
  GIT_OPTIONAL_LOCKS: "0",
@@ -4095,6 +5089,39 @@ var MacSeatbeltBackend = class {
4095
5089
  }
4096
5090
  };
4097
5091
  var createMacMxcShellBackend = () => new MacSeatbeltBackend("mxc");
5092
+ var createLinuxMxcShellBackend = () => new LinuxMxcBackend();
5093
+ var SCRUBBED_LOGIN_ENV_KEYS = /* @__PURE__ */ new Set([
5094
+ "BASH_ENV",
5095
+ "ENV",
5096
+ "SHELLOPTS",
5097
+ "BASHOPTS",
5098
+ "PS4",
5099
+ "PROMPT_COMMAND",
5100
+ "CDPATH",
5101
+ "GLOBIGNORE",
5102
+ "FPATH",
5103
+ "ZDOTDIR",
5104
+ "IFS",
5105
+ "NODE_OPTIONS",
5106
+ "PYTHONSTARTUP",
5107
+ "PERL5OPT",
5108
+ "RUBYOPT",
5109
+ "LD_PRELOAD",
5110
+ "LD_LIBRARY_PATH",
5111
+ "DYLD_INSERT_LIBRARIES",
5112
+ "DYLD_LIBRARY_PATH",
5113
+ "DYLD_FRAMEWORK_PATH"
5114
+ ]);
5115
+ var loginUserEnvironment = (sourceEnv = process.env) => {
5116
+ const env = {};
5117
+ for (const [key, value] of Object.entries(sourceEnv)) {
5118
+ if (value === void 0) continue;
5119
+ if (SCRUBBED_LOGIN_ENV_KEYS.has(key) || key.startsWith("BASH_FUNC_") || key.startsWith("LD_") || key.startsWith("DYLD_"))
5120
+ continue;
5121
+ env[key] = value;
5122
+ }
5123
+ return env;
5124
+ };
4098
5125
  var UserShellBackend = class {
4099
5126
  supportsCommandBinding = true;
4100
5127
  supports(protection) {
@@ -4108,16 +5135,17 @@ var UserShellBackend = class {
4108
5135
  shell: false,
4109
5136
  windowsHide: true,
4110
5137
  env: {
5138
+ ...loginUserEnvironment(),
4111
5139
  PATH: shellPathForLaunch(protection.binPaths),
4112
- HOME: os2.homedir(),
4113
- TMPDIR: os2.tmpdir(),
5140
+ HOME: os3.homedir(),
5141
+ TMPDIR: os3.tmpdir(),
4114
5142
  LANG: "C",
4115
5143
  ...protection.toolchainHomes,
4116
5144
  ...process.platform === "win32" && {
4117
5145
  SystemRoot: process.env.SystemRoot,
4118
- USERPROFILE: os2.homedir(),
4119
- TEMP: os2.tmpdir(),
4120
- TMP: os2.tmpdir()
5146
+ USERPROFILE: os3.homedir(),
5147
+ TEMP: os3.tmpdir(),
5148
+ TMP: os3.tmpdir()
4121
5149
  }
4122
5150
  },
4123
5151
  stdio: [protection.stdin === "pipe" ? "pipe" : "ignore", "pipe", "pipe"]
@@ -4126,18 +5154,24 @@ var UserShellBackend = class {
4126
5154
  };
4127
5155
  var standardMacBackend;
4128
5156
  var explicitMacMxcBackend;
4129
- var standardLinuxBackend;
5157
+ var standardLinuxMxcBackend;
5158
+ var fallbackLinuxRunscBackend;
4130
5159
  var selectProtectedShellBackend = ({
4131
5160
  platform = process.platform,
4132
5161
  allowStandard,
4133
5162
  adapter,
4134
- macBackend = "seatbelt"
5163
+ macBackend = "seatbelt",
5164
+ linuxBackend = "mxc"
4135
5165
  }) => {
4136
5166
  if (adapter) return adapter;
4137
5167
  if (!allowStandard) return void 0;
4138
5168
  if (platform === "linux") {
4139
- standardLinuxBackend ??= new LinuxRunscBackend();
4140
- return standardLinuxBackend;
5169
+ if (linuxBackend === "gvisor") {
5170
+ fallbackLinuxRunscBackend ??= new LinuxRunscBackend();
5171
+ return fallbackLinuxRunscBackend;
5172
+ }
5173
+ standardLinuxMxcBackend ??= new LinuxMxcBackend();
5174
+ return standardLinuxMxcBackend;
4141
5175
  }
4142
5176
  if (platform === "darwin") {
4143
5177
  if (macBackend === "mxc") {
@@ -4150,7 +5184,7 @@ var selectProtectedShellBackend = ({
4150
5184
  return void 0;
4151
5185
  };
4152
5186
  var directoryIdentity = (directory) => {
4153
- const stat = statSync5(directory, { bigint: true });
5187
+ const stat = statSync6(directory, { bigint: true });
4154
5188
  if (!stat.isDirectory()) throw new Error("invalid_working_directory");
4155
5189
  return `${stat.dev}:${stat.ino}`;
4156
5190
  };
@@ -5088,10 +6122,10 @@ var createRuntimeModel = async ({
5088
6122
 
5089
6123
  // src/runtime-state.ts
5090
6124
  import crypto from "crypto";
5091
- import { realpathSync as realpathSync9 } from "fs";
6125
+ import { realpathSync as realpathSync10 } from "fs";
5092
6126
 
5093
6127
  // src/environment.ts
5094
- import path14 from "path";
6128
+ import path15 from "path";
5095
6129
  import {
5096
6130
  parseSandboxMode
5097
6131
  } from "@codelia/shared-types";
@@ -5104,7 +6138,7 @@ var cloneContract = (contract) => ({
5104
6138
  persistence: { ...contract.persistence },
5105
6139
  events: { ...contract.events }
5106
6140
  });
5107
- var defaultWorkspaceRoot = () => process.env.CODELIA_SANDBOX_ROOT ? path14.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
6141
+ var defaultWorkspaceRoot = () => process.env.CODELIA_SANDBOX_ROOT ? path15.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
5108
6142
  var runtimeEnvironmentPresets = {
5109
6143
  "tui-local": {
5110
6144
  workspace: {
@@ -5229,11 +6263,11 @@ var resolveRuntimeEnvironment = (options = {}) => {
5229
6263
  if (contract.workspace.sandboxMode !== void 0 && !parseSandboxMode(contract.workspace.sandboxMode))
5230
6264
  throw new Error("Invalid workspace.sandboxMode");
5231
6265
  if (contract.workspace.filesystem === "enabled" || contract.workspace.process === "runtime") {
5232
- contract.workspace.root = path14.resolve(
6266
+ contract.workspace.root = path15.resolve(
5233
6267
  contract.workspace.root ?? defaultWorkspaceRoot()
5234
6268
  );
5235
6269
  } else if (contract.workspace.root) {
5236
- contract.workspace.root = path14.resolve(contract.workspace.root);
6270
+ contract.workspace.root = path15.resolve(contract.workspace.root);
5237
6271
  }
5238
6272
  rejectContract(
5239
6273
  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"),
@@ -5473,7 +6507,7 @@ var RuntimeState = class {
5473
6507
  if (scope === "workspace") {
5474
6508
  const root = this.runtimeSandboxRoot ?? this.runtimeWorkingDir;
5475
6509
  return JSON.stringify([
5476
- root === null ? null : realpathSync9(root),
6510
+ root === null ? null : realpathSync10(root),
5477
6511
  this.sandboxMode.value,
5478
6512
  connection,
5479
6513
  authority
@@ -5783,7 +6817,7 @@ var RuntimeState = class {
5783
6817
  };
5784
6818
 
5785
6819
  // src/subagents/bootstrap.ts
5786
- import path15 from "path";
6820
+ import path16 from "path";
5787
6821
  import { sandboxModes } from "@codelia/shared-types";
5788
6822
  import { z as z3 } from "zod";
5789
6823
 
@@ -5857,8 +6891,8 @@ var subagentBootstrapSchema = z3.object({
5857
6891
  version: z3.literal(1),
5858
6892
  task_id: z3.string().uuid(),
5859
6893
  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(),
6894
+ workspace_root: z3.string().refine(path16.isAbsolute),
6895
+ protected_paths: z3.array(z3.string().refine(path16.isAbsolute)).optional(),
5862
6896
  lineage: z3.object({
5863
6897
  name: subagentNameSchema.optional(),
5864
6898
  tree_id: z3.string().min(1),
@@ -6780,19 +7814,19 @@ var redactSubagentJson = (value, secrets = []) => JSON.parse(
6780
7814
 
6781
7815
  // src/subagents/read-tools.ts
6782
7816
  import { promises as fs6 } from "fs";
6783
- import path18 from "path";
7817
+ import path19 from "path";
6784
7818
  import { defineTool } from "@codelia/core";
6785
7819
  import { z as z5 } from "zod";
6786
7820
 
6787
7821
  // src/sandbox/context.ts
6788
7822
  import crypto3 from "crypto";
6789
7823
  import {
6790
- constants as constants6,
7824
+ constants as constants7,
6791
7825
  promises as fs4,
6792
- lstatSync as lstatSync10,
6793
- realpathSync as realpathSync10
7826
+ lstatSync as lstatSync12,
7827
+ realpathSync as realpathSync11
6794
7828
  } from "fs";
6795
- import path16 from "path";
7829
+ import path17 from "path";
6796
7830
  var SecurityError = class extends Error {
6797
7831
  constructor(message) {
6798
7832
  super(message);
@@ -6802,22 +7836,22 @@ var SecurityError = class extends Error {
6802
7836
  var identity = (info) => `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
6803
7837
  var directoryIdentity2 = (stat) => `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
6804
7838
  var selectMissingFile = (entry) => {
6805
- let parent = path16.dirname(entry.target);
7839
+ let parent = path17.dirname(entry.target);
6806
7840
  for (; ; ) {
6807
7841
  try {
6808
- const stat = lstatSync10(parent, { bigint: true });
6809
- if (!stat.isDirectory() || realpathSync10(parent) !== parent)
7842
+ const stat = lstatSync12(parent, { bigint: true });
7843
+ if (!stat.isDirectory() || realpathSync11(parent) !== parent)
6810
7844
  throw new SecurityError("Expected a canonical parent directory");
6811
7845
  return Object.freeze({
6812
7846
  ...entry,
6813
7847
  identity: null,
6814
7848
  parent,
6815
7849
  parentIdentity: directoryIdentity2(stat),
6816
- tail: path16.relative(parent, entry.target)
7850
+ tail: path17.relative(parent, entry.target)
6817
7851
  });
6818
7852
  } catch (error) {
6819
7853
  if (error.code !== "ENOENT") throw error;
6820
- const ancestor = path16.dirname(parent);
7854
+ const ancestor = path17.dirname(parent);
6821
7855
  if (ancestor === parent) throw error;
6822
7856
  parent = ancestor;
6823
7857
  }
@@ -6825,15 +7859,15 @@ var selectMissingFile = (entry) => {
6825
7859
  };
6826
7860
  var missingDestinationCurrent = (selection) => {
6827
7861
  try {
6828
- const segments = selection.tail.split(path16.sep);
7862
+ const segments = selection.tail.split(path17.sep);
6829
7863
  if (segments.some(
6830
7864
  (segment) => !segment || segment === "." || segment === ".."
6831
- ) || path16.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
7865
+ ) || path17.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
6832
7866
  return false;
6833
7867
  let current = selection.parent;
6834
7868
  for (const [index, segment] of segments.entries()) {
6835
- current = path16.join(current, segment);
6836
- const stat = lstatSync10(current);
7869
+ current = path17.join(current, segment);
7870
+ const stat = lstatSync12(current);
6837
7871
  if (index === segments.length - 1 || !stat.isDirectory()) return false;
6838
7872
  }
6839
7873
  return false;
@@ -6843,8 +7877,8 @@ var missingDestinationCurrent = (selection) => {
6843
7877
  };
6844
7878
  var directoryBindingCurrent = (selection) => {
6845
7879
  try {
6846
- const stat = lstatSync10(selection.parent, { bigint: true });
6847
- return stat.isDirectory() && directoryIdentity2(stat) === selection.parentIdentity && realpathSync10(selection.parent) === selection.parent;
7880
+ const stat = lstatSync12(selection.parent, { bigint: true });
7881
+ return stat.isDirectory() && directoryIdentity2(stat) === selection.parentIdentity && realpathSync11(selection.parent) === selection.parent;
6848
7882
  } catch {
6849
7883
  return false;
6850
7884
  }
@@ -6878,7 +7912,7 @@ var SandboxContext = class _SandboxContext {
6878
7912
  }
6879
7913
  static async create(rootDir, options = {}) {
6880
7914
  const sessionId = crypto3.randomUUID().slice(0, 8);
6881
- const root = rootDir ? path16.resolve(rootDir) : process.cwd();
7915
+ const root = rootDir ? path17.resolve(rootDir) : process.cwd();
6882
7916
  if (options.sandboxMode !== "readonly")
6883
7917
  await fs4.mkdir(root, { recursive: true });
6884
7918
  const directory = options.protectResources ? await fs4.realpath(root) : root;
@@ -6903,7 +7937,7 @@ var SandboxContext = class _SandboxContext {
6903
7937
  resolvePath(targetPath, access = "write") {
6904
7938
  if (access === "write" && this.sandboxMode === "readonly")
6905
7939
  throw new SecurityError("Sandbox mode is readonly");
6906
- const resolved = path16.isAbsolute(targetPath) ? path16.resolve(targetPath) : path16.resolve(this.workingDir, targetPath);
7940
+ const resolved = path17.isAbsolute(targetPath) ? path17.resolve(targetPath) : path17.resolve(this.workingDir, targetPath);
6907
7941
  if (this.protectedPaths) return this.resolveProtectedPath(resolved, access);
6908
7942
  if (this.approvalMode === "full-access") {
6909
7943
  return resolved;
@@ -6921,12 +7955,12 @@ var SandboxContext = class _SandboxContext {
6921
7955
  selectFile(operand, access, directoryEntry = false) {
6922
7956
  const target = this.resolvePath(operand, access);
6923
7957
  if (directoryEntry) {
6924
- const lexical = path16.resolve(this.workingDir, operand);
6925
- const name = path16.join(
6926
- resolvePolicyPath(path16.dirname(lexical)),
6927
- path16.basename(lexical)
7958
+ const lexical = path17.resolve(this.workingDir, operand);
7959
+ const name = path17.join(
7960
+ resolvePolicyPath(path17.dirname(lexical)),
7961
+ path17.basename(lexical)
6928
7962
  );
6929
- if (target !== name || lstatSync10(name, { throwIfNoEntry: false })?.isSymbolicLink())
7963
+ if (target !== name || lstatSync12(name, { throwIfNoEntry: false })?.isSymbolicLink())
6930
7964
  throw new SecurityError(
6931
7965
  "Patch deletion and move require a regular directory entry without a symbolic link"
6932
7966
  );
@@ -6938,7 +7972,7 @@ var SandboxContext = class _SandboxContext {
6938
7972
  ...directoryEntry ? { directoryEntry: true } : {}
6939
7973
  };
6940
7974
  try {
6941
- const info = lstatSync10(target, { bigint: true });
7975
+ const info = lstatSync12(target, { bigint: true });
6942
7976
  if (!info.isFile())
6943
7977
  throw new SecurityError("Expected a regular file for this operation");
6944
7978
  return Object.freeze({
@@ -6986,7 +8020,7 @@ var SandboxContext = class _SandboxContext {
6986
8020
  error.code = "ENOENT";
6987
8021
  throw error;
6988
8022
  }
6989
- const flags = (mode === "read" ? constants6.O_RDONLY : constants6.O_RDWR) | (constants6.O_NOFOLLOW ?? 0) | (constants6.O_NONBLOCK ?? 0);
8023
+ const flags = (mode === "read" ? constants7.O_RDONLY : constants7.O_RDWR) | (constants7.O_NOFOLLOW ?? 0) | (constants7.O_NONBLOCK ?? 0);
6990
8024
  const handle = await fs4.open(selected.target, flags);
6991
8025
  try {
6992
8026
  const opened = await handle.stat({ bigint: true });
@@ -7080,7 +8114,7 @@ var SandboxContext = class _SandboxContext {
7080
8114
  writeProtection(target, alias = false) {
7081
8115
  const { readOnlyPaths } = gitMetadataPaths(
7082
8116
  this.rootDir,
7083
- path16.dirname(target)
8117
+ path17.dirname(target)
7084
8118
  );
7085
8119
  const projectConfig = workspaceConfigProtection(this.rootDir);
7086
8120
  return [
@@ -7112,16 +8146,16 @@ var SandboxContext = class _SandboxContext {
7112
8146
  let probe = resolved;
7113
8147
  for (; ; ) {
7114
8148
  try {
7115
- const actual = realpathSync10(probe);
7116
- const target = path16.resolve(actual, path16.relative(probe, resolved));
8149
+ const actual = realpathSync11(probe);
8150
+ const target = path17.resolve(actual, path17.relative(probe, resolved));
7117
8151
  rejectProtected(target);
7118
8152
  if (target !== resolved) rejectWrite(target);
7119
8153
  if (probe === resolved) {
7120
- const stat = lstatSync10(target);
8154
+ const stat = lstatSync12(target);
7121
8155
  if (!stat.isFile() && !stat.isDirectory())
7122
8156
  throw new SecurityError("Unsupported file type");
7123
8157
  if (stat.isFile() && stat.nlink > 1) {
7124
- const inode2 = lstatSync10(target, { bigint: true });
8158
+ const inode2 = lstatSync12(target, { bigint: true });
7125
8159
  if (isProtectedAlias(inode2, protectedPaths))
7126
8160
  throw new SecurityError("Path aliases a protected file");
7127
8161
  if (access === "write" && this.isReadOnlyAlias(inode2, target))
@@ -7131,10 +8165,10 @@ var SandboxContext = class _SandboxContext {
7131
8165
  return target;
7132
8166
  } catch (error) {
7133
8167
  if (error.code !== "ENOENT") throw error;
7134
- const ancestor = path16.dirname(probe);
8168
+ const ancestor = path17.dirname(probe);
7135
8169
  if (ancestor === probe) throw error;
7136
8170
  try {
7137
- if (lstatSync10(probe).isSymbolicLink())
8171
+ if (lstatSync12(probe).isSymbolicLink())
7138
8172
  throw new SecurityError("Path contains a dangling symlink");
7139
8173
  } catch (entryError) {
7140
8174
  if (entryError.code !== "ENOENT")
@@ -7180,8 +8214,8 @@ var appendReadMetadata = (output, content) => `${output}
7180
8214
  [read_metadata] content_sha256=${hashUtf8Content(content)}`;
7181
8215
 
7182
8216
  // src/subagents/workspace-files.ts
7183
- import { constants as constants7, promises as fs5 } from "fs";
7184
- import path17 from "path";
8217
+ import { constants as constants8, promises as fs5 } from "fs";
8218
+ import path18 from "path";
7185
8219
  var MAX_CHILD_FILE_BYTES = 4 * 1024 * 1024;
7186
8220
  var readContent = async (handle) => {
7187
8221
  const buffer = Buffer.alloc(MAX_CHILD_FILE_BYTES + 1);
@@ -7208,15 +8242,15 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7208
8242
  );
7209
8243
  const blocked = (target) => protectedPaths.some((entry) => resourceContainsPath(entry, target));
7210
8244
  const resolve = async (name, allowMissing = false) => {
7211
- const candidate = path17.resolve(root, name);
8245
+ const candidate = path18.resolve(root, name);
7212
8246
  if (blocked(candidate))
7213
8247
  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))
8248
+ const relative = path18.relative(root, candidate);
8249
+ if (relative === ".." || relative.startsWith(`..${path18.sep}`) || path18.isAbsolute(relative))
7216
8250
  throw new Error("Path outside delegated workspace");
7217
8251
  let part = root;
7218
- for (const segment of relative.split(path17.sep).filter(Boolean)) {
7219
- part = path17.join(part, segment);
8252
+ for (const segment of relative.split(path18.sep).filter(Boolean)) {
8253
+ part = path18.join(part, segment);
7220
8254
  try {
7221
8255
  if ((await fs5.lstat(part)).isSymbolicLink())
7222
8256
  throw new Error(
@@ -7256,7 +8290,7 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7256
8290
  const file = await resolve(name, expected === "missing");
7257
8291
  const repositoryReadOnly = gitMetadataPaths(
7258
8292
  root,
7259
- path17.dirname(file)
8293
+ path18.dirname(file)
7260
8294
  ).readOnlyPaths;
7261
8295
  const projectConfig = workspaceConfigProtection(root);
7262
8296
  if (homeDotDirectory2 && isHomeWriteReserved(homeDotDirectory2, file) || isWorkspaceConfigName(root, file) || [
@@ -7279,12 +8313,12 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7279
8313
  if (approval && expected === "missing")
7280
8314
  throw new Error("File already exists");
7281
8315
  if (expected === "missing") {
7282
- await fs5.mkdir(path17.dirname(file), { recursive: true });
8316
+ await fs5.mkdir(path18.dirname(file), { recursive: true });
7283
8317
  await resolve(name, true);
7284
8318
  }
7285
8319
  const handle = await fs5.open(
7286
8320
  file,
7287
- expected === "missing" ? "wx" : constants7.O_RDWR | (constants7.O_NOFOLLOW ?? 0)
8321
+ expected === "missing" ? "wx" : constants8.O_RDWR | (constants8.O_NOFOLLOW ?? 0)
7288
8322
  );
7289
8323
  try {
7290
8324
  const stat = await handle.stat({ bigint: true });
@@ -7328,16 +8362,16 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7328
8362
  };
7329
8363
  const update = async (name, expected, transform, signal, approval) => {
7330
8364
  const previous = pendingUpdate;
7331
- let release2;
8365
+ let release3;
7332
8366
  pendingUpdate = new Promise((done) => {
7333
- release2 = done;
8367
+ release3 = done;
7334
8368
  });
7335
8369
  try {
7336
8370
  await previous;
7337
8371
  signal?.throwIfAborted();
7338
8372
  return await updateFile(name, expected, transform, approval);
7339
8373
  } finally {
7340
- release2();
8374
+ release3();
7341
8375
  }
7342
8376
  };
7343
8377
  return { resolve, read, selectRead, update, blocked };
@@ -7388,17 +8422,17 @@ var createSubagentReadTools = (root, protectedPaths, options = {}) => {
7388
8422
  signal?.throwIfAborted();
7389
8423
  const dir = pending.shift();
7390
8424
  if (!dir) break;
7391
- const entries = await fs6.opendir(await resolve(path18.relative(root2, dir)));
8425
+ const entries = await fs6.opendir(await resolve(path19.relative(root2, dir)));
7392
8426
  for await (const entry of entries) {
7393
8427
  if (entry.isSymbolicLink() || entry.name === ".git" || entry.name === "node_modules")
7394
8428
  continue;
7395
- const child = path18.join(dir, entry.name);
8429
+ const child = path19.join(dir, entry.name);
7396
8430
  if (blocked(child)) continue;
7397
8431
  if (entry.isDirectory()) {
7398
8432
  if (pending.length >= 2e3) return { paths, truncated: true };
7399
8433
  pending.push(child);
7400
8434
  } else if (entry.isFile()) {
7401
- const name = path18.relative(root2, child);
8435
+ const name = path19.relative(root2, child);
7402
8436
  const selected = await selectRead(name, sandbox).catch(
7403
8437
  () => void 0
7404
8438
  );
@@ -7957,12 +8991,14 @@ export {
7957
8991
  isSimpleAndChain,
7958
8992
  analyzeShell,
7959
8993
  fixedFileMutation,
8994
+ isProtectedAlias,
7960
8995
  shellBinPaths,
7961
8996
  resolveShellExecutable,
7962
8997
  bindBashCommand,
7963
8998
  bindKnownSystemExecutable,
7964
8999
  isRootControlledSharedExecutable,
7965
9000
  areAllExecutableLinksOutsideRestrictedPaths,
9001
+ LinuxMxcBackend,
7966
9002
  resolveSystemBash,
7967
9003
  confinedAutoLaunchDirectoryName,
7968
9004
  supportsProtectedShell,
@@ -7971,9 +9007,10 @@ export {
7971
9007
  canonicalPolicyPaths,
7972
9008
  runtimeReadOnlyPaths,
7973
9009
  workspacePathProtection,
7974
- macAdditionalWriteLauncherPaths,
9010
+ mxcAdditionalWriteLauncherPaths,
7975
9011
  MacSeatbeltBackend,
7976
9012
  createMacMxcShellBackend,
9013
+ createLinuxMxcShellBackend,
7977
9014
  UserShellBackend,
7978
9015
  selectProtectedShellBackend,
7979
9016
  directoryIdentity,