@codelia/runtime 0.1.90 → 0.1.93

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,7 +23,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  ));
24
24
 
25
25
  // src/subagents/child-entry.ts
26
- var import_node_fs20 = require("fs");
26
+ var import_node_fs21 = require("fs");
27
27
 
28
28
  // src/config.ts
29
29
  var import_node_fs = require("fs");
@@ -47,6 +47,37 @@ var resolveConfigPath = () => {
47
47
  return storage.resolvePaths().configFile;
48
48
  };
49
49
  var resolveProjectConfigPath = (workingDir) => import_node_path.default.resolve(workingDir, ".codelia", "config.json");
50
+ var resolveDistinctProjectConfigPath = (workingDir) => {
51
+ if (!workingDir) return null;
52
+ const projectPath = resolveProjectConfigPath(workingDir);
53
+ return (0, import_storage.isSameConfigFilePath)(resolveConfigPath(), projectPath) ? null : projectPath;
54
+ };
55
+ var loadConfigLayers = async (workingDir) => {
56
+ const configPath = resolveConfigPath();
57
+ let globalConfig = null;
58
+ try {
59
+ globalConfig = await (0, import_config_loader.loadConfig)(configPath);
60
+ } catch (error) {
61
+ const message = error instanceof Error ? error.message : String(error);
62
+ throw new Error(`Failed to load config.json: ${message}`);
63
+ }
64
+ let projectConfig = null;
65
+ const projectPath = resolveDistinctProjectConfigPath(workingDir);
66
+ if (projectPath) {
67
+ try {
68
+ projectConfig = await (0, import_config_loader.loadConfig)(projectPath);
69
+ } catch (error) {
70
+ const message = error instanceof Error ? error.message : String(error);
71
+ throw new Error(`Failed to load project config.json: ${message}`);
72
+ }
73
+ }
74
+ return { globalConfig, projectConfig };
75
+ };
76
+ var resolveAuthOAuthBrowser = async (workingDir) => {
77
+ const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
78
+ const effective = import_config.configRegistry.resolve([globalConfig, projectConfig]);
79
+ return effective.auth?.oauth_browser;
80
+ };
50
81
  var normalizeModelLevel = (value) => value.trim().toLowerCase();
51
82
  var resolveReasoningEffort = (value) => {
52
83
  return resolveModelLevelOption(value, "model.reasoning", {
@@ -100,6 +131,7 @@ var serializeMessage = (msg) => ({
100
131
  `,
101
132
  label: describeRpcMessage(msg)
102
133
  });
134
+ var transportBackpressureEvents = 0;
103
135
  var send = (msg) => {
104
136
  const { payload, label } = serializeMessage(msg);
105
137
  const writable = process.stdout.write(payload, (error) => {
@@ -108,6 +140,7 @@ var send = (msg) => {
108
140
  }
109
141
  });
110
142
  if (!writable) {
143
+ transportBackpressureEvents += 1;
111
144
  (0, import_logger.debugLog)(`transport.backpressure label=${label} bytes=${payload.length}`);
112
145
  }
113
146
  };
@@ -126,8 +159,18 @@ var schemaFor = (method, slot) => {
126
159
  throw new Error(`${method} is a notification without a result`);
127
160
  return spec.result;
128
161
  };
162
+ var cachedProtocolAssertRaw;
163
+ var cachedProtocolAssertEnabled = false;
164
+ var isProtocolAssertEnabled = () => {
165
+ const raw = process.env.CODELIA_TEST_PROTOCOL_ASSERT;
166
+ if (raw !== cachedProtocolAssertRaw) {
167
+ cachedProtocolAssertRaw = raw;
168
+ cachedProtocolAssertEnabled = raw === "1";
169
+ }
170
+ return cachedProtocolAssertEnabled;
171
+ };
129
172
  var assertOutgoing = (method, slot, value) => {
130
- if (process.env.CODELIA_PROTOCOL_ASSERT !== "1") return;
173
+ if (!isProtocolAssertEnabled()) return;
131
174
  const result = schemaFor(method, slot).safeParse(value);
132
175
  if (!result.success)
133
176
  throw new Error(
@@ -241,14 +284,14 @@ var readBrowserMode = (value) => {
241
284
  return null;
242
285
  };
243
286
  var hasSshSession = (env) => !!env.SSH_CONNECTION || !!env.SSH_CLIENT || !!env.SSH_TTY;
244
- var resolveOAuthBrowserMode = (env = process.env) => {
245
- const configured = readBrowserMode(env.CODELIA_OAUTH_BROWSER);
287
+ var resolveOAuthBrowserMode = (configuredMode, env = process.env) => {
288
+ const configured = readBrowserMode(configuredMode);
246
289
  if (configured) {
247
290
  return configured;
248
291
  }
249
292
  return hasSshSession(env) ? "manual" : "auto";
250
293
  };
251
- var shouldAutoOpenOAuthBrowser = (env = process.env) => resolveOAuthBrowserMode(env) === "auto";
294
+ var shouldAutoOpenOAuthBrowser = (configuredMode, env = process.env) => resolveOAuthBrowserMode(configuredMode, env) === "auto";
252
295
  var parseCallbackParams = (input) => {
253
296
  const trimmed = input.trim();
254
297
  if (!trimmed) {
@@ -421,7 +464,7 @@ var OPENAI_OAUTH_ORIGINATOR = "codelia";
421
464
  var OPENAI_OAUTH_USER_AGENT = "codelia-cli";
422
465
  var HTML_SUCCESS = "<!doctype html><html><head><title>codelia - Authorization successful</title></head><body><h2>Authorization successful</h2><p>You can close this window.</p></body></html>";
423
466
  var HTML_ERROR = (message) => `<!doctype html><html><head><title>codelia - Authorization failed</title></head><body><h2>Authorization failed</h2><pre>${message}</pre></body></html>`;
424
- var clientId = () => process.env.CODELIA_OPENAI_OAUTH_CLIENT_ID ?? DEFAULT_CLIENT_ID;
467
+ var clientId = () => DEFAULT_CLIENT_ID;
425
468
  var oauthPort = () => readPositiveIntEnv("CODELIA_OPENAI_OAUTH_PORT", DEFAULT_PORT);
426
469
  var buildAuthorizeUrl = (redirectUri, pkce, state) => {
427
470
  const params = new URLSearchParams({
@@ -645,11 +688,8 @@ var DEFAULT_CLIENT_ID2 = "app_EMoamEEZ73f0CkXaXp7hrann";
645
688
  var ISSUER2 = "https://auth.openai.com";
646
689
  var DEFAULT_TIMEOUT_MS = 15 * 60 * 1e3;
647
690
  var DEFAULT_INTERVAL_SECONDS = 5;
648
- var clientId2 = () => process.env.CODELIA_OPENAI_OAUTH_CLIENT_ID ?? DEFAULT_CLIENT_ID2;
649
- var deviceCodeTimeoutMs = () => readPositiveIntEnv(
650
- "CODELIA_OPENAI_DEVICE_CODE_TIMEOUT_MS",
651
- DEFAULT_TIMEOUT_MS
652
- );
691
+ var clientId2 = () => DEFAULT_CLIENT_ID2;
692
+ var deviceCodeTimeoutMs = () => DEFAULT_TIMEOUT_MS;
653
693
  var cancelledError = () => new Error("device code login cancelled");
654
694
  var sleep = (ms, signal) => new Promise((resolve, reject) => {
655
695
  if (signal?.aborted) {
@@ -1318,7 +1358,10 @@ var AuthResolver = class _AuthResolver {
1318
1358
  if (!supportsPick || !supportsPrompt) {
1319
1359
  throw new Error("UI does not support auth prompts");
1320
1360
  }
1321
- const prefersDeviceCode = resolveOAuthBrowserMode() === "manual";
1361
+ const configuredBrowser = await resolveAuthOAuthBrowser(
1362
+ this.state.runtimeWorkingDir ?? void 0
1363
+ ).catch(() => void 0);
1364
+ const prefersDeviceCode = resolveOAuthBrowserMode(configuredBrowser) === "manual";
1322
1365
  const pick = await requestUiPick(this.state, {
1323
1366
  title: "How would you like to connect OpenAI?",
1324
1367
  items: prefersDeviceCode ? [
@@ -1377,7 +1420,10 @@ var AuthResolver = class _AuthResolver {
1377
1420
  throw new Error("UI does not support device code confirmation");
1378
1421
  }
1379
1422
  const session = await createOpenAiDeviceCodeSession();
1380
- const shouldAutoOpen = shouldAutoOpenOAuthBrowser();
1423
+ const configuredBrowser = await resolveAuthOAuthBrowser(
1424
+ this.state.runtimeWorkingDir ?? void 0
1425
+ ).catch(() => void 0);
1426
+ const shouldAutoOpen = shouldAutoOpenOAuthBrowser(configuredBrowser);
1381
1427
  const confirm = await requestUiConfirm(this.state, {
1382
1428
  title: "OpenAI device code",
1383
1429
  message: [
@@ -1420,7 +1466,10 @@ var AuthResolver = class _AuthResolver {
1420
1466
  if (!supportsConfirm) {
1421
1467
  throw new Error("UI does not support OAuth confirmation");
1422
1468
  }
1423
- const shouldAutoOpen = shouldAutoOpenOAuthBrowser();
1469
+ const configuredBrowser = await resolveAuthOAuthBrowser(
1470
+ this.state.runtimeWorkingDir ?? void 0
1471
+ ).catch(() => void 0);
1472
+ const shouldAutoOpen = shouldAutoOpenOAuthBrowser(configuredBrowser);
1424
1473
  const canPasteCallback = !shouldAutoOpen && supportsPrompt;
1425
1474
  const session = await createOAuthSession({
1426
1475
  callbackMode: canPasteCallback ? "paste" : "server"
@@ -1506,6 +1555,7 @@ var AuthResolver = class _AuthResolver {
1506
1555
 
1507
1556
  // src/model-factory.ts
1508
1557
  var import_core6 = require("@codelia/core");
1558
+ var import_logger5 = require("@codelia/logger");
1509
1559
  var import_model_metadata = require("@codelia/model-metadata");
1510
1560
  var import_storage4 = require("@codelia/storage");
1511
1561
 
@@ -2030,17 +2080,12 @@ var requireApiKeyAuth = (provider, auth) => {
2030
2080
  }
2031
2081
  return auth.api_key;
2032
2082
  };
2033
- var envTruthy = (value) => {
2034
- if (!value) return false;
2035
- const normalized = value.trim().toLowerCase();
2036
- return normalized === "1" || normalized === "true";
2037
- };
2038
2083
  var buildOpenAiClientOptions = (getOpenAiAccessToken, auth, log2) => {
2039
2084
  if (auth.method === "api_key") {
2040
2085
  return { apiKey: auth.api_key };
2041
2086
  }
2042
2087
  let accountId = auth.oauth.account_id;
2043
- const enableDebugHttp = envTruthy(process.env.CODELIA_DEBUG);
2088
+ const enableDebugHttp = (0, import_logger5.isDebugEnabled)();
2044
2089
  const apiKey = async () => {
2045
2090
  if (!getOpenAiAccessToken) {
2046
2091
  throw new Error("OpenAI OAuth token refresh is unavailable");
@@ -2630,6 +2675,213 @@ var defaultSandboxMode = Object.freeze({
2630
2675
  source: "fallback"
2631
2676
  });
2632
2677
 
2678
+ // src/telemetry.ts
2679
+ var MAX_RECENT_CALLS = 64;
2680
+ var MAX_RECENT_TOOLS = 64;
2681
+ var cloneModelUsage = (entry) => ({
2682
+ ...entry
2683
+ });
2684
+ var createEmptyTelemetrySummary = () => ({
2685
+ total_calls: 0,
2686
+ total_tokens: 0,
2687
+ total_input_tokens: 0,
2688
+ total_output_tokens: 0,
2689
+ total_output_reasoning_tokens: 0,
2690
+ total_cached_input_tokens: 0,
2691
+ total_cache_creation_tokens: 0,
2692
+ total_input_image_tokens: 0,
2693
+ cache_hit_calls: 0,
2694
+ cache_miss_calls: 0,
2695
+ cache_unknown_calls: 0,
2696
+ total_cost_usd: null,
2697
+ retry_count: 0,
2698
+ retry_wait_ms: 0,
2699
+ tool_calls: 0,
2700
+ tool_errors: 0,
2701
+ tool_exec_ms: 0,
2702
+ tool_approval_wait_ms: 0,
2703
+ compaction_count: 0,
2704
+ compaction_duration_ms: 0,
2705
+ by_model: {}
2706
+ });
2707
+ var cloneTelemetrySummary = (summary) => ({
2708
+ ...summary,
2709
+ by_model: Object.fromEntries(
2710
+ Object.entries(summary.by_model).map(([model, entry]) => [
2711
+ model,
2712
+ cloneModelUsage(entry)
2713
+ ])
2714
+ )
2715
+ });
2716
+ var applyCallToSummary = (summary, call) => {
2717
+ const usage = call.usage ?? null;
2718
+ const inputTokens = usage?.input_tokens ?? 0;
2719
+ const outputTokens = usage?.output_tokens ?? 0;
2720
+ const reasoningTokens = usage?.output_reasoning_tokens ?? 0;
2721
+ const cachedTokens = usage?.input_cached_tokens ?? 0;
2722
+ const cacheCreationTokens = usage?.input_cache_creation_tokens ?? 0;
2723
+ const imageTokens = usage?.input_image_tokens ?? 0;
2724
+ const totalTokens = usage?.total_tokens ?? 0;
2725
+ const hitState = call.cache?.hit_state ?? (typeof usage?.input_cached_tokens === "number" ? cachedTokens > 0 ? "hit" : "miss" : "unknown");
2726
+ const validCost = typeof call.cost_usd === "number" && Number.isFinite(call.cost_usd) && call.cost_usd >= 0 ? call.cost_usd : null;
2727
+ summary.total_calls += 1;
2728
+ summary.total_tokens += totalTokens;
2729
+ summary.total_input_tokens += inputTokens;
2730
+ summary.total_output_tokens += outputTokens;
2731
+ summary.total_output_reasoning_tokens += reasoningTokens;
2732
+ summary.total_cached_input_tokens += cachedTokens;
2733
+ summary.total_cache_creation_tokens += cacheCreationTokens;
2734
+ summary.total_input_image_tokens += imageTokens;
2735
+ if (hitState === "hit") summary.cache_hit_calls += 1;
2736
+ else if (hitState === "miss") summary.cache_miss_calls += 1;
2737
+ else summary.cache_unknown_calls += 1;
2738
+ if (validCost !== null) {
2739
+ summary.total_cost_usd = (summary.total_cost_usd ?? 0) + validCost;
2740
+ }
2741
+ const modelKey = call.model ?? "unknown";
2742
+ const existing = summary.by_model[modelKey];
2743
+ if (!existing) {
2744
+ summary.by_model[modelKey] = {
2745
+ calls: 1,
2746
+ input_tokens: inputTokens,
2747
+ output_tokens: outputTokens,
2748
+ output_reasoning_tokens: reasoningTokens,
2749
+ cached_input_tokens: cachedTokens,
2750
+ cache_creation_tokens: cacheCreationTokens,
2751
+ input_image_tokens: imageTokens,
2752
+ cache_hit_calls: hitState === "hit" ? 1 : 0,
2753
+ cache_miss_calls: hitState === "miss" ? 1 : 0,
2754
+ cache_unknown_calls: hitState === "unknown" ? 1 : 0,
2755
+ total_tokens: totalTokens,
2756
+ cost_usd: validCost
2757
+ };
2758
+ } else {
2759
+ existing.calls += 1;
2760
+ existing.input_tokens += inputTokens;
2761
+ existing.output_tokens += outputTokens;
2762
+ existing.output_reasoning_tokens += reasoningTokens;
2763
+ existing.cached_input_tokens += cachedTokens;
2764
+ existing.cache_creation_tokens += cacheCreationTokens;
2765
+ existing.input_image_tokens += imageTokens;
2766
+ if (hitState === "hit") existing.cache_hit_calls += 1;
2767
+ else if (hitState === "miss") existing.cache_miss_calls += 1;
2768
+ else existing.cache_unknown_calls += 1;
2769
+ existing.total_tokens += totalTokens;
2770
+ if (validCost !== null) {
2771
+ existing.cost_usd = (existing.cost_usd ?? 0) + validCost;
2772
+ }
2773
+ }
2774
+ };
2775
+ var applyToolToSummary = (summary, record) => {
2776
+ summary.tool_calls += 1;
2777
+ if (record.status === "error") {
2778
+ summary.tool_errors += 1;
2779
+ }
2780
+ summary.tool_exec_ms += Math.max(
2781
+ 0,
2782
+ record.exec_duration_ms ?? record.duration_ms
2783
+ );
2784
+ summary.tool_approval_wait_ms += Math.max(0, record.approval_wait_ms ?? 0);
2785
+ };
2786
+ var applyRetryToSummary = (summary, delayMs) => {
2787
+ summary.retry_count += 1;
2788
+ summary.retry_wait_ms += Math.max(0, Math.round(delayMs));
2789
+ };
2790
+ var applyCompactionToSummary = (summary, durationMs) => {
2791
+ summary.compaction_count += 1;
2792
+ summary.compaction_duration_ms += Math.max(0, durationMs);
2793
+ };
2794
+ var RuntimeTelemetryStore = class {
2795
+ sessionSummary = createEmptyTelemetrySummary();
2796
+ currentRunId = null;
2797
+ currentRunSummary = null;
2798
+ recentCalls = [];
2799
+ recentTools = [];
2800
+ startupPhases = [];
2801
+ agentInitPhases = [];
2802
+ resetSession() {
2803
+ this.sessionSummary = createEmptyTelemetrySummary();
2804
+ this.currentRunId = null;
2805
+ this.currentRunSummary = null;
2806
+ this.recentCalls.length = 0;
2807
+ this.recentTools.length = 0;
2808
+ }
2809
+ beginRun(runId) {
2810
+ this.currentRunId = runId;
2811
+ this.currentRunSummary = createEmptyTelemetrySummary();
2812
+ }
2813
+ recordLlmCall(call) {
2814
+ applyCallToSummary(this.sessionSummary, call);
2815
+ if (this.currentRunId === call.run_id && this.currentRunSummary) {
2816
+ applyCallToSummary(this.currentRunSummary, call);
2817
+ }
2818
+ const { session: _session, ...callRecord } = call;
2819
+ this.recentCalls.push(callRecord);
2820
+ if (this.recentCalls.length > MAX_RECENT_CALLS) {
2821
+ this.recentCalls.shift();
2822
+ }
2823
+ }
2824
+ recordToolComplete(record) {
2825
+ applyToolToSummary(this.sessionSummary, record);
2826
+ if (this.currentRunId === record.run_id && this.currentRunSummary) {
2827
+ applyToolToSummary(this.currentRunSummary, record);
2828
+ }
2829
+ this.recentTools.push(record);
2830
+ if (this.recentTools.length > MAX_RECENT_TOOLS) {
2831
+ this.recentTools.shift();
2832
+ }
2833
+ }
2834
+ recordRetry(runId, delayMs) {
2835
+ applyRetryToSummary(this.sessionSummary, delayMs);
2836
+ if (this.currentRunId === runId && this.currentRunSummary) {
2837
+ applyRetryToSummary(this.currentRunSummary, delayMs);
2838
+ }
2839
+ }
2840
+ recordRetryWait(runId, waitMs) {
2841
+ const rounded = Math.max(0, Math.round(waitMs));
2842
+ this.sessionSummary.retry_wait_ms += rounded;
2843
+ if (this.currentRunId === runId && this.currentRunSummary) {
2844
+ this.currentRunSummary.retry_wait_ms += rounded;
2845
+ }
2846
+ }
2847
+ recordCompaction(runId, durationMs) {
2848
+ applyCompactionToSummary(this.sessionSummary, durationMs);
2849
+ if (this.currentRunId === runId && this.currentRunSummary) {
2850
+ applyCompactionToSummary(this.currentRunSummary, durationMs);
2851
+ }
2852
+ }
2853
+ recordStartupPhase(name, durationMs) {
2854
+ this.startupPhases.push({
2855
+ name,
2856
+ duration_ms: Math.max(0, Math.round(durationMs))
2857
+ });
2858
+ }
2859
+ setAgentInitPhases(phases) {
2860
+ this.agentInitPhases = phases.map((phase) => ({
2861
+ name: phase.name,
2862
+ duration_ms: Math.max(0, Math.round(phase.duration_ms))
2863
+ }));
2864
+ }
2865
+ getSessionSummary() {
2866
+ return cloneTelemetrySummary(this.sessionSummary);
2867
+ }
2868
+ getRunSummary() {
2869
+ return this.currentRunSummary ? cloneTelemetrySummary(this.currentRunSummary) : null;
2870
+ }
2871
+ getRecentCalls() {
2872
+ return this.recentCalls.slice();
2873
+ }
2874
+ getRecentTools() {
2875
+ return this.recentTools.slice();
2876
+ }
2877
+ getStartupPhases() {
2878
+ return this.startupPhases.slice();
2879
+ }
2880
+ getAgentInitPhases() {
2881
+ return this.agentInitPhases.slice();
2882
+ }
2883
+ };
2884
+
2633
2885
  // src/runtime-state.ts
2634
2886
  var RuntimeState = class {
2635
2887
  attachments;
@@ -2762,6 +3014,7 @@ var RuntimeState = class {
2762
3014
  set sessionId(value) {
2763
3015
  if (value === this.boundSessionId) return;
2764
3016
  this.boundSessionId = value;
3017
+ this.telemetry.resetSession();
2765
3018
  this.receiptOwner.abort();
2766
3019
  this.receiptOwner = new AbortController();
2767
3020
  this.signalApprovalChange();
@@ -2825,7 +3078,7 @@ var RuntimeState = class {
2825
3078
  currentModelName = null;
2826
3079
  currentModelSource = null;
2827
3080
  sessionModelOverride = null;
2828
- diagnosticsEnabled = false;
3081
+ telemetry = new RuntimeTelemetryStore();
2829
3082
  setRuntimeEnvironment(options) {
2830
3083
  this.effectiveEnvironment = resolveRuntimeEnvironment(options);
2831
3084
  const value = this.effectiveEnvironment.workspace.sandboxMode;
@@ -3220,7 +3473,7 @@ var createChildChannel = (send3) => {
3220
3473
 
3221
3474
  // src/subagents/child-runtime.ts
3222
3475
  var import_node_crypto7 = require("crypto");
3223
- var import_node_fs19 = require("fs");
3476
+ var import_node_fs20 = require("fs");
3224
3477
  var import_core12 = require("@codelia/core");
3225
3478
  var import_storage10 = require("@codelia/storage");
3226
3479
 
@@ -3525,21 +3778,26 @@ var createTaskProgressTracker = (options) => {
3525
3778
  };
3526
3779
 
3527
3780
  // src/subagents/read-tools.ts
3528
- var import_node_fs18 = require("fs");
3529
- var import_node_path19 = __toESM(require("path"), 1);
3781
+ var import_node_fs19 = require("fs");
3782
+ var import_node_path20 = __toESM(require("path"), 1);
3530
3783
  var import_core10 = require("@codelia/core");
3531
3784
  var import_zod7 = require("zod");
3532
3785
 
3533
3786
  // src/sandbox/context.ts
3534
3787
  var import_node_crypto5 = __toESM(require("crypto"), 1);
3535
- var import_node_fs16 = require("fs");
3536
- var import_node_path17 = __toESM(require("path"), 1);
3788
+ var import_node_fs17 = require("fs");
3789
+ var import_node_path18 = __toESM(require("path"), 1);
3537
3790
 
3538
3791
  // src/permissions/git-metadata.ts
3539
3792
  var import_node_fs5 = require("fs");
3793
+ var import_node_os = __toESM(require("os"), 1);
3540
3794
  var import_node_path4 = __toESM(require("path"), 1);
3541
3795
  var isMissing = (error) => error.code === "ENOENT";
3542
3796
  var metadataPathSize = 16 * 1024;
3797
+ var gitConfigMaxBytes = 256 * 1024;
3798
+ var maxSymlinkHops = 64;
3799
+ var maxConfigDepth = 8;
3800
+ var maxConfigFiles = 32;
3543
3801
  var readPointer = (filename, prefix) => {
3544
3802
  const fd = (0, import_node_fs5.openSync)(
3545
3803
  filename,
@@ -3641,6 +3899,7 @@ var eligibleObjectDirectory = (gitDirectory, commonDirectory, marker) => {
3641
3899
  };
3642
3900
  var discoverGitMetadata = (directories, includeObjectDirectories) => {
3643
3901
  const readOnlyPaths = /* @__PURE__ */ new Set();
3902
+ const repositories = [];
3644
3903
  const reservedMarkers = /* @__PURE__ */ new Set();
3645
3904
  const objectDirectories = /* @__PURE__ */ new Map();
3646
3905
  const hookAliases = /* @__PURE__ */ new Map();
@@ -3665,22 +3924,47 @@ var discoverGitMetadata = (directories, includeObjectDirectories) => {
3665
3924
  readOnlyPaths.add(actual);
3666
3925
  return actual;
3667
3926
  };
3927
+ const rootDirectory = directories[0];
3928
+ const verifyLinkedWorktree = (gitDirectory, commonDirectory, actualMarker) => {
3929
+ try {
3930
+ if (gitDirectory === commonDirectory) return false;
3931
+ if (import_node_path4.default.dirname(gitDirectory) !== import_node_path4.default.join(commonDirectory, "worktrees"))
3932
+ return false;
3933
+ const backPointer = readPointer(import_node_path4.default.join(gitDirectory, "gitdir"), "");
3934
+ const resolvedBack = import_node_path4.default.resolve(gitDirectory, backPointer);
3935
+ const backStat = (0, import_node_fs5.lstatSync)(resolvedBack);
3936
+ if (backStat.isSymbolicLink() || !backStat.isFile()) return false;
3937
+ return (0, import_node_fs5.realpathSync)(import_node_path4.default.dirname(resolvedBack)) === import_node_path4.default.dirname(actualMarker) && (0, import_node_fs5.realpathSync)(resolvedBack) === actualMarker;
3938
+ } catch {
3939
+ return false;
3940
+ }
3941
+ };
3668
3942
  for (const directory of new Set(directories)) {
3943
+ const fromRoot = directory === rootDirectory;
3669
3944
  const marker = findMarker(directory);
3670
3945
  const localMarker = import_node_path4.default.join(directory, ".git");
3671
3946
  if (marker !== localMarker) reservedMarkers.add(localMarker);
3672
3947
  if (!marker) continue;
3673
3948
  if (readOnlyPaths.has(marker)) continue;
3949
+ const isWorkspaceRootRepo = fromRoot && marker === localMarker;
3950
+ const markerLstat = (0, import_node_fs5.lstatSync)(marker);
3674
3951
  const actualMarker = (0, import_node_fs5.realpathSync)(marker);
3675
3952
  readOnlyPaths.add(marker);
3676
3953
  readOnlyPaths.add(actualMarker);
3677
3954
  const markerInfo = (0, import_node_fs5.statSync)(actualMarker);
3678
- const gitDirectory = markerInfo.isDirectory() ? actualMarker : addDirectory(
3679
- import_node_path4.default.resolve(
3955
+ const directoryEntries = [];
3956
+ let gitDirectory;
3957
+ if (markerInfo.isDirectory()) {
3958
+ gitDirectory = actualMarker;
3959
+ directoryEntries.push(marker, actualMarker);
3960
+ } else {
3961
+ const location = import_node_path4.default.resolve(
3680
3962
  import_node_path4.default.dirname(marker),
3681
3963
  readPointer(actualMarker, "gitdir: ")
3682
- )
3683
- );
3964
+ );
3965
+ gitDirectory = addDirectory(location);
3966
+ directoryEntries.push(location, gitDirectory);
3967
+ }
3684
3968
  if (!(0, import_node_fs5.statSync)(import_node_path4.default.join(gitDirectory, "HEAD")).isFile())
3685
3969
  throw new Error("invalid_git_metadata_directory");
3686
3970
  const commonPointer = import_node_path4.default.join(gitDirectory, "commondir");
@@ -3690,19 +3974,34 @@ var discoverGitMetadata = (directories, includeObjectDirectories) => {
3690
3974
  } catch (error) {
3691
3975
  if (!isMissing(error)) throw error;
3692
3976
  recordObjects(gitDirectory, gitDirectory, actualMarker);
3977
+ repositories.push({
3978
+ gitDirectory,
3979
+ commonDirectory: gitDirectory,
3980
+ worktreeRoot: import_node_path4.default.dirname(actualMarker),
3981
+ directoryEntries,
3982
+ writable: isWorkspaceRootRepo && markerLstat.isDirectory() && !markerLstat.isSymbolicLink()
3983
+ });
3693
3984
  continue;
3694
3985
  }
3695
3986
  readOnlyPaths.add(commonPointer);
3696
3987
  readOnlyPaths.add(common);
3697
- const commonDirectory = addDirectory(
3698
- import_node_path4.default.resolve(gitDirectory, readPointer(common, ""))
3699
- );
3988
+ const commonLocation = import_node_path4.default.resolve(gitDirectory, readPointer(common, ""));
3989
+ const commonDirectory = addDirectory(commonLocation);
3990
+ directoryEntries.push(commonLocation, commonDirectory);
3700
3991
  if (!(0, import_node_fs5.statSync)(import_node_path4.default.join(commonDirectory, "objects")).isDirectory())
3701
3992
  throw new Error("invalid_git_common_directory");
3702
3993
  recordObjects(gitDirectory, commonDirectory, actualMarker);
3994
+ repositories.push({
3995
+ gitDirectory,
3996
+ commonDirectory,
3997
+ worktreeRoot: import_node_path4.default.dirname(actualMarker),
3998
+ directoryEntries,
3999
+ writable: isWorkspaceRootRepo && markerLstat.isFile() && !markerLstat.isSymbolicLink() && verifyLinkedWorktree(gitDirectory, commonDirectory, actualMarker)
4000
+ });
3703
4001
  }
3704
4002
  return Object.freeze({
3705
4003
  readOnlyPaths: Object.freeze([...readOnlyPaths].sort()),
4004
+ repositories: Object.freeze(repositories),
3706
4005
  reservedMarkers: Object.freeze([...reservedMarkers].sort()),
3707
4006
  objectDirectories: Object.freeze([...objectDirectories.values()]),
3708
4007
  hookAliases: Object.freeze([...hookAliases.values()])
@@ -3717,10 +4016,395 @@ var resolveGitMetadata = (directories, includeObjectDirectories) => {
3717
4016
  };
3718
4017
  var gitMetadataPaths = (...directories) => resolveGitMetadata(directories, false);
3719
4018
  var gitMetadataWithObjectDirectories = (...directories) => resolveGitMetadata(directories, true);
4019
+ var joinPreservingDotDot = (base, target) => {
4020
+ if (import_node_path4.default.isAbsolute(target)) return target;
4021
+ const separator = process.platform === "win32" ? import_node_path4.default.sep : "/";
4022
+ const trimmedBase = base.length > 1 && base.endsWith(separator) ? base.slice(0, -1) : base;
4023
+ return `${trimmedBase}${separator}${target}`;
4024
+ };
4025
+ var traceSymlinkHops = (target) => {
4026
+ const rawAbsolute = import_node_path4.default.isAbsolute(target) ? target : joinPreservingDotDot(process.cwd(), target);
4027
+ const root = import_node_path4.default.parse(rawAbsolute).root;
4028
+ const collected = /* @__PURE__ */ new Set([target, import_node_path4.default.resolve(rawAbsolute)]);
4029
+ let resolvedParts = [];
4030
+ let queue = rawAbsolute.slice(root.length).split(process.platform === "win32" ? /[\\/]/u : "/").filter(Boolean);
4031
+ let hops = 0;
4032
+ while (queue.length > 0) {
4033
+ const part = queue.shift();
4034
+ if (part === ".") continue;
4035
+ if (part === "..") {
4036
+ resolvedParts.pop();
4037
+ continue;
4038
+ }
4039
+ const candidate = import_node_path4.default.join(root, ...resolvedParts, part);
4040
+ const stat = (0, import_node_fs5.lstatSync)(candidate, { throwIfNoEntry: false });
4041
+ if (!stat) {
4042
+ if (queue.some((entry) => entry === ".."))
4043
+ throw new Error("reserved_path_unresolved");
4044
+ resolvedParts.push(part, ...queue.filter((entry) => entry !== "."));
4045
+ queue = [];
4046
+ break;
4047
+ }
4048
+ if (stat.isSymbolicLink()) {
4049
+ if (import_node_path4.default.dirname(candidate) !== root) collected.add(candidate);
4050
+ if (++hops > maxSymlinkHops) throw new Error("symlink_chain_too_deep");
4051
+ const referent = (0, import_node_fs5.readlinkSync)(candidate);
4052
+ const referentParts = referent.split(process.platform === "win32" ? /[\\/]/u : "/").filter(Boolean);
4053
+ if (import_node_path4.default.isAbsolute(referent)) resolvedParts = [];
4054
+ queue = [...referentParts, ...queue];
4055
+ continue;
4056
+ }
4057
+ resolvedParts.push(part);
4058
+ }
4059
+ collected.add(import_node_path4.default.join(root, ...resolvedParts));
4060
+ return [...collected];
4061
+ };
4062
+ var readBoundedTextFile = (filename) => {
4063
+ let fd;
4064
+ try {
4065
+ fd = (0, import_node_fs5.openSync)(filename, import_node_fs5.constants.O_RDONLY | (import_node_fs5.constants.O_NONBLOCK ?? 0));
4066
+ } catch (error) {
4067
+ if (isMissing(error)) return void 0;
4068
+ throw error;
4069
+ }
4070
+ try {
4071
+ const stat = (0, import_node_fs5.fstatSync)(fd);
4072
+ if (!stat.isFile() || stat.size > gitConfigMaxBytes)
4073
+ throw new Error("unreadable_git_config");
4074
+ const bytes = Buffer.alloc(stat.size + 1);
4075
+ const length = (0, import_node_fs5.readSync)(fd, bytes, 0, bytes.length, 0);
4076
+ if (length !== stat.size || length > gitConfigMaxBytes)
4077
+ throw new Error("unreadable_git_config");
4078
+ return new TextDecoder("utf-8", { fatal: true }).decode(
4079
+ bytes.subarray(0, length)
4080
+ );
4081
+ } finally {
4082
+ (0, import_node_fs5.closeSync)(fd);
4083
+ }
4084
+ };
4085
+ var parseGitConfigValue = (raw) => {
4086
+ let result = "";
4087
+ let inQuotes = false;
4088
+ let pendingSpace = "";
4089
+ let i = 0;
4090
+ while (i < raw.length && (raw[i] === " " || raw[i] === " ")) i++;
4091
+ for (; i < raw.length; i++) {
4092
+ const ch = raw[i];
4093
+ if (ch === "\\") {
4094
+ if (i + 1 >= raw.length) {
4095
+ throw new Error("unsupported_git_config_continuation");
4096
+ }
4097
+ const next = raw[++i];
4098
+ if (pendingSpace) {
4099
+ result += pendingSpace;
4100
+ pendingSpace = "";
4101
+ }
4102
+ if (next === "n") result += "\n";
4103
+ else if (next === "t") result += " ";
4104
+ else if (next === "b") result += "\b";
4105
+ else if (next === '"' || next === "\\") result += next;
4106
+ else throw new Error("unsupported_git_config_escape");
4107
+ continue;
4108
+ }
4109
+ if (ch === '"') {
4110
+ if (pendingSpace && !inQuotes) {
4111
+ result += pendingSpace;
4112
+ pendingSpace = "";
4113
+ }
4114
+ inQuotes = !inQuotes;
4115
+ continue;
4116
+ }
4117
+ if (!inQuotes && (ch === "#" || ch === ";")) break;
4118
+ if (!inQuotes && (ch === " " || ch === " ")) {
4119
+ pendingSpace += ch;
4120
+ continue;
4121
+ }
4122
+ if (pendingSpace) {
4123
+ result += pendingSpace;
4124
+ pendingSpace = "";
4125
+ }
4126
+ result += ch;
4127
+ }
4128
+ if (inQuotes) throw new Error("unterminated_git_config_quote");
4129
+ return result;
4130
+ };
4131
+ var parseIrrelevantLineContinuation = (raw, initialInQuotes = false) => {
4132
+ let inQuotes = initialInQuotes;
4133
+ for (let i = 0; i < raw.length; i++) {
4134
+ const ch = raw[i];
4135
+ if (ch === "\\") {
4136
+ if (i + 1 >= raw.length) {
4137
+ return { continues: true, inQuotes };
4138
+ }
4139
+ i++;
4140
+ continue;
4141
+ }
4142
+ if (ch === '"') {
4143
+ inQuotes = !inQuotes;
4144
+ continue;
4145
+ }
4146
+ if (!inQuotes && (ch === "#" || ch === ";")) {
4147
+ return { continues: false, inQuotes: false };
4148
+ }
4149
+ }
4150
+ return { continues: false, inQuotes: false };
4151
+ };
4152
+ var expandGitHome = (value) => {
4153
+ if (value === "~") return import_node_os.default.homedir();
4154
+ if (value.startsWith("~/")) return import_node_path4.default.join(import_node_os.default.homedir(), value.slice(2));
4155
+ return value;
4156
+ };
4157
+ var collectGitConfigProtectedPaths = (configPath, worktreeRoot, seen, depth) => {
4158
+ if (depth > maxConfigDepth || seen.size >= maxConfigFiles)
4159
+ throw new Error("git_config_include_limit");
4160
+ let canonicalConfig = configPath;
4161
+ try {
4162
+ canonicalConfig = (0, import_node_fs5.realpathSync)(configPath);
4163
+ } catch (error) {
4164
+ if (isMissing(error)) return [];
4165
+ throw error;
4166
+ }
4167
+ const openedConfigDir = import_node_path4.default.dirname(configPath);
4168
+ const seenKey = `${openedConfigDir}\0${canonicalConfig}`;
4169
+ if (seen.has(seenKey)) return [];
4170
+ seen.add(seenKey);
4171
+ const content = readBoundedTextFile(canonicalConfig);
4172
+ if (content === void 0) return [];
4173
+ const results = [];
4174
+ const recordReferencedDirective = (directiveSection, rawValue) => {
4175
+ const parsed = parseGitConfigValue(rawValue);
4176
+ if (!parsed) throw new Error("empty_git_config_path");
4177
+ const expanded = expandGitHome(parsed);
4178
+ if (directiveSection === "core") {
4179
+ const bases2 = /* @__PURE__ */ new Set([
4180
+ ...worktreeRoot ? [worktreeRoot] : [],
4181
+ openedConfigDir
4182
+ ]);
4183
+ for (const base of bases2) {
4184
+ results.push({
4185
+ path: import_node_path4.default.isAbsolute(expanded) ? expanded : joinPreservingDotDot(base, expanded),
4186
+ kind: "hooks"
4187
+ });
4188
+ }
4189
+ return;
4190
+ }
4191
+ const target = import_node_path4.default.isAbsolute(expanded) ? expanded : joinPreservingDotDot(openedConfigDir, expanded);
4192
+ results.push({ path: target, kind: "config" });
4193
+ results.push(
4194
+ ...collectGitConfigProtectedPaths(target, worktreeRoot, seen, depth + 1)
4195
+ );
4196
+ };
4197
+ let section = "";
4198
+ let continuingIrrelevantLine = false;
4199
+ let continuingIrrelevantQuotes = false;
4200
+ for (const rawLine of content.split(/\r?\n/u)) {
4201
+ const trimmed = rawLine.trim();
4202
+ if (continuingIrrelevantLine) {
4203
+ const state = parseIrrelevantLineContinuation(
4204
+ rawLine,
4205
+ continuingIrrelevantQuotes
4206
+ );
4207
+ continuingIrrelevantLine = state.continues;
4208
+ continuingIrrelevantQuotes = state.inQuotes;
4209
+ continue;
4210
+ }
4211
+ if (!trimmed || trimmed.startsWith("#") || trimmed.startsWith(";"))
4212
+ continue;
4213
+ if (trimmed.startsWith("[")) {
4214
+ const header = /^\[([A-Za-z0-9-]+)(?:\s+"(?:[^"\\]|\\.)*"|\.[A-Za-z0-9.-]+)?\s*\](.*)$/u.exec(
4215
+ trimmed
4216
+ );
4217
+ if (!header) throw new Error("unsupported_git_config_section");
4218
+ section = header[1].toLowerCase();
4219
+ const rest = header[2].trim();
4220
+ if (!rest || rest.startsWith("#") || rest.startsWith(";")) continue;
4221
+ const eq2 = rest.indexOf("=");
4222
+ if (eq2 < 0) continue;
4223
+ const key2 = rest.slice(0, eq2).trim().toLowerCase();
4224
+ const rawValue2 = rest.slice(eq2 + 1);
4225
+ if ((section === "include" || section === "includeif") && key2 === "path" || section === "core" && key2 === "hookspath") {
4226
+ recordReferencedDirective(section, rawValue2);
4227
+ } else {
4228
+ const state = parseIrrelevantLineContinuation(rawValue2);
4229
+ continuingIrrelevantLine = state.continues;
4230
+ continuingIrrelevantQuotes = state.inQuotes;
4231
+ }
4232
+ continue;
4233
+ }
4234
+ const eq = rawLine.indexOf("=");
4235
+ if (eq < 0) {
4236
+ const bareKey = trimmed.replace(/[#;].*$/u, "").trim().toLowerCase();
4237
+ if ((section === "include" || section === "includeif") && bareKey === "path" || section === "core" && bareKey === "hookspath")
4238
+ throw new Error("empty_git_config_path");
4239
+ continue;
4240
+ }
4241
+ const key = rawLine.slice(0, eq).trim().toLowerCase();
4242
+ const rawValue = rawLine.slice(eq + 1);
4243
+ if ((section === "include" || section === "includeif") && key === "path" || section === "core" && key === "hookspath") {
4244
+ recordReferencedDirective(section, rawValue);
4245
+ } else {
4246
+ const state = parseIrrelevantLineContinuation(rawValue);
4247
+ continuingIrrelevantLine = state.continues;
4248
+ continuingIrrelevantQuotes = state.inQuotes;
4249
+ }
4250
+ }
4251
+ return results;
4252
+ };
4253
+ var externalGitConfigFiles = () => {
4254
+ const files = /* @__PURE__ */ new Set();
4255
+ const home = import_node_os.default.homedir();
4256
+ const xdgConfigHome = process.env.XDG_CONFIG_HOME && import_node_path4.default.isAbsolute(process.env.XDG_CONFIG_HOME) ? process.env.XDG_CONFIG_HOME : import_node_path4.default.join(home, ".config");
4257
+ if (process.env.GIT_CONFIG_GLOBAL) {
4258
+ files.add(process.env.GIT_CONFIG_GLOBAL);
4259
+ } else {
4260
+ files.add(import_node_path4.default.join(home, ".gitconfig"));
4261
+ files.add(import_node_path4.default.join(xdgConfigHome, "git", "config"));
4262
+ }
4263
+ if (process.env.GIT_CONFIG_NOSYSTEM !== "1") {
4264
+ files.add(process.env.GIT_CONFIG_SYSTEM || "/etc/gitconfig");
4265
+ }
4266
+ return [...files];
4267
+ };
4268
+ var gitWriteScope = (repositories) => {
4269
+ const writeRoots = /* @__PURE__ */ new Set();
4270
+ const readOnly = /* @__PURE__ */ new Set();
4271
+ const released = /* @__PURE__ */ new Set();
4272
+ for (const {
4273
+ gitDirectory,
4274
+ commonDirectory,
4275
+ worktreeRoot,
4276
+ directoryEntries,
4277
+ writable
4278
+ } of repositories) {
4279
+ if (!writable) continue;
4280
+ const repoReadOnly = /* @__PURE__ */ new Set();
4281
+ const addProtected = (entry) => {
4282
+ for (const hop of traceSymlinkHops(entry)) repoReadOnly.add(hop);
4283
+ };
4284
+ const protectHooksDirectory = (hooksPath) => {
4285
+ addProtected(hooksPath);
4286
+ let resolvedHooks;
4287
+ try {
4288
+ const real = (0, import_node_fs5.realpathSync)(hooksPath);
4289
+ if ((0, import_node_fs5.statSync)(real).isDirectory()) resolvedHooks = real;
4290
+ } catch (error) {
4291
+ if (!["ENOENT", "ENOTDIR", "ELOOP", "EACCES", "EPERM"].includes(
4292
+ error.code ?? ""
4293
+ ))
4294
+ throw error;
4295
+ }
4296
+ if (resolvedHooks) {
4297
+ for (const entry of (0, import_node_fs5.readdirSync)(resolvedHooks, {
4298
+ withFileTypes: true
4299
+ })) {
4300
+ if (entry.isSymbolicLink())
4301
+ addProtected(import_node_path4.default.join(resolvedHooks, entry.name));
4302
+ }
4303
+ }
4304
+ };
4305
+ try {
4306
+ const objectsDirectory = import_node_path4.default.join(commonDirectory, "objects");
4307
+ const objectsInfo = import_node_path4.default.join(objectsDirectory, "info");
4308
+ const configFiles = [
4309
+ import_node_path4.default.join(commonDirectory, "config"),
4310
+ import_node_path4.default.join(commonDirectory, "config.worktree"),
4311
+ import_node_path4.default.join(gitDirectory, "config.worktree")
4312
+ ];
4313
+ for (const entry of [
4314
+ ...configFiles,
4315
+ import_node_path4.default.join(commonDirectory, "hooks"),
4316
+ import_node_path4.default.join(commonDirectory, "commondir"),
4317
+ import_node_path4.default.join(gitDirectory, "commondir"),
4318
+ import_node_path4.default.join(gitDirectory, "gitdir"),
4319
+ ...gitObjectStoreConfigPaths(objectsDirectory),
4320
+ import_node_path4.default.join(commonDirectory, "remotes"),
4321
+ import_node_path4.default.join(commonDirectory, "branches"),
4322
+ import_node_path4.default.join(commonDirectory, "modules"),
4323
+ // Rebase/sequencer todo files can contain `exec <cmd>` lines that
4324
+ // execute during a later unconfined `git rebase --continue`.
4325
+ import_node_path4.default.join(commonDirectory, "rebase-merge"),
4326
+ import_node_path4.default.join(commonDirectory, "rebase-apply"),
4327
+ import_node_path4.default.join(commonDirectory, "sequencer"),
4328
+ import_node_path4.default.join(gitDirectory, "rebase-merge"),
4329
+ import_node_path4.default.join(gitDirectory, "rebase-apply"),
4330
+ import_node_path4.default.join(gitDirectory, "sequencer")
4331
+ ])
4332
+ addProtected(entry);
4333
+ if ((0, import_node_fs5.lstatSync)(objectsInfo, { throwIfNoEntry: false })?.isSymbolicLink()) {
4334
+ const hops = traceSymlinkHops(objectsInfo);
4335
+ for (const hop of hops) repoReadOnly.add(hop);
4336
+ const targetInfo = hops[hops.length - 1];
4337
+ if (targetInfo) {
4338
+ addProtected(import_node_path4.default.join(targetInfo, "alternates"));
4339
+ addProtected(import_node_path4.default.join(targetInfo, "http-alternates"));
4340
+ }
4341
+ }
4342
+ protectHooksDirectory(import_node_path4.default.join(commonDirectory, "hooks"));
4343
+ const siblingConfigs = [];
4344
+ const worktrees = import_node_path4.default.join(commonDirectory, "worktrees");
4345
+ if ((0, import_node_fs5.lstatSync)(worktrees, { throwIfNoEntry: false })?.isDirectory()) {
4346
+ for (const entry of (0, import_node_fs5.readdirSync)(worktrees, { withFileTypes: true })) {
4347
+ if (!entry.isDirectory()) continue;
4348
+ const siblingDir = import_node_path4.default.join(worktrees, entry.name);
4349
+ for (const name of [
4350
+ "gitdir",
4351
+ "commondir",
4352
+ "config.worktree",
4353
+ "rebase-merge",
4354
+ "rebase-apply",
4355
+ "sequencer"
4356
+ ])
4357
+ addProtected(import_node_path4.default.join(siblingDir, name));
4358
+ let siblingWorktreeRoot;
4359
+ try {
4360
+ const pointer = readPointer(import_node_path4.default.join(siblingDir, "gitdir"), "");
4361
+ siblingWorktreeRoot = import_node_path4.default.dirname(
4362
+ (0, import_node_fs5.realpathSync)(import_node_path4.default.resolve(siblingDir, pointer))
4363
+ );
4364
+ } catch {
4365
+ siblingWorktreeRoot = void 0;
4366
+ }
4367
+ siblingConfigs.push({
4368
+ file: import_node_path4.default.join(siblingDir, "config.worktree"),
4369
+ worktreeRoot: siblingWorktreeRoot
4370
+ });
4371
+ }
4372
+ }
4373
+ const seenConfigs = /* @__PURE__ */ new Set();
4374
+ const configSources = [
4375
+ ...configFiles.map((file) => ({ file, worktreeRoot })),
4376
+ ...siblingConfigs,
4377
+ ...externalGitConfigFiles().map((file) => ({ file, worktreeRoot }))
4378
+ ];
4379
+ for (const source of configSources) {
4380
+ for (const referenced of collectGitConfigProtectedPaths(
4381
+ source.file,
4382
+ source.worktreeRoot,
4383
+ seenConfigs,
4384
+ 0
4385
+ )) {
4386
+ if (referenced.kind === "hooks")
4387
+ protectHooksDirectory(referenced.path);
4388
+ else addProtected(referenced.path);
4389
+ }
4390
+ }
4391
+ writeRoots.add(gitDirectory);
4392
+ writeRoots.add(commonDirectory);
4393
+ for (const entry of directoryEntries) released.add(entry);
4394
+ for (const entry of repoReadOnly) readOnly.add(entry);
4395
+ } catch {
4396
+ }
4397
+ }
4398
+ return Object.freeze({
4399
+ writeRoots: Object.freeze([...writeRoots].sort()),
4400
+ readOnlyPaths: Object.freeze([...readOnly].sort()),
4401
+ releasedPaths: Object.freeze([...released].sort())
4402
+ });
4403
+ };
3720
4404
 
3721
4405
  // src/permissions/home-dot-paths.ts
3722
4406
  var import_node_fs7 = require("fs");
3723
- var import_node_os = __toESM(require("os"), 1);
4407
+ var import_node_os2 = __toESM(require("os"), 1);
3724
4408
  var import_node_path6 = __toESM(require("path"), 1);
3725
4409
 
3726
4410
  // src/permissions/resource-paths.ts
@@ -3810,7 +4494,7 @@ function resolveReservedTarget(target, remaining = 64) {
3810
4494
  }
3811
4495
 
3812
4496
  // src/permissions/home-dot-paths.ts
3813
- var homeDotDirectory = (writeRoots, home = import_node_os.default.homedir()) => {
4497
+ var homeDotDirectory = (writeRoots, home = import_node_os2.default.homedir()) => {
3814
4498
  if (!writeRoots.length) return void 0;
3815
4499
  const canonicalHome = resolveReservedTarget(home);
3816
4500
  return writeRoots.some(
@@ -3868,7 +4552,17 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
3868
4552
  try {
3869
4553
  return (0, import_node_fs8.realpathSync)(entry);
3870
4554
  } catch (error) {
3871
- if (error.code === "ENOENT") return entry;
4555
+ const code = error.code;
4556
+ if (code === "ENOENT") return entry;
4557
+ if (code === "EOPNOTSUPP" || code === "ENXIO") {
4558
+ const info = (0, import_node_fs8.lstatSync)(entry, { throwIfNoEntry: false });
4559
+ if (info && !info.isSymbolicLink()) {
4560
+ return import_node_path7.default.join(
4561
+ (0, import_node_fs8.realpathSync)(import_node_path7.default.dirname(entry)),
4562
+ import_node_path7.default.basename(entry)
4563
+ );
4564
+ }
4565
+ }
3872
4566
  throw error;
3873
4567
  }
3874
4568
  });
@@ -3895,7 +4589,8 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
3895
4589
  throw new Error("protected_alias_index_unavailable");
3896
4590
  try {
3897
4591
  const metadata = (0, import_node_fs8.lstatSync)(file, { bigint: true });
3898
- if (metadata.isFile() && metadata.nlink > 1n) yield inode(metadata);
4592
+ if ((metadata.isFile() || metadata.isSocket() || metadata.isFIFO()) && metadata.nlink > 1n)
4593
+ yield inode(metadata);
3899
4594
  if (metadata.isSymbolicLink() && ignored.size) {
3900
4595
  if (verifiedHook(file)) continue;
3901
4596
  pending.push(...ignored);
@@ -3932,9 +4627,9 @@ var isProtectedAlias = (stat, paths) => stat.nlink > 1n && findProtectedAliases(
3932
4627
 
3933
4628
  // src/permissions/shell-backend.ts
3934
4629
  var import_node_child_process4 = require("child_process");
3935
- var import_node_fs15 = require("fs");
3936
- var import_node_os2 = __toESM(require("os"), 1);
3937
- var import_node_path16 = __toESM(require("path"), 1);
4630
+ var import_node_fs16 = require("fs");
4631
+ var import_node_os5 = __toESM(require("os"), 1);
4632
+ var import_node_path17 = __toESM(require("path"), 1);
3938
4633
  var import_storage9 = require("@codelia/storage");
3939
4634
 
3940
4635
  // src/sandbox/file-mutation-helper.ts
@@ -3947,53 +4642,64 @@ var isWithin = (root, target) => {
3947
4642
  return relative === "" || !import_node_path9.default.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${import_node_path9.default.sep}`);
3948
4643
  };
3949
4644
 
3950
- // src/permissions/linux-shell-backend.ts
3951
- var import_node_child_process2 = require("child_process");
3952
- var import_node_fs11 = require("fs");
3953
- var import_node_path12 = __toESM(require("path"), 1);
4645
+ // src/permissions/linux-mxc-backend.ts
4646
+ var import_node_fs12 = require("fs");
4647
+ var import_node_os3 = require("os");
4648
+ var import_node_path13 = __toESM(require("path"), 1);
3954
4649
 
3955
4650
  // src/permissions/linux-mountinfo.ts
3956
4651
  var import_node_fs9 = require("fs");
3957
4652
  var import_node_path10 = __toESM(require("path"), 1);
3958
4653
 
4654
+ // src/permissions/mxc-launcher.ts
4655
+ var import_node_child_process2 = require("child_process");
4656
+ var import_node_fs10 = require("fs");
4657
+ var import_node_path11 = __toESM(require("path"), 1);
4658
+ var import_node_url = require("url");
4659
+ var import_meta = {};
4660
+ var MAX_MXC_FRAME_BYTES = 256 * 1024;
4661
+ var moduleDir = typeof __dirname === "string" ? __dirname : import_node_path11.default.dirname((0, import_node_url.fileURLToPath)(import_meta.url));
4662
+
3959
4663
  // src/permissions/shell-analysis.ts
3960
4664
  var MAX_SOURCE_BYTES = 32 * 1024;
3961
4665
 
3962
4666
  // src/permissions/shell-path.ts
3963
- var import_node_fs10 = require("fs");
3964
- var import_node_path11 = __toESM(require("path"), 1);
4667
+ var import_node_fs11 = require("fs");
4668
+ var import_node_path12 = __toESM(require("path"), 1);
3965
4669
 
3966
- // src/permissions/mxc-launcher.ts
4670
+ // src/permissions/linux-mxc-backend.ts
4671
+ var virtualRoots = ["/proc", "/dev", "/sys", "/run", "/var/run"];
4672
+ var MAX_FILESYSTEM_SPEC_BYTES = MAX_MXC_FRAME_BYTES - 16 * 1024;
4673
+ var disallowedExtraReadRoots = /* @__PURE__ */ new Set(["/", "/tmp", ...virtualRoots]);
4674
+
4675
+ // src/permissions/linux-shell-backend.ts
3967
4676
  var import_node_child_process3 = require("child_process");
3968
- var import_node_fs12 = require("fs");
3969
- var import_node_path13 = __toESM(require("path"), 1);
3970
- var import_node_url = require("url");
3971
- var import_meta = {};
3972
- var packagePath = import_node_path13.default.join("node_modules", "@codelia", "tui-darwin-arm64");
3973
- var moduleDir = typeof __dirname === "string" ? __dirname : import_node_path13.default.dirname((0, import_node_url.fileURLToPath)(import_meta.url));
4677
+ var import_node_fs13 = require("fs");
4678
+ var import_node_os4 = require("os");
4679
+ var import_node_path14 = __toESM(require("path"), 1);
3974
4680
 
3975
4681
  // src/permissions/system-bash.ts
3976
- var import_node_fs13 = require("fs");
3977
- var import_node_path14 = require("path");
4682
+ var import_node_fs14 = require("fs");
4683
+ var import_node_path15 = require("path");
3978
4684
 
3979
4685
  // src/permissions/workspace-config-paths.ts
3980
- var import_node_fs14 = require("fs");
3981
- var import_node_path15 = __toESM(require("path"), 1);
4686
+ var import_node_fs15 = require("fs");
4687
+ var import_node_path16 = __toESM(require("path"), 1);
3982
4688
  var import_storage8 = require("@codelia/storage");
3983
4689
  var confinedAutoLaunchDirectoryName = "confined-auto-launch";
3984
- var isWorkspaceConfigName = (root, target) => resourceContainsPath(import_node_path15.default.dirname(resolveProjectConfigPath(root)), target);
4690
+ var isWorkspaceConfigName = (root, target) => resourceContainsPath(import_node_path16.default.dirname(resolveProjectConfigPath(root)), target);
3985
4691
  var missing2 = (error) => error.code === "ENOENT";
3986
4692
  function resolveConfigTarget(target, remaining = 64) {
3987
4693
  if (!remaining) throw new Error("workspace_config_path_unresolved");
3988
4694
  try {
3989
- return (0, import_node_fs14.realpathSync)(target);
4695
+ return (0, import_node_fs15.realpathSync)(target);
3990
4696
  } catch (error) {
3991
- const parent = import_node_path15.default.dirname(target);
4697
+ const parent = import_node_path16.default.dirname(target);
3992
4698
  if (!missing2(error) || parent === target) throw error;
3993
4699
  const canonicalParent = resolveConfigTarget(parent, remaining - 1);
3994
- if (!(0, import_node_fs14.lstatSync)(target, { throwIfNoEntry: false })?.isSymbolicLink())
3995
- return import_node_path15.default.join(canonicalParent, import_node_path15.default.basename(target));
3996
- const referent = (0, import_node_fs14.readlinkSync)(target);
4700
+ if (!(0, import_node_fs15.lstatSync)(target, { throwIfNoEntry: false })?.isSymbolicLink())
4701
+ return import_node_path16.default.join(canonicalParent, import_node_path16.default.basename(target));
4702
+ const referent = (0, import_node_fs15.readlinkSync)(target);
3997
4703
  let seenName = false;
3998
4704
  for (const part of referent.split(
3999
4705
  process.platform === "win32" ? /[\\/]/u : "/"
@@ -4003,14 +4709,14 @@ function resolveConfigTarget(target, remaining = 64) {
4003
4709
  if (part && part !== "." && part !== "..") seenName = true;
4004
4710
  }
4005
4711
  return resolveConfigTarget(
4006
- import_node_path15.default.resolve(canonicalParent, referent),
4712
+ import_node_path16.default.resolve(canonicalParent, referent),
4007
4713
  remaining - 1
4008
4714
  );
4009
4715
  }
4010
4716
  }
4011
4717
  var workspaceConfigProtection = (root) => {
4012
4718
  const config = resolveProjectConfigPath(root);
4013
- const directory = import_node_path15.default.dirname(config);
4719
+ const directory = import_node_path16.default.dirname(config);
4014
4720
  const readOnlyPaths = /* @__PURE__ */ new Set([directory]);
4015
4721
  const readOnlyAliasPaths = /* @__PURE__ */ new Set();
4016
4722
  const reserveTarget = (file) => {
@@ -4018,12 +4724,12 @@ var workspaceConfigProtection = (root) => {
4018
4724
  readOnlyPaths.add(target);
4019
4725
  readOnlyAliasPaths.add(target);
4020
4726
  };
4021
- if ((0, import_node_fs14.lstatSync)(directory, { throwIfNoEntry: false })) {
4727
+ if ((0, import_node_fs15.lstatSync)(directory, { throwIfNoEntry: false })) {
4022
4728
  const canonical = resolveConfigTarget(directory);
4023
4729
  readOnlyPaths.add(canonical);
4024
- if ((0, import_node_fs14.lstatSync)(canonical, { throwIfNoEntry: false })?.isDirectory()) {
4025
- const file = import_node_path15.default.join(canonical, import_node_path15.default.basename(config));
4026
- if ((0, import_node_fs14.lstatSync)(file, { throwIfNoEntry: false })) reserveTarget(file);
4730
+ if ((0, import_node_fs15.lstatSync)(canonical, { throwIfNoEntry: false })?.isDirectory()) {
4731
+ const file = import_node_path16.default.join(canonical, import_node_path16.default.basename(config));
4732
+ if ((0, import_node_fs15.lstatSync)(file, { throwIfNoEntry: false })) reserveTarget(file);
4027
4733
  const storage = (0, import_storage8.resolveStoragePaths)();
4028
4734
  const globalStorage = [
4029
4735
  (0, import_storage8.resolveStoragePaths)({ layout: "home" }).root,
@@ -4031,24 +4737,24 @@ var workspaceConfigProtection = (root) => {
4031
4737
  storage.configDir
4032
4738
  ].some((entry) => {
4033
4739
  try {
4034
- return (0, import_node_fs14.realpathSync)(entry) === canonical;
4740
+ return (0, import_node_fs15.realpathSync)(entry) === canonical;
4035
4741
  } catch (error) {
4036
4742
  if (!missing2(error)) throw error;
4037
4743
  return false;
4038
4744
  }
4039
4745
  });
4040
4746
  if (!globalStorage) {
4041
- const worktrees = import_node_path15.default.join(canonical, "worktrees");
4747
+ const worktrees = import_node_path16.default.join(canonical, "worktrees");
4042
4748
  const pending = [canonical];
4043
4749
  for (const current of pending) {
4044
- const children = (0, import_node_fs14.opendirSync)(current);
4750
+ const children = (0, import_node_fs15.opendirSync)(current);
4045
4751
  try {
4046
4752
  for (let entry = children.readSync(); entry; entry = children.readSync()) {
4047
- const target = import_node_path15.default.join(current, entry.name);
4753
+ const target = import_node_path16.default.join(current, entry.name);
4048
4754
  if (target === file || target === worktrees) continue;
4049
4755
  if (entry.isSymbolicLink()) reserveTarget(target);
4050
4756
  else if (entry.isDirectory()) pending.push(target);
4051
- else if (entry.isFile() && ((0, import_node_fs14.lstatSync)(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
4757
+ else if (entry.isFile() && ((0, import_node_fs15.lstatSync)(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
4052
4758
  readOnlyAliasPaths.add(target);
4053
4759
  }
4054
4760
  } finally {
@@ -4067,27 +4773,27 @@ var workspaceConfigProtection = (root) => {
4067
4773
  // src/permissions/shell-backend.ts
4068
4774
  var realOrLexical = (value) => {
4069
4775
  try {
4070
- return (0, import_node_fs15.realpathSync)(value);
4776
+ return (0, import_node_fs16.realpathSync)(value);
4071
4777
  } catch {
4072
- return import_node_path16.default.resolve(value);
4778
+ return import_node_path17.default.resolve(value);
4073
4779
  }
4074
4780
  };
4075
4781
  var resolvePolicyPath = (target) => {
4076
- const absolute = import_node_path16.default.resolve(target);
4782
+ const absolute = import_node_path17.default.resolve(target);
4077
4783
  try {
4078
- return (0, import_node_fs15.realpathSync)(absolute);
4784
+ return (0, import_node_fs16.realpathSync)(absolute);
4079
4785
  } catch (error) {
4080
- const parent = import_node_path16.default.dirname(absolute);
4786
+ const parent = import_node_path17.default.dirname(absolute);
4081
4787
  if (error.code !== "ENOENT" || parent === absolute)
4082
4788
  throw error;
4083
- if ((0, import_node_fs15.lstatSync)(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
4789
+ if ((0, import_node_fs16.lstatSync)(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
4084
4790
  throw error;
4085
- return import_node_path16.default.join(resolvePolicyPath(parent), import_node_path16.default.basename(absolute));
4791
+ return import_node_path17.default.join(resolvePolicyPath(parent), import_node_path17.default.basename(absolute));
4086
4792
  }
4087
4793
  };
4088
4794
  var canonicalPolicyPaths = (paths) => Object.freeze([
4089
4795
  ...new Set(
4090
- paths.flatMap((entry) => [import_node_path16.default.resolve(entry), resolvePolicyPath(entry)])
4796
+ paths.flatMap((entry) => [import_node_path17.default.resolve(entry), resolvePolicyPath(entry)])
4091
4797
  )
4092
4798
  ]);
4093
4799
  var runtimeReadOnlyPaths = () => {
@@ -4104,15 +4810,15 @@ var runtimeProtectedCredentialPaths = () => {
4104
4810
  const targets = [];
4105
4811
  if (process.platform === "linux") {
4106
4812
  try {
4107
- (0, import_node_fs15.mkdirSync)(storage.credentialsDir, { recursive: true, mode: 448 });
4813
+ (0, import_node_fs16.mkdirSync)(storage.credentialsDir, { recursive: true, mode: 448 });
4108
4814
  targets.push(storage.credentialsDir);
4109
4815
  } catch {
4110
- if ((0, import_node_fs15.lstatSync)(storage.credentialsDir, { throwIfNoEntry: false })) {
4816
+ if ((0, import_node_fs16.lstatSync)(storage.credentialsDir, { throwIfNoEntry: false })) {
4111
4817
  targets.push(storage.credentialsDir);
4112
4818
  }
4113
4819
  }
4114
4820
  for (const legacy of [storage.legacyAuthFile, storage.legacyMcpAuthFile]) {
4115
- if ((0, import_node_fs15.lstatSync)(legacy, { throwIfNoEntry: false })) {
4821
+ if ((0, import_node_fs16.lstatSync)(legacy, { throwIfNoEntry: false })) {
4116
4822
  targets.push(legacy);
4117
4823
  }
4118
4824
  }
@@ -4128,8 +4834,8 @@ var runtimeProtectedCredentialPaths = () => {
4128
4834
  var runtimeAuthorityAliasPaths = () => {
4129
4835
  const storage = (0, import_storage9.resolveStoragePaths)();
4130
4836
  const databasePaths = [
4131
- import_node_path16.default.join(storage.configDir, ".projects-policy-lock.sqlite"),
4132
- import_node_path16.default.join(storage.sessionsDir, "state.db")
4837
+ import_node_path17.default.join(storage.configDir, ".projects-policy-lock.sqlite"),
4838
+ import_node_path17.default.join(storage.sessionsDir, "state.db")
4133
4839
  ];
4134
4840
  return canonicalPolicyPaths([
4135
4841
  resolveConfigPath(),
@@ -4139,15 +4845,22 @@ var runtimeAuthorityAliasPaths = () => {
4139
4845
  "launch-approvals",
4140
4846
  "auto-review.json",
4141
4847
  confinedAutoLaunchDirectoryName
4142
- ].map((entry) => import_node_path16.default.join(storage.configDir, entry)),
4848
+ ].map((entry) => import_node_path17.default.join(storage.configDir, entry)),
4143
4849
  ...databasePaths.flatMap(
4144
4850
  (file) => ["", "-wal", "-shm", "-journal"].map((suffix) => `${file}${suffix}`)
4145
4851
  )
4146
4852
  ]);
4147
4853
  };
4148
4854
  var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectories = [], sandboxMode = "workspace-write", allowSharedGitObjects = false, extraReadOnlyPaths = [], homeScope = {}) => {
4149
- const discover = allowSharedGitObjects && sandboxMode === "workspace-write" ? gitMetadataWithObjectDirectories : gitMetadataPaths;
4150
- const { readOnlyPaths, reservedMarkers, objectDirectories, hookAliases } = discover(root, ...relatedDirectories);
4855
+ const discover = allowSharedGitObjects && sandboxMode === "workspace-write" && !homeScope.gitWrites ? gitMetadataWithObjectDirectories : gitMetadataPaths;
4856
+ const metadata = discover(root, ...relatedDirectories);
4857
+ const { reservedMarkers, objectDirectories, hookAliases } = metadata;
4858
+ const gitScope = homeScope.gitWrites ? gitWriteScope(metadata.repositories) : void 0;
4859
+ const released = new Set(gitScope?.releasedPaths ?? []);
4860
+ const readOnlyPaths = gitScope ? [
4861
+ ...metadata.readOnlyPaths.filter((entry) => !released.has(entry)),
4862
+ ...gitScope.readOnlyPaths
4863
+ ] : metadata.readOnlyPaths;
4151
4864
  const protectedPaths = canonicalPolicyPaths([
4152
4865
  ...extraProtectedPaths,
4153
4866
  ...runtimeProtectedCredentialPaths()
@@ -4173,14 +4886,23 @@ var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectorie
4173
4886
  const objectDirectoriesWithSharedFiles = objectDirectories.filter(
4174
4887
  (directory) => {
4175
4888
  const overlaps = (other) => resourceContainsPath(other, directory.path) || resourceContainsPath(directory.path, other);
4176
- const commonDirectory = import_node_path16.default.dirname(directory.path);
4889
+ const commonDirectory = import_node_path17.default.dirname(directory.path);
4177
4890
  return !strongerPaths.some(overlaps) && !readOnlyPaths.some(
4178
4891
  (other) => overlaps(other) && realOrLexical(other) !== commonDirectory
4179
4892
  );
4180
4893
  }
4181
4894
  );
4895
+ const gitWriteRoots = (gitScope?.writeRoots ?? []).filter(
4896
+ (directory) => directory !== import_node_path17.default.parse(directory).root && !(homeScope.writeRoots ?? []).some((root2) => isWithin(root2, directory)) && !strongerPaths.some(
4897
+ (entry) => isWithin(entry, directory) || isWithin(directory, entry)
4898
+ )
4899
+ );
4182
4900
  return {
4183
4901
  ...protectedHome ? { homeDotDirectory: protectedHome } : {},
4902
+ ...gitScope && gitScope.releasedPaths.length > 0 ? {
4903
+ ...gitWriteRoots.length ? { gitWriteRoots } : {},
4904
+ gitProtectedPaths: gitScope.readOnlyPaths
4905
+ } : {},
4184
4906
  protectedPaths,
4185
4907
  protectedAliasPaths: protectedPaths,
4186
4908
  readOnlyPaths: Object.freeze(
@@ -4214,22 +4936,22 @@ var SecurityError = class extends Error {
4214
4936
  var identity = (info) => `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
4215
4937
  var directoryIdentity = (stat) => `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
4216
4938
  var selectMissingFile = (entry) => {
4217
- let parent = import_node_path17.default.dirname(entry.target);
4939
+ let parent = import_node_path18.default.dirname(entry.target);
4218
4940
  for (; ; ) {
4219
4941
  try {
4220
- const stat = (0, import_node_fs16.lstatSync)(parent, { bigint: true });
4221
- if (!stat.isDirectory() || (0, import_node_fs16.realpathSync)(parent) !== parent)
4942
+ const stat = (0, import_node_fs17.lstatSync)(parent, { bigint: true });
4943
+ if (!stat.isDirectory() || (0, import_node_fs17.realpathSync)(parent) !== parent)
4222
4944
  throw new SecurityError("Expected a canonical parent directory");
4223
4945
  return Object.freeze({
4224
4946
  ...entry,
4225
4947
  identity: null,
4226
4948
  parent,
4227
4949
  parentIdentity: directoryIdentity(stat),
4228
- tail: import_node_path17.default.relative(parent, entry.target)
4950
+ tail: import_node_path18.default.relative(parent, entry.target)
4229
4951
  });
4230
4952
  } catch (error) {
4231
4953
  if (error.code !== "ENOENT") throw error;
4232
- const ancestor = import_node_path17.default.dirname(parent);
4954
+ const ancestor = import_node_path18.default.dirname(parent);
4233
4955
  if (ancestor === parent) throw error;
4234
4956
  parent = ancestor;
4235
4957
  }
@@ -4237,15 +4959,15 @@ var selectMissingFile = (entry) => {
4237
4959
  };
4238
4960
  var missingDestinationCurrent = (selection) => {
4239
4961
  try {
4240
- const segments = selection.tail.split(import_node_path17.default.sep);
4962
+ const segments = selection.tail.split(import_node_path18.default.sep);
4241
4963
  if (segments.some(
4242
4964
  (segment) => !segment || segment === "." || segment === ".."
4243
- ) || import_node_path17.default.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
4965
+ ) || import_node_path18.default.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
4244
4966
  return false;
4245
4967
  let current = selection.parent;
4246
4968
  for (const [index, segment] of segments.entries()) {
4247
- current = import_node_path17.default.join(current, segment);
4248
- const stat = (0, import_node_fs16.lstatSync)(current);
4969
+ current = import_node_path18.default.join(current, segment);
4970
+ const stat = (0, import_node_fs17.lstatSync)(current);
4249
4971
  if (index === segments.length - 1 || !stat.isDirectory()) return false;
4250
4972
  }
4251
4973
  return false;
@@ -4255,8 +4977,8 @@ var missingDestinationCurrent = (selection) => {
4255
4977
  };
4256
4978
  var directoryBindingCurrent = (selection) => {
4257
4979
  try {
4258
- const stat = (0, import_node_fs16.lstatSync)(selection.parent, { bigint: true });
4259
- return stat.isDirectory() && directoryIdentity(stat) === selection.parentIdentity && (0, import_node_fs16.realpathSync)(selection.parent) === selection.parent;
4980
+ const stat = (0, import_node_fs17.lstatSync)(selection.parent, { bigint: true });
4981
+ return stat.isDirectory() && directoryIdentity(stat) === selection.parentIdentity && (0, import_node_fs17.realpathSync)(selection.parent) === selection.parent;
4260
4982
  } catch {
4261
4983
  return false;
4262
4984
  }
@@ -4290,10 +5012,10 @@ var SandboxContext = class _SandboxContext {
4290
5012
  }
4291
5013
  static async create(rootDir, options = {}) {
4292
5014
  const sessionId = import_node_crypto5.default.randomUUID().slice(0, 8);
4293
- const root = rootDir ? import_node_path17.default.resolve(rootDir) : process.cwd();
5015
+ const root = rootDir ? import_node_path18.default.resolve(rootDir) : process.cwd();
4294
5016
  if (options.sandboxMode !== "readonly")
4295
- await import_node_fs16.promises.mkdir(root, { recursive: true });
4296
- const directory = options.protectResources ? await import_node_fs16.promises.realpath(root) : root;
5017
+ await import_node_fs17.promises.mkdir(root, { recursive: true });
5018
+ const directory = options.protectResources ? await import_node_fs17.promises.realpath(root) : root;
4297
5019
  return new _SandboxContext({
4298
5020
  rootDir: directory,
4299
5021
  workingDir: directory,
@@ -4315,7 +5037,7 @@ var SandboxContext = class _SandboxContext {
4315
5037
  resolvePath(targetPath, access = "write") {
4316
5038
  if (access === "write" && this.sandboxMode === "readonly")
4317
5039
  throw new SecurityError("Sandbox mode is readonly");
4318
- const resolved = import_node_path17.default.isAbsolute(targetPath) ? import_node_path17.default.resolve(targetPath) : import_node_path17.default.resolve(this.workingDir, targetPath);
5040
+ const resolved = import_node_path18.default.isAbsolute(targetPath) ? import_node_path18.default.resolve(targetPath) : import_node_path18.default.resolve(this.workingDir, targetPath);
4319
5041
  if (this.protectedPaths) return this.resolveProtectedPath(resolved, access);
4320
5042
  if (this.approvalMode === "full-access") {
4321
5043
  return resolved;
@@ -4333,12 +5055,12 @@ var SandboxContext = class _SandboxContext {
4333
5055
  selectFile(operand, access, directoryEntry = false) {
4334
5056
  const target = this.resolvePath(operand, access);
4335
5057
  if (directoryEntry) {
4336
- const lexical = import_node_path17.default.resolve(this.workingDir, operand);
4337
- const name = import_node_path17.default.join(
4338
- resolvePolicyPath(import_node_path17.default.dirname(lexical)),
4339
- import_node_path17.default.basename(lexical)
5058
+ const lexical = import_node_path18.default.resolve(this.workingDir, operand);
5059
+ const name = import_node_path18.default.join(
5060
+ resolvePolicyPath(import_node_path18.default.dirname(lexical)),
5061
+ import_node_path18.default.basename(lexical)
4340
5062
  );
4341
- if (target !== name || (0, import_node_fs16.lstatSync)(name, { throwIfNoEntry: false })?.isSymbolicLink())
5063
+ if (target !== name || (0, import_node_fs17.lstatSync)(name, { throwIfNoEntry: false })?.isSymbolicLink())
4342
5064
  throw new SecurityError(
4343
5065
  "Patch deletion and move require a regular directory entry without a symbolic link"
4344
5066
  );
@@ -4350,7 +5072,7 @@ var SandboxContext = class _SandboxContext {
4350
5072
  ...directoryEntry ? { directoryEntry: true } : {}
4351
5073
  };
4352
5074
  try {
4353
- const info = (0, import_node_fs16.lstatSync)(target, { bigint: true });
5075
+ const info = (0, import_node_fs17.lstatSync)(target, { bigint: true });
4354
5076
  if (!info.isFile())
4355
5077
  throw new SecurityError("Expected a regular file for this operation");
4356
5078
  return Object.freeze({
@@ -4398,8 +5120,8 @@ var SandboxContext = class _SandboxContext {
4398
5120
  error.code = "ENOENT";
4399
5121
  throw error;
4400
5122
  }
4401
- const flags = (mode === "read" ? import_node_fs16.constants.O_RDONLY : import_node_fs16.constants.O_RDWR) | (import_node_fs16.constants.O_NOFOLLOW ?? 0) | (import_node_fs16.constants.O_NONBLOCK ?? 0);
4402
- const handle = await import_node_fs16.promises.open(selected.target, flags);
5123
+ const flags = (mode === "read" ? import_node_fs17.constants.O_RDONLY : import_node_fs17.constants.O_RDWR) | (import_node_fs17.constants.O_NOFOLLOW ?? 0) | (import_node_fs17.constants.O_NONBLOCK ?? 0);
5124
+ const handle = await import_node_fs17.promises.open(selected.target, flags);
4403
5125
  try {
4404
5126
  const opened = await handle.stat({ bigint: true });
4405
5127
  if (!opened.isFile() || identity(opened) !== selected.identity || isProtectedAlias(
@@ -4492,7 +5214,7 @@ var SandboxContext = class _SandboxContext {
4492
5214
  writeProtection(target, alias = false) {
4493
5215
  const { readOnlyPaths } = gitMetadataPaths(
4494
5216
  this.rootDir,
4495
- import_node_path17.default.dirname(target)
5217
+ import_node_path18.default.dirname(target)
4496
5218
  );
4497
5219
  const projectConfig = workspaceConfigProtection(this.rootDir);
4498
5220
  return [
@@ -4524,16 +5246,16 @@ var SandboxContext = class _SandboxContext {
4524
5246
  let probe = resolved;
4525
5247
  for (; ; ) {
4526
5248
  try {
4527
- const actual = (0, import_node_fs16.realpathSync)(probe);
4528
- const target = import_node_path17.default.resolve(actual, import_node_path17.default.relative(probe, resolved));
5249
+ const actual = (0, import_node_fs17.realpathSync)(probe);
5250
+ const target = import_node_path18.default.resolve(actual, import_node_path18.default.relative(probe, resolved));
4529
5251
  rejectProtected(target);
4530
5252
  if (target !== resolved) rejectWrite(target);
4531
5253
  if (probe === resolved) {
4532
- const stat = (0, import_node_fs16.lstatSync)(target);
5254
+ const stat = (0, import_node_fs17.lstatSync)(target);
4533
5255
  if (!stat.isFile() && !stat.isDirectory())
4534
5256
  throw new SecurityError("Unsupported file type");
4535
5257
  if (stat.isFile() && stat.nlink > 1) {
4536
- const inode2 = (0, import_node_fs16.lstatSync)(target, { bigint: true });
5258
+ const inode2 = (0, import_node_fs17.lstatSync)(target, { bigint: true });
4537
5259
  if (isProtectedAlias(inode2, protectedPaths))
4538
5260
  throw new SecurityError("Path aliases a protected file");
4539
5261
  if (access === "write" && this.isReadOnlyAlias(inode2, target))
@@ -4543,10 +5265,10 @@ var SandboxContext = class _SandboxContext {
4543
5265
  return target;
4544
5266
  } catch (error) {
4545
5267
  if (error.code !== "ENOENT") throw error;
4546
- const ancestor = import_node_path17.default.dirname(probe);
5268
+ const ancestor = import_node_path18.default.dirname(probe);
4547
5269
  if (ancestor === probe) throw error;
4548
5270
  try {
4549
- if ((0, import_node_fs16.lstatSync)(probe).isSymbolicLink())
5271
+ if ((0, import_node_fs17.lstatSync)(probe).isSymbolicLink())
4550
5272
  throw new SecurityError("Path contains a dangling symlink");
4551
5273
  } catch (entryError) {
4552
5274
  if (entryError.code !== "ENOENT")
@@ -4574,8 +5296,8 @@ var appendReadMetadata = (output, content) => `${output}
4574
5296
  [read_metadata] content_sha256=${hashUtf8Content(content)}`;
4575
5297
 
4576
5298
  // src/subagents/workspace-files.ts
4577
- var import_node_fs17 = require("fs");
4578
- var import_node_path18 = __toESM(require("path"), 1);
5299
+ var import_node_fs18 = require("fs");
5300
+ var import_node_path19 = __toESM(require("path"), 1);
4579
5301
  var MAX_CHILD_FILE_BYTES = 4 * 1024 * 1024;
4580
5302
  var readContent = async (handle) => {
4581
5303
  const buffer = Buffer.alloc(MAX_CHILD_FILE_BYTES + 1);
@@ -4602,17 +5324,17 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
4602
5324
  );
4603
5325
  const blocked = (target) => protectedPaths.some((entry) => resourceContainsPath(entry, target));
4604
5326
  const resolve = async (name, allowMissing = false) => {
4605
- const candidate = import_node_path18.default.resolve(root, name);
5327
+ const candidate = import_node_path19.default.resolve(root, name);
4606
5328
  if (blocked(candidate))
4607
5329
  throw new Error("Path is protected by the resource policy");
4608
- const relative = import_node_path18.default.relative(root, candidate);
4609
- if (relative === ".." || relative.startsWith(`..${import_node_path18.default.sep}`) || import_node_path18.default.isAbsolute(relative))
5330
+ const relative = import_node_path19.default.relative(root, candidate);
5331
+ if (relative === ".." || relative.startsWith(`..${import_node_path19.default.sep}`) || import_node_path19.default.isAbsolute(relative))
4610
5332
  throw new Error("Path outside delegated workspace");
4611
5333
  let part = root;
4612
- for (const segment of relative.split(import_node_path18.default.sep).filter(Boolean)) {
4613
- part = import_node_path18.default.join(part, segment);
5334
+ for (const segment of relative.split(import_node_path19.default.sep).filter(Boolean)) {
5335
+ part = import_node_path19.default.join(part, segment);
4614
5336
  try {
4615
- if ((await import_node_fs17.promises.lstat(part)).isSymbolicLink())
5337
+ if ((await import_node_fs18.promises.lstat(part)).isSymbolicLink())
4616
5338
  throw new Error(
4617
5339
  "Symbolic links are not available to delegated tools"
4618
5340
  );
@@ -4650,7 +5372,7 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
4650
5372
  const file = await resolve(name, expected === "missing");
4651
5373
  const repositoryReadOnly = gitMetadataPaths(
4652
5374
  root,
4653
- import_node_path18.default.dirname(file)
5375
+ import_node_path19.default.dirname(file)
4654
5376
  ).readOnlyPaths;
4655
5377
  const projectConfig = workspaceConfigProtection(root);
4656
5378
  if (homeDotDirectory2 && isHomeWriteReserved(homeDotDirectory2, file) || isWorkspaceConfigName(root, file) || [
@@ -4668,17 +5390,17 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
4668
5390
  await approval.bound.writeSelectedFile(name, value);
4669
5391
  return hashUtf8Content(value);
4670
5392
  }
4671
- if (approval && (!selection?.identity || selection.target !== await import_node_fs17.promises.realpath(file)))
5393
+ if (approval && (!selection?.identity || selection.target !== await import_node_fs18.promises.realpath(file)))
4672
5394
  throw new Error("File selection changed after approval");
4673
5395
  if (approval && expected === "missing")
4674
5396
  throw new Error("File already exists");
4675
5397
  if (expected === "missing") {
4676
- await import_node_fs17.promises.mkdir(import_node_path18.default.dirname(file), { recursive: true });
5398
+ await import_node_fs18.promises.mkdir(import_node_path19.default.dirname(file), { recursive: true });
4677
5399
  await resolve(name, true);
4678
5400
  }
4679
- const handle = await import_node_fs17.promises.open(
5401
+ const handle = await import_node_fs18.promises.open(
4680
5402
  file,
4681
- expected === "missing" ? "wx" : import_node_fs17.constants.O_RDWR | (import_node_fs17.constants.O_NOFOLLOW ?? 0)
5403
+ expected === "missing" ? "wx" : import_node_fs18.constants.O_RDWR | (import_node_fs18.constants.O_NOFOLLOW ?? 0)
4682
5404
  );
4683
5405
  try {
4684
5406
  const stat = await handle.stat({ bigint: true });
@@ -4754,7 +5476,7 @@ var clipJsonString = (text, limit) => {
4754
5476
  var createSubagentReadTools = (root, protectedPaths, options = {}) => {
4755
5477
  const permits = options.permits ?? (() => true);
4756
5478
  const resolveWorkspace = async () => {
4757
- const sandbox = await SandboxContext.create(await import_node_fs18.promises.realpath(root), {
5479
+ const sandbox = await SandboxContext.create(await import_node_fs19.promises.realpath(root), {
4758
5480
  protectResources: true,
4759
5481
  extraProtectedPaths: protectedPaths
4760
5482
  });
@@ -4782,17 +5504,17 @@ var createSubagentReadTools = (root, protectedPaths, options = {}) => {
4782
5504
  signal?.throwIfAborted();
4783
5505
  const dir = pending.shift();
4784
5506
  if (!dir) break;
4785
- const entries = await import_node_fs18.promises.opendir(await resolve(import_node_path19.default.relative(root2, dir)));
5507
+ const entries = await import_node_fs19.promises.opendir(await resolve(import_node_path20.default.relative(root2, dir)));
4786
5508
  for await (const entry of entries) {
4787
5509
  if (entry.isSymbolicLink() || entry.name === ".git" || entry.name === "node_modules")
4788
5510
  continue;
4789
- const child = import_node_path19.default.join(dir, entry.name);
5511
+ const child = import_node_path20.default.join(dir, entry.name);
4790
5512
  if (blocked(child)) continue;
4791
5513
  if (entry.isDirectory()) {
4792
5514
  if (pending.length >= 2e3) return { paths, truncated: true };
4793
5515
  pending.push(child);
4794
5516
  } else if (entry.isFile()) {
4795
- const name = import_node_path19.default.relative(root2, child);
5517
+ const name = import_node_path20.default.relative(root2, child);
4796
5518
  const selected = await selectRead(name, sandbox).catch(
4797
5519
  () => void 0
4798
5520
  );
@@ -5023,7 +5745,7 @@ var createSubagentWriteTools = (root, channel, protection, protectedPaths) => {
5023
5745
 
5024
5746
  // src/subagents/child-runtime.ts
5025
5747
  var createChildRun = async (input, llm, options = {}) => {
5026
- const workspace = await import_node_fs19.promises.realpath(input.workspace_root);
5748
+ const workspace = await import_node_fs20.promises.realpath(input.workspace_root);
5027
5749
  const session_id = (0, import_node_crypto7.randomUUID)();
5028
5750
  const run_id = (0, import_node_crypto7.randomUUID)();
5029
5751
  const sessions = options.sessions ?? new import_storage10.SessionStateStoreImpl();
@@ -5247,7 +5969,7 @@ var createChildRun = async (input, llm, options = {}) => {
5247
5969
  };
5248
5970
 
5249
5971
  // src/subagents/child-entry.ts
5250
- var bootstrap = (0, import_node_fs20.createReadStream)("", { fd: 3, autoClose: false });
5972
+ var bootstrap = (0, import_node_fs21.createReadStream)("", { fd: 3, autoClose: false });
5251
5973
  bootstrap.setEncoding("utf8");
5252
5974
  var controller = new AbortController();
5253
5975
  var exitTimer;