@codelia/runtime 0.1.89 → 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.
@@ -325,6 +325,7 @@ var updateTuiTheme = async (workingDir, theme) => {
325
325
  await updateTuiConfig(target.path, { theme });
326
326
  return target;
327
327
  };
328
+ var normalizeModelLevel = (value) => value.trim().toLowerCase();
328
329
  var resolveReasoningEffort = (value) => {
329
330
  return resolveModelLevelOption(value, "model.reasoning", {
330
331
  allowXhigh: true
@@ -337,7 +338,7 @@ var resolveTextVerbosity = (value) => {
337
338
  };
338
339
  function resolveModelLevelOption(value, fieldName, options) {
339
340
  if (!value) return void 0;
340
- const normalized = value.trim().toLowerCase();
341
+ const normalized = normalizeModelLevel(value);
341
342
  if (normalized === "low" || normalized === "medium" || normalized === "high") {
342
343
  return normalized;
343
344
  }
@@ -367,16 +368,20 @@ Working directory: ${workingDir}`;
367
368
 
368
369
  // src/rpc/ui-requests.ts
369
370
  import {
370
- RPC_ERROR_CODE
371
+ RPC_ERROR_CODE as RPC_ERROR_CODE2
371
372
  } from "@codelia/protocol";
372
373
 
373
- // src/rpc/transport.ts
374
- import { AsyncLocalStorage } from "async_hooks";
375
-
376
374
  // src/logger.ts
377
375
  import { debugLog, isDebugEnabled, log } from "@codelia/logger";
378
376
 
377
+ // src/rpc/protocol.ts
378
+ import {
379
+ protocolMethods,
380
+ RPC_ERROR_CODE
381
+ } from "@codelia/protocol";
382
+
379
383
  // src/rpc/transport.ts
384
+ import { AsyncLocalStorage } from "async_hooks";
380
385
  var responseContext = new AsyncLocalStorage();
381
386
  var withRpcResponseContext = (id, callback) => responseContext.run({ id, sent: false }, callback);
382
387
  var hasRpcResponse = (id) => {
@@ -477,65 +482,107 @@ var sendResponse = (response) => {
477
482
  var sendAgentEvent = (state, runId, event) => {
478
483
  if (state.shouldSuppressEvent(runId)) return null;
479
484
  const seq = state.nextSequence(runId);
480
- const notify = {
481
- jsonrpc: "2.0",
482
- method: "agent.event",
483
- params: {
484
- run_id: runId,
485
- seq,
486
- event
487
- }
488
- };
489
- sendNotification(state, notify);
485
+ sendNotification(
486
+ state,
487
+ notificationMessage("agent.event", { run_id: runId, seq, event })
488
+ );
490
489
  return seq;
491
490
  };
492
491
  var sendRunStatus = (state, runId, status, message, error, extras) => {
493
- const notify = {
494
- jsonrpc: "2.0",
495
- method: "run.status",
496
- params: {
497
- run_id: runId,
498
- status,
499
- message,
500
- ...error ? { error } : {},
501
- ...extras?.unconsumed_steer_ids?.length ? { unconsumed_steer_ids: extras.unconsumed_steer_ids } : {}
502
- }
503
- };
492
+ const notify = notificationMessage("run.status", {
493
+ run_id: runId,
494
+ status,
495
+ message,
496
+ ...error ? { error } : {},
497
+ ...extras?.unconsumed_steer_ids?.length ? { unconsumed_steer_ids: extras.unconsumed_steer_ids } : {},
498
+ ...extras?.unconsumed_client_steer_ids?.length ? { unconsumed_client_steer_ids: extras.unconsumed_client_steer_ids } : {}
499
+ });
504
500
  sendNotification(state, notify);
505
501
  };
506
502
  var sendRunContext = (state, runId, contextLeftPercent) => {
507
- const notify = {
508
- jsonrpc: "2.0",
509
- method: "run.context",
510
- params: {
503
+ sendNotification(
504
+ state,
505
+ notificationMessage("run.context", {
511
506
  run_id: runId,
512
507
  context_left_percent: contextLeftPercent
513
- }
514
- };
515
- sendNotification(state, notify);
508
+ })
509
+ );
516
510
  };
517
511
  var sendRunDiagnostics = (state, params) => {
518
- const notify = {
519
- jsonrpc: "2.0",
520
- method: "run.diagnostics",
521
- params
522
- };
523
- sendNotification(state, notify);
512
+ sendNotification(state, notificationMessage("run.diagnostics", params));
524
513
  };
525
514
  var sendRunMetrics = (state, params) => {
526
- sendNotification(state, { jsonrpc: "2.0", method: "run.metrics", params });
515
+ sendNotification(state, notificationMessage("run.metrics", params));
516
+ };
517
+
518
+ // src/rpc/protocol.ts
519
+ var MAX_ISSUES = 10;
520
+ var describeIssues = (error) => error.issues.slice(0, MAX_ISSUES).map((issue) => ({
521
+ path: issue.path.map(String).join("."),
522
+ code: issue.code,
523
+ message: issue.message
524
+ }));
525
+ var schemaFor = (method, slot) => {
526
+ const spec = protocolMethods[method];
527
+ if (slot === "params") return spec.params;
528
+ if (!("result" in spec))
529
+ throw new Error(`${method} is a notification without a result`);
530
+ return spec.result;
531
+ };
532
+ var assertOutgoing = (method, slot, value) => {
533
+ if (process.env.CODELIA_PROTOCOL_ASSERT !== "1") return;
534
+ const result = schemaFor(method, slot).safeParse(value);
535
+ if (!result.success)
536
+ throw new Error(
537
+ `protocol assertion failed for ${method} ${slot}: ${JSON.stringify(describeIssues(result.error))}`
538
+ );
539
+ };
540
+ var parseRequestParams = (method, raw) => {
541
+ const result = schemaFor(method, "params").safeParse(
542
+ raw === void 0 ? {} : raw
543
+ );
544
+ if (result.success) return { ok: true, params: result.data };
545
+ const issues = describeIssues(result.error);
546
+ const first = issues[0];
547
+ return {
548
+ ok: false,
549
+ error: {
550
+ code: RPC_ERROR_CODE.INVALID_PARAMS,
551
+ // The first issue names the field; issue messages never echo values.
552
+ message: first ? `invalid ${method} params: ${first.path || "params"}: ${first.message}` : `invalid ${method} params`,
553
+ data: { issues }
554
+ }
555
+ };
556
+ };
557
+ var parseUiNotificationParams = (method, raw) => {
558
+ const result = schemaFor(method, "params").safeParse(
559
+ raw === void 0 ? {} : raw
560
+ );
561
+ return result.success ? result.data : null;
562
+ };
563
+ var sendRequestResult = (method, id, result) => {
564
+ assertOutgoing(method, "result", result);
565
+ sendResult(id, result);
566
+ };
567
+ var notificationMessage = (method, params) => {
568
+ assertOutgoing(method, "params", params);
569
+ return { jsonrpc: "2.0", method, params };
570
+ };
571
+ var requestMessage = (method, id, params) => {
572
+ assertOutgoing(method, "params", params);
573
+ return { jsonrpc: "2.0", id, method, params };
574
+ };
575
+ var parseUiResult = (method, raw) => {
576
+ const result = schemaFor(method, "result").safeParse(raw);
577
+ if (result.success) return { ok: true, result: result.data };
578
+ return { ok: false, issues: describeIssues(result.error) };
527
579
  };
528
580
 
529
581
  // src/rpc/ui-requests.ts
530
582
  var requestUi = async (state, method, params, signal) => {
531
583
  if (signal?.aborted) return null;
532
584
  const id = state.nextUiRequestId();
533
- const request = {
534
- jsonrpc: "2.0",
535
- id,
536
- method,
537
- params
538
- };
585
+ const request = requestMessage(method, id, params);
539
586
  const response = state.waitForUiResponse(id);
540
587
  let sent = false;
541
588
  const abort = () => {
@@ -543,13 +590,12 @@ var requestUi = async (state, method, params, signal) => {
543
590
  jsonrpc: "2.0",
544
591
  id,
545
592
  error: {
546
- code: RPC_ERROR_CODE.RUNTIME_INTERNAL,
593
+ code: RPC_ERROR_CODE2.RUNTIME_INTERNAL,
547
594
  message: "UI request cancelled"
548
595
  }
549
596
  });
550
- if (cancelled && sent && method === "ui.pick.request") {
551
- send({ jsonrpc: "2.0", method: "ui.pick.cancelled", params: { id } });
552
- }
597
+ if (!cancelled || !sent || method !== "ui.pick.request") return;
598
+ send(notificationMessage("ui.pick.cancelled", { id }));
553
599
  };
554
600
  signal?.addEventListener("abort", abort, { once: true });
555
601
  try {
@@ -558,7 +604,12 @@ var requestUi = async (state, method, params, signal) => {
558
604
  send(request);
559
605
  sent = true;
560
606
  }
561
- return await response;
607
+ const parsed = parseUiResult(method, await response);
608
+ if (parsed.ok) return parsed.result;
609
+ log(
610
+ `protocol mismatch: ${method} result: ${JSON.stringify(parsed.issues)}`
611
+ );
612
+ return null;
562
613
  } catch {
563
614
  return null;
564
615
  } finally {
@@ -1933,15 +1984,15 @@ var AuthResolver = class _AuthResolver {
1933
1984
  // src/permissions/shell-backend.ts
1934
1985
  import { spawn as spawn4, spawnSync as spawnSync3 } from "child_process";
1935
1986
  import {
1936
- lstatSync as lstatSync9,
1987
+ lstatSync as lstatSync11,
1937
1988
  mkdirSync as mkdirSync2,
1938
- mkdtempSync as mkdtempSync2,
1939
- realpathSync as realpathSync8,
1940
- rmSync as rmSync2,
1941
- statSync as statSync5
1989
+ mkdtempSync as mkdtempSync3,
1990
+ realpathSync as realpathSync9,
1991
+ rmSync as rmSync3,
1992
+ statSync as statSync6
1942
1993
  } from "fs";
1943
- import os2 from "os";
1944
- import path13 from "path";
1994
+ import os3 from "os";
1995
+ import path14 from "path";
1945
1996
  import { resolveStoragePaths as resolveStoragePaths3 } from "@codelia/storage";
1946
1997
 
1947
1998
  // src/sandbox/file-mutation-helper.ts
@@ -2062,13 +2113,19 @@ import {
2062
2113
  lstatSync,
2063
2114
  openSync as openSync2,
2064
2115
  readdirSync,
2116
+ readlinkSync,
2065
2117
  readSync,
2066
2118
  realpathSync,
2067
2119
  statSync
2068
2120
  } from "fs";
2121
+ import os from "os";
2069
2122
  import path4 from "path";
2070
2123
  var isMissing = (error) => error.code === "ENOENT";
2071
2124
  var metadataPathSize = 16 * 1024;
2125
+ var gitConfigMaxBytes = 256 * 1024;
2126
+ var maxSymlinkHops = 64;
2127
+ var maxConfigDepth = 8;
2128
+ var maxConfigFiles = 32;
2072
2129
  var readPointer = (filename, prefix) => {
2073
2130
  const fd = openSync2(
2074
2131
  filename,
@@ -2170,6 +2227,7 @@ var eligibleObjectDirectory = (gitDirectory, commonDirectory, marker) => {
2170
2227
  };
2171
2228
  var discoverGitMetadata = (directories, includeObjectDirectories) => {
2172
2229
  const readOnlyPaths = /* @__PURE__ */ new Set();
2230
+ const repositories = [];
2173
2231
  const reservedMarkers = /* @__PURE__ */ new Set();
2174
2232
  const objectDirectories = /* @__PURE__ */ new Map();
2175
2233
  const hookAliases = /* @__PURE__ */ new Map();
@@ -2194,22 +2252,47 @@ var discoverGitMetadata = (directories, includeObjectDirectories) => {
2194
2252
  readOnlyPaths.add(actual);
2195
2253
  return actual;
2196
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
+ };
2197
2270
  for (const directory of new Set(directories)) {
2271
+ const fromRoot = directory === rootDirectory;
2198
2272
  const marker = findMarker(directory);
2199
2273
  const localMarker = path4.join(directory, ".git");
2200
2274
  if (marker !== localMarker) reservedMarkers.add(localMarker);
2201
2275
  if (!marker) continue;
2202
2276
  if (readOnlyPaths.has(marker)) continue;
2277
+ const isWorkspaceRootRepo = fromRoot && marker === localMarker;
2278
+ const markerLstat = lstatSync(marker);
2203
2279
  const actualMarker = realpathSync(marker);
2204
2280
  readOnlyPaths.add(marker);
2205
2281
  readOnlyPaths.add(actualMarker);
2206
2282
  const markerInfo = statSync(actualMarker);
2207
- const gitDirectory = markerInfo.isDirectory() ? actualMarker : addDirectory(
2208
- 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(
2209
2290
  path4.dirname(marker),
2210
2291
  readPointer(actualMarker, "gitdir: ")
2211
- )
2212
- );
2292
+ );
2293
+ gitDirectory = addDirectory(location);
2294
+ directoryEntries.push(location, gitDirectory);
2295
+ }
2213
2296
  if (!statSync(path4.join(gitDirectory, "HEAD")).isFile())
2214
2297
  throw new Error("invalid_git_metadata_directory");
2215
2298
  const commonPointer = path4.join(gitDirectory, "commondir");
@@ -2219,19 +2302,34 @@ var discoverGitMetadata = (directories, includeObjectDirectories) => {
2219
2302
  } catch (error) {
2220
2303
  if (!isMissing(error)) throw error;
2221
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
+ });
2222
2312
  continue;
2223
2313
  }
2224
2314
  readOnlyPaths.add(commonPointer);
2225
2315
  readOnlyPaths.add(common);
2226
- const commonDirectory = addDirectory(
2227
- path4.resolve(gitDirectory, readPointer(common, ""))
2228
- );
2316
+ const commonLocation = path4.resolve(gitDirectory, readPointer(common, ""));
2317
+ const commonDirectory = addDirectory(commonLocation);
2318
+ directoryEntries.push(commonLocation, commonDirectory);
2229
2319
  if (!statSync(path4.join(commonDirectory, "objects")).isDirectory())
2230
2320
  throw new Error("invalid_git_common_directory");
2231
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
+ });
2232
2329
  }
2233
2330
  return Object.freeze({
2234
2331
  readOnlyPaths: Object.freeze([...readOnlyPaths].sort()),
2332
+ repositories: Object.freeze(repositories),
2235
2333
  reservedMarkers: Object.freeze([...reservedMarkers].sort()),
2236
2334
  objectDirectories: Object.freeze([...objectDirectories.values()]),
2237
2335
  hookAliases: Object.freeze([...hookAliases.values()])
@@ -2246,17 +2344,402 @@ var resolveGitMetadata = (directories, includeObjectDirectories) => {
2246
2344
  };
2247
2345
  var gitMetadataPaths = (...directories) => resolveGitMetadata(directories, false);
2248
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
+ };
2249
2732
 
2250
2733
  // src/permissions/home-dot-paths.ts
2251
- import { readdirSync as readdirSync2, readlinkSync as readlinkSync2 } from "fs";
2252
- import os from "os";
2734
+ import { lstatSync as lstatSync3, readdirSync as readdirSync2, readlinkSync as readlinkSync3 } from "fs";
2735
+ import os2 from "os";
2253
2736
  import path6 from "path";
2254
2737
 
2255
2738
  // src/permissions/resource-paths.ts
2256
2739
  import {
2257
2740
  lstatSync as lstatSync2,
2258
2741
  opendirSync,
2259
- readlinkSync,
2742
+ readlinkSync as readlinkSync2,
2260
2743
  realpathSync as realpathSync2
2261
2744
  } from "fs";
2262
2745
  import path5 from "path";
@@ -2327,7 +2810,7 @@ function resolveReservedTarget(target, remaining = 64) {
2327
2810
  const canonicalParent = resolveReservedTarget(parent, remaining - 1);
2328
2811
  if (!lstatSync2(target, { throwIfNoEntry: false })?.isSymbolicLink())
2329
2812
  return path5.join(canonicalParent, path5.basename(target));
2330
- const referent = readlinkSync(target);
2813
+ const referent = readlinkSync2(target);
2331
2814
  let seenName = false;
2332
2815
  for (const part of referent.split(
2333
2816
  process.platform === "win32" ? /[\\/]/u : "/"
@@ -2344,7 +2827,7 @@ function resolveReservedTarget(target, remaining = 64) {
2344
2827
  }
2345
2828
 
2346
2829
  // src/permissions/home-dot-paths.ts
2347
- var homeDotDirectory = (writeRoots, home = os.homedir()) => {
2830
+ var homeDotDirectory = (writeRoots, home = os2.homedir()) => {
2348
2831
  if (!writeRoots.length) return void 0;
2349
2832
  const canonicalHome = resolveReservedTarget(home);
2350
2833
  return writeRoots.some(
@@ -2366,7 +2849,7 @@ var hasClosedHomeDotCycle = (home, start) => {
2366
2849
  seen.add(current);
2367
2850
  let link;
2368
2851
  try {
2369
- link = readlinkSync2(current);
2852
+ link = readlinkSync3(current);
2370
2853
  } catch {
2371
2854
  return false;
2372
2855
  }
@@ -2391,23 +2874,50 @@ var homeDotLinkTargets = (home) => readdirSync2(home, { withFileTypes: true }).f
2391
2874
  }
2392
2875
  });
2393
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
+ };
2394
2906
 
2395
- // src/permissions/linux-shell-backend.ts
2396
- import { spawn as spawn2, spawnSync } from "child_process";
2907
+ // src/permissions/linux-mxc-backend.ts
2397
2908
  import {
2398
2909
  accessSync as accessSync2,
2399
2910
  constants as constants4,
2400
- lstatSync as lstatSync5,
2401
- mkdirSync,
2911
+ lstatSync as lstatSync7,
2402
2912
  mkdtempSync,
2403
- readdirSync as readdirSync5,
2404
- readFileSync as readFileSync3,
2405
- realpathSync as realpathSync5,
2913
+ readdirSync as readdirSync6,
2914
+ readFileSync as readFileSync4,
2915
+ realpathSync as realpathSync6,
2406
2916
  rmSync,
2407
- statSync as statSync3,
2408
- writeFileSync
2917
+ statSync as statSync4
2409
2918
  } from "fs";
2410
- import path10 from "path";
2919
+ import { homedir } from "os";
2920
+ import path11 from "path";
2411
2921
 
2412
2922
  // src/permissions/linux-mountinfo.ts
2413
2923
  import { readFileSync as readFileSync2 } from "fs";
@@ -2494,62 +3004,325 @@ function executableMountSnapshot(file, dev, text = readFileSync2("/proc/self/mou
2494
3004
  ).map(({ line }) => line).join("\n");
2495
3005
  }
2496
3006
 
2497
- // src/permissions/protected-aliases.ts
3007
+ // src/permissions/mxc-launcher.ts
3008
+ import { spawn as spawn2, spawnSync } from "child_process";
2498
3009
  import {
2499
- lstatSync as lstatSync3,
3010
+ lstatSync as lstatSync4,
2500
3011
  readdirSync as readdirSync3,
2501
- realpathSync as realpathSync3
3012
+ readFileSync as readFileSync3,
3013
+ realpathSync as realpathSync3,
3014
+ statSync as statSync2
2502
3015
  } from "fs";
2503
3016
  import path8 from "path";
2504
- var maxEntries = 4096;
2505
- var inode = (stat) => `${stat.dev}:${stat.ino}`;
2506
- function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifiedHooks = []) {
2507
- const pending = roots.map((entry) => {
2508
- try {
2509
- return realpathSync3(entry);
2510
- } catch (error) {
2511
- if (error.code === "ENOENT") return entry;
2512
- throw error;
2513
- }
2514
- });
2515
- const visited = /* @__PURE__ */ new Set();
2516
- const ignored = new Set(ignoredObjectDirectories);
2517
- const inputs = new Set(roots);
2518
- const hooks = new Map(
2519
- verifiedHooks.filter((hook) => inputs.has(hook.target)).map((hook) => [hook.path, hook.target])
2520
- );
2521
- const verifiedHook = (file) => {
2522
- const target = hooks.get(file);
2523
- if (!target) return false;
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;
2524
3063
  try {
2525
- return realpathSync3(file) === target && lstatSync3(target).isFile();
3064
+ names = readdirSync3(item.dir);
2526
3065
  } catch {
2527
- return false;
3066
+ continue;
2528
3067
  }
2529
- };
2530
- while (pending.length) {
2531
- const file = pending.pop();
2532
- if (!file || visited.has(file)) continue;
2533
- visited.add(file);
2534
- if (visited.size > entryLimit)
2535
- throw new Error("protected_alias_index_unavailable");
2536
- try {
2537
- const metadata = lstatSync3(file, { bigint: true });
2538
- if (metadata.isFile() && metadata.nlink > 1n) yield inode(metadata);
2539
- if (metadata.isSymbolicLink() && ignored.size) {
2540
- if (verifiedHook(file)) continue;
2541
- pending.push(...ignored);
2542
- ignored.clear();
2543
- } else if (metadata.isDirectory()) {
2544
- const children = readdirSync3(file);
2545
- if (children.length + pending.length + visited.size > entryLimit)
2546
- throw new Error("protected_alias_index_unavailable");
2547
- for (const name of children) {
2548
- const child = path8.join(file, name);
2549
- if (!ignored.has(child)) pending.push(child);
2550
- }
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 });
2551
3088
  }
2552
- } catch (error) {
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";
3266
+ var maxEntries = 4096;
3267
+ var inode = (stat) => `${stat.dev}:${stat.ino}`;
3268
+ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifiedHooks = []) {
3269
+ const pending = roots.map((entry) => {
3270
+ try {
3271
+ return realpathSync4(entry);
3272
+ } catch (error) {
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
+ }
3284
+ throw error;
3285
+ }
3286
+ });
3287
+ const visited = /* @__PURE__ */ new Set();
3288
+ const ignored = new Set(ignoredObjectDirectories);
3289
+ const inputs = new Set(roots);
3290
+ const hooks = new Map(
3291
+ verifiedHooks.filter((hook) => inputs.has(hook.target)).map((hook) => [hook.path, hook.target])
3292
+ );
3293
+ const verifiedHook = (file) => {
3294
+ const target = hooks.get(file);
3295
+ if (!target) return false;
3296
+ try {
3297
+ return realpathSync4(file) === target && lstatSync5(target).isFile();
3298
+ } catch {
3299
+ return false;
3300
+ }
3301
+ };
3302
+ while (pending.length) {
3303
+ const file = pending.pop();
3304
+ if (!file || visited.has(file)) continue;
3305
+ visited.add(file);
3306
+ if (visited.size > entryLimit)
3307
+ throw new Error("protected_alias_index_unavailable");
3308
+ try {
3309
+ const metadata = lstatSync5(file, { bigint: true });
3310
+ if ((metadata.isFile() || metadata.isSocket() || metadata.isFIFO()) && metadata.nlink > 1n)
3311
+ yield inode(metadata);
3312
+ if (metadata.isSymbolicLink() && ignored.size) {
3313
+ if (verifiedHook(file)) continue;
3314
+ pending.push(...ignored);
3315
+ ignored.clear();
3316
+ } else if (metadata.isDirectory()) {
3317
+ const children = readdirSync4(file);
3318
+ if (children.length + pending.length + visited.size > entryLimit)
3319
+ throw new Error("protected_alias_index_unavailable");
3320
+ for (const name of children) {
3321
+ const child = path9.join(file, name);
3322
+ if (!ignored.has(child)) pending.push(child);
3323
+ }
3324
+ }
3325
+ } catch (error) {
2553
3326
  if (error.code !== "ENOENT") throw error;
2554
3327
  }
2555
3328
  }
@@ -2819,29 +3592,29 @@ var analyzeShell = (invocation) => {
2819
3592
  import {
2820
3593
  accessSync,
2821
3594
  constants as constants3,
2822
- lstatSync as lstatSync4,
2823
- readdirSync as readdirSync4,
2824
- readlinkSync as readlinkSync3,
2825
- realpathSync as realpathSync4,
2826
- statSync as statSync2
3595
+ lstatSync as lstatSync6,
3596
+ readdirSync as readdirSync5,
3597
+ readlinkSync as readlinkSync4,
3598
+ realpathSync as realpathSync5,
3599
+ statSync as statSync3
2827
3600
  } from "fs";
2828
- import path9 from "path";
2829
- var shellBinPaths = (override) => Object.freeze((override ?? process.env.PATH ?? "").split(path9.delimiter));
2830
- 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);
2831
3604
  var resolveShellExecutable = (name, paths, cwd = process.cwd()) => {
2832
- 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("\\")))
2833
3606
  throw new Error("invalid_executable");
2834
- const executable = process.platform === "win32" && !path9.extname(name) ? `${name}.exe` : name;
2835
- 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) => {
2836
3609
  const directory = process.platform === "win32" && entry.startsWith('"') && entry.endsWith('"') ? entry.slice(1, -1) : entry;
2837
- const resolved = path9.isAbsolute(directory) ? directory : `${cwd}${path9.sep}${directory || "."}`;
2838
- return `${resolved}${path9.sep}${executable}`;
3610
+ const resolved = path10.isAbsolute(directory) ? directory : `${cwd}${path10.sep}${directory || "."}`;
3611
+ return `${resolved}${path10.sep}${executable}`;
2839
3612
  });
2840
3613
  for (const candidate of candidates) {
2841
3614
  try {
2842
3615
  accessSync(candidate, constants3.X_OK);
2843
- const actual = realpathSync4(candidate);
2844
- if (statSync2(actual).isFile()) return actual;
3616
+ const actual = realpathSync5(candidate);
3617
+ if (statSync3(actual).isFile()) return actual;
2845
3618
  } catch {
2846
3619
  }
2847
3620
  }
@@ -2855,11 +3628,11 @@ var inspectBashPath = (candidate, policy) => {
2855
3628
  while (components.length) {
2856
3629
  const component = components.shift();
2857
3630
  if (!component || component === ".") continue;
2858
- const name = path9.join(current, component);
3631
+ const name = path10.join(current, component);
2859
3632
  const restriction = policy(name);
2860
3633
  if (restriction === "unbound") throw new Error("unbound_shell_path");
2861
3634
  masked ||= restriction === "masked";
2862
- const entry = lstatSync4(name, { throwIfNoEntry: false });
3635
+ const entry = lstatSync6(name, { throwIfNoEntry: false });
2863
3636
  if (!entry) return void 0;
2864
3637
  if (!entry.isSymbolicLink()) {
2865
3638
  if (components.length && !entry.isDirectory()) return void 0;
@@ -2867,27 +3640,27 @@ var inspectBashPath = (candidate, policy) => {
2867
3640
  continue;
2868
3641
  }
2869
3642
  if (++links > 40) throw new Error("unbound_shell_path");
2870
- const destination = readlinkSync3(name);
2871
- if (path9.isAbsolute(destination)) current = "/";
3643
+ const destination = readlinkSync4(name);
3644
+ if (path10.isAbsolute(destination)) current = "/";
2872
3645
  components = [...destination.split("/"), ...components];
2873
3646
  }
2874
3647
  return { file: current, masked };
2875
3648
  };
2876
3649
  var bindBashCommand = (name, paths, policy, acceptShared = () => false) => {
2877
- const absolute = path9.isAbsolute(name);
3650
+ const absolute = path10.isAbsolute(name);
2878
3651
  try {
2879
3652
  for (const directory of absolute ? [""] : paths) {
2880
- if (!absolute && (!path9.isAbsolute(directory) || directory.split("/").includes("..")))
3653
+ if (!absolute && (!path10.isAbsolute(directory) || directory.split("/").includes("..")))
2881
3654
  return void 0;
2882
3655
  const inspected = inspectBashPath(
2883
3656
  absolute ? name : `${directory}/${name}`,
2884
3657
  policy
2885
3658
  );
2886
3659
  if (!inspected) continue;
2887
- const executable = realpathSync4(inspected.file);
3660
+ const executable = realpathSync5(inspected.file);
2888
3661
  const restriction = policy(executable);
2889
3662
  if (restriction === "unbound") return void 0;
2890
- const info = statSync2(executable, { bigint: true });
3663
+ const info = statSync3(executable, { bigint: true });
2891
3664
  if (!info.isFile()) continue;
2892
3665
  if (info.nlink !== 1n && !acceptShared(executable, info))
2893
3666
  return void 0;
@@ -2910,11 +3683,11 @@ var bindBashCommand = (name, paths, policy, acceptShared = () => false) => {
2910
3683
  };
2911
3684
  function bindKnownSystemExecutable(program, paths, policy, directArgv) {
2912
3685
  if (process.platform === "win32") return void 0;
2913
- const name = path9.basename(program);
3686
+ const name = path10.basename(program);
2914
3687
  const known = new Set(
2915
3688
  [`/usr/bin/${name}`, `/bin/${name}`].flatMap((entry) => {
2916
3689
  try {
2917
- return [realpathSync4(entry)];
3690
+ return [realpathSync5(entry)];
2918
3691
  } catch {
2919
3692
  return [];
2920
3693
  }
@@ -2933,73 +3706,471 @@ var isRootControlledSharedExecutable = (file, info) => {
2933
3706
  const uid = process.getuid?.();
2934
3707
  return uid !== void 0 && uid !== 0 && uid === process.geteuid?.() && info.uid === 0n && (info.mode & 0o022n) === 0n && notWritable(file);
2935
3708
  };
2936
- 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;
2937
- 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) => {
2938
4049
  try {
2939
- const parent = path9.dirname(file);
2940
- if (policy(parent) || realpathSync4(parent) !== parent) return false;
2941
- const directory = lstatSync4(parent, { bigint: true });
2942
- const executable = lstatSync4(file, { bigint: true });
2943
- 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 {
2944
4088
  return false;
2945
- const mounts = process.platform === "linux" ? executableMountSnapshot(file, executable.dev) : void 0;
2946
- let links = 0n;
2947
- let foundExecutable = false;
2948
- const entries = readdirSync4(parent, { encoding: "buffer" });
2949
- if (entries.length > 4096) return false;
2950
- for (const entry of entries) {
2951
- const name = entry.toString();
2952
- if (!Buffer.from(name).equals(entry)) return false;
2953
- const peer = path9.join(parent, name);
2954
- const peerInfo = lstatSync4(peer, { bigint: true });
2955
- if (peerInfo.dev !== executable.dev || peerInfo.ino !== executable.ino)
2956
- continue;
2957
- if (!peerInfo.isFile() || policy(peer) || !sameLinkMetadata(executable, peerInfo))
2958
- return false;
2959
- foundExecutable ||= peer === file;
2960
- links++;
2961
4089
  }
2962
- 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);
2963
- } catch {
2964
- return false;
2965
4090
  }
2966
- }
2967
- var notWritable = (file) => {
2968
- try {
2969
- accessSync(file, constants3.W_OK);
2970
- return false;
2971
- } catch (error) {
2972
- return ["EACCES", "EPERM", "EROFS"].includes(
2973
- error.code ?? ""
2974
- );
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
+ }
2975
4130
  }
2976
4131
  };
2977
4132
 
2978
4133
  // src/permissions/linux-shell-backend.ts
2979
- var within2 = (root, name) => root === "/" || root === name || name.startsWith(`${root}/`);
2980
- 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"];
2981
4152
  var managedTool = (name) => {
2982
- const resolved = realpathSync5(name);
4153
+ const resolved = realpathSync7(name);
2983
4154
  let current = resolved;
2984
4155
  for (; ; ) {
2985
- const info = statSync3(current);
4156
+ const info = statSync5(current);
2986
4157
  if (info.uid !== 0 || (info.mode & 18) !== 0)
2987
4158
  throw new Error("untrusted_sandbox_installation");
2988
4159
  if (current === resolved && (!info.isFile() || (info.mode & 73) === 0))
2989
4160
  throw new Error("sandbox_executable_unavailable");
2990
4161
  if (current === "/") return resolved;
2991
- current = path10.dirname(current);
4162
+ current = path12.dirname(current);
2992
4163
  }
2993
4164
  };
2994
4165
  var masksFor = (policy) => {
2995
4166
  const paths = /* @__PURE__ */ new Set();
2996
4167
  for (const item of [...policy.protectedPaths, "/run"]) {
2997
- if (!path10.isAbsolute(item) || item !== path10.normalize(item) || item === "/")
4168
+ if (!path12.isAbsolute(item) || item !== path12.normalize(item) || item === "/")
2998
4169
  throw new Error("invalid_protected_path");
2999
4170
  if (item === "/dev") continue;
3000
4171
  let resolved;
3001
4172
  try {
3002
- resolved = realpathSync5(item);
4173
+ resolved = realpathSync7(item);
3003
4174
  } catch (error) {
3004
4175
  if (error.code !== "ENOENT") throw error;
3005
4176
  resolved = item;
@@ -3010,34 +4181,34 @@ var masksFor = (policy) => {
3010
4181
  }
3011
4182
  const selected = [];
3012
4183
  for (const item of [...paths].sort((a, b) => a.length - b.length)) {
3013
- if (!selected.some((mask) => within2(mask, item))) selected.push(item);
4184
+ if (!selected.some((mask) => within3(mask, item))) selected.push(item);
3014
4185
  }
3015
4186
  return selected;
3016
4187
  };
3017
- var readOnlyMount = (entry, projectedHome) => {
4188
+ var readOnlyMount2 = (entry, projectedHome) => {
3018
4189
  try {
3019
- if (realpathSync5(entry) !== entry)
4190
+ if (realpathSync7(entry) !== entry)
3020
4191
  throw new Error("unbound_read_only_path");
3021
4192
  return entry;
3022
4193
  } catch (error) {
3023
- if (error.code !== "ENOENT" || !projectedHome || !within2(projectedHome, entry) || resolveReservedTarget(entry) !== entry)
4194
+ if (error.code !== "ENOENT" || !projectedHome || !within3(projectedHome, entry) || resolveReservedTarget(entry) !== entry)
3024
4195
  throw error;
3025
4196
  }
3026
- let parent = path10.dirname(entry);
3027
- while (within2(projectedHome, parent)) {
3028
- const info = lstatSync5(parent, { throwIfNoEntry: false });
4197
+ let parent = path12.dirname(entry);
4198
+ while (within3(projectedHome, parent)) {
4199
+ const info = lstatSync8(parent, { throwIfNoEntry: false });
3029
4200
  if (info) {
3030
- if (info.isDirectory() && realpathSync5(parent) === parent) return parent;
4201
+ if (info.isDirectory() && realpathSync7(parent) === parent) return parent;
3031
4202
  break;
3032
4203
  }
3033
4204
  if (parent === projectedHome) break;
3034
- parent = path10.dirname(parent);
4205
+ parent = path12.dirname(parent);
3035
4206
  }
3036
4207
  throw new Error("unbound_read_only_path");
3037
4208
  };
3038
4209
  var linuxRunscMountArgs = (policy, state, masks) => {
3039
4210
  const mountpoints = masks.map((target) => {
3040
- const info = statSync3(target, { throwIfNoEntry: false });
4211
+ const info = statSync5(target, { throwIfNoEntry: false });
3041
4212
  if (!info) throw new Error("missing_protected_mountpoint");
3042
4213
  if (!info.isDirectory() && !info.isFile())
3043
4214
  throw new Error("unsupported_protected_mountpoint");
@@ -3050,37 +4221,37 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3050
4221
  const home = policy.homeDotDirectory;
3051
4222
  const projectedHome = home && policy.writeRoots.includes(home) ? home : void 0;
3052
4223
  const protectedTargets = [...masks, ...readOnly];
3053
- const covered = (target) => protectedTargets.some((entry) => within2(entry, target));
4224
+ const covered = (target) => protectedTargets.some((entry) => within3(entry, target));
3054
4225
  const writableRoots = /* @__PURE__ */ new Set();
3055
4226
  const flags = ["--ro-bind", "/", "/", "--ro-bind", "/tmp", "/tmp"];
3056
4227
  for (const root of policy.writeRoots) {
3057
- if (home && root !== home && (within2(root, home) || resourceContainsPath(root, home)))
4228
+ if (home && root !== home && (within3(root, home) || resourceContainsPath(root, home)))
3058
4229
  throw new Error("unsupported_home_write_root");
3059
- 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)))
3060
4231
  throw new Error("invalid_write_root");
3061
- if (within2(state, root)) continue;
3062
- if (masks.some((mask) => within2(mask, root)))
4232
+ if (within3(state, root)) continue;
4233
+ if (masks.some((mask) => within3(mask, root)))
3063
4234
  throw new Error("invalid_write_root");
3064
- if (readOnly.some((entry) => within2(entry, root))) continue;
4235
+ if (readOnly.some((entry) => within3(entry, root))) continue;
3065
4236
  if (root !== home) writableRoots.add(root);
3066
4237
  }
3067
4238
  if (projectedHome) {
3068
4239
  if (projectedHome !== "/tmp")
3069
4240
  flags.push("--ro-bind", projectedHome, projectedHome);
3070
- for (const name of readdirSync5(projectedHome)) {
3071
- const child = path10.join(projectedHome, name);
4241
+ for (const name of readdirSync7(projectedHome)) {
4242
+ const child = path12.join(projectedHome, name);
3072
4243
  if (child === state || isHomeDotTarget(projectedHome, child, "linux") || covered(child))
3073
4244
  continue;
3074
- const info = lstatSync5(child, { throwIfNoEntry: false });
3075
- if ((info?.isDirectory() || info?.isFile()) && realpathSync5(child) === child)
4245
+ const info = lstatSync8(child, { throwIfNoEntry: false });
4246
+ if ((info?.isDirectory() || info?.isFile()) && realpathSync7(child) === child)
3076
4247
  writableRoots.add(child);
3077
4248
  }
3078
4249
  }
3079
4250
  const readOnlyMounts = /* @__PURE__ */ new Set();
3080
4251
  const proposedRoots = [...writableRoots];
3081
4252
  for (const entry of [...readOnly].sort((a, b) => a.length - b.length)) {
3082
- if (!masks.some((mask) => within2(mask, entry)) && proposedRoots.some((root) => within2(root, entry)) && ![...readOnlyMounts].some((mount) => within2(mount, entry))) {
3083
- 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));
3084
4255
  }
3085
4256
  }
3086
4257
  protectedTargets.push(...readOnlyMounts);
@@ -3090,19 +4261,19 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3090
4261
  const writeRoots = [...writableRoots];
3091
4262
  const anchors = /* @__PURE__ */ new Set();
3092
4263
  for (const entry of [...readOnlyMounts, ...masks]) {
3093
- let parent = path10.dirname(entry);
3094
- 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))) {
3095
4266
  if (!writableRoots.has(parent) && !covered(parent)) anchors.add(parent);
3096
- parent = path10.dirname(parent);
4267
+ parent = path12.dirname(parent);
3097
4268
  }
3098
4269
  }
3099
4270
  for (const anchor of anchors) {
3100
- const info = statSync3(anchor, { throwIfNoEntry: false });
4271
+ const info = statSync5(anchor, { throwIfNoEntry: false });
3101
4272
  if (!info) {
3102
4273
  anchors.delete(anchor);
3103
4274
  continue;
3104
4275
  }
3105
- if (!info.isDirectory() || realpathSync5(anchor) !== anchor)
4276
+ if (!info.isDirectory() || realpathSync7(anchor) !== anchor)
3106
4277
  throw new Error("unbound_protected_ancestor");
3107
4278
  }
3108
4279
  for (const root of [...writeRoots, ...anchors].sort(
@@ -3110,7 +4281,7 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3110
4281
  ))
3111
4282
  flags.push("--bind", root, root);
3112
4283
  for (const entry of [...readOnlyMounts].sort((a, b) => a.length - b.length)) {
3113
- if (!writeRoots.some((root) => within2(root, entry))) continue;
4284
+ if (!writeRoots.some((root) => within3(root, entry))) continue;
3114
4285
  flags.push("--ro-bind", entry, entry);
3115
4286
  }
3116
4287
  for (const { target, placeholder } of mountpoints)
@@ -3119,7 +4290,7 @@ var linuxRunscMountArgs = (policy, state, masks) => {
3119
4290
  return flags;
3120
4291
  };
3121
4292
  var prepare = (policy, state, runsc, unshare) => {
3122
- 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)
3123
4294
  throw new Error("unsupported_protection");
3124
4295
  const masks = masksFor(policy);
3125
4296
  if (findProtectedAliases(policy.protectedAliasPaths ?? policy.protectedPaths).size)
@@ -3127,7 +4298,9 @@ var prepare = (policy, state, runsc, unshare) => {
3127
4298
  const readOnly = policy.readOnlyPaths ?? [];
3128
4299
  if (policy.writeRoots.length && hasReadOnlyAliases(policy.readOnlyAliasPaths ?? readOnly))
3129
4300
  throw new Error("read_only_file_has_alias");
3130
- 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"));
3131
4304
  return [
3132
4305
  "--pdeathsig",
3133
4306
  "KILL",
@@ -3156,9 +4329,11 @@ var prepare = (policy, state, runsc, unshare) => {
3156
4329
  "ALL",
3157
4330
  "--clearenv",
3158
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.
3159
4334
  "--setenv",
3160
4335
  "HOME",
3161
- state,
4336
+ homedir2(),
3162
4337
  "--setenv",
3163
4338
  "TMPDIR",
3164
4339
  state,
@@ -3181,16 +4356,16 @@ var prepare = (policy, state, runsc, unshare) => {
3181
4356
  "--"
3182
4357
  ];
3183
4358
  };
3184
- var release = (root) => rmSync(root, { recursive: true, force: true });
4359
+ var release2 = (root) => rmSync2(root, { recursive: true, force: true });
3185
4360
  var allocate = () => {
3186
- const root = mkdtempSync("/tmp/codelia-runsc-");
4361
+ const root = mkdtempSync2("/tmp/codelia-runsc-");
3187
4362
  try {
3188
4363
  mkdirSync(`${root}/runsc`, { mode: 448 });
3189
4364
  mkdirSync(`${root}/empty-dir`, { mode: 320 });
3190
4365
  writeFileSync(`${root}/empty-file`, "", { flag: "wx", mode: 256 });
3191
4366
  return root;
3192
4367
  } catch (error) {
3193
- release(root);
4368
+ release2(root);
3194
4369
  throw error;
3195
4370
  }
3196
4371
  };
@@ -3213,10 +4388,10 @@ var LinuxRunscBackend = class {
3213
4388
  for (const candidate of ["/usr/local/bin/runsc", "/usr/bin/runsc"]) {
3214
4389
  try {
3215
4390
  const runsc = managedTool(candidate);
3216
- const sidecars = path10.join(path10.dirname(runsc), "gvisor-bin");
3217
- accessSync2(path10.join(sidecars, "gvisor_sentry"), constants4.X_OK);
3218
- for (const executable of readdirSync5(sidecars)) {
3219
- 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));
3220
4395
  }
3221
4396
  this.tools = { setpriv, unshare, runsc };
3222
4397
  return this.tools;
@@ -3243,7 +4418,7 @@ var LinuxRunscBackend = class {
3243
4418
  }
3244
4419
  state = allocate();
3245
4420
  const args = prepare(policy, state, launcher.runsc, launcher.unshare);
3246
- const probe = spawnSync(launcher.setpriv, [...args, "/usr/bin/true"], {
4421
+ const probe = spawnSync2(launcher.setpriv, [...args, "/usr/bin/true"], {
3247
4422
  env: { PATH: "/usr/bin:/bin" },
3248
4423
  stdio: "ignore",
3249
4424
  timeout: 8e3,
@@ -3256,7 +4431,7 @@ var LinuxRunscBackend = class {
3256
4431
  } catch {
3257
4432
  return false;
3258
4433
  } finally {
3259
- if (state) release(state);
4434
+ if (state) release2(state);
3260
4435
  }
3261
4436
  }
3262
4437
  supportsLaunchBinding(candidate) {
@@ -3269,11 +4444,11 @@ var LinuxRunscBackend = class {
3269
4444
  launch(invocation, policy) {
3270
4445
  if (!this.supports(policy)) throw new Error("sandbox_unavailable");
3271
4446
  const state = allocate();
3272
- const cleanup = () => release(state);
4447
+ const cleanup = () => release2(state);
3273
4448
  try {
3274
4449
  const tools = this.resolveTools();
3275
4450
  const args = prepare(policy, state, tools.runsc, tools.unshare);
3276
- const child = spawn2(
4451
+ const child = spawn3(
3277
4452
  tools.setpriv,
3278
4453
  [...args, invocation.executable, ...shellInvocationArgs(invocation)],
3279
4454
  {
@@ -3292,194 +4467,21 @@ var LinuxRunscBackend = class {
3292
4467
  }
3293
4468
  };
3294
4469
 
3295
- // src/permissions/mxc-launcher.ts
3296
- import { spawn as spawn3, spawnSync as spawnSync2 } from "child_process";
3297
- import { lstatSync as lstatSync6, readFileSync as readFileSync4, realpathSync as realpathSync6, statSync as statSync4 } from "fs";
3298
- import path11 from "path";
3299
- import { fileURLToPath } from "url";
3300
- var binaryName = "codelia-mxc-launcher";
3301
- var packagePath = path11.join("node_modules", "@codelia", "tui-darwin-arm64");
3302
- var moduleDir = typeof __dirname === "string" ? __dirname : path11.dirname(fileURLToPath(import.meta.url));
3303
- var packageVersion = (directory, name) => {
3304
- try {
3305
- const manifest = path11.join(directory, "package.json");
3306
- const info = lstatSync6(manifest);
3307
- if (!info.isFile() || info.size > 64 * 1024) return void 0;
3308
- const parsed = JSON.parse(readFileSync4(manifest, "utf8"));
3309
- return parsed.name === name && typeof parsed.version === "string" ? parsed.version : void 0;
3310
- } catch {
3311
- return void 0;
3312
- }
3313
- };
3314
- var directoryId = (info) => `${info.dev}:${info.ino}`;
3315
- var trustedLauncher = (candidate, writableDirs, uid, protectedHome) => {
3316
- try {
3317
- const directory = realpathSync6(path11.dirname(candidate));
3318
- const file = path11.join(directory, binaryName);
3319
- const info = lstatSync6(file, { bigint: true });
3320
- if (!info.isFile() || info.nlink !== 1n || info.size === 0n || info.uid !== uid && info.uid !== 0n || (info.mode & 0o6022n) !== 0n || (info.mode & 0o100n) === 0n)
3321
- return void 0;
3322
- const protectedInHomeDot = protectedHome !== void 0 && isHomeDotTarget(protectedHome, directory);
3323
- let current = directory;
3324
- for (; ; ) {
3325
- const parent = statSync4(current, { bigint: true });
3326
- const systemSticky = parent.uid === 0n && (parent.mode & 0o1000n) !== 0n;
3327
- const isWritableParent = writableDirs.has(directoryId(parent)) && !(protectedInHomeDot && current === protectedHome);
3328
- if (!parent.isDirectory() || isWritableParent || parent.uid !== uid && parent.uid !== 0n || (parent.mode & 0o022n) !== 0n && !systemSticky)
3329
- return void 0;
3330
- const next = path11.dirname(current);
3331
- if (next === current) break;
3332
- current = next;
3333
- }
3334
- return {
3335
- candidate,
3336
- file,
3337
- identity: `${directoryId(info)}:${info.size}:${info.ctimeNs}`
3338
- };
3339
- } catch {
3340
- return void 0;
3341
- }
3342
- };
3343
- var resolveMxcLauncher = (protection) => {
3344
- const uid = process.geteuid?.();
3345
- if (process.platform !== "darwin" || process.arch !== "arm64" || uid === void 0)
3346
- return void 0;
3347
- try {
3348
- const mutable = new Set(
3349
- [protection.root, ...protection.writeRoots].map(
3350
- (root) => directoryId(statSync4(root, { bigint: true }))
3351
- )
3352
- );
3353
- const actualModule = realpathSync6(moduleDir);
3354
- const projectPackage = path11.basename(actualModule) === "permissions" ? path11.resolve(actualModule, "../..") : path11.dirname(actualModule);
3355
- const suffix = path11.join("packages", "runtime");
3356
- if (projectPackage.endsWith(`${path11.sep}${suffix}`)) {
3357
- const checkout = path11.resolve(projectPackage, "../..");
3358
- const built = trustedLauncher(
3359
- path11.join(checkout, "crates/mxc-launcher/target/release", binaryName),
3360
- mutable,
3361
- BigInt(uid)
3362
- );
3363
- if (built) return built;
3364
- }
3365
- const version = packageVersion(projectPackage, "@codelia/runtime");
3366
- if (!version) return void 0;
3367
- let directory = actualModule;
3368
- for (; ; ) {
3369
- const candidatePackage = path11.join(directory, packagePath);
3370
- const installed = packageVersion(candidatePackage, "@codelia/tui-darwin-arm64") === version ? trustedLauncher(
3371
- path11.join(candidatePackage, "bin", binaryName),
3372
- mutable,
3373
- BigInt(uid),
3374
- protection.homeDotDirectory
3375
- ) : void 0;
3376
- if (installed) return installed;
3377
- const parent = path11.dirname(directory);
3378
- if (parent === directory) return void 0;
3379
- directory = parent;
3380
- }
3381
- } catch {
3382
- return void 0;
3383
- }
3384
- };
3385
- var probeMxcLauncher = (launcher) => spawnSync2(launcher.file, ["--probe"], {
3386
- cwd: "/private/tmp",
3387
- env: {},
3388
- stdio: "ignore",
3389
- timeout: 2500,
3390
- killSignal: "SIGKILL"
3391
- }).status === 0;
3392
- var lifecycles = /* @__PURE__ */ new WeakMap();
3393
- var mxcLifecycle = (child) => lifecycles.get(child);
3394
- var launchMxc = (launcher, request, stdin) => {
3395
- const frame = `${JSON.stringify({ version: 1, ...request })}
3396
- `;
3397
- if (Buffer.byteLength(frame) > 256 * 1024)
3398
- throw new Error("sandbox_launch_failed");
3399
- const child = spawn3(launcher.file, ["--run"], {
3400
- cwd: "/private/tmp",
3401
- env: {},
3402
- detached: true,
3403
- stdio: [stdin === "pipe" ? "pipe" : "ignore", "pipe", "pipe", "pipe"]
3404
- });
3405
- const control2 = child.stdio[3];
3406
- let pending = "";
3407
- let accepted = false;
3408
- let failed = false;
3409
- let expectedExit;
3410
- let deadline;
3411
- let reportCompletion;
3412
- const completed = new Promise((resolve) => {
3413
- reportCompletion = resolve;
3414
- });
3415
- const boundCleanup = () => {
3416
- deadline ??= setTimeout(() => {
3417
- reportCompletion("unconfirmed");
3418
- control2.destroy();
3419
- child.stdin?.destroy();
3420
- child.stdout.destroy();
3421
- child.stderr.destroy();
3422
- child.unref();
3423
- }, 8e3);
3424
- };
3425
- const revoke = () => {
3426
- if (!control2.writableEnded && !control2.destroyed) control2.end();
3427
- boundCleanup();
3428
- };
3429
- const rejectReport = () => {
3430
- failed = true;
3431
- revoke();
3432
- };
3433
- control2.setEncoding("utf8");
3434
- control2.on("error", rejectReport);
3435
- control2.on("data", (chunk) => {
3436
- if (failed) return;
3437
- pending += chunk;
3438
- if (pending.length > 256) return rejectReport();
3439
- let newline = pending.indexOf("\n");
3440
- while (newline !== -1) {
3441
- try {
3442
- const value = JSON.parse(pending.slice(0, newline));
3443
- if (expectedExit !== void 0) return rejectReport();
3444
- if (value.event === "started" && !accepted) accepted = true;
3445
- else if (value.event === "cancelled") expectedExit = 143;
3446
- else if (accepted && value.event === "finished" && Number.isInteger(value.exit_code) && value.exit_code >= 0 && value.exit_code <= 255)
3447
- expectedExit = value.exit_code;
3448
- else return rejectReport();
3449
- } catch {
3450
- return rejectReport();
3451
- }
3452
- pending = pending.slice(newline + 1);
3453
- newline = pending.indexOf("\n");
3454
- }
3455
- });
3456
- child.once("exit", boundCleanup);
3457
- child.once("close", (code, signal) => {
3458
- clearTimeout(deadline);
3459
- reportCompletion(
3460
- !failed && pending === "" && signal === null && code === expectedExit ? "clean" : "unconfirmed"
3461
- );
3462
- });
3463
- lifecycles.set(child, { revoke, completed });
3464
- control2.write(frame);
3465
- return child;
3466
- };
3467
-
3468
4470
  // src/permissions/system-bash.ts
3469
4471
  import {
3470
- accessSync as accessSync3,
3471
- constants as constants5,
3472
- lstatSync as lstatSync7,
3473
- readlinkSync as readlinkSync4
4472
+ accessSync as accessSync4,
4473
+ constants as constants6,
4474
+ lstatSync as lstatSync9,
4475
+ readlinkSync as readlinkSync5
3474
4476
  } from "fs";
3475
4477
  import { posix } from "path";
3476
4478
  var conventional = ["/bin/bash", "/usr/bin/bash"];
3477
4479
  var nixSystemBash = "/run/current-system/sw/bin/bash";
3478
4480
  var nixStoreBash = /^\/nix\/store\/[^/]+\/bin\/bash$/u;
3479
4481
  var hostEntries = {
3480
- stat: (name) => lstatSync7(name, { throwIfNoEntry: false }),
3481
- readLink: readlinkSync4,
3482
- 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)
3483
4485
  };
3484
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
3485
4487
  // cannot replace the existing root-owned links and outputs we use.
@@ -3526,23 +4528,23 @@ var resolveSystemBash = (platform = process.platform, entries = hostEntries) =>
3526
4528
  };
3527
4529
 
3528
4530
  // src/permissions/workspace-config-paths.ts
3529
- import { lstatSync as lstatSync8, opendirSync as opendirSync2, readlinkSync as readlinkSync5, realpathSync as realpathSync7 } from "fs";
3530
- 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";
3531
4533
  import { resolveStoragePaths as resolveStoragePaths2 } from "@codelia/storage";
3532
4534
  var confinedAutoLaunchDirectoryName = "confined-auto-launch";
3533
- var isWorkspaceConfigName = (root, target) => resourceContainsPath(path12.dirname(resolveProjectConfigPath(root)), target);
4535
+ var isWorkspaceConfigName = (root, target) => resourceContainsPath(path13.dirname(resolveProjectConfigPath(root)), target);
3534
4536
  var missing2 = (error) => error.code === "ENOENT";
3535
4537
  function resolveConfigTarget(target, remaining = 64) {
3536
4538
  if (!remaining) throw new Error("workspace_config_path_unresolved");
3537
4539
  try {
3538
- return realpathSync7(target);
4540
+ return realpathSync8(target);
3539
4541
  } catch (error) {
3540
- const parent = path12.dirname(target);
4542
+ const parent = path13.dirname(target);
3541
4543
  if (!missing2(error) || parent === target) throw error;
3542
4544
  const canonicalParent = resolveConfigTarget(parent, remaining - 1);
3543
- if (!lstatSync8(target, { throwIfNoEntry: false })?.isSymbolicLink())
3544
- return path12.join(canonicalParent, path12.basename(target));
3545
- const referent = readlinkSync5(target);
4545
+ if (!lstatSync10(target, { throwIfNoEntry: false })?.isSymbolicLink())
4546
+ return path13.join(canonicalParent, path13.basename(target));
4547
+ const referent = readlinkSync6(target);
3546
4548
  let seenName = false;
3547
4549
  for (const part of referent.split(
3548
4550
  process.platform === "win32" ? /[\\/]/u : "/"
@@ -3552,14 +4554,14 @@ function resolveConfigTarget(target, remaining = 64) {
3552
4554
  if (part && part !== "." && part !== "..") seenName = true;
3553
4555
  }
3554
4556
  return resolveConfigTarget(
3555
- path12.resolve(canonicalParent, referent),
4557
+ path13.resolve(canonicalParent, referent),
3556
4558
  remaining - 1
3557
4559
  );
3558
4560
  }
3559
4561
  }
3560
4562
  var workspaceConfigProtection = (root) => {
3561
4563
  const config = resolveProjectConfigPath(root);
3562
- const directory = path12.dirname(config);
4564
+ const directory = path13.dirname(config);
3563
4565
  const readOnlyPaths = /* @__PURE__ */ new Set([directory]);
3564
4566
  const readOnlyAliasPaths = /* @__PURE__ */ new Set();
3565
4567
  const reserveTarget = (file) => {
@@ -3567,12 +4569,12 @@ var workspaceConfigProtection = (root) => {
3567
4569
  readOnlyPaths.add(target);
3568
4570
  readOnlyAliasPaths.add(target);
3569
4571
  };
3570
- if (lstatSync8(directory, { throwIfNoEntry: false })) {
4572
+ if (lstatSync10(directory, { throwIfNoEntry: false })) {
3571
4573
  const canonical = resolveConfigTarget(directory);
3572
4574
  readOnlyPaths.add(canonical);
3573
- if (lstatSync8(canonical, { throwIfNoEntry: false })?.isDirectory()) {
3574
- const file = path12.join(canonical, path12.basename(config));
3575
- 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);
3576
4578
  const storage = resolveStoragePaths2();
3577
4579
  const globalStorage = [
3578
4580
  resolveStoragePaths2({ layout: "home" }).root,
@@ -3580,24 +4582,24 @@ var workspaceConfigProtection = (root) => {
3580
4582
  storage.configDir
3581
4583
  ].some((entry) => {
3582
4584
  try {
3583
- return realpathSync7(entry) === canonical;
4585
+ return realpathSync8(entry) === canonical;
3584
4586
  } catch (error) {
3585
4587
  if (!missing2(error)) throw error;
3586
4588
  return false;
3587
4589
  }
3588
4590
  });
3589
4591
  if (!globalStorage) {
3590
- const worktrees = path12.join(canonical, "worktrees");
4592
+ const worktrees = path13.join(canonical, "worktrees");
3591
4593
  const pending = [canonical];
3592
4594
  for (const current of pending) {
3593
4595
  const children = opendirSync2(current);
3594
4596
  try {
3595
4597
  for (let entry = children.readSync(); entry; entry = children.readSync()) {
3596
- const target = path12.join(current, entry.name);
4598
+ const target = path13.join(current, entry.name);
3597
4599
  if (target === file || target === worktrees) continue;
3598
4600
  if (entry.isSymbolicLink()) reserveTarget(target);
3599
4601
  else if (entry.isDirectory()) pending.push(target);
3600
- else if (entry.isFile() && (lstatSync8(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
4602
+ else if (entry.isFile() && (lstatSync10(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
3601
4603
  readOnlyAliasPaths.add(target);
3602
4604
  }
3603
4605
  } finally {
@@ -3635,11 +4637,11 @@ var platformShellSource = (source) => {
3635
4637
  return fixedBash(source, executable);
3636
4638
  }
3637
4639
  const systemRoot = process.env.SystemRoot;
3638
- if (!systemRoot || !path13.isAbsolute(systemRoot))
4640
+ if (!systemRoot || !path14.isAbsolute(systemRoot))
3639
4641
  throw new Error("windows_system_directory_unavailable");
3640
4642
  return Object.freeze({
3641
4643
  kind: "source",
3642
- executable: path13.join(
4644
+ executable: path14.join(
3643
4645
  systemRoot,
3644
4646
  "System32",
3645
4647
  "WindowsPowerShell",
@@ -3658,27 +4660,27 @@ var platformShellSource = (source) => {
3658
4660
  };
3659
4661
  var realOrLexical = (value) => {
3660
4662
  try {
3661
- return realpathSync8(value);
4663
+ return realpathSync9(value);
3662
4664
  } catch {
3663
- return path13.resolve(value);
4665
+ return path14.resolve(value);
3664
4666
  }
3665
4667
  };
3666
4668
  var resolvePolicyPath = (target) => {
3667
- const absolute = path13.resolve(target);
4669
+ const absolute = path14.resolve(target);
3668
4670
  try {
3669
- return realpathSync8(absolute);
4671
+ return realpathSync9(absolute);
3670
4672
  } catch (error) {
3671
- const parent = path13.dirname(absolute);
4673
+ const parent = path14.dirname(absolute);
3672
4674
  if (error.code !== "ENOENT" || parent === absolute)
3673
4675
  throw error;
3674
- if (lstatSync9(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
4676
+ if (lstatSync11(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
3675
4677
  throw error;
3676
- return path13.join(resolvePolicyPath(parent), path13.basename(absolute));
4678
+ return path14.join(resolvePolicyPath(parent), path14.basename(absolute));
3677
4679
  }
3678
4680
  };
3679
4681
  var canonicalPolicyPaths = (paths) => Object.freeze([
3680
4682
  ...new Set(
3681
- paths.flatMap((entry) => [path13.resolve(entry), resolvePolicyPath(entry)])
4683
+ paths.flatMap((entry) => [path14.resolve(entry), resolvePolicyPath(entry)])
3682
4684
  )
3683
4685
  ]);
3684
4686
  var runtimeReadOnlyPaths = () => {
@@ -3698,12 +4700,12 @@ var runtimeProtectedCredentialPaths = () => {
3698
4700
  mkdirSync2(storage.credentialsDir, { recursive: true, mode: 448 });
3699
4701
  targets.push(storage.credentialsDir);
3700
4702
  } catch {
3701
- if (lstatSync9(storage.credentialsDir, { throwIfNoEntry: false })) {
4703
+ if (lstatSync11(storage.credentialsDir, { throwIfNoEntry: false })) {
3702
4704
  targets.push(storage.credentialsDir);
3703
4705
  }
3704
4706
  }
3705
4707
  for (const legacy of [storage.legacyAuthFile, storage.legacyMcpAuthFile]) {
3706
- if (lstatSync9(legacy, { throwIfNoEntry: false })) {
4708
+ if (lstatSync11(legacy, { throwIfNoEntry: false })) {
3707
4709
  targets.push(legacy);
3708
4710
  }
3709
4711
  }
@@ -3719,8 +4721,8 @@ var runtimeProtectedCredentialPaths = () => {
3719
4721
  var runtimeAuthorityAliasPaths = () => {
3720
4722
  const storage = resolveStoragePaths3();
3721
4723
  const databasePaths = [
3722
- path13.join(storage.configDir, ".projects-policy-lock.sqlite"),
3723
- path13.join(storage.sessionsDir, "state.db")
4724
+ path14.join(storage.configDir, ".projects-policy-lock.sqlite"),
4725
+ path14.join(storage.sessionsDir, "state.db")
3724
4726
  ];
3725
4727
  return canonicalPolicyPaths([
3726
4728
  resolveConfigPath(),
@@ -3730,15 +4732,22 @@ var runtimeAuthorityAliasPaths = () => {
3730
4732
  "launch-approvals",
3731
4733
  "auto-review.json",
3732
4734
  confinedAutoLaunchDirectoryName
3733
- ].map((entry) => path13.join(storage.configDir, entry)),
4735
+ ].map((entry) => path14.join(storage.configDir, entry)),
3734
4736
  ...databasePaths.flatMap(
3735
4737
  (file) => ["", "-wal", "-shm", "-journal"].map((suffix) => `${file}${suffix}`)
3736
4738
  )
3737
4739
  ]);
3738
4740
  };
3739
4741
  var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectories = [], sandboxMode = "workspace-write", allowSharedGitObjects = false, extraReadOnlyPaths = [], homeScope = {}) => {
3740
- const discover = allowSharedGitObjects && sandboxMode === "workspace-write" ? gitMetadataWithObjectDirectories : gitMetadataPaths;
3741
- 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;
3742
4751
  const protectedPaths = canonicalPolicyPaths([
3743
4752
  ...extraProtectedPaths,
3744
4753
  ...runtimeProtectedCredentialPaths()
@@ -3764,14 +4773,23 @@ var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectorie
3764
4773
  const objectDirectoriesWithSharedFiles = objectDirectories.filter(
3765
4774
  (directory) => {
3766
4775
  const overlaps = (other) => resourceContainsPath(other, directory.path) || resourceContainsPath(directory.path, other);
3767
- const commonDirectory = path13.dirname(directory.path);
4776
+ const commonDirectory = path14.dirname(directory.path);
3768
4777
  return !strongerPaths.some(overlaps) && !readOnlyPaths.some(
3769
4778
  (other) => overlaps(other) && realOrLexical(other) !== commonDirectory
3770
4779
  );
3771
4780
  }
3772
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
+ );
3773
4787
  return {
3774
4788
  ...protectedHome ? { homeDotDirectory: protectedHome } : {},
4789
+ ...gitScope && gitScope.releasedPaths.length > 0 ? {
4790
+ ...gitWriteRoots.length ? { gitWriteRoots } : {},
4791
+ gitProtectedPaths: gitScope.readOnlyPaths
4792
+ } : {},
3775
4793
  protectedPaths,
3776
4794
  protectedAliasPaths: protectedPaths,
3777
4795
  readOnlyPaths: Object.freeze(
@@ -3808,26 +4826,48 @@ var protectedSeatbeltAncestors = (base) => {
3808
4826
  ...base.readOnlyPaths ?? [],
3809
4827
  ...base.homeDotDirectory ? [base.homeDotDirectory] : []
3810
4828
  ]) {
3811
- for (let child = protectedPath, parent = path13.dirname(child); parent !== child; child = parent, parent = path13.dirname(child)) {
3812
- 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 }))
3813
4846
  parents.add(parent);
3814
4847
  }
3815
4848
  }
3816
4849
  return [...parents];
3817
4850
  };
3818
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]+$"))`;
3819
4857
  var seatbeltProfile = (base, scratch, mutation) => {
3820
4858
  const deviceAndIpcPaths = ["/dev", "/private/var/run"];
3821
- const ancestors = protectedSeatbeltAncestors({
4859
+ const ancestorList = protectedSeatbeltAncestors({
3822
4860
  ...base,
3823
4861
  protectedPaths: [...base.protectedPaths, ...deviceAndIpcPaths]
3824
- }).map(literal).join(" ");
4862
+ });
4863
+ const ancestors = ancestorList.map(literal).join(" ");
4864
+ const absentAncestors = absentProtectedSeatbeltAncestors(base).map(literal).join(" ");
3825
4865
  const home = base.homeDotDirectory;
3826
- 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")])})` : "";
3827
4867
  const approvedHomeDotRoots = !mutation && home ? base.writeRoots.filter(
3828
4868
  (root) => root !== home && isHomeDotTarget(home, root)
3829
4869
  ) : [];
3830
- const writeTrees = mutation ? [scratch] : [scratch, ...base.writeRoots];
4870
+ const writeTrees = mutation ? [scratch] : [scratch, ...base.writeRoots, ...base.gitWriteRoots ?? []];
3831
4871
  const fixedWriteRules = mutation && [
3832
4872
  mutation.directories.length ? `(allow file-write-create ${mutation.directories.map(literal).join(" ")})` : "",
3833
4873
  mutation.destination ? `(allow file-write-create file-write-data file-write-mode ${literal(mutation.destination)})` : "",
@@ -3847,17 +4887,19 @@ ${fixedWriteRules ?? ""}
3847
4887
  (allow file-read* (literal "/dev/null") (literal "/dev/zero")
3848
4888
  (literal "/dev/random") (literal "/dev/urandom"))
3849
4889
  (allow file-write-data (literal "/dev/null"))
4890
+ ${mutation ? "" : pseudoTerminalRules}
3850
4891
  ${homeRule}
3851
4892
  ${approvedHomeDotRoots.length ? `(allow file-write* ${subpaths(approvedHomeDotRoots)})` : ""}
3852
4893
  ${base.protectedPaths.length ? `(deny file-read* file-write* ${subpaths(base.protectedPaths)})` : ""}
3853
4894
  ${base.readOnlyPaths?.length ? `(deny file-write* ${subpaths(base.readOnlyPaths)})` : ""}
3854
4895
  ${ancestors ? `(deny file-write-unlink ${ancestors})` : ""}
4896
+ ${absentAncestors ? `(deny file-write-create ${absentAncestors})` : ""}
3855
4897
  (deny network*)
3856
4898
  (deny file-write-setugid)
3857
4899
  `;
3858
4900
  };
3859
4901
  var sandboxExec = "/usr/bin/sandbox-exec";
3860
- var macAdditionalWriteLauncherPaths = (protection) => {
4902
+ var mxcAdditionalWriteLauncherPaths = (protection) => {
3861
4903
  const baseline = resolveMxcLauncher({
3862
4904
  ...protection,
3863
4905
  writeRoots: [protection.root],
@@ -3865,11 +4907,12 @@ var macAdditionalWriteLauncherPaths = (protection) => {
3865
4907
  });
3866
4908
  const selected = resolveMxcLauncher(protection);
3867
4909
  return [
3868
- ...new Set(
3869
- [baseline, selected].flatMap(
4910
+ .../* @__PURE__ */ new Set([
4911
+ ...[baseline, selected].flatMap(
3870
4912
  (launcher) => launcher ? [launcher.candidate, launcher.file] : []
3871
- )
3872
- )
4913
+ ),
4914
+ ...linuxMxcManagedToolPaths()
4915
+ ])
3873
4916
  ];
3874
4917
  };
3875
4918
  var MacSeatbeltBackend = class {
@@ -3879,6 +4922,7 @@ var MacSeatbeltBackend = class {
3879
4922
  launcher;
3880
4923
  supportsReadOnlyPaths = true;
3881
4924
  supportsHomeDotProtection = true;
4925
+ supportsAbsentPathDenial = true;
3882
4926
  supportsCommandBinding = true;
3883
4927
  available;
3884
4928
  mxcProbe;
@@ -3895,7 +4939,7 @@ var MacSeatbeltBackend = class {
3895
4939
  return false;
3896
4940
  try {
3897
4941
  if (mutation && (protection.profile !== "development" || protection.stdin !== "pipe" || [...mutation.directories, mutation.destination, mutation.source].some(
3898
- (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(
3899
4943
  (root) => entry !== root && isWithin(root, entry)
3900
4944
  ))
3901
4945
  )))
@@ -3980,12 +5024,12 @@ var MacSeatbeltBackend = class {
3980
5024
  launchWithPolicy(invocation, protection, mutation) {
3981
5025
  if (!(mutation ? this.supportsPolicy(protection, mutation) : this.supports(protection)))
3982
5026
  throw new Error("sandbox_unavailable");
3983
- const scratch = realpathSync8(
3984
- mkdtempSync2(path13.join(os2.tmpdir(), "codelia-shell-"))
5027
+ const scratch = realpathSync9(
5028
+ mkdtempSync3(path14.join(os3.tmpdir(), "codelia-shell-"))
3985
5029
  );
3986
5030
  const cleanup = () => {
3987
5031
  try {
3988
- rmSync2(scratch, { recursive: true, force: true });
5032
+ rmSync3(scratch, { recursive: true, force: true });
3989
5033
  } catch {
3990
5034
  }
3991
5035
  };
@@ -4005,6 +5049,7 @@ var MacSeatbeltBackend = class {
4005
5049
  profile,
4006
5050
  scratch,
4007
5051
  path: shellPathForLaunch(protection.binPaths),
5052
+ home: os3.homedir(),
4008
5053
  cargo_home: protection.toolchainHomes?.CARGO_HOME,
4009
5054
  rustup_home: protection.toolchainHomes?.RUSTUP_HOME
4010
5055
  },
@@ -4021,7 +5066,7 @@ var MacSeatbeltBackend = class {
4021
5066
  env: {
4022
5067
  PATH: shellPathForLaunch(protection.binPaths),
4023
5068
  LANG: "C",
4024
- HOME: scratch,
5069
+ HOME: os3.homedir(),
4025
5070
  TMPDIR: scratch,
4026
5071
  XDG_CACHE_HOME: scratch,
4027
5072
  GIT_OPTIONAL_LOCKS: "0",
@@ -4044,6 +5089,39 @@ var MacSeatbeltBackend = class {
4044
5089
  }
4045
5090
  };
4046
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
+ };
4047
5125
  var UserShellBackend = class {
4048
5126
  supportsCommandBinding = true;
4049
5127
  supports(protection) {
@@ -4057,16 +5135,17 @@ var UserShellBackend = class {
4057
5135
  shell: false,
4058
5136
  windowsHide: true,
4059
5137
  env: {
5138
+ ...loginUserEnvironment(),
4060
5139
  PATH: shellPathForLaunch(protection.binPaths),
4061
- HOME: os2.homedir(),
4062
- TMPDIR: os2.tmpdir(),
5140
+ HOME: os3.homedir(),
5141
+ TMPDIR: os3.tmpdir(),
4063
5142
  LANG: "C",
4064
5143
  ...protection.toolchainHomes,
4065
5144
  ...process.platform === "win32" && {
4066
5145
  SystemRoot: process.env.SystemRoot,
4067
- USERPROFILE: os2.homedir(),
4068
- TEMP: os2.tmpdir(),
4069
- TMP: os2.tmpdir()
5146
+ USERPROFILE: os3.homedir(),
5147
+ TEMP: os3.tmpdir(),
5148
+ TMP: os3.tmpdir()
4070
5149
  }
4071
5150
  },
4072
5151
  stdio: [protection.stdin === "pipe" ? "pipe" : "ignore", "pipe", "pipe"]
@@ -4075,18 +5154,24 @@ var UserShellBackend = class {
4075
5154
  };
4076
5155
  var standardMacBackend;
4077
5156
  var explicitMacMxcBackend;
4078
- var standardLinuxBackend;
5157
+ var standardLinuxMxcBackend;
5158
+ var fallbackLinuxRunscBackend;
4079
5159
  var selectProtectedShellBackend = ({
4080
5160
  platform = process.platform,
4081
5161
  allowStandard,
4082
5162
  adapter,
4083
- macBackend = "seatbelt"
5163
+ macBackend = "seatbelt",
5164
+ linuxBackend = "mxc"
4084
5165
  }) => {
4085
5166
  if (adapter) return adapter;
4086
5167
  if (!allowStandard) return void 0;
4087
5168
  if (platform === "linux") {
4088
- standardLinuxBackend ??= new LinuxRunscBackend();
4089
- return standardLinuxBackend;
5169
+ if (linuxBackend === "gvisor") {
5170
+ fallbackLinuxRunscBackend ??= new LinuxRunscBackend();
5171
+ return fallbackLinuxRunscBackend;
5172
+ }
5173
+ standardLinuxMxcBackend ??= new LinuxMxcBackend();
5174
+ return standardLinuxMxcBackend;
4090
5175
  }
4091
5176
  if (platform === "darwin") {
4092
5177
  if (macBackend === "mxc") {
@@ -4099,7 +5184,7 @@ var selectProtectedShellBackend = ({
4099
5184
  return void 0;
4100
5185
  };
4101
5186
  var directoryIdentity = (directory) => {
4102
- const stat = statSync5(directory, { bigint: true });
5187
+ const stat = statSync6(directory, { bigint: true });
4103
5188
  if (!stat.isDirectory()) throw new Error("invalid_working_directory");
4104
5189
  return `${stat.dev}:${stat.ino}`;
4105
5190
  };
@@ -5037,10 +6122,10 @@ var createRuntimeModel = async ({
5037
6122
 
5038
6123
  // src/runtime-state.ts
5039
6124
  import crypto from "crypto";
5040
- import { realpathSync as realpathSync9 } from "fs";
6125
+ import { realpathSync as realpathSync10 } from "fs";
5041
6126
 
5042
6127
  // src/environment.ts
5043
- import path14 from "path";
6128
+ import path15 from "path";
5044
6129
  import {
5045
6130
  parseSandboxMode
5046
6131
  } from "@codelia/shared-types";
@@ -5053,7 +6138,7 @@ var cloneContract = (contract) => ({
5053
6138
  persistence: { ...contract.persistence },
5054
6139
  events: { ...contract.events }
5055
6140
  });
5056
- 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();
5057
6142
  var runtimeEnvironmentPresets = {
5058
6143
  "tui-local": {
5059
6144
  workspace: {
@@ -5178,11 +6263,11 @@ var resolveRuntimeEnvironment = (options = {}) => {
5178
6263
  if (contract.workspace.sandboxMode !== void 0 && !parseSandboxMode(contract.workspace.sandboxMode))
5179
6264
  throw new Error("Invalid workspace.sandboxMode");
5180
6265
  if (contract.workspace.filesystem === "enabled" || contract.workspace.process === "runtime") {
5181
- contract.workspace.root = path14.resolve(
6266
+ contract.workspace.root = path15.resolve(
5182
6267
  contract.workspace.root ?? defaultWorkspaceRoot()
5183
6268
  );
5184
6269
  } else if (contract.workspace.root) {
5185
- contract.workspace.root = path14.resolve(contract.workspace.root);
6270
+ contract.workspace.root = path15.resolve(contract.workspace.root);
5186
6271
  }
5187
6272
  rejectContract(
5188
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"),
@@ -5422,7 +6507,7 @@ var RuntimeState = class {
5422
6507
  if (scope === "workspace") {
5423
6508
  const root = this.runtimeSandboxRoot ?? this.runtimeWorkingDir;
5424
6509
  return JSON.stringify([
5425
- root === null ? null : realpathSync9(root),
6510
+ root === null ? null : realpathSync10(root),
5426
6511
  this.sandboxMode.value,
5427
6512
  connection,
5428
6513
  authority
@@ -5438,6 +6523,7 @@ var RuntimeState = class {
5438
6523
  authority
5439
6524
  ]);
5440
6525
  }
6526
+ acceptedSteerIds = /* @__PURE__ */ new Map();
5441
6527
  pendingSteersByRun = /* @__PURE__ */ new Map();
5442
6528
  steerClosedRuns = /* @__PURE__ */ new Set();
5443
6529
  uiRequestCounter = 0;
@@ -5572,6 +6658,7 @@ var RuntimeState = class {
5572
6658
  this.lastContextLeftPercent = null;
5573
6659
  this.runSeq.delete(runId);
5574
6660
  this.pendingSteersByRun.delete(runId);
6661
+ this.acceptedSteerIds.delete(runId);
5575
6662
  this.steerClosedRuns.delete(runId);
5576
6663
  if (this.activeRunId === null) {
5577
6664
  this.sessionAppend = null;
@@ -5584,10 +6671,18 @@ var RuntimeState = class {
5584
6671
  canSteerRun(runId) {
5585
6672
  return this.activeRunId === runId && !this.cancelRequested && !this.steerClosedRuns.has(runId);
5586
6673
  }
6674
+ acceptedRunSteerId(runId, clientSteerId) {
6675
+ return this.acceptedSteerIds.get(runId)?.get(clientSteerId);
6676
+ }
5587
6677
  enqueueRunSteer(runId, content, clientSteerId, approvalUserText) {
5588
6678
  this.signalApprovalChange();
5589
6679
  this.runSteerCounter += 1;
5590
6680
  const steerId = `s${this.runSteerCounter}`;
6681
+ if (clientSteerId !== void 0) {
6682
+ const accepted = this.acceptedSteerIds.get(runId) ?? /* @__PURE__ */ new Map();
6683
+ accepted.set(clientSteerId, steerId);
6684
+ this.acceptedSteerIds.set(runId, accepted);
6685
+ }
5591
6686
  if (this.approvalIntent?.runId === runId) {
5592
6687
  this.approvalIntent.steers.push({
5593
6688
  id: steerId,
@@ -5598,7 +6693,7 @@ var RuntimeState = class {
5598
6693
  const queue = this.pendingSteersByRun.get(runId) ?? [];
5599
6694
  queue.push({
5600
6695
  steer_id: steerId,
5601
- ...clientSteerId ? { client_steer_id: clientSteerId } : {},
6696
+ ...clientSteerId !== void 0 ? { client_steer_id: clientSteerId } : {},
5602
6697
  content
5603
6698
  });
5604
6699
  this.pendingSteersByRun.set(runId, queue);
@@ -5722,7 +6817,7 @@ var RuntimeState = class {
5722
6817
  };
5723
6818
 
5724
6819
  // src/subagents/bootstrap.ts
5725
- import path15 from "path";
6820
+ import path16 from "path";
5726
6821
  import { sandboxModes } from "@codelia/shared-types";
5727
6822
  import { z as z3 } from "zod";
5728
6823
 
@@ -5796,8 +6891,8 @@ var subagentBootstrapSchema = z3.object({
5796
6891
  version: z3.literal(1),
5797
6892
  task_id: z3.string().uuid(),
5798
6893
  prompt: z3.string().min(1).max(32768),
5799
- workspace_root: z3.string().refine(path15.isAbsolute),
5800
- 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(),
5801
6896
  lineage: z3.object({
5802
6897
  name: subagentNameSchema.optional(),
5803
6898
  tree_id: z3.string().min(1),
@@ -6719,19 +7814,19 @@ var redactSubagentJson = (value, secrets = []) => JSON.parse(
6719
7814
 
6720
7815
  // src/subagents/read-tools.ts
6721
7816
  import { promises as fs6 } from "fs";
6722
- import path18 from "path";
7817
+ import path19 from "path";
6723
7818
  import { defineTool } from "@codelia/core";
6724
7819
  import { z as z5 } from "zod";
6725
7820
 
6726
7821
  // src/sandbox/context.ts
6727
7822
  import crypto3 from "crypto";
6728
7823
  import {
6729
- constants as constants6,
7824
+ constants as constants7,
6730
7825
  promises as fs4,
6731
- lstatSync as lstatSync10,
6732
- realpathSync as realpathSync10
7826
+ lstatSync as lstatSync12,
7827
+ realpathSync as realpathSync11
6733
7828
  } from "fs";
6734
- import path16 from "path";
7829
+ import path17 from "path";
6735
7830
  var SecurityError = class extends Error {
6736
7831
  constructor(message) {
6737
7832
  super(message);
@@ -6741,22 +7836,22 @@ var SecurityError = class extends Error {
6741
7836
  var identity = (info) => `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
6742
7837
  var directoryIdentity2 = (stat) => `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
6743
7838
  var selectMissingFile = (entry) => {
6744
- let parent = path16.dirname(entry.target);
7839
+ let parent = path17.dirname(entry.target);
6745
7840
  for (; ; ) {
6746
7841
  try {
6747
- const stat = lstatSync10(parent, { bigint: true });
6748
- if (!stat.isDirectory() || realpathSync10(parent) !== parent)
7842
+ const stat = lstatSync12(parent, { bigint: true });
7843
+ if (!stat.isDirectory() || realpathSync11(parent) !== parent)
6749
7844
  throw new SecurityError("Expected a canonical parent directory");
6750
7845
  return Object.freeze({
6751
7846
  ...entry,
6752
7847
  identity: null,
6753
7848
  parent,
6754
7849
  parentIdentity: directoryIdentity2(stat),
6755
- tail: path16.relative(parent, entry.target)
7850
+ tail: path17.relative(parent, entry.target)
6756
7851
  });
6757
7852
  } catch (error) {
6758
7853
  if (error.code !== "ENOENT") throw error;
6759
- const ancestor = path16.dirname(parent);
7854
+ const ancestor = path17.dirname(parent);
6760
7855
  if (ancestor === parent) throw error;
6761
7856
  parent = ancestor;
6762
7857
  }
@@ -6764,15 +7859,15 @@ var selectMissingFile = (entry) => {
6764
7859
  };
6765
7860
  var missingDestinationCurrent = (selection) => {
6766
7861
  try {
6767
- const segments = selection.tail.split(path16.sep);
7862
+ const segments = selection.tail.split(path17.sep);
6768
7863
  if (segments.some(
6769
7864
  (segment) => !segment || segment === "." || segment === ".."
6770
- ) || path16.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
7865
+ ) || path17.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
6771
7866
  return false;
6772
7867
  let current = selection.parent;
6773
7868
  for (const [index, segment] of segments.entries()) {
6774
- current = path16.join(current, segment);
6775
- const stat = lstatSync10(current);
7869
+ current = path17.join(current, segment);
7870
+ const stat = lstatSync12(current);
6776
7871
  if (index === segments.length - 1 || !stat.isDirectory()) return false;
6777
7872
  }
6778
7873
  return false;
@@ -6782,8 +7877,8 @@ var missingDestinationCurrent = (selection) => {
6782
7877
  };
6783
7878
  var directoryBindingCurrent = (selection) => {
6784
7879
  try {
6785
- const stat = lstatSync10(selection.parent, { bigint: true });
6786
- 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;
6787
7882
  } catch {
6788
7883
  return false;
6789
7884
  }
@@ -6817,7 +7912,7 @@ var SandboxContext = class _SandboxContext {
6817
7912
  }
6818
7913
  static async create(rootDir, options = {}) {
6819
7914
  const sessionId = crypto3.randomUUID().slice(0, 8);
6820
- const root = rootDir ? path16.resolve(rootDir) : process.cwd();
7915
+ const root = rootDir ? path17.resolve(rootDir) : process.cwd();
6821
7916
  if (options.sandboxMode !== "readonly")
6822
7917
  await fs4.mkdir(root, { recursive: true });
6823
7918
  const directory = options.protectResources ? await fs4.realpath(root) : root;
@@ -6842,7 +7937,7 @@ var SandboxContext = class _SandboxContext {
6842
7937
  resolvePath(targetPath, access = "write") {
6843
7938
  if (access === "write" && this.sandboxMode === "readonly")
6844
7939
  throw new SecurityError("Sandbox mode is readonly");
6845
- 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);
6846
7941
  if (this.protectedPaths) return this.resolveProtectedPath(resolved, access);
6847
7942
  if (this.approvalMode === "full-access") {
6848
7943
  return resolved;
@@ -6860,12 +7955,12 @@ var SandboxContext = class _SandboxContext {
6860
7955
  selectFile(operand, access, directoryEntry = false) {
6861
7956
  const target = this.resolvePath(operand, access);
6862
7957
  if (directoryEntry) {
6863
- const lexical = path16.resolve(this.workingDir, operand);
6864
- const name = path16.join(
6865
- resolvePolicyPath(path16.dirname(lexical)),
6866
- 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)
6867
7962
  );
6868
- if (target !== name || lstatSync10(name, { throwIfNoEntry: false })?.isSymbolicLink())
7963
+ if (target !== name || lstatSync12(name, { throwIfNoEntry: false })?.isSymbolicLink())
6869
7964
  throw new SecurityError(
6870
7965
  "Patch deletion and move require a regular directory entry without a symbolic link"
6871
7966
  );
@@ -6877,7 +7972,7 @@ var SandboxContext = class _SandboxContext {
6877
7972
  ...directoryEntry ? { directoryEntry: true } : {}
6878
7973
  };
6879
7974
  try {
6880
- const info = lstatSync10(target, { bigint: true });
7975
+ const info = lstatSync12(target, { bigint: true });
6881
7976
  if (!info.isFile())
6882
7977
  throw new SecurityError("Expected a regular file for this operation");
6883
7978
  return Object.freeze({
@@ -6925,7 +8020,7 @@ var SandboxContext = class _SandboxContext {
6925
8020
  error.code = "ENOENT";
6926
8021
  throw error;
6927
8022
  }
6928
- 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);
6929
8024
  const handle = await fs4.open(selected.target, flags);
6930
8025
  try {
6931
8026
  const opened = await handle.stat({ bigint: true });
@@ -7019,7 +8114,7 @@ var SandboxContext = class _SandboxContext {
7019
8114
  writeProtection(target, alias = false) {
7020
8115
  const { readOnlyPaths } = gitMetadataPaths(
7021
8116
  this.rootDir,
7022
- path16.dirname(target)
8117
+ path17.dirname(target)
7023
8118
  );
7024
8119
  const projectConfig = workspaceConfigProtection(this.rootDir);
7025
8120
  return [
@@ -7051,16 +8146,16 @@ var SandboxContext = class _SandboxContext {
7051
8146
  let probe = resolved;
7052
8147
  for (; ; ) {
7053
8148
  try {
7054
- const actual = realpathSync10(probe);
7055
- const target = path16.resolve(actual, path16.relative(probe, resolved));
8149
+ const actual = realpathSync11(probe);
8150
+ const target = path17.resolve(actual, path17.relative(probe, resolved));
7056
8151
  rejectProtected(target);
7057
8152
  if (target !== resolved) rejectWrite(target);
7058
8153
  if (probe === resolved) {
7059
- const stat = lstatSync10(target);
8154
+ const stat = lstatSync12(target);
7060
8155
  if (!stat.isFile() && !stat.isDirectory())
7061
8156
  throw new SecurityError("Unsupported file type");
7062
8157
  if (stat.isFile() && stat.nlink > 1) {
7063
- const inode2 = lstatSync10(target, { bigint: true });
8158
+ const inode2 = lstatSync12(target, { bigint: true });
7064
8159
  if (isProtectedAlias(inode2, protectedPaths))
7065
8160
  throw new SecurityError("Path aliases a protected file");
7066
8161
  if (access === "write" && this.isReadOnlyAlias(inode2, target))
@@ -7070,10 +8165,10 @@ var SandboxContext = class _SandboxContext {
7070
8165
  return target;
7071
8166
  } catch (error) {
7072
8167
  if (error.code !== "ENOENT") throw error;
7073
- const ancestor = path16.dirname(probe);
8168
+ const ancestor = path17.dirname(probe);
7074
8169
  if (ancestor === probe) throw error;
7075
8170
  try {
7076
- if (lstatSync10(probe).isSymbolicLink())
8171
+ if (lstatSync12(probe).isSymbolicLink())
7077
8172
  throw new SecurityError("Path contains a dangling symlink");
7078
8173
  } catch (entryError) {
7079
8174
  if (entryError.code !== "ENOENT")
@@ -7119,8 +8214,8 @@ var appendReadMetadata = (output, content) => `${output}
7119
8214
  [read_metadata] content_sha256=${hashUtf8Content(content)}`;
7120
8215
 
7121
8216
  // src/subagents/workspace-files.ts
7122
- import { constants as constants7, promises as fs5 } from "fs";
7123
- import path17 from "path";
8217
+ import { constants as constants8, promises as fs5 } from "fs";
8218
+ import path18 from "path";
7124
8219
  var MAX_CHILD_FILE_BYTES = 4 * 1024 * 1024;
7125
8220
  var readContent = async (handle) => {
7126
8221
  const buffer = Buffer.alloc(MAX_CHILD_FILE_BYTES + 1);
@@ -7147,15 +8242,15 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7147
8242
  );
7148
8243
  const blocked = (target) => protectedPaths.some((entry) => resourceContainsPath(entry, target));
7149
8244
  const resolve = async (name, allowMissing = false) => {
7150
- const candidate = path17.resolve(root, name);
8245
+ const candidate = path18.resolve(root, name);
7151
8246
  if (blocked(candidate))
7152
8247
  throw new Error("Path is protected by the resource policy");
7153
- const relative = path17.relative(root, candidate);
7154
- 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))
7155
8250
  throw new Error("Path outside delegated workspace");
7156
8251
  let part = root;
7157
- for (const segment of relative.split(path17.sep).filter(Boolean)) {
7158
- part = path17.join(part, segment);
8252
+ for (const segment of relative.split(path18.sep).filter(Boolean)) {
8253
+ part = path18.join(part, segment);
7159
8254
  try {
7160
8255
  if ((await fs5.lstat(part)).isSymbolicLink())
7161
8256
  throw new Error(
@@ -7195,7 +8290,7 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7195
8290
  const file = await resolve(name, expected === "missing");
7196
8291
  const repositoryReadOnly = gitMetadataPaths(
7197
8292
  root,
7198
- path17.dirname(file)
8293
+ path18.dirname(file)
7199
8294
  ).readOnlyPaths;
7200
8295
  const projectConfig = workspaceConfigProtection(root);
7201
8296
  if (homeDotDirectory2 && isHomeWriteReserved(homeDotDirectory2, file) || isWorkspaceConfigName(root, file) || [
@@ -7218,12 +8313,12 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7218
8313
  if (approval && expected === "missing")
7219
8314
  throw new Error("File already exists");
7220
8315
  if (expected === "missing") {
7221
- await fs5.mkdir(path17.dirname(file), { recursive: true });
8316
+ await fs5.mkdir(path18.dirname(file), { recursive: true });
7222
8317
  await resolve(name, true);
7223
8318
  }
7224
8319
  const handle = await fs5.open(
7225
8320
  file,
7226
- expected === "missing" ? "wx" : constants7.O_RDWR | (constants7.O_NOFOLLOW ?? 0)
8321
+ expected === "missing" ? "wx" : constants8.O_RDWR | (constants8.O_NOFOLLOW ?? 0)
7227
8322
  );
7228
8323
  try {
7229
8324
  const stat = await handle.stat({ bigint: true });
@@ -7267,16 +8362,16 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
7267
8362
  };
7268
8363
  const update = async (name, expected, transform, signal, approval) => {
7269
8364
  const previous = pendingUpdate;
7270
- let release2;
8365
+ let release3;
7271
8366
  pendingUpdate = new Promise((done) => {
7272
- release2 = done;
8367
+ release3 = done;
7273
8368
  });
7274
8369
  try {
7275
8370
  await previous;
7276
8371
  signal?.throwIfAborted();
7277
8372
  return await updateFile(name, expected, transform, approval);
7278
8373
  } finally {
7279
- release2();
8374
+ release3();
7280
8375
  }
7281
8376
  };
7282
8377
  return { resolve, read, selectRead, update, blocked };
@@ -7327,17 +8422,17 @@ var createSubagentReadTools = (root, protectedPaths, options = {}) => {
7327
8422
  signal?.throwIfAborted();
7328
8423
  const dir = pending.shift();
7329
8424
  if (!dir) break;
7330
- const entries = await fs6.opendir(await resolve(path18.relative(root2, dir)));
8425
+ const entries = await fs6.opendir(await resolve(path19.relative(root2, dir)));
7331
8426
  for await (const entry of entries) {
7332
8427
  if (entry.isSymbolicLink() || entry.name === ".git" || entry.name === "node_modules")
7333
8428
  continue;
7334
- const child = path18.join(dir, entry.name);
8429
+ const child = path19.join(dir, entry.name);
7335
8430
  if (blocked(child)) continue;
7336
8431
  if (entry.isDirectory()) {
7337
8432
  if (pending.length >= 2e3) return { paths, truncated: true };
7338
8433
  pending.push(child);
7339
8434
  } else if (entry.isFile()) {
7340
- const name = path18.relative(root2, child);
8435
+ const name = path19.relative(root2, child);
7341
8436
  const selected = await selectRead(name, sandbox).catch(
7342
8437
  () => void 0
7343
8438
  );
@@ -7846,6 +8941,7 @@ export {
7846
8941
  resolveMcpServers,
7847
8942
  updateModel,
7848
8943
  updateTuiTheme,
8944
+ normalizeModelLevel,
7849
8945
  resolveReasoningEffort,
7850
8946
  loadSystemPrompt,
7851
8947
  builtinApiKeyBase,
@@ -7855,12 +8951,17 @@ export {
7855
8951
  sendNotificationAsync,
7856
8952
  send,
7857
8953
  sendError,
7858
- sendResult,
7859
8954
  sendAgentEvent,
7860
8955
  sendRunStatus,
7861
8956
  sendRunContext,
7862
8957
  sendRunDiagnostics,
7863
8958
  sendRunMetrics,
8959
+ parseRequestParams,
8960
+ parseUiNotificationParams,
8961
+ sendRequestResult,
8962
+ notificationMessage,
8963
+ requestMessage,
8964
+ parseUiResult,
7864
8965
  requestUiConfirm,
7865
8966
  requestUiPrompt,
7866
8967
  requestUiPick,
@@ -7890,12 +8991,14 @@ export {
7890
8991
  isSimpleAndChain,
7891
8992
  analyzeShell,
7892
8993
  fixedFileMutation,
8994
+ isProtectedAlias,
7893
8995
  shellBinPaths,
7894
8996
  resolveShellExecutable,
7895
8997
  bindBashCommand,
7896
8998
  bindKnownSystemExecutable,
7897
8999
  isRootControlledSharedExecutable,
7898
9000
  areAllExecutableLinksOutsideRestrictedPaths,
9001
+ LinuxMxcBackend,
7899
9002
  resolveSystemBash,
7900
9003
  confinedAutoLaunchDirectoryName,
7901
9004
  supportsProtectedShell,
@@ -7904,9 +9007,10 @@ export {
7904
9007
  canonicalPolicyPaths,
7905
9008
  runtimeReadOnlyPaths,
7906
9009
  workspacePathProtection,
7907
- macAdditionalWriteLauncherPaths,
9010
+ mxcAdditionalWriteLauncherPaths,
7908
9011
  MacSeatbeltBackend,
7909
9012
  createMacMxcShellBackend,
9013
+ createLinuxMxcShellBackend,
7910
9014
  UserShellBackend,
7911
9015
  selectProtectedShellBackend,
7912
9016
  directoryIdentity,