@codelia/runtime 0.1.86 → 0.1.90

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.
@@ -16,7 +16,11 @@ import {
16
16
  isModelReasoningLevel,
17
17
  MODEL_REASONING_LEVELS
18
18
  } from "@codelia/shared-types";
19
- import { StoragePathServiceImpl } from "@codelia/storage";
19
+ import {
20
+ isSameConfigFilePath,
21
+ isTrustedGlobalConfigLocationSync,
22
+ StoragePathServiceImpl
23
+ } from "@codelia/storage";
20
24
  var DEFAULT_SYSTEM_PROMPT = "You are a coding assistant.";
21
25
  var DEFAULT_MCP_REQUEST_TIMEOUT_MS = 3e4;
22
26
  var DEFAULT_SKILLS_INITIAL_MAX_ENTRIES = 200;
@@ -43,7 +47,13 @@ var resolveConfigPath = () => {
43
47
  const storage = new StoragePathServiceImpl();
44
48
  return storage.resolvePaths().configFile;
45
49
  };
50
+ var SHARED_PROJECT_CONFIG_ERROR = "project config shares the global config file in this workspace; use global scope instead";
46
51
  var resolveProjectConfigPath = (workingDir) => path.resolve(workingDir, ".codelia", "config.json");
52
+ var resolveDistinctProjectConfigPath = (workingDir) => {
53
+ if (!workingDir) return null;
54
+ const projectPath = resolveProjectConfigPath(workingDir);
55
+ return isSameConfigFilePath(resolveConfigPath(), projectPath) ? null : projectPath;
56
+ };
47
57
  var loadConfigLayers = async (workingDir) => {
48
58
  const configPath = resolveConfigPath();
49
59
  let globalConfig = null;
@@ -54,8 +64,8 @@ var loadConfigLayers = async (workingDir) => {
54
64
  throw new Error(`Failed to load config.json: ${message}`);
55
65
  }
56
66
  let projectConfig = null;
57
- if (workingDir) {
58
- const projectPath = resolveProjectConfigPath(workingDir);
67
+ const projectPath = resolveDistinctProjectConfigPath(workingDir);
68
+ if (projectPath) {
59
69
  try {
60
70
  projectConfig = await loadConfig(projectPath);
61
71
  } catch (error) {
@@ -65,6 +75,7 @@ var loadConfigLayers = async (workingDir) => {
65
75
  }
66
76
  return { globalConfig, projectConfig };
67
77
  };
78
+ var resolveConfigLayers = async (workingDir) => loadConfigLayers(workingDir);
68
79
  var resolveImageGenerationConfig = async (workingDir) => {
69
80
  const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
70
81
  return configRegistry.resolve([globalConfig, projectConfig]).image_generation ?? {
@@ -251,6 +262,7 @@ var normalizeMcpTimeoutMs = (value) => {
251
262
  };
252
263
  var resolveMcpServers = async (workingDir) => {
253
264
  const { globalConfig, projectConfig } = await loadConfigLayers(workingDir);
265
+ const globalSource = workingDir && !isTrustedGlobalConfigLocationSync(workingDir, resolveConfigPath()) ? "project" : "global";
254
266
  const globalServers = globalConfig?.mcp?.servers ?? {};
255
267
  const projectServers = projectConfig?.mcp?.servers ?? {};
256
268
  const allIds = /* @__PURE__ */ new Set([
@@ -266,7 +278,7 @@ var resolveMcpServers = async (workingDir) => {
266
278
  resolved.push({
267
279
  ...server,
268
280
  id,
269
- source: project ? "project" : "global",
281
+ source: project ? "project" : globalSource,
270
282
  enabled: server.enabled !== false,
271
283
  request_timeout_ms: normalizeMcpTimeoutMs(server.request_timeout_ms)
272
284
  });
@@ -289,19 +301,19 @@ var hasDefinedGroup = (group, value) => {
289
301
  };
290
302
  var resolveWriteTarget = async (workingDir, group) => {
291
303
  const globalPath = resolveConfigPath();
292
- const projectPath = resolveProjectConfigPath(workingDir);
304
+ const projectPath = resolveDistinctProjectConfigPath(workingDir);
293
305
  const [globalConfig, projectConfig] = await Promise.all([
294
306
  loadConfig(globalPath),
295
- loadConfig(projectPath)
307
+ projectPath ? loadConfig(projectPath) : Promise.resolve(null)
296
308
  ]);
297
- if (hasDefinedGroup(group, projectConfig)) {
309
+ if (projectPath && hasDefinedGroup(group, projectConfig)) {
298
310
  return { scope: "project", path: projectPath };
299
311
  }
300
312
  if (hasDefinedGroup(group, globalConfig)) {
301
313
  return { scope: "global", path: globalPath };
302
314
  }
303
315
  const defaultScope = CONFIG_GROUP_DEFAULT_WRITE_SCOPE[group];
304
- return defaultScope === "project" ? { scope: "project", path: projectPath } : { scope: "global", path: globalPath };
316
+ return defaultScope === "project" && projectPath ? { scope: "project", path: projectPath } : { scope: "global", path: globalPath };
305
317
  };
306
318
  var updateModel = async (workingDir, model) => {
307
319
  const target = await resolveWriteTarget(workingDir, "model");
@@ -313,6 +325,7 @@ var updateTuiTheme = async (workingDir, theme) => {
313
325
  await updateTuiConfig(target.path, { theme });
314
326
  return target;
315
327
  };
328
+ var normalizeModelLevel = (value) => value.trim().toLowerCase();
316
329
  var resolveReasoningEffort = (value) => {
317
330
  return resolveModelLevelOption(value, "model.reasoning", {
318
331
  allowXhigh: true
@@ -325,7 +338,7 @@ var resolveTextVerbosity = (value) => {
325
338
  };
326
339
  function resolveModelLevelOption(value, fieldName, options) {
327
340
  if (!value) return void 0;
328
- const normalized = value.trim().toLowerCase();
341
+ const normalized = normalizeModelLevel(value);
329
342
  if (normalized === "low" || normalized === "medium" || normalized === "high") {
330
343
  return normalized;
331
344
  }
@@ -355,16 +368,20 @@ Working directory: ${workingDir}`;
355
368
 
356
369
  // src/rpc/ui-requests.ts
357
370
  import {
358
- RPC_ERROR_CODE
371
+ RPC_ERROR_CODE as RPC_ERROR_CODE2
359
372
  } from "@codelia/protocol";
360
373
 
361
- // src/rpc/transport.ts
362
- import { AsyncLocalStorage } from "async_hooks";
363
-
364
374
  // src/logger.ts
365
375
  import { debugLog, isDebugEnabled, log } from "@codelia/logger";
366
376
 
377
+ // src/rpc/protocol.ts
378
+ import {
379
+ protocolMethods,
380
+ RPC_ERROR_CODE
381
+ } from "@codelia/protocol";
382
+
367
383
  // src/rpc/transport.ts
384
+ import { AsyncLocalStorage } from "async_hooks";
368
385
  var responseContext = new AsyncLocalStorage();
369
386
  var withRpcResponseContext = (id, callback) => responseContext.run({ id, sent: false }, callback);
370
387
  var hasRpcResponse = (id) => {
@@ -465,65 +482,107 @@ var sendResponse = (response) => {
465
482
  var sendAgentEvent = (state, runId, event) => {
466
483
  if (state.shouldSuppressEvent(runId)) return null;
467
484
  const seq = state.nextSequence(runId);
468
- const notify = {
469
- jsonrpc: "2.0",
470
- method: "agent.event",
471
- params: {
472
- run_id: runId,
473
- seq,
474
- event
475
- }
476
- };
477
- sendNotification(state, notify);
485
+ sendNotification(
486
+ state,
487
+ notificationMessage("agent.event", { run_id: runId, seq, event })
488
+ );
478
489
  return seq;
479
490
  };
480
491
  var sendRunStatus = (state, runId, status, message, error, extras) => {
481
- const notify = {
482
- jsonrpc: "2.0",
483
- method: "run.status",
484
- params: {
485
- run_id: runId,
486
- status,
487
- message,
488
- ...error ? { error } : {},
489
- ...extras?.unconsumed_steer_ids?.length ? { unconsumed_steer_ids: extras.unconsumed_steer_ids } : {}
490
- }
491
- };
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
+ });
492
500
  sendNotification(state, notify);
493
501
  };
494
502
  var sendRunContext = (state, runId, contextLeftPercent) => {
495
- const notify = {
496
- jsonrpc: "2.0",
497
- method: "run.context",
498
- params: {
503
+ sendNotification(
504
+ state,
505
+ notificationMessage("run.context", {
499
506
  run_id: runId,
500
507
  context_left_percent: contextLeftPercent
501
- }
502
- };
503
- sendNotification(state, notify);
508
+ })
509
+ );
504
510
  };
505
511
  var sendRunDiagnostics = (state, params) => {
506
- const notify = {
507
- jsonrpc: "2.0",
508
- method: "run.diagnostics",
509
- params
510
- };
511
- sendNotification(state, notify);
512
+ sendNotification(state, notificationMessage("run.diagnostics", params));
512
513
  };
513
514
  var sendRunMetrics = (state, params) => {
514
- 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) };
515
579
  };
516
580
 
517
581
  // src/rpc/ui-requests.ts
518
582
  var requestUi = async (state, method, params, signal) => {
519
583
  if (signal?.aborted) return null;
520
584
  const id = state.nextUiRequestId();
521
- const request = {
522
- jsonrpc: "2.0",
523
- id,
524
- method,
525
- params
526
- };
585
+ const request = requestMessage(method, id, params);
527
586
  const response = state.waitForUiResponse(id);
528
587
  let sent = false;
529
588
  const abort = () => {
@@ -531,13 +590,12 @@ var requestUi = async (state, method, params, signal) => {
531
590
  jsonrpc: "2.0",
532
591
  id,
533
592
  error: {
534
- code: RPC_ERROR_CODE.RUNTIME_INTERNAL,
593
+ code: RPC_ERROR_CODE2.RUNTIME_INTERNAL,
535
594
  message: "UI request cancelled"
536
595
  }
537
596
  });
538
- if (cancelled && sent && method === "ui.pick.request") {
539
- send({ jsonrpc: "2.0", method: "ui.pick.cancelled", params: { id } });
540
- }
597
+ if (!cancelled || !sent || method !== "ui.pick.request") return;
598
+ send(notificationMessage("ui.pick.cancelled", { id }));
541
599
  };
542
600
  signal?.addEventListener("abort", abort, { once: true });
543
601
  try {
@@ -546,7 +604,12 @@ var requestUi = async (state, method, params, signal) => {
546
604
  send(request);
547
605
  sent = true;
548
606
  }
549
- 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;
550
613
  } catch {
551
614
  return null;
552
615
  } finally {
@@ -778,6 +841,7 @@ var startOAuthCallbackServer = (options) => {
778
841
  // src/auth/openai-oauth.ts
779
842
  import { spawn } from "child_process";
780
843
  import { ProviderFailureError } from "@codelia/core";
844
+ import { DEFAULT_OAUTH_REFRESH_TIMEOUT_MS } from "@codelia/storage";
781
845
  var DEFAULT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
782
846
  var ISSUER = "https://auth.openai.com";
783
847
  var DEFAULT_PORT = 1455;
@@ -804,6 +868,32 @@ var buildAuthorizeUrl = (redirectUri, pkce, state) => {
804
868
  });
805
869
  return `${ISSUER}/oauth/authorize?${params.toString()}`;
806
870
  };
871
+ var withSignalAbort = (promise, signal) => {
872
+ if (!signal) return promise;
873
+ if (signal.aborted) {
874
+ return Promise.reject(
875
+ signal.reason instanceof Error ? signal.reason : new Error("Request aborted")
876
+ );
877
+ }
878
+ return new Promise((resolve, reject) => {
879
+ const onAbort = () => {
880
+ reject(
881
+ signal.reason instanceof Error ? signal.reason : new Error("Request aborted")
882
+ );
883
+ };
884
+ signal.addEventListener("abort", onAbort, { once: true });
885
+ promise.then(
886
+ (value) => {
887
+ signal.removeEventListener("abort", onAbort);
888
+ resolve(value);
889
+ },
890
+ (error) => {
891
+ signal.removeEventListener("abort", onAbort);
892
+ reject(error);
893
+ }
894
+ );
895
+ });
896
+ };
807
897
  var requestToken = async (params, operation, signal) => {
808
898
  const response = await fetch(`${ISSUER}/oauth/token`, {
809
899
  method: "POST",
@@ -813,9 +903,9 @@ var requestToken = async (params, operation, signal) => {
813
903
  body: new URLSearchParams(params).toString()
814
904
  });
815
905
  if (!response.ok) {
816
- throw await tokenFailure(response, operation);
906
+ throw await withSignalAbort(tokenFailure(response, operation), signal);
817
907
  }
818
- return response.json();
908
+ return withSignalAbort(response.json(), signal);
819
909
  };
820
910
  var oauthReasons = {
821
911
  refresh_token_reused: "The refresh token has already been used.",
@@ -852,16 +942,40 @@ var exchangeCodeForTokens = async (code, redirectUri, pkce) => {
852
942
  "exchange"
853
943
  );
854
944
  };
855
- var refreshAccessToken = async (refreshToken, signal) => {
856
- return requestToken(
857
- {
858
- grant_type: "refresh_token",
859
- refresh_token: refreshToken,
860
- client_id: clientId()
861
- },
862
- "refresh",
863
- signal
864
- );
945
+ var refreshAccessToken = async (refreshToken, signal, options) => {
946
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_OAUTH_REFRESH_TIMEOUT_MS;
947
+ const timeoutController = new AbortController();
948
+ let timedOut = false;
949
+ const timer = setTimeout(() => {
950
+ timedOut = true;
951
+ timeoutController.abort(new Error("OAuth token refresh timed out"));
952
+ }, timeoutMs);
953
+ const effectiveSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
954
+ try {
955
+ return await requestToken(
956
+ {
957
+ grant_type: "refresh_token",
958
+ refresh_token: refreshToken,
959
+ client_id: clientId()
960
+ },
961
+ "refresh",
962
+ effectiveSignal
963
+ );
964
+ } catch (error) {
965
+ if (timedOut) {
966
+ throw new ProviderFailureError({
967
+ provider: "openai",
968
+ kind: "provider",
969
+ code: "oauth_refresh_timeout",
970
+ safeMessage: "OpenAI OAuth token refresh timed out.",
971
+ detail: "The OAuth token endpoint did not respond before the timeout.",
972
+ retryable: true
973
+ });
974
+ }
975
+ throw error;
976
+ } finally {
977
+ clearTimeout(timer);
978
+ }
865
979
  };
866
980
  var parseJwt = (token) => {
867
981
  const parts = token.split(".");
@@ -1150,93 +1264,335 @@ import {
1150
1264
  openSync,
1151
1265
  readFileSync
1152
1266
  } from "fs";
1153
- import { ensureStorageDirs, resolveStoragePaths } from "@codelia/storage";
1154
- var AUTH_VERSION = 1;
1155
- var authWriteQueues = /* @__PURE__ */ new Map();
1156
- var parseAuthFile = (text) => {
1157
- const parsed = JSON.parse(text);
1158
- if (!parsed || parsed.version !== AUTH_VERSION)
1159
- throw new Error("auth.json has unsupported version");
1160
- return { version: AUTH_VERSION, providers: parsed.providers ?? {} };
1161
- };
1162
- var absentAuthFile = (error) => {
1163
- if (error?.code === "ENOENT")
1164
- return { version: AUTH_VERSION, providers: {} };
1165
- throw error;
1267
+ import {
1268
+ AUTH_VERSION_V1,
1269
+ AUTH_VERSION_V2,
1270
+ authLockPathFor,
1271
+ CODELIA_AUTH_KEYCHAIN_SERVICE,
1272
+ CredentialConflictError,
1273
+ canonicalJsonEqual,
1274
+ clearStoreAcrossAllLocationsUnlocked,
1275
+ coordinateCredentialBackendUnlocked,
1276
+ ensureStorageDirs,
1277
+ keychainAccountForConfigDir,
1278
+ MacOsKeychainClient,
1279
+ mcpAuthStoreAdapter,
1280
+ parseAuthDocument,
1281
+ providerAuthStoreAdapter,
1282
+ readAuthStorageStateSync,
1283
+ resolveConfiguredAuthStorageMode,
1284
+ resolveStoragePaths,
1285
+ verifyWindowsCredentialFileAcl,
1286
+ verifyWindowsCredentialFileAclSync,
1287
+ withAuthStoreLock,
1288
+ writeFileAtomic
1289
+ } from "@codelia/storage";
1290
+ var normalizeAuthFileToV2 = (auth) => parseAuthDocument(JSON.stringify(auth)).normalized;
1291
+ var getChatProviderAuth = (auth, provider) => {
1292
+ if (!Object.hasOwn(auth.providers, provider)) return void 0;
1293
+ const entry = auth.providers[provider];
1294
+ if (entry.chat_method === "oauth" && entry.credentials.oauth) {
1295
+ return { method: "oauth", oauth: entry.credentials.oauth };
1296
+ }
1297
+ if (entry.chat_method === "api_key" && entry.credentials.api_key) {
1298
+ return { method: "api_key", ...entry.credentials.api_key };
1299
+ }
1300
+ return void 0;
1301
+ };
1302
+ var getStoredProviderApiKey = (auth, provider) => Object.hasOwn(auth.providers, provider) ? auth.providers[provider].credentials.api_key : void 0;
1303
+ var setProviderChatAuth = (auth, provider, next) => {
1304
+ const existing = Object.hasOwn(auth.providers, provider) ? auth.providers[provider] : void 0;
1305
+ const credentials = {
1306
+ ...existing?.credentials ?? {}
1307
+ };
1308
+ if (next.method === "api_key") {
1309
+ credentials.api_key = {
1310
+ api_key: next.api_key,
1311
+ ...next.api_base ? { api_base: next.api_base } : {}
1312
+ };
1313
+ } else {
1314
+ credentials.oauth = next.oauth;
1315
+ }
1316
+ auth.providers[provider] = {
1317
+ chat_method: next.method,
1318
+ credentials
1319
+ };
1320
+ };
1321
+ var updateProviderOAuthTokens = (auth, provider, oauth2) => {
1322
+ if (!Object.hasOwn(auth.providers, provider)) return false;
1323
+ const entry = auth.providers[provider];
1324
+ if (!entry.credentials.oauth) return false;
1325
+ auth.providers[provider] = {
1326
+ ...entry.chat_method ? { chat_method: entry.chat_method } : {},
1327
+ credentials: {
1328
+ ...entry.credentials,
1329
+ oauth: oauth2
1330
+ }
1331
+ };
1332
+ return true;
1333
+ };
1334
+ var clearProviderEntry = (auth, provider) => {
1335
+ delete auth.providers[provider];
1336
+ };
1337
+ var projectAuthV2ToV1View = (auth) => {
1338
+ const providers = {};
1339
+ for (const name of Object.keys(auth.providers)) {
1340
+ const chatAuth = getChatProviderAuth(auth, name);
1341
+ if (chatAuth) {
1342
+ providers[name] = chatAuth;
1343
+ }
1344
+ }
1345
+ return { version: AUTH_VERSION_V1, providers };
1346
+ };
1347
+ var readTextIfPresent = async (filePath) => {
1348
+ if (!await verifyWindowsCredentialFileAcl(filePath)) return null;
1349
+ try {
1350
+ return await fs2.readFile(filePath, "utf8");
1351
+ } catch (error) {
1352
+ if (error?.code === "ENOENT") return null;
1353
+ throw error;
1354
+ }
1166
1355
  };
1356
+ var readAuthFileSyncStrict = (filePath, legacy = false) => {
1357
+ if (!verifyWindowsCredentialFileAclSync(filePath, legacy)) return null;
1358
+ let fd;
1359
+ try {
1360
+ fd = openSync(
1361
+ filePath,
1362
+ constants.O_RDONLY | constants.O_NONBLOCK | (constants.O_NOFOLLOW ?? 0)
1363
+ );
1364
+ } catch (error) {
1365
+ if (error?.code === "ENOENT") return null;
1366
+ throw error;
1367
+ }
1368
+ try {
1369
+ const stat = fstatSync(fd);
1370
+ if (!stat.isFile() || stat.size > 1024 * 1024) {
1371
+ throw new Error("auth.json cannot be read at approval time");
1372
+ }
1373
+ return parseAuthDocument(readFileSync(fd, "utf8")).normalized;
1374
+ } finally {
1375
+ closeSync(fd);
1376
+ }
1377
+ };
1378
+ var isAuthNonEmpty = (doc) => doc !== null && Object.keys(doc.providers).length > 0;
1167
1379
  var AuthStore = class {
1168
1380
  paths;
1169
- constructor(paths) {
1381
+ lockOptions;
1382
+ storageMode;
1383
+ keychain;
1384
+ constructor(paths, options) {
1170
1385
  this.paths = paths ?? resolveStoragePaths();
1386
+ this.lockOptions = options?.lock;
1387
+ this.storageMode = options?.storageMode;
1388
+ this.keychain = options?.keychain ?? new MacOsKeychainClient({
1389
+ credentialsDir: this.paths.credentialsDir
1390
+ });
1171
1391
  }
1172
- async load() {
1173
- try {
1174
- return parseAuthFile(await fs2.readFile(this.paths.authFile, "utf8"));
1175
- } catch (error) {
1176
- return absentAuthFile(error);
1177
- }
1392
+ lockPath() {
1393
+ return authLockPathFor(this.paths.credentialsDir);
1178
1394
  }
1179
- /** Synchronous snapshot for a one-use local approval consumed immediately before spawn. */
1180
- loadForApproval() {
1181
- let fd;
1182
- try {
1183
- fd = openSync(
1184
- this.paths.authFile,
1185
- constants.O_RDONLY | constants.O_NONBLOCK
1395
+ keychainAccount() {
1396
+ return keychainAccountForConfigDir(this.paths.configDir);
1397
+ }
1398
+ resolveBackendUnlocked() {
1399
+ return coordinateCredentialBackendUnlocked({
1400
+ paths: this.paths,
1401
+ storageMode: this.storageMode,
1402
+ keychain: this.keychain,
1403
+ authAdapter: providerAuthStoreAdapter,
1404
+ mcpAdapter: mcpAuthStoreAdapter
1405
+ });
1406
+ }
1407
+ async readFromBackend(active) {
1408
+ if (active === "keyring") {
1409
+ const text2 = await this.keychain.get(
1410
+ CODELIA_AUTH_KEYCHAIN_SERVICE,
1411
+ this.keychainAccount()
1186
1412
  );
1187
- } catch (error) {
1188
- return absentAuthFile(error);
1413
+ if (text2 === null) {
1414
+ return { version: AUTH_VERSION_V2, providers: {} };
1415
+ }
1416
+ const parsed2 = parseAuthDocument(text2);
1417
+ if (parsed2.sourceVersion === 1) {
1418
+ await this.writeToBackend("keyring", parsed2.normalized);
1419
+ }
1420
+ return parsed2.normalized;
1189
1421
  }
1190
- try {
1191
- const stat = fstatSync(fd);
1192
- if (!stat.isFile() || stat.size > 1024 * 1024)
1193
- throw new Error("auth.json cannot be read at approval time");
1194
- return parseAuthFile(readFileSync(fd, "utf8"));
1195
- } finally {
1196
- closeSync(fd);
1422
+ const text = await readTextIfPresent(this.paths.authFile);
1423
+ if (text === null) {
1424
+ return { version: AUTH_VERSION_V2, providers: {} };
1425
+ }
1426
+ const parsed = parseAuthDocument(text);
1427
+ if (parsed.sourceVersion === 1) {
1428
+ await this.writeToBackend("file", parsed.normalized);
1197
1429
  }
1430
+ return parsed.normalized;
1198
1431
  }
1199
- async enqueue(fn) {
1200
- const key = this.paths.authFile;
1201
- const previous = authWriteQueues.get(key) ?? Promise.resolve();
1202
- const next = previous.then(fn, fn);
1203
- const settled = next.then(
1204
- () => void 0,
1205
- () => void 0
1432
+ async writeToBackend(active, auth) {
1433
+ if (active === "keyring") {
1434
+ await this.keychain.set(
1435
+ CODELIA_AUTH_KEYCHAIN_SERVICE,
1436
+ this.keychainAccount(),
1437
+ JSON.stringify(auth)
1438
+ );
1439
+ return;
1440
+ }
1441
+ await ensureStorageDirs(this.paths);
1442
+ const data = JSON.stringify(auth, null, 2);
1443
+ await writeFileAtomic(this.paths.authFile, data, { mode: 384 });
1444
+ }
1445
+ /**
1446
+ * Load normalized v2 credentials from the active backend (macOS Keychain or
1447
+ * protected `credentials/` file), running two-phase migration if needed.
1448
+ */
1449
+ async loadV2() {
1450
+ return withAuthStoreLock(
1451
+ this.lockPath(),
1452
+ async () => {
1453
+ const resolved = await this.resolveBackendUnlocked();
1454
+ return this.readFromBackend(resolved.active);
1455
+ },
1456
+ this.lockOptions
1206
1457
  );
1207
- authWriteQueues.set(key, settled);
1208
- try {
1209
- return await next;
1210
- } finally {
1211
- if (authWriteQueues.get(key) === settled) authWriteQueues.delete(key);
1458
+ }
1459
+ /**
1460
+ * Synchronous v2 snapshot for a one-use local approval consumed immediately
1461
+ * before spawn. Fails closed (throws) on corrupt `storage-state.json`,
1462
+ * in-progress migrations or pending cleanup, dual-store conflicts, or
1463
+ * locked/unavailable/timed-out Keychain access.
1464
+ */
1465
+ loadForApprovalV2() {
1466
+ const configured = resolveConfiguredAuthStorageMode(
1467
+ this.paths,
1468
+ this.storageMode
1469
+ );
1470
+ const state = readAuthStorageStateSync(this.paths.authStateFile);
1471
+ if (state?.status === "migrating") {
1472
+ throw new Error(
1473
+ "Credential storage migration is in progress; approval-time auth is unavailable"
1474
+ );
1475
+ }
1476
+ if (configured === "file" && state?.active_backend === "keyring") {
1477
+ throw new Error(
1478
+ "Credential reverse migration to file is pending; approval-time auth is unavailable"
1479
+ );
1480
+ }
1481
+ const useKeychain = configured === "keyring" || configured === "auto" && state?.active_backend === "keyring";
1482
+ const currentFile = readAuthFileSyncStrict(this.paths.authFile);
1483
+ const legacyFile = readAuthFileSyncStrict(this.paths.legacyAuthFile, true);
1484
+ if (isAuthNonEmpty(currentFile) && isAuthNonEmpty(legacyFile) && !canonicalJsonEqual(currentFile, legacyFile)) {
1485
+ throw new CredentialConflictError("auth");
1486
+ }
1487
+ if (useKeychain) {
1488
+ const text = this.keychain.getSync(
1489
+ CODELIA_AUTH_KEYCHAIN_SERVICE,
1490
+ this.keychainAccount(),
1491
+ 2e3
1492
+ );
1493
+ const keychainDoc = text === null ? { version: AUTH_VERSION_V2, providers: {} } : parseAuthDocument(text).normalized;
1494
+ for (const fileCandidate of [currentFile, legacyFile]) {
1495
+ if (isAuthNonEmpty(fileCandidate) && isAuthNonEmpty(keychainDoc) && !canonicalJsonEqual(keychainDoc, fileCandidate)) {
1496
+ throw new CredentialConflictError("auth");
1497
+ }
1498
+ }
1499
+ return keychainDoc;
1212
1500
  }
1501
+ if (isAuthNonEmpty(currentFile)) return currentFile;
1502
+ if (isAuthNonEmpty(legacyFile)) return legacyFile;
1503
+ return currentFile ?? legacyFile ?? { version: AUTH_VERSION_V2, providers: {} };
1504
+ }
1505
+ /** Legacy v1-projected read view over the underlying v2 store. */
1506
+ async load() {
1507
+ return projectAuthV2ToV1View(await this.loadV2());
1508
+ }
1509
+ /** Synchronous legacy v1-projected snapshot for approval checks. */
1510
+ loadForApproval() {
1511
+ return projectAuthV2ToV1View(this.loadForApprovalV2());
1213
1512
  }
1214
1513
  /**
1215
- * Reload, mutate and save under a per-file queue. Use this for every
1216
- * credential change made outside the cached-resolver flow.
1514
+ * Reload v2, mutate, and atomically save under the interprocess SQLite lock.
1515
+ * Skips writing if the serialized v2 document did not change.
1516
+ */
1517
+ updateV2(mutate) {
1518
+ return withAuthStoreLock(
1519
+ this.lockPath(),
1520
+ async () => {
1521
+ const resolved = await this.resolveBackendUnlocked();
1522
+ const auth = await this.readFromBackend(resolved.active);
1523
+ const before = JSON.stringify(auth);
1524
+ const result = await mutate(auth);
1525
+ if (JSON.stringify(auth) !== before) {
1526
+ await this.writeToBackend(resolved.active, auth);
1527
+ }
1528
+ return result;
1529
+ },
1530
+ this.lockOptions
1531
+ );
1532
+ }
1533
+ /**
1534
+ * Legacy v1-projected update helper. Applies v1 mutations onto the underlying
1535
+ * v2 document while preserving coexisting credentials on untouched slots.
1217
1536
  */
1218
1537
  update(mutate) {
1219
- return this.enqueue(async () => {
1220
- const auth = await this.load();
1221
- const result = await mutate(auth);
1222
- await this.save(auth);
1538
+ return this.updateV2(async (v2) => {
1539
+ const beforeView = projectAuthV2ToV1View(v2);
1540
+ const workingView = {
1541
+ version: AUTH_VERSION_V1,
1542
+ providers: { ...beforeView.providers }
1543
+ };
1544
+ const result = await mutate(workingView);
1545
+ const touched = /* @__PURE__ */ new Set([
1546
+ ...Object.keys(beforeView.providers),
1547
+ ...Object.keys(workingView.providers)
1548
+ ]);
1549
+ for (const name of touched) {
1550
+ const had = Object.hasOwn(beforeView.providers, name);
1551
+ const has = Object.hasOwn(workingView.providers, name);
1552
+ if (!has && had) {
1553
+ clearProviderEntry(v2, name);
1554
+ } else if (has) {
1555
+ const next = workingView.providers[name];
1556
+ if (!had || !canonicalJsonEqual(beforeView.providers[name], next)) {
1557
+ setProviderChatAuth(v2, name, next);
1558
+ }
1559
+ }
1560
+ }
1223
1561
  return result;
1224
1562
  });
1225
1563
  }
1226
- /** Queued removal of every provider; works even if the file is unreadable. */
1564
+ /**
1565
+ * Locked removal of every provider across all credential locations
1566
+ * (`credentials/auth.json`, legacy `auth.json`, and Keychain if active/reachable).
1567
+ * Succeeds even when an `auth` storage conflict or corrupt file exists so
1568
+ * full logout always gives users a clean recovery path (never touches `mcp-auth`).
1569
+ */
1227
1570
  clearAll() {
1228
- return this.enqueue(
1229
- () => this.save({ version: AUTH_VERSION, providers: {} })
1571
+ return withAuthStoreLock(
1572
+ this.lockPath(),
1573
+ async () => {
1574
+ await clearStoreAcrossAllLocationsUnlocked({
1575
+ paths: this.paths,
1576
+ adapter: providerAuthStoreAdapter,
1577
+ keychain: this.keychain
1578
+ });
1579
+ },
1580
+ this.lockOptions
1581
+ );
1582
+ }
1583
+ async saveV2(auth) {
1584
+ await withAuthStoreLock(
1585
+ this.lockPath(),
1586
+ async () => {
1587
+ const resolved = await this.resolveBackendUnlocked();
1588
+ await this.writeToBackend(resolved.active, auth);
1589
+ },
1590
+ this.lockOptions
1230
1591
  );
1231
1592
  }
1232
1593
  async save(auth) {
1233
- await ensureStorageDirs(this.paths);
1234
- const data = JSON.stringify(auth, null, 2);
1235
- await fs2.writeFile(this.paths.authFile, data, { mode: 384 });
1236
- try {
1237
- await fs2.chmod(this.paths.authFile, 384);
1238
- } catch {
1239
- }
1594
+ const normalized = normalizeAuthFileToV2(auth);
1595
+ await this.saveV2(normalized);
1240
1596
  }
1241
1597
  };
1242
1598
 
@@ -1276,8 +1632,9 @@ var configuredApiKeyAuth = (provider, apiKey) => {
1276
1632
  };
1277
1633
  };
1278
1634
  var readConfiguredProviderAuth = (provider) => {
1279
- const { providers } = new AuthStore().loadForApproval();
1280
- if (Object.hasOwn(providers, provider)) return providers[provider];
1635
+ const auth = new AuthStore().loadForApprovalV2();
1636
+ const chatAuth = getChatProviderAuth(auth, provider);
1637
+ if (chatAuth) return chatAuth;
1281
1638
  const apiKey = readProviderEnvApiKey(provider);
1282
1639
  return apiKey ? configuredApiKeyAuth(provider, apiKey) : void 0;
1283
1640
  };
@@ -1308,12 +1665,12 @@ var AuthResolver = class _AuthResolver {
1308
1665
  }
1309
1666
  static async create(state, log2, providers = {}) {
1310
1667
  const store = new AuthStore();
1311
- const auth = await store.load();
1668
+ const auth = await store.loadV2();
1312
1669
  return new _AuthResolver(state, log2, store, auth, providers);
1313
1670
  }
1314
1671
  hasAnyAvailableAuth() {
1315
1672
  return this.availableProviders.some((provider) => {
1316
- if (this.auth.providers[provider]) return true;
1673
+ if (getChatProviderAuth(this.auth, provider)) return true;
1317
1674
  return Boolean(this.envApiKey(provider));
1318
1675
  });
1319
1676
  }
@@ -1323,7 +1680,7 @@ var AuthResolver = class _AuthResolver {
1323
1680
  throw new Error(`Unsupported model.provider: ${preferred}`);
1324
1681
  if (preferredProvider) return preferredProvider;
1325
1682
  const providersWithAuth = this.availableProviders.filter(
1326
- (provider) => !!this.auth.providers[provider]
1683
+ (provider) => !!getChatProviderAuth(this.auth, provider)
1327
1684
  );
1328
1685
  if (providersWithAuth.length === 1) {
1329
1686
  return providersWithAuth[0];
@@ -1354,13 +1711,11 @@ var AuthResolver = class _AuthResolver {
1354
1711
  async resolveProviderAuth(provider) {
1355
1712
  if (!this.availableProviders.includes(provider))
1356
1713
  throw new Error(`Unsupported provider: ${provider}`);
1357
- const existing = this.auth.providers[provider];
1714
+ const existing = getChatProviderAuth(this.auth, provider);
1358
1715
  if (existing) return existing;
1359
1716
  const envValue = this.envApiKey(provider);
1360
1717
  if (envValue) {
1361
- const auth = configuredApiKeyAuth(provider, envValue);
1362
- await this.setProviderAuth(provider, auth);
1363
- return auth;
1718
+ return configuredApiKeyAuth(provider, envValue);
1364
1719
  }
1365
1720
  if (provider === "openai") {
1366
1721
  return this.promptOpenAiAuth();
@@ -1395,7 +1750,7 @@ var AuthResolver = class _AuthResolver {
1395
1750
  if (options?.matches && !options.matches(oauth3))
1396
1751
  throw new Error("OpenAI OAuth account changed");
1397
1752
  };
1398
- const entry = this.auth.providers.openai;
1753
+ const entry = getChatProviderAuth(this.auth, "openai");
1399
1754
  if (entry?.method !== "oauth") {
1400
1755
  throw new Error("OpenAI OAuth is not configured");
1401
1756
  }
@@ -1403,15 +1758,15 @@ var AuthResolver = class _AuthResolver {
1403
1758
  options?.signal?.throwIfAborted();
1404
1759
  checkAccount(oauth2);
1405
1760
  if (oauth2.expires_at <= Date.now() + 6e4) {
1406
- oauth2 = await this.store.update(async (auth) => {
1407
- const current = auth.providers.openai;
1761
+ const updated = await this.store.updateV2(async (auth) => {
1762
+ const current = getChatProviderAuth(auth, "openai");
1408
1763
  if (current?.method !== "oauth") {
1409
1764
  throw new Error("OpenAI OAuth is not configured");
1410
1765
  }
1411
1766
  options?.signal?.throwIfAborted();
1412
1767
  checkAccount(current.oauth);
1413
1768
  if (current.oauth.expires_at > Date.now() + 6e4) {
1414
- return current.oauth;
1769
+ return { oauth: current.oauth, auth };
1415
1770
  }
1416
1771
  this.log("refreshing OpenAI OAuth token");
1417
1772
  const tokens = await refreshAccessToken(current.oauth.refresh_token);
@@ -1423,10 +1778,13 @@ var AuthResolver = class _AuthResolver {
1423
1778
  ...accountId ? { account_id: accountId } : {}
1424
1779
  };
1425
1780
  checkAccount(refreshed);
1426
- auth.providers.openai = { method: "oauth", oauth: refreshed };
1427
- return refreshed;
1781
+ if (!updateProviderOAuthTokens(auth, "openai", refreshed)) {
1782
+ throw new Error("OpenAI OAuth is not configured");
1783
+ }
1784
+ return { oauth: refreshed, auth };
1428
1785
  });
1429
- this.auth.providers.openai = { method: "oauth", oauth: oauth2 };
1786
+ oauth2 = updated.oauth;
1787
+ this.auth = updated.auth;
1430
1788
  }
1431
1789
  options?.signal?.throwIfAborted();
1432
1790
  return { token: oauth2.access_token, accountId: oauth2.account_id };
@@ -1616,8 +1974,8 @@ var AuthResolver = class _AuthResolver {
1616
1974
  return auth;
1617
1975
  }
1618
1976
  async setProviderAuth(provider, auth) {
1619
- this.auth = await this.store.update((latest) => {
1620
- latest.providers[provider] = auth;
1977
+ this.auth = await this.store.updateV2((latest) => {
1978
+ setProviderChatAuth(latest, provider, auth);
1621
1979
  return latest;
1622
1980
  });
1623
1981
  }
@@ -1626,14 +1984,15 @@ var AuthResolver = class _AuthResolver {
1626
1984
  // src/permissions/shell-backend.ts
1627
1985
  import { spawn as spawn4, spawnSync as spawnSync3 } from "child_process";
1628
1986
  import {
1629
- lstatSync as lstatSync8,
1987
+ lstatSync as lstatSync9,
1988
+ mkdirSync as mkdirSync2,
1630
1989
  mkdtempSync as mkdtempSync2,
1631
- realpathSync as realpathSync7,
1990
+ realpathSync as realpathSync8,
1632
1991
  rmSync as rmSync2,
1633
1992
  statSync as statSync5
1634
1993
  } from "fs";
1635
- import os from "os";
1636
- import path12 from "path";
1994
+ import os2 from "os";
1995
+ import path13 from "path";
1637
1996
  import { resolveStoragePaths as resolveStoragePaths3 } from "@codelia/storage";
1638
1997
 
1639
1998
  // src/sandbox/file-mutation-helper.ts
@@ -1939,25 +2298,171 @@ var resolveGitMetadata = (directories, includeObjectDirectories) => {
1939
2298
  var gitMetadataPaths = (...directories) => resolveGitMetadata(directories, false);
1940
2299
  var gitMetadataWithObjectDirectories = (...directories) => resolveGitMetadata(directories, true);
1941
2300
 
2301
+ // src/permissions/home-dot-paths.ts
2302
+ import { readdirSync as readdirSync2, readlinkSync as readlinkSync2 } from "fs";
2303
+ import os from "os";
2304
+ import path6 from "path";
2305
+
2306
+ // src/permissions/resource-paths.ts
2307
+ import {
2308
+ lstatSync as lstatSync2,
2309
+ opendirSync,
2310
+ readlinkSync,
2311
+ realpathSync as realpathSync2
2312
+ } from "fs";
2313
+ import path5 from "path";
2314
+ var lookup = (pathname) => lstatSync2(pathname, { bigint: true, throwIfNoEntry: false });
2315
+ var sameEntry = (left, right) => left.dev === right.dev && left.ino === right.ino;
2316
+ var comparableResourceName = (pathname) => {
2317
+ const folded = pathname.normalize("NFD").toUpperCase().toLowerCase();
2318
+ return process.platform === "win32" ? folded.replace(/[ .]+(?=[\\/]|$)/gu, "") : folded;
2319
+ };
2320
+ function distinguishesAsciiCase(parent) {
2321
+ try {
2322
+ const directory = opendirSync(parent);
2323
+ try {
2324
+ for (let index = 0; index < 16; index++) {
2325
+ const name = directory.readSync()?.name;
2326
+ if (!name) break;
2327
+ const changed = name.replace(
2328
+ /[A-Za-z]/u,
2329
+ (letter) => letter === letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase()
2330
+ );
2331
+ if (name === changed) continue;
2332
+ const original = lookup(path5.join(parent, name));
2333
+ const alternate = lookup(path5.join(parent, changed));
2334
+ if (original) return !alternate || !sameEntry(original, alternate);
2335
+ }
2336
+ } finally {
2337
+ directory.closeSync();
2338
+ }
2339
+ } catch {
2340
+ }
2341
+ return false;
2342
+ }
2343
+ function resourceContainsPath(resource, target) {
2344
+ if (target === resource || target.startsWith(
2345
+ resource.endsWith(path5.sep) ? resource : `${resource}${path5.sep}`
2346
+ ))
2347
+ return true;
2348
+ const root = path5.parse(resource).root;
2349
+ const targetRoot = path5.parse(target).root;
2350
+ if (comparableResourceName(root) !== comparableResourceName(targetRoot))
2351
+ return false;
2352
+ const parts = resource.slice(root.length).split(path5.sep);
2353
+ const overlapping = target.slice(targetRoot.length).split(path5.sep).slice(0, parts.length);
2354
+ if (overlapping.length !== parts.length) return false;
2355
+ const candidate = path5.join(targetRoot, ...overlapping);
2356
+ const namesMayMatch = comparableResourceName(resource) === comparableResourceName(candidate);
2357
+ try {
2358
+ const targetEntry = lookup(candidate);
2359
+ if (!targetEntry && !namesMayMatch) return false;
2360
+ const protectedEntry = lookup(resource);
2361
+ if (protectedEntry || targetEntry)
2362
+ return !!protectedEntry && !!targetEntry && sameEntry(protectedEntry, targetEntry);
2363
+ if (!namesMayMatch) return false;
2364
+ const parent = path5.dirname(resource);
2365
+ return path5.dirname(candidate) !== parent || !/^[\x20-\x7e]+$/u.test(path5.basename(resource)) || !/^[\x20-\x7e]+$/u.test(path5.basename(candidate)) || path5.basename(resource).toLowerCase() !== path5.basename(candidate).toLowerCase() || !distinguishesAsciiCase(parent);
2366
+ } catch {
2367
+ return namesMayMatch;
2368
+ }
2369
+ }
2370
+ var missing = (error) => error.code === "ENOENT";
2371
+ function resolveReservedTarget(target, remaining = 64) {
2372
+ if (!remaining) throw new Error("reserved_path_unresolved");
2373
+ try {
2374
+ return realpathSync2(target);
2375
+ } catch (error) {
2376
+ const parent = path5.dirname(target);
2377
+ if (!missing(error) || parent === target) throw error;
2378
+ const canonicalParent = resolveReservedTarget(parent, remaining - 1);
2379
+ if (!lstatSync2(target, { throwIfNoEntry: false })?.isSymbolicLink())
2380
+ return path5.join(canonicalParent, path5.basename(target));
2381
+ const referent = readlinkSync(target);
2382
+ let seenName = false;
2383
+ for (const part of referent.split(
2384
+ process.platform === "win32" ? /[\\/]/u : "/"
2385
+ )) {
2386
+ if (part === ".." && seenName)
2387
+ throw new Error("reserved_path_unresolved");
2388
+ if (part && part !== "." && part !== "..") seenName = true;
2389
+ }
2390
+ return resolveReservedTarget(
2391
+ path5.resolve(canonicalParent, referent),
2392
+ remaining - 1
2393
+ );
2394
+ }
2395
+ }
2396
+
2397
+ // src/permissions/home-dot-paths.ts
2398
+ var homeDotDirectory = (writeRoots, home = os.homedir()) => {
2399
+ if (!writeRoots.length) return void 0;
2400
+ const canonicalHome = resolveReservedTarget(home);
2401
+ return writeRoots.some(
2402
+ (root) => resourceContainsPath(resolveReservedTarget(root), canonicalHome)
2403
+ ) ? canonicalHome : void 0;
2404
+ };
2405
+ var isHomeDotTarget = (home, target, platform = process.platform) => {
2406
+ if (!resourceContainsPath(home, target)) return false;
2407
+ const root = path6.parse(home).root;
2408
+ const depth = home.slice(root.length).split(path6.sep).filter(Boolean).length;
2409
+ const first = target.slice(path6.parse(target).root.length).split(path6.sep).filter(Boolean)[depth];
2410
+ return !!first && (first.startsWith(".") || platform === "darwin" && resourceContainsPath(path6.join(home, "Library"), target));
2411
+ };
2412
+ var hasClosedHomeDotCycle = (home, start) => {
2413
+ const seen = /* @__PURE__ */ new Set();
2414
+ let current = start;
2415
+ while (seen.size < 64) {
2416
+ if (seen.has(current)) return true;
2417
+ seen.add(current);
2418
+ let link;
2419
+ try {
2420
+ link = readlinkSync2(current);
2421
+ } catch {
2422
+ return false;
2423
+ }
2424
+ const next = path6.resolve(home, link);
2425
+ const name = path6.basename(next);
2426
+ if (path6.dirname(next) !== home || !isHomeDotTarget(home, next) || link !== next && link !== name && link !== `.${path6.sep}${name}`)
2427
+ return false;
2428
+ current = next;
2429
+ }
2430
+ return false;
2431
+ };
2432
+ var homeDotLinkTargets = (home) => readdirSync2(home, { withFileTypes: true }).filter(
2433
+ (entry) => entry.isSymbolicLink() && isHomeDotTarget(home, path6.join(home, entry.name))
2434
+ ).flatMap((entry) => {
2435
+ const link = path6.join(home, entry.name);
2436
+ try {
2437
+ return [resolveReservedTarget(link)];
2438
+ } catch (error) {
2439
+ if (error.code === "ELOOP" && hasClosedHomeDotCycle(home, link))
2440
+ return [];
2441
+ throw error;
2442
+ }
2443
+ });
2444
+ var isHomeWriteReserved = (home, target) => isHomeDotTarget(home, target) || homeDotLinkTargets(home).some((link) => resourceContainsPath(link, target));
2445
+
1942
2446
  // src/permissions/linux-shell-backend.ts
1943
2447
  import { spawn as spawn2, spawnSync } from "child_process";
1944
2448
  import {
1945
2449
  accessSync as accessSync2,
1946
2450
  constants as constants4,
2451
+ lstatSync as lstatSync5,
1947
2452
  mkdirSync,
1948
2453
  mkdtempSync,
1949
- readdirSync as readdirSync4,
2454
+ readdirSync as readdirSync5,
1950
2455
  readFileSync as readFileSync3,
1951
- realpathSync as realpathSync4,
2456
+ realpathSync as realpathSync5,
1952
2457
  rmSync,
1953
2458
  statSync as statSync3,
1954
2459
  writeFileSync
1955
2460
  } from "fs";
1956
- import path8 from "path";
2461
+ import path10 from "path";
1957
2462
 
1958
2463
  // src/permissions/linux-mountinfo.ts
1959
2464
  import { readFileSync as readFileSync2 } from "fs";
1960
- import path5 from "path";
2465
+ import path7 from "path";
1961
2466
  var within = (root, name) => root === "/" || root === name || name.startsWith(`${root}/`);
1962
2467
  var replacedSystemTrees = ["/proc", "/dev", "/sys"];
1963
2468
  function parseMountInfo(text) {
@@ -2012,7 +2517,7 @@ function executableMountSnapshot(file, dev, text = readFileSync2("/proc/self/mou
2012
2517
  /[ \t\n\\]/g,
2013
2518
  (char) => `\\${char.charCodeAt(0).toString(8).padStart(3, "0")}`
2014
2519
  );
2015
- const parent = path5.posix.dirname(executable);
2520
+ const parent = path7.posix.dirname(executable);
2016
2521
  const mounts = parseMountInfo(text);
2017
2522
  const ancestors = mounts.filter(({ target }) => within(target, parent)).sort((left, right) => right.target.length - left.target.length);
2018
2523
  const [selected] = ancestors;
@@ -2021,11 +2526,11 @@ function executableMountSnapshot(file, dev, text = readFileSync2("/proc/self/mou
2021
2526
  ))
2022
2527
  throw new Error("unbound_executable_mount");
2023
2528
  checkMountViews([selected]);
2024
- const installed = path5.posix.join(
2529
+ const installed = path7.posix.join(
2025
2530
  selected.root,
2026
- path5.posix.relative(selected.target, parent)
2531
+ path7.posix.relative(selected.target, parent)
2027
2532
  );
2028
- const directChild = (directory, entry) => entry !== directory && path5.posix.dirname(entry) === directory;
2533
+ const directChild = (directory, entry) => entry !== directory && path7.posix.dirname(entry) === directory;
2029
2534
  const directMounts = mounts.filter(
2030
2535
  ({ target }) => directChild(parent, target)
2031
2536
  );
@@ -2042,17 +2547,17 @@ function executableMountSnapshot(file, dev, text = readFileSync2("/proc/self/mou
2042
2547
 
2043
2548
  // src/permissions/protected-aliases.ts
2044
2549
  import {
2045
- lstatSync as lstatSync2,
2046
- readdirSync as readdirSync2,
2047
- realpathSync as realpathSync2
2550
+ lstatSync as lstatSync3,
2551
+ readdirSync as readdirSync3,
2552
+ realpathSync as realpathSync3
2048
2553
  } from "fs";
2049
- import path6 from "path";
2554
+ import path8 from "path";
2050
2555
  var maxEntries = 4096;
2051
2556
  var inode = (stat) => `${stat.dev}:${stat.ino}`;
2052
2557
  function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifiedHooks = []) {
2053
2558
  const pending = roots.map((entry) => {
2054
2559
  try {
2055
- return realpathSync2(entry);
2560
+ return realpathSync3(entry);
2056
2561
  } catch (error) {
2057
2562
  if (error.code === "ENOENT") return entry;
2058
2563
  throw error;
@@ -2068,7 +2573,7 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
2068
2573
  const target = hooks.get(file);
2069
2574
  if (!target) return false;
2070
2575
  try {
2071
- return realpathSync2(file) === target && lstatSync2(target).isFile();
2576
+ return realpathSync3(file) === target && lstatSync3(target).isFile();
2072
2577
  } catch {
2073
2578
  return false;
2074
2579
  }
@@ -2080,18 +2585,18 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
2080
2585
  if (visited.size > entryLimit)
2081
2586
  throw new Error("protected_alias_index_unavailable");
2082
2587
  try {
2083
- const metadata = lstatSync2(file, { bigint: true });
2588
+ const metadata = lstatSync3(file, { bigint: true });
2084
2589
  if (metadata.isFile() && metadata.nlink > 1n) yield inode(metadata);
2085
2590
  if (metadata.isSymbolicLink() && ignored.size) {
2086
2591
  if (verifiedHook(file)) continue;
2087
2592
  pending.push(...ignored);
2088
2593
  ignored.clear();
2089
2594
  } else if (metadata.isDirectory()) {
2090
- const children = readdirSync2(file);
2595
+ const children = readdirSync3(file);
2091
2596
  if (children.length + pending.length + visited.size > entryLimit)
2092
2597
  throw new Error("protected_alias_index_unavailable");
2093
2598
  for (const name of children) {
2094
- const child = path6.join(file, name);
2599
+ const child = path8.join(file, name);
2095
2600
  if (!ignored.has(child)) pending.push(child);
2096
2601
  }
2097
2602
  }
@@ -2365,28 +2870,28 @@ var analyzeShell = (invocation) => {
2365
2870
  import {
2366
2871
  accessSync,
2367
2872
  constants as constants3,
2368
- lstatSync as lstatSync3,
2369
- readdirSync as readdirSync3,
2370
- readlinkSync,
2371
- realpathSync as realpathSync3,
2873
+ lstatSync as lstatSync4,
2874
+ readdirSync as readdirSync4,
2875
+ readlinkSync as readlinkSync3,
2876
+ realpathSync as realpathSync4,
2372
2877
  statSync as statSync2
2373
2878
  } from "fs";
2374
- import path7 from "path";
2375
- var shellBinPaths = (override) => Object.freeze((override ?? process.env.PATH ?? "").split(path7.delimiter));
2376
- var shellPathForLaunch = (binPaths) => (binPaths ?? shellBinPaths()).join(path7.delimiter);
2879
+ import path9 from "path";
2880
+ var shellBinPaths = (override) => Object.freeze((override ?? process.env.PATH ?? "").split(path9.delimiter));
2881
+ var shellPathForLaunch = (binPaths) => (binPaths ?? shellBinPaths()).join(path9.delimiter);
2377
2882
  var resolveShellExecutable = (name, paths, cwd = process.cwd()) => {
2378
- if (!name || name.includes("\0") || !path7.isAbsolute(name) && (name.includes("/") || process.platform === "win32" && name.includes("\\")))
2883
+ if (!name || name.includes("\0") || !path9.isAbsolute(name) && (name.includes("/") || process.platform === "win32" && name.includes("\\")))
2379
2884
  throw new Error("invalid_executable");
2380
- const executable = process.platform === "win32" && !path7.extname(name) ? `${name}.exe` : name;
2381
- const candidates = path7.isAbsolute(executable) ? [executable] : paths.map((entry) => {
2885
+ const executable = process.platform === "win32" && !path9.extname(name) ? `${name}.exe` : name;
2886
+ const candidates = path9.isAbsolute(executable) ? [executable] : paths.map((entry) => {
2382
2887
  const directory = process.platform === "win32" && entry.startsWith('"') && entry.endsWith('"') ? entry.slice(1, -1) : entry;
2383
- const resolved = path7.isAbsolute(directory) ? directory : `${cwd}${path7.sep}${directory || "."}`;
2384
- return `${resolved}${path7.sep}${executable}`;
2888
+ const resolved = path9.isAbsolute(directory) ? directory : `${cwd}${path9.sep}${directory || "."}`;
2889
+ return `${resolved}${path9.sep}${executable}`;
2385
2890
  });
2386
2891
  for (const candidate of candidates) {
2387
2892
  try {
2388
2893
  accessSync(candidate, constants3.X_OK);
2389
- const actual = realpathSync3(candidate);
2894
+ const actual = realpathSync4(candidate);
2390
2895
  if (statSync2(actual).isFile()) return actual;
2391
2896
  } catch {
2392
2897
  }
@@ -2401,11 +2906,11 @@ var inspectBashPath = (candidate, policy) => {
2401
2906
  while (components.length) {
2402
2907
  const component = components.shift();
2403
2908
  if (!component || component === ".") continue;
2404
- const name = path7.join(current, component);
2909
+ const name = path9.join(current, component);
2405
2910
  const restriction = policy(name);
2406
2911
  if (restriction === "unbound") throw new Error("unbound_shell_path");
2407
2912
  masked ||= restriction === "masked";
2408
- const entry = lstatSync3(name, { throwIfNoEntry: false });
2913
+ const entry = lstatSync4(name, { throwIfNoEntry: false });
2409
2914
  if (!entry) return void 0;
2410
2915
  if (!entry.isSymbolicLink()) {
2411
2916
  if (components.length && !entry.isDirectory()) return void 0;
@@ -2413,24 +2918,24 @@ var inspectBashPath = (candidate, policy) => {
2413
2918
  continue;
2414
2919
  }
2415
2920
  if (++links > 40) throw new Error("unbound_shell_path");
2416
- const destination = readlinkSync(name);
2417
- if (path7.isAbsolute(destination)) current = "/";
2921
+ const destination = readlinkSync3(name);
2922
+ if (path9.isAbsolute(destination)) current = "/";
2418
2923
  components = [...destination.split("/"), ...components];
2419
2924
  }
2420
2925
  return { file: current, masked };
2421
2926
  };
2422
2927
  var bindBashCommand = (name, paths, policy, acceptShared = () => false) => {
2423
- const absolute = path7.isAbsolute(name);
2928
+ const absolute = path9.isAbsolute(name);
2424
2929
  try {
2425
2930
  for (const directory of absolute ? [""] : paths) {
2426
- if (!absolute && (!path7.isAbsolute(directory) || directory.split("/").includes("..")))
2931
+ if (!absolute && (!path9.isAbsolute(directory) || directory.split("/").includes("..")))
2427
2932
  return void 0;
2428
2933
  const inspected = inspectBashPath(
2429
2934
  absolute ? name : `${directory}/${name}`,
2430
2935
  policy
2431
2936
  );
2432
2937
  if (!inspected) continue;
2433
- const executable = realpathSync3(inspected.file);
2938
+ const executable = realpathSync4(inspected.file);
2434
2939
  const restriction = policy(executable);
2435
2940
  if (restriction === "unbound") return void 0;
2436
2941
  const info = statSync2(executable, { bigint: true });
@@ -2456,11 +2961,11 @@ var bindBashCommand = (name, paths, policy, acceptShared = () => false) => {
2456
2961
  };
2457
2962
  function bindKnownSystemExecutable(program, paths, policy, directArgv) {
2458
2963
  if (process.platform === "win32") return void 0;
2459
- const name = path7.basename(program);
2964
+ const name = path9.basename(program);
2460
2965
  const known = new Set(
2461
2966
  [`/usr/bin/${name}`, `/bin/${name}`].flatMap((entry) => {
2462
2967
  try {
2463
- return [realpathSync3(entry)];
2968
+ return [realpathSync4(entry)];
2464
2969
  } catch {
2465
2970
  return [];
2466
2971
  }
@@ -2482,22 +2987,22 @@ var isRootControlledSharedExecutable = (file, info) => {
2482
2987
  var sameLinkMetadata = (left, right) => left.dev === right.dev && left.ino === right.ino && left.nlink === right.nlink && left.mode === right.mode && left.uid === right.uid && left.gid === right.gid && left.size === right.size && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
2483
2988
  function areAllExecutableLinksOutsideRestrictedPaths(file, info, policy) {
2484
2989
  try {
2485
- const parent = path7.dirname(file);
2486
- if (policy(parent) || realpathSync3(parent) !== parent) return false;
2487
- const directory = lstatSync3(parent, { bigint: true });
2488
- const executable = lstatSync3(file, { bigint: true });
2990
+ const parent = path9.dirname(file);
2991
+ if (policy(parent) || realpathSync4(parent) !== parent) return false;
2992
+ const directory = lstatSync4(parent, { bigint: true });
2993
+ const executable = lstatSync4(file, { bigint: true });
2489
2994
  if (!directory.isDirectory() || !executable.isFile() || !sameLinkMetadata(executable, info) || executable.nlink < 2n)
2490
2995
  return false;
2491
2996
  const mounts = process.platform === "linux" ? executableMountSnapshot(file, executable.dev) : void 0;
2492
2997
  let links = 0n;
2493
2998
  let foundExecutable = false;
2494
- const entries = readdirSync3(parent, { encoding: "buffer" });
2999
+ const entries = readdirSync4(parent, { encoding: "buffer" });
2495
3000
  if (entries.length > 4096) return false;
2496
3001
  for (const entry of entries) {
2497
3002
  const name = entry.toString();
2498
3003
  if (!Buffer.from(name).equals(entry)) return false;
2499
- const peer = path7.join(parent, name);
2500
- const peerInfo = lstatSync3(peer, { bigint: true });
3004
+ const peer = path9.join(parent, name);
3005
+ const peerInfo = lstatSync4(peer, { bigint: true });
2501
3006
  if (peerInfo.dev !== executable.dev || peerInfo.ino !== executable.ino)
2502
3007
  continue;
2503
3008
  if (!peerInfo.isFile() || policy(peer) || !sameLinkMetadata(executable, peerInfo))
@@ -2505,7 +3010,7 @@ function areAllExecutableLinksOutsideRestrictedPaths(file, info, policy) {
2505
3010
  foundExecutable ||= peer === file;
2506
3011
  links++;
2507
3012
  }
2508
- return foundExecutable && links === executable.nlink && realpathSync3(parent) === parent && sameLinkMetadata(directory, lstatSync3(parent, { bigint: true })) && sameLinkMetadata(executable, lstatSync3(file, { bigint: true })) && (mounts === void 0 || executableMountSnapshot(file, executable.dev) === mounts);
3013
+ return foundExecutable && links === executable.nlink && realpathSync4(parent) === parent && sameLinkMetadata(directory, lstatSync4(parent, { bigint: true })) && sameLinkMetadata(executable, lstatSync4(file, { bigint: true })) && (mounts === void 0 || executableMountSnapshot(file, executable.dev) === mounts);
2509
3014
  } catch {
2510
3015
  return false;
2511
3016
  }
@@ -2525,7 +3030,7 @@ var notWritable = (file) => {
2525
3030
  var within2 = (root, name) => root === "/" || root === name || name.startsWith(`${root}/`);
2526
3031
  var virtualRoots = ["/proc", "/dev", "/sys"];
2527
3032
  var managedTool = (name) => {
2528
- const resolved = realpathSync4(name);
3033
+ const resolved = realpathSync5(name);
2529
3034
  let current = resolved;
2530
3035
  for (; ; ) {
2531
3036
  const info = statSync3(current);
@@ -2534,18 +3039,18 @@ var managedTool = (name) => {
2534
3039
  if (current === resolved && (!info.isFile() || (info.mode & 73) === 0))
2535
3040
  throw new Error("sandbox_executable_unavailable");
2536
3041
  if (current === "/") return resolved;
2537
- current = path8.dirname(current);
3042
+ current = path10.dirname(current);
2538
3043
  }
2539
3044
  };
2540
3045
  var masksFor = (policy) => {
2541
3046
  const paths = /* @__PURE__ */ new Set();
2542
3047
  for (const item of [...policy.protectedPaths, "/run"]) {
2543
- if (!path8.isAbsolute(item) || item !== path8.normalize(item) || item === "/")
3048
+ if (!path10.isAbsolute(item) || item !== path10.normalize(item) || item === "/")
2544
3049
  throw new Error("invalid_protected_path");
2545
3050
  if (item === "/dev") continue;
2546
3051
  let resolved;
2547
3052
  try {
2548
- resolved = realpathSync4(item);
3053
+ resolved = realpathSync5(item);
2549
3054
  } catch (error) {
2550
3055
  if (error.code !== "ENOENT") throw error;
2551
3056
  resolved = item;
@@ -2560,10 +3065,28 @@ var masksFor = (policy) => {
2560
3065
  }
2561
3066
  return selected;
2562
3067
  };
2563
- var prepare = (policy, state, runsc, unshare) => {
2564
- const masks = masksFor(policy);
2565
- if (policy.profile === "full-access" || policy.profile === "investigation" && policy.writeRoots.length)
2566
- throw new Error("unsupported_protection");
3068
+ var readOnlyMount = (entry, projectedHome) => {
3069
+ try {
3070
+ if (realpathSync5(entry) !== entry)
3071
+ throw new Error("unbound_read_only_path");
3072
+ return entry;
3073
+ } catch (error) {
3074
+ if (error.code !== "ENOENT" || !projectedHome || !within2(projectedHome, entry) || resolveReservedTarget(entry) !== entry)
3075
+ throw error;
3076
+ }
3077
+ let parent = path10.dirname(entry);
3078
+ while (within2(projectedHome, parent)) {
3079
+ const info = lstatSync5(parent, { throwIfNoEntry: false });
3080
+ if (info) {
3081
+ if (info.isDirectory() && realpathSync5(parent) === parent) return parent;
3082
+ break;
3083
+ }
3084
+ if (parent === projectedHome) break;
3085
+ parent = path10.dirname(parent);
3086
+ }
3087
+ throw new Error("unbound_read_only_path");
3088
+ };
3089
+ var linuxRunscMountArgs = (policy, state, masks) => {
2567
3090
  const mountpoints = masks.map((target) => {
2568
3091
  const info = statSync3(target, { throwIfNoEntry: false });
2569
3092
  if (!info) throw new Error("missing_protected_mountpoint");
@@ -2574,13 +3097,89 @@ var prepare = (policy, state, runsc, unshare) => {
2574
3097
  placeholder: info.isDirectory() ? "empty-dir" : "empty-file"
2575
3098
  };
2576
3099
  });
3100
+ const readOnly = policy.readOnlyPaths ?? [];
3101
+ const home = policy.homeDotDirectory;
3102
+ const projectedHome = home && policy.writeRoots.includes(home) ? home : void 0;
3103
+ const protectedTargets = [...masks, ...readOnly];
3104
+ const covered = (target) => protectedTargets.some((entry) => within2(entry, target));
3105
+ const writableRoots = /* @__PURE__ */ new Set();
3106
+ const flags = ["--ro-bind", "/", "/", "--ro-bind", "/tmp", "/tmp"];
3107
+ for (const root of policy.writeRoots) {
3108
+ if (home && root !== home && (within2(root, home) || resourceContainsPath(root, home)))
3109
+ throw new Error("unsupported_home_write_root");
3110
+ if (root === "/" || realpathSync5(root) !== root || !statSync3(root).isDirectory() || virtualRoots.some((name) => within2(name, root)))
3111
+ throw new Error("invalid_write_root");
3112
+ if (within2(state, root)) continue;
3113
+ if (masks.some((mask) => within2(mask, root)))
3114
+ throw new Error("invalid_write_root");
3115
+ if (readOnly.some((entry) => within2(entry, root))) continue;
3116
+ if (root !== home) writableRoots.add(root);
3117
+ }
3118
+ if (projectedHome) {
3119
+ if (projectedHome !== "/tmp")
3120
+ flags.push("--ro-bind", projectedHome, projectedHome);
3121
+ for (const name of readdirSync5(projectedHome)) {
3122
+ const child = path10.join(projectedHome, name);
3123
+ if (child === state || isHomeDotTarget(projectedHome, child, "linux") || covered(child))
3124
+ continue;
3125
+ const info = lstatSync5(child, { throwIfNoEntry: false });
3126
+ if ((info?.isDirectory() || info?.isFile()) && realpathSync5(child) === child)
3127
+ writableRoots.add(child);
3128
+ }
3129
+ }
3130
+ const readOnlyMounts = /* @__PURE__ */ new Set();
3131
+ const proposedRoots = [...writableRoots];
3132
+ for (const entry of [...readOnly].sort((a, b) => a.length - b.length)) {
3133
+ if (!masks.some((mask) => within2(mask, entry)) && proposedRoots.some((root) => within2(root, entry)) && ![...readOnlyMounts].some((mount) => within2(mount, entry))) {
3134
+ readOnlyMounts.add(readOnlyMount(entry, projectedHome));
3135
+ }
3136
+ }
3137
+ protectedTargets.push(...readOnlyMounts);
3138
+ for (const root of writableRoots) {
3139
+ if (covered(root)) writableRoots.delete(root);
3140
+ }
3141
+ const writeRoots = [...writableRoots];
3142
+ const anchors = /* @__PURE__ */ new Set();
3143
+ for (const entry of [...readOnlyMounts, ...masks]) {
3144
+ let parent = path10.dirname(entry);
3145
+ while (writeRoots.some((root) => root !== parent && within2(root, parent))) {
3146
+ if (!writableRoots.has(parent) && !covered(parent)) anchors.add(parent);
3147
+ parent = path10.dirname(parent);
3148
+ }
3149
+ }
3150
+ for (const anchor of anchors) {
3151
+ const info = statSync3(anchor, { throwIfNoEntry: false });
3152
+ if (!info) {
3153
+ anchors.delete(anchor);
3154
+ continue;
3155
+ }
3156
+ if (!info.isDirectory() || realpathSync5(anchor) !== anchor)
3157
+ throw new Error("unbound_protected_ancestor");
3158
+ }
3159
+ for (const root of [...writeRoots, ...anchors].sort(
3160
+ (a, b) => a.length - b.length
3161
+ ))
3162
+ flags.push("--bind", root, root);
3163
+ for (const entry of [...readOnlyMounts].sort((a, b) => a.length - b.length)) {
3164
+ if (!writeRoots.some((root) => within2(root, entry))) continue;
3165
+ flags.push("--ro-bind", entry, entry);
3166
+ }
3167
+ for (const { target, placeholder } of mountpoints)
3168
+ flags.push("--ro-bind", `${state}/${placeholder}`, target);
3169
+ flags.push("--tmpfs", state);
3170
+ return flags;
3171
+ };
3172
+ var prepare = (policy, state, runsc, unshare) => {
3173
+ if (policy.profile === "full-access" || policy.profile === "investigation" && policy.writeRoots.length)
3174
+ throw new Error("unsupported_protection");
3175
+ const masks = masksFor(policy);
2577
3176
  if (findProtectedAliases(policy.protectedAliasPaths ?? policy.protectedPaths).size)
2578
3177
  throw new Error("protected_file_has_alias");
2579
3178
  const readOnly = policy.readOnlyPaths ?? [];
2580
3179
  if (policy.writeRoots.length && hasReadOnlyAliases(policy.readOnlyAliasPaths ?? readOnly))
2581
3180
  throw new Error("read_only_file_has_alias");
2582
3181
  checkLinuxMountTopology(readFileSync3("/proc/self/mountinfo", "utf8"));
2583
- const flags = [
3182
+ return [
2584
3183
  "--pdeathsig",
2585
3184
  "KILL",
2586
3185
  "--",
@@ -2607,46 +3206,7 @@ var prepare = (policy, state, runsc, unshare) => {
2607
3206
  "--cap-drop",
2608
3207
  "ALL",
2609
3208
  "--clearenv",
2610
- "--ro-bind",
2611
- "/",
2612
- "/",
2613
- "--ro-bind",
2614
- "/tmp",
2615
- "/tmp"
2616
- ];
2617
- for (const root of policy.writeRoots) {
2618
- if (root === "/" || realpathSync4(root) !== root || !statSync3(root).isDirectory() || virtualRoots.some((name) => within2(name, root)) || readOnly.some((name) => within2(name, root)) || masks.some((mask) => within2(mask, root)))
2619
- throw new Error("invalid_write_root");
2620
- flags.push("--bind", root, root);
2621
- }
2622
- const anchors = /* @__PURE__ */ new Set();
2623
- for (const entry of [...readOnly, ...masks]) {
2624
- let parent = path8.dirname(entry);
2625
- while (policy.writeRoots.some((root) => root !== parent && within2(root, parent))) {
2626
- if (!masks.some((mask) => within2(mask, parent)) && !readOnly.some((ro) => within2(ro, parent)))
2627
- anchors.add(parent);
2628
- parent = path8.dirname(parent);
2629
- }
2630
- }
2631
- for (const anchor of [...anchors].sort((a, b) => a.length - b.length)) {
2632
- const info = statSync3(anchor, { throwIfNoEntry: false });
2633
- if (!info) continue;
2634
- if (!info.isDirectory() || realpathSync4(anchor) !== anchor)
2635
- throw new Error("unbound_protected_ancestor");
2636
- flags.push("--bind", anchor, anchor);
2637
- }
2638
- for (const entry of readOnly) {
2639
- if (masks.some((mask) => within2(mask, entry))) continue;
2640
- if (!policy.writeRoots.some((root) => within2(root, entry))) continue;
2641
- if (realpathSync4(entry) !== entry)
2642
- throw new Error("unbound_read_only_path");
2643
- flags.push("--ro-bind", entry, entry);
2644
- }
2645
- for (const { target, placeholder } of mountpoints)
2646
- flags.push("--ro-bind", `${state}/${placeholder}`, target);
2647
- flags.push(
2648
- "--tmpfs",
2649
- state,
3209
+ ...linuxRunscMountArgs(policy, state, masks),
2650
3210
  "--setenv",
2651
3211
  "HOME",
2652
3212
  state,
@@ -2670,8 +3230,7 @@ var prepare = (policy, state, runsc, unshare) => {
2670
3230
  "--chdir",
2671
3231
  policy.cwd,
2672
3232
  "--"
2673
- );
2674
- return flags;
3233
+ ];
2675
3234
  };
2676
3235
  var release = (root) => rmSync(root, { recursive: true, force: true });
2677
3236
  var allocate = () => {
@@ -2688,6 +3247,7 @@ var allocate = () => {
2688
3247
  };
2689
3248
  var LinuxRunscBackend = class {
2690
3249
  supportsReadOnlyPaths = true;
3250
+ supportsHomeDotProtection = true;
2691
3251
  supportsCommandBinding = true;
2692
3252
  tools;
2693
3253
  probed = /* @__PURE__ */ new Set();
@@ -2704,10 +3264,10 @@ var LinuxRunscBackend = class {
2704
3264
  for (const candidate of ["/usr/local/bin/runsc", "/usr/bin/runsc"]) {
2705
3265
  try {
2706
3266
  const runsc = managedTool(candidate);
2707
- const sidecars = path8.join(path8.dirname(runsc), "gvisor-bin");
2708
- accessSync2(path8.join(sidecars, "gvisor_sentry"), constants4.X_OK);
2709
- for (const executable of readdirSync4(sidecars)) {
2710
- managedTool(path8.join(sidecars, executable));
3267
+ const sidecars = path10.join(path10.dirname(runsc), "gvisor-bin");
3268
+ accessSync2(path10.join(sidecars, "gvisor_sentry"), constants4.X_OK);
3269
+ for (const executable of readdirSync5(sidecars)) {
3270
+ managedTool(path10.join(sidecars, executable));
2711
3271
  }
2712
3272
  this.tools = { setpriv, unshare, runsc };
2713
3273
  return this.tools;
@@ -2785,16 +3345,16 @@ var LinuxRunscBackend = class {
2785
3345
 
2786
3346
  // src/permissions/mxc-launcher.ts
2787
3347
  import { spawn as spawn3, spawnSync as spawnSync2 } from "child_process";
2788
- import { lstatSync as lstatSync4, readFileSync as readFileSync4, realpathSync as realpathSync5, statSync as statSync4 } from "fs";
2789
- import path9 from "path";
3348
+ import { lstatSync as lstatSync6, readFileSync as readFileSync4, realpathSync as realpathSync6, statSync as statSync4 } from "fs";
3349
+ import path11 from "path";
2790
3350
  import { fileURLToPath } from "url";
2791
3351
  var binaryName = "codelia-mxc-launcher";
2792
- var packagePath = path9.join("node_modules", "@codelia", "tui-darwin-arm64");
2793
- var moduleDir = typeof __dirname === "string" ? __dirname : path9.dirname(fileURLToPath(import.meta.url));
3352
+ var packagePath = path11.join("node_modules", "@codelia", "tui-darwin-arm64");
3353
+ var moduleDir = typeof __dirname === "string" ? __dirname : path11.dirname(fileURLToPath(import.meta.url));
2794
3354
  var packageVersion = (directory, name) => {
2795
3355
  try {
2796
- const manifest = path9.join(directory, "package.json");
2797
- const info = lstatSync4(manifest);
3356
+ const manifest = path11.join(directory, "package.json");
3357
+ const info = lstatSync6(manifest);
2798
3358
  if (!info.isFile() || info.size > 64 * 1024) return void 0;
2799
3359
  const parsed = JSON.parse(readFileSync4(manifest, "utf8"));
2800
3360
  return parsed.name === name && typeof parsed.version === "string" ? parsed.version : void 0;
@@ -2803,24 +3363,27 @@ var packageVersion = (directory, name) => {
2803
3363
  }
2804
3364
  };
2805
3365
  var directoryId = (info) => `${info.dev}:${info.ino}`;
2806
- var trustedLauncher = (candidate, writableDirs, uid) => {
3366
+ var trustedLauncher = (candidate, writableDirs, uid, protectedHome) => {
2807
3367
  try {
2808
- const directory = realpathSync5(path9.dirname(candidate));
2809
- const file = path9.join(directory, binaryName);
2810
- const info = lstatSync4(file, { bigint: true });
3368
+ const directory = realpathSync6(path11.dirname(candidate));
3369
+ const file = path11.join(directory, binaryName);
3370
+ const info = lstatSync6(file, { bigint: true });
2811
3371
  if (!info.isFile() || info.nlink !== 1n || info.size === 0n || info.uid !== uid && info.uid !== 0n || (info.mode & 0o6022n) !== 0n || (info.mode & 0o100n) === 0n)
2812
3372
  return void 0;
3373
+ const protectedInHomeDot = protectedHome !== void 0 && isHomeDotTarget(protectedHome, directory);
2813
3374
  let current = directory;
2814
3375
  for (; ; ) {
2815
3376
  const parent = statSync4(current, { bigint: true });
2816
3377
  const systemSticky = parent.uid === 0n && (parent.mode & 0o1000n) !== 0n;
2817
- if (!parent.isDirectory() || writableDirs.has(directoryId(parent)) || parent.uid !== uid && parent.uid !== 0n || (parent.mode & 0o022n) !== 0n && !systemSticky)
3378
+ const isWritableParent = writableDirs.has(directoryId(parent)) && !(protectedInHomeDot && current === protectedHome);
3379
+ if (!parent.isDirectory() || isWritableParent || parent.uid !== uid && parent.uid !== 0n || (parent.mode & 0o022n) !== 0n && !systemSticky)
2818
3380
  return void 0;
2819
- const next = path9.dirname(current);
3381
+ const next = path11.dirname(current);
2820
3382
  if (next === current) break;
2821
3383
  current = next;
2822
3384
  }
2823
3385
  return {
3386
+ candidate,
2824
3387
  file,
2825
3388
  identity: `${directoryId(info)}:${info.size}:${info.ctimeNs}`
2826
3389
  };
@@ -2838,13 +3401,13 @@ var resolveMxcLauncher = (protection) => {
2838
3401
  (root) => directoryId(statSync4(root, { bigint: true }))
2839
3402
  )
2840
3403
  );
2841
- const actualModule = realpathSync5(moduleDir);
2842
- const projectPackage = path9.basename(actualModule) === "permissions" ? path9.resolve(actualModule, "../..") : path9.dirname(actualModule);
2843
- const suffix = path9.join("packages", "runtime");
2844
- if (projectPackage.endsWith(`${path9.sep}${suffix}`)) {
2845
- const checkout = path9.resolve(projectPackage, "../..");
3404
+ const actualModule = realpathSync6(moduleDir);
3405
+ const projectPackage = path11.basename(actualModule) === "permissions" ? path11.resolve(actualModule, "../..") : path11.dirname(actualModule);
3406
+ const suffix = path11.join("packages", "runtime");
3407
+ if (projectPackage.endsWith(`${path11.sep}${suffix}`)) {
3408
+ const checkout = path11.resolve(projectPackage, "../..");
2846
3409
  const built = trustedLauncher(
2847
- path9.join(checkout, "crates/mxc-launcher/target/release", binaryName),
3410
+ path11.join(checkout, "crates/mxc-launcher/target/release", binaryName),
2848
3411
  mutable,
2849
3412
  BigInt(uid)
2850
3413
  );
@@ -2854,14 +3417,15 @@ var resolveMxcLauncher = (protection) => {
2854
3417
  if (!version) return void 0;
2855
3418
  let directory = actualModule;
2856
3419
  for (; ; ) {
2857
- const candidatePackage = path9.join(directory, packagePath);
3420
+ const candidatePackage = path11.join(directory, packagePath);
2858
3421
  const installed = packageVersion(candidatePackage, "@codelia/tui-darwin-arm64") === version ? trustedLauncher(
2859
- path9.join(candidatePackage, "bin", binaryName),
3422
+ path11.join(candidatePackage, "bin", binaryName),
2860
3423
  mutable,
2861
- BigInt(uid)
3424
+ BigInt(uid),
3425
+ protection.homeDotDirectory
2862
3426
  ) : void 0;
2863
3427
  if (installed) return installed;
2864
- const parent = path9.dirname(directory);
3428
+ const parent = path11.dirname(directory);
2865
3429
  if (parent === directory) return void 0;
2866
3430
  directory = parent;
2867
3431
  }
@@ -2952,80 +3516,20 @@ var launchMxc = (launcher, request, stdin) => {
2952
3516
  return child;
2953
3517
  };
2954
3518
 
2955
- // src/permissions/resource-paths.ts
2956
- import { lstatSync as lstatSync5, opendirSync } from "fs";
2957
- import path10 from "path";
2958
- var lookup = (pathname) => lstatSync5(pathname, { bigint: true, throwIfNoEntry: false });
2959
- var sameEntry = (left, right) => left.dev === right.dev && left.ino === right.ino;
2960
- var comparableResourceName = (pathname) => {
2961
- const folded = pathname.normalize("NFD").toUpperCase().toLowerCase();
2962
- return process.platform === "win32" ? folded.replace(/[ .]+(?=[\\/]|$)/gu, "") : folded;
2963
- };
2964
- function distinguishesAsciiCase(parent) {
2965
- try {
2966
- const directory = opendirSync(parent);
2967
- try {
2968
- for (let index = 0; index < 16; index++) {
2969
- const name = directory.readSync()?.name;
2970
- if (!name) break;
2971
- const changed = name.replace(
2972
- /[A-Za-z]/u,
2973
- (letter) => letter === letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase()
2974
- );
2975
- if (name === changed) continue;
2976
- const original = lookup(path10.join(parent, name));
2977
- const alternate = lookup(path10.join(parent, changed));
2978
- if (original) return !alternate || !sameEntry(original, alternate);
2979
- }
2980
- } finally {
2981
- directory.closeSync();
2982
- }
2983
- } catch {
2984
- }
2985
- return false;
2986
- }
2987
- function resourceContainsPath(resource, target) {
2988
- if (target === resource || target.startsWith(
2989
- resource.endsWith(path10.sep) ? resource : `${resource}${path10.sep}`
2990
- ))
2991
- return true;
2992
- const root = path10.parse(resource).root;
2993
- const targetRoot = path10.parse(target).root;
2994
- if (comparableResourceName(root) !== comparableResourceName(targetRoot))
2995
- return false;
2996
- const parts = resource.slice(root.length).split(path10.sep);
2997
- const overlapping = target.slice(targetRoot.length).split(path10.sep).slice(0, parts.length);
2998
- if (overlapping.length !== parts.length) return false;
2999
- const candidate = path10.join(targetRoot, ...overlapping);
3000
- const namesMayMatch = comparableResourceName(resource) === comparableResourceName(candidate);
3001
- try {
3002
- const targetEntry = lookup(candidate);
3003
- if (!targetEntry && !namesMayMatch) return false;
3004
- const protectedEntry = lookup(resource);
3005
- if (protectedEntry || targetEntry)
3006
- return !!protectedEntry && !!targetEntry && sameEntry(protectedEntry, targetEntry);
3007
- if (!namesMayMatch) return false;
3008
- const parent = path10.dirname(resource);
3009
- return path10.dirname(candidate) !== parent || !/^[\x20-\x7e]+$/u.test(path10.basename(resource)) || !/^[\x20-\x7e]+$/u.test(path10.basename(candidate)) || path10.basename(resource).toLowerCase() !== path10.basename(candidate).toLowerCase() || !distinguishesAsciiCase(parent);
3010
- } catch {
3011
- return namesMayMatch;
3012
- }
3013
- }
3014
-
3015
3519
  // src/permissions/system-bash.ts
3016
3520
  import {
3017
3521
  accessSync as accessSync3,
3018
3522
  constants as constants5,
3019
- lstatSync as lstatSync6,
3020
- readlinkSync as readlinkSync2
3523
+ lstatSync as lstatSync7,
3524
+ readlinkSync as readlinkSync4
3021
3525
  } from "fs";
3022
3526
  import { posix } from "path";
3023
3527
  var conventional = ["/bin/bash", "/usr/bin/bash"];
3024
3528
  var nixSystemBash = "/run/current-system/sw/bin/bash";
3025
3529
  var nixStoreBash = /^\/nix\/store\/[^/]+\/bin\/bash$/u;
3026
3530
  var hostEntries = {
3027
- stat: (name) => lstatSync6(name, { throwIfNoEntry: false }),
3028
- readLink: readlinkSync2,
3531
+ stat: (name) => lstatSync7(name, { throwIfNoEntry: false }),
3532
+ readLink: readlinkSync4,
3029
3533
  canExecute: (name) => accessSync3(name, constants5.X_OK)
3030
3534
  };
3031
3535
  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
@@ -3073,23 +3577,23 @@ var resolveSystemBash = (platform = process.platform, entries = hostEntries) =>
3073
3577
  };
3074
3578
 
3075
3579
  // src/permissions/workspace-config-paths.ts
3076
- import { lstatSync as lstatSync7, opendirSync as opendirSync2, readlinkSync as readlinkSync3, realpathSync as realpathSync6 } from "fs";
3077
- import path11 from "path";
3580
+ import { lstatSync as lstatSync8, opendirSync as opendirSync2, readlinkSync as readlinkSync5, realpathSync as realpathSync7 } from "fs";
3581
+ import path12 from "path";
3078
3582
  import { resolveStoragePaths as resolveStoragePaths2 } from "@codelia/storage";
3079
3583
  var confinedAutoLaunchDirectoryName = "confined-auto-launch";
3080
- var isWorkspaceConfigName = (root, target) => resourceContainsPath(path11.dirname(resolveProjectConfigPath(root)), target);
3081
- var missing = (error) => error.code === "ENOENT";
3584
+ var isWorkspaceConfigName = (root, target) => resourceContainsPath(path12.dirname(resolveProjectConfigPath(root)), target);
3585
+ var missing2 = (error) => error.code === "ENOENT";
3082
3586
  function resolveConfigTarget(target, remaining = 64) {
3083
3587
  if (!remaining) throw new Error("workspace_config_path_unresolved");
3084
3588
  try {
3085
- return realpathSync6(target);
3589
+ return realpathSync7(target);
3086
3590
  } catch (error) {
3087
- const parent = path11.dirname(target);
3088
- if (!missing(error) || parent === target) throw error;
3591
+ const parent = path12.dirname(target);
3592
+ if (!missing2(error) || parent === target) throw error;
3089
3593
  const canonicalParent = resolveConfigTarget(parent, remaining - 1);
3090
- if (!lstatSync7(target, { throwIfNoEntry: false })?.isSymbolicLink())
3091
- return path11.join(canonicalParent, path11.basename(target));
3092
- const referent = readlinkSync3(target);
3594
+ if (!lstatSync8(target, { throwIfNoEntry: false })?.isSymbolicLink())
3595
+ return path12.join(canonicalParent, path12.basename(target));
3596
+ const referent = readlinkSync5(target);
3093
3597
  let seenName = false;
3094
3598
  for (const part of referent.split(
3095
3599
  process.platform === "win32" ? /[\\/]/u : "/"
@@ -3099,14 +3603,14 @@ function resolveConfigTarget(target, remaining = 64) {
3099
3603
  if (part && part !== "." && part !== "..") seenName = true;
3100
3604
  }
3101
3605
  return resolveConfigTarget(
3102
- path11.resolve(canonicalParent, referent),
3606
+ path12.resolve(canonicalParent, referent),
3103
3607
  remaining - 1
3104
3608
  );
3105
3609
  }
3106
3610
  }
3107
3611
  var workspaceConfigProtection = (root) => {
3108
3612
  const config = resolveProjectConfigPath(root);
3109
- const directory = path11.dirname(config);
3613
+ const directory = path12.dirname(config);
3110
3614
  const readOnlyPaths = /* @__PURE__ */ new Set([directory]);
3111
3615
  const readOnlyAliasPaths = /* @__PURE__ */ new Set();
3112
3616
  const reserveTarget = (file) => {
@@ -3114,12 +3618,12 @@ var workspaceConfigProtection = (root) => {
3114
3618
  readOnlyPaths.add(target);
3115
3619
  readOnlyAliasPaths.add(target);
3116
3620
  };
3117
- if (lstatSync7(directory, { throwIfNoEntry: false })) {
3621
+ if (lstatSync8(directory, { throwIfNoEntry: false })) {
3118
3622
  const canonical = resolveConfigTarget(directory);
3119
3623
  readOnlyPaths.add(canonical);
3120
- if (lstatSync7(canonical, { throwIfNoEntry: false })?.isDirectory()) {
3121
- const file = path11.join(canonical, path11.basename(config));
3122
- if (lstatSync7(file, { throwIfNoEntry: false })) reserveTarget(file);
3624
+ if (lstatSync8(canonical, { throwIfNoEntry: false })?.isDirectory()) {
3625
+ const file = path12.join(canonical, path12.basename(config));
3626
+ if (lstatSync8(file, { throwIfNoEntry: false })) reserveTarget(file);
3123
3627
  const storage = resolveStoragePaths2();
3124
3628
  const globalStorage = [
3125
3629
  resolveStoragePaths2({ layout: "home" }).root,
@@ -3127,24 +3631,24 @@ var workspaceConfigProtection = (root) => {
3127
3631
  storage.configDir
3128
3632
  ].some((entry) => {
3129
3633
  try {
3130
- return realpathSync6(entry) === canonical;
3634
+ return realpathSync7(entry) === canonical;
3131
3635
  } catch (error) {
3132
- if (!missing(error)) throw error;
3636
+ if (!missing2(error)) throw error;
3133
3637
  return false;
3134
3638
  }
3135
3639
  });
3136
3640
  if (!globalStorage) {
3137
- const worktrees = path11.join(canonical, "worktrees");
3641
+ const worktrees = path12.join(canonical, "worktrees");
3138
3642
  const pending = [canonical];
3139
3643
  for (const current of pending) {
3140
3644
  const children = opendirSync2(current);
3141
3645
  try {
3142
3646
  for (let entry = children.readSync(); entry; entry = children.readSync()) {
3143
- const target = path11.join(current, entry.name);
3647
+ const target = path12.join(current, entry.name);
3144
3648
  if (target === file || target === worktrees) continue;
3145
3649
  if (entry.isSymbolicLink()) reserveTarget(target);
3146
3650
  else if (entry.isDirectory()) pending.push(target);
3147
- else if (entry.isFile() && (lstatSync7(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
3651
+ else if (entry.isFile() && (lstatSync8(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
3148
3652
  readOnlyAliasPaths.add(target);
3149
3653
  }
3150
3654
  } finally {
@@ -3163,7 +3667,7 @@ var workspaceConfigProtection = (root) => {
3163
3667
  // src/permissions/shell-backend.ts
3164
3668
  var supportsProtectedShell = (backend, protection, invocation) => {
3165
3669
  try {
3166
- return (protection.profile === "full-access" || !protection.readOnlyPaths?.length || backend.supportsReadOnlyPaths === true) && backend.supports(protection) === true && (!invocation || !backend.supportsInvocation || backend.supportsInvocation(invocation, protection) === true);
3670
+ return (protection.profile === "full-access" || (!protection.readOnlyPaths?.length || backend.supportsReadOnlyPaths === true) && (!protection.homeDotDirectory || backend.supportsHomeDotProtection === true)) && backend.supports(protection) === true && (!invocation || !backend.supportsInvocation || backend.supportsInvocation(invocation, protection) === true);
3167
3671
  } catch {
3168
3672
  return false;
3169
3673
  }
@@ -3182,11 +3686,11 @@ var platformShellSource = (source) => {
3182
3686
  return fixedBash(source, executable);
3183
3687
  }
3184
3688
  const systemRoot = process.env.SystemRoot;
3185
- if (!systemRoot || !path12.isAbsolute(systemRoot))
3689
+ if (!systemRoot || !path13.isAbsolute(systemRoot))
3186
3690
  throw new Error("windows_system_directory_unavailable");
3187
3691
  return Object.freeze({
3188
3692
  kind: "source",
3189
- executable: path12.join(
3693
+ executable: path13.join(
3190
3694
  systemRoot,
3191
3695
  "System32",
3192
3696
  "WindowsPowerShell",
@@ -3205,27 +3709,27 @@ var platformShellSource = (source) => {
3205
3709
  };
3206
3710
  var realOrLexical = (value) => {
3207
3711
  try {
3208
- return realpathSync7(value);
3712
+ return realpathSync8(value);
3209
3713
  } catch {
3210
- return path12.resolve(value);
3714
+ return path13.resolve(value);
3211
3715
  }
3212
3716
  };
3213
3717
  var resolvePolicyPath = (target) => {
3214
- const absolute = path12.resolve(target);
3718
+ const absolute = path13.resolve(target);
3215
3719
  try {
3216
- return realpathSync7(absolute);
3720
+ return realpathSync8(absolute);
3217
3721
  } catch (error) {
3218
- const parent = path12.dirname(absolute);
3722
+ const parent = path13.dirname(absolute);
3219
3723
  if (error.code !== "ENOENT" || parent === absolute)
3220
3724
  throw error;
3221
- if (lstatSync8(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
3725
+ if (lstatSync9(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
3222
3726
  throw error;
3223
- return path12.join(resolvePolicyPath(parent), path12.basename(absolute));
3727
+ return path13.join(resolvePolicyPath(parent), path13.basename(absolute));
3224
3728
  }
3225
3729
  };
3226
3730
  var canonicalPolicyPaths = (paths) => Object.freeze([
3227
3731
  ...new Set(
3228
- paths.flatMap((entry) => [path12.resolve(entry), resolvePolicyPath(entry)])
3732
+ paths.flatMap((entry) => [path13.resolve(entry), resolvePolicyPath(entry)])
3229
3733
  )
3230
3734
  ]);
3231
3735
  var runtimeReadOnlyPaths = () => {
@@ -3237,37 +3741,68 @@ var runtimeReadOnlyPaths = () => {
3237
3741
  resolveConfigPath()
3238
3742
  ]);
3239
3743
  };
3744
+ var runtimeProtectedCredentialPaths = () => {
3745
+ const storage = resolveStoragePaths3();
3746
+ const targets = [];
3747
+ if (process.platform === "linux") {
3748
+ try {
3749
+ mkdirSync2(storage.credentialsDir, { recursive: true, mode: 448 });
3750
+ targets.push(storage.credentialsDir);
3751
+ } catch {
3752
+ if (lstatSync9(storage.credentialsDir, { throwIfNoEntry: false })) {
3753
+ targets.push(storage.credentialsDir);
3754
+ }
3755
+ }
3756
+ for (const legacy of [storage.legacyAuthFile, storage.legacyMcpAuthFile]) {
3757
+ if (lstatSync9(legacy, { throwIfNoEntry: false })) {
3758
+ targets.push(legacy);
3759
+ }
3760
+ }
3761
+ } else {
3762
+ targets.push(
3763
+ storage.credentialsDir,
3764
+ storage.legacyAuthFile,
3765
+ storage.legacyMcpAuthFile
3766
+ );
3767
+ }
3768
+ return canonicalPolicyPaths(targets);
3769
+ };
3240
3770
  var runtimeAuthorityAliasPaths = () => {
3241
3771
  const storage = resolveStoragePaths3();
3242
3772
  const databasePaths = [
3243
- path12.join(storage.configDir, ".projects-policy-lock.sqlite"),
3244
- path12.join(storage.sessionsDir, "state.db")
3773
+ path13.join(storage.configDir, ".projects-policy-lock.sqlite"),
3774
+ path13.join(storage.sessionsDir, "state.db")
3245
3775
  ];
3246
3776
  return canonicalPolicyPaths([
3247
3777
  resolveConfigPath(),
3248
3778
  storage.configFile,
3249
3779
  storage.projectsFile,
3250
- storage.authFile,
3251
- storage.mcpAuthFile,
3252
3780
  ...[
3253
3781
  "launch-approvals",
3254
3782
  "auto-review.json",
3255
3783
  confinedAutoLaunchDirectoryName
3256
- ].map((entry) => path12.join(storage.configDir, entry)),
3784
+ ].map((entry) => path13.join(storage.configDir, entry)),
3257
3785
  ...databasePaths.flatMap(
3258
3786
  (file) => ["", "-wal", "-shm", "-journal"].map((suffix) => `${file}${suffix}`)
3259
3787
  )
3260
3788
  ]);
3261
3789
  };
3262
- var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectories = [], sandboxMode = "workspace-write", allowSharedGitObjects = false, extraReadOnlyPaths = []) => {
3790
+ var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectories = [], sandboxMode = "workspace-write", allowSharedGitObjects = false, extraReadOnlyPaths = [], homeScope = {}) => {
3263
3791
  const discover = allowSharedGitObjects && sandboxMode === "workspace-write" ? gitMetadataWithObjectDirectories : gitMetadataPaths;
3264
3792
  const { readOnlyPaths, reservedMarkers, objectDirectories, hookAliases } = discover(root, ...relatedDirectories);
3265
- const protectedPaths = canonicalPolicyPaths(extraProtectedPaths);
3793
+ const protectedPaths = canonicalPolicyPaths([
3794
+ ...extraProtectedPaths,
3795
+ ...runtimeProtectedCredentialPaths()
3796
+ ]);
3266
3797
  const projectConfig = workspaceConfigProtection(root);
3267
3798
  const hostReadOnlyPaths = canonicalPolicyPaths(extraReadOnlyPaths);
3268
3799
  const runtimeRoots = runtimeReadOnlyPaths();
3269
3800
  const runtimeAuthority = runtimeAuthorityAliasPaths();
3801
+ const protectedHome = homeDotDirectory(
3802
+ homeScope.writeRoots ?? (sandboxMode === "readonly" ? [] : [root])
3803
+ );
3270
3804
  const additionalReadOnlyPaths = [
3805
+ ...protectedHome && !homeScope.recheckHomeLinksOnWrite ? homeDotLinkTargets(protectedHome) : [],
3271
3806
  ...reservedMarkers,
3272
3807
  ...projectConfig.readOnlyPaths,
3273
3808
  ...hostReadOnlyPaths,
@@ -3280,13 +3815,14 @@ var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectorie
3280
3815
  const objectDirectoriesWithSharedFiles = objectDirectories.filter(
3281
3816
  (directory) => {
3282
3817
  const overlaps = (other) => resourceContainsPath(other, directory.path) || resourceContainsPath(directory.path, other);
3283
- const commonDirectory = path12.dirname(directory.path);
3818
+ const commonDirectory = path13.dirname(directory.path);
3284
3819
  return !strongerPaths.some(overlaps) && !readOnlyPaths.some(
3285
3820
  (other) => overlaps(other) && realOrLexical(other) !== commonDirectory
3286
3821
  );
3287
3822
  }
3288
3823
  );
3289
3824
  return {
3825
+ ...protectedHome ? { homeDotDirectory: protectedHome } : {},
3290
3826
  protectedPaths,
3291
3827
  protectedAliasPaths: protectedPaths,
3292
3828
  readOnlyPaths: Object.freeze(
@@ -3317,11 +3853,13 @@ var sbplString = (value) => {
3317
3853
  var subpaths = (paths) => paths.map((entry) => `(subpath ${sbplString(entry)})`).join(" ");
3318
3854
  var protectedSeatbeltAncestors = (base) => {
3319
3855
  const parents = /* @__PURE__ */ new Set();
3856
+ if (base.homeDotDirectory) parents.add(base.homeDotDirectory);
3320
3857
  for (const protectedPath of [
3321
3858
  ...base.protectedPaths,
3322
- ...base.readOnlyPaths ?? []
3859
+ ...base.readOnlyPaths ?? [],
3860
+ ...base.homeDotDirectory ? [base.homeDotDirectory] : []
3323
3861
  ]) {
3324
- for (let child = protectedPath, parent = path12.dirname(child); parent !== child; child = parent, parent = path12.dirname(child)) {
3862
+ for (let child = protectedPath, parent = path13.dirname(child); parent !== child; child = parent, parent = path13.dirname(child)) {
3325
3863
  if (base.writeRoots.some((root) => isWithin(root, parent)))
3326
3864
  parents.add(parent);
3327
3865
  }
@@ -3335,6 +3873,11 @@ var seatbeltProfile = (base, scratch, mutation) => {
3335
3873
  ...base,
3336
3874
  protectedPaths: [...base.protectedPaths, ...deviceAndIpcPaths]
3337
3875
  }).map(literal).join(" ");
3876
+ const home = base.homeDotDirectory;
3877
+ const homeRule = home ? `(deny file-write* (prefix ${sbplString(`${path13.join(home, "/")}.`)}) ${subpaths([path13.join(home, "Library")])})` : "";
3878
+ const approvedHomeDotRoots = !mutation && home ? base.writeRoots.filter(
3879
+ (root) => root !== home && isHomeDotTarget(home, root)
3880
+ ) : [];
3338
3881
  const writeTrees = mutation ? [scratch] : [scratch, ...base.writeRoots];
3339
3882
  const fixedWriteRules = mutation && [
3340
3883
  mutation.directories.length ? `(allow file-write-create ${mutation.directories.map(literal).join(" ")})` : "",
@@ -3355,6 +3898,8 @@ ${fixedWriteRules ?? ""}
3355
3898
  (allow file-read* (literal "/dev/null") (literal "/dev/zero")
3356
3899
  (literal "/dev/random") (literal "/dev/urandom"))
3357
3900
  (allow file-write-data (literal "/dev/null"))
3901
+ ${homeRule}
3902
+ ${approvedHomeDotRoots.length ? `(allow file-write* ${subpaths(approvedHomeDotRoots)})` : ""}
3358
3903
  ${base.protectedPaths.length ? `(deny file-read* file-write* ${subpaths(base.protectedPaths)})` : ""}
3359
3904
  ${base.readOnlyPaths?.length ? `(deny file-write* ${subpaths(base.readOnlyPaths)})` : ""}
3360
3905
  ${ancestors ? `(deny file-write-unlink ${ancestors})` : ""}
@@ -3363,12 +3908,28 @@ ${ancestors ? `(deny file-write-unlink ${ancestors})` : ""}
3363
3908
  `;
3364
3909
  };
3365
3910
  var sandboxExec = "/usr/bin/sandbox-exec";
3911
+ var macAdditionalWriteLauncherPaths = (protection) => {
3912
+ const baseline = resolveMxcLauncher({
3913
+ ...protection,
3914
+ writeRoots: [protection.root],
3915
+ homeDotDirectory: homeDotDirectory([protection.root])
3916
+ });
3917
+ const selected = resolveMxcLauncher(protection);
3918
+ return [
3919
+ ...new Set(
3920
+ [baseline, selected].flatMap(
3921
+ (launcher) => launcher ? [launcher.candidate, launcher.file] : []
3922
+ )
3923
+ )
3924
+ ];
3925
+ };
3366
3926
  var MacSeatbeltBackend = class {
3367
3927
  constructor(launcher = "seatbelt") {
3368
3928
  this.launcher = launcher;
3369
3929
  }
3370
3930
  launcher;
3371
3931
  supportsReadOnlyPaths = true;
3932
+ supportsHomeDotProtection = true;
3372
3933
  supportsCommandBinding = true;
3373
3934
  available;
3374
3935
  mxcProbe;
@@ -3385,7 +3946,7 @@ var MacSeatbeltBackend = class {
3385
3946
  return false;
3386
3947
  try {
3387
3948
  if (mutation && (protection.profile !== "development" || protection.stdin !== "pipe" || [...mutation.directories, mutation.destination, mutation.source].some(
3388
- (entry) => entry !== void 0 && (!path12.isAbsolute(entry) || path12.normalize(entry) !== entry || !protection.writeRoots.some(
3949
+ (entry) => entry !== void 0 && (!path13.isAbsolute(entry) || path13.normalize(entry) !== entry || !protection.writeRoots.some(
3389
3950
  (root) => entry !== root && isWithin(root, entry)
3390
3951
  ))
3391
3952
  )))
@@ -3470,8 +4031,8 @@ var MacSeatbeltBackend = class {
3470
4031
  launchWithPolicy(invocation, protection, mutation) {
3471
4032
  if (!(mutation ? this.supportsPolicy(protection, mutation) : this.supports(protection)))
3472
4033
  throw new Error("sandbox_unavailable");
3473
- const scratch = realpathSync7(
3474
- mkdtempSync2(path12.join(os.tmpdir(), "codelia-shell-"))
4034
+ const scratch = realpathSync8(
4035
+ mkdtempSync2(path13.join(os2.tmpdir(), "codelia-shell-"))
3475
4036
  );
3476
4037
  const cleanup = () => {
3477
4038
  try {
@@ -3548,15 +4109,15 @@ var UserShellBackend = class {
3548
4109
  windowsHide: true,
3549
4110
  env: {
3550
4111
  PATH: shellPathForLaunch(protection.binPaths),
3551
- HOME: os.homedir(),
3552
- TMPDIR: os.tmpdir(),
4112
+ HOME: os2.homedir(),
4113
+ TMPDIR: os2.tmpdir(),
3553
4114
  LANG: "C",
3554
4115
  ...protection.toolchainHomes,
3555
4116
  ...process.platform === "win32" && {
3556
4117
  SystemRoot: process.env.SystemRoot,
3557
- USERPROFILE: os.homedir(),
3558
- TEMP: os.tmpdir(),
3559
- TMP: os.tmpdir()
4118
+ USERPROFILE: os2.homedir(),
4119
+ TEMP: os2.tmpdir(),
4120
+ TMP: os2.tmpdir()
3560
4121
  }
3561
4122
  },
3562
4123
  stdio: [protection.stdin === "pipe" ? "pipe" : "ignore", "pipe", "pipe"]
@@ -4527,10 +5088,10 @@ var createRuntimeModel = async ({
4527
5088
 
4528
5089
  // src/runtime-state.ts
4529
5090
  import crypto from "crypto";
4530
- import { realpathSync as realpathSync8 } from "fs";
5091
+ import { realpathSync as realpathSync9 } from "fs";
4531
5092
 
4532
5093
  // src/environment.ts
4533
- import path13 from "path";
5094
+ import path14 from "path";
4534
5095
  import {
4535
5096
  parseSandboxMode
4536
5097
  } from "@codelia/shared-types";
@@ -4543,7 +5104,7 @@ var cloneContract = (contract) => ({
4543
5104
  persistence: { ...contract.persistence },
4544
5105
  events: { ...contract.events }
4545
5106
  });
4546
- var defaultWorkspaceRoot = () => process.env.CODELIA_SANDBOX_ROOT ? path13.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
5107
+ var defaultWorkspaceRoot = () => process.env.CODELIA_SANDBOX_ROOT ? path14.resolve(process.env.CODELIA_SANDBOX_ROOT) : process.cwd();
4547
5108
  var runtimeEnvironmentPresets = {
4548
5109
  "tui-local": {
4549
5110
  workspace: {
@@ -4668,11 +5229,11 @@ var resolveRuntimeEnvironment = (options = {}) => {
4668
5229
  if (contract.workspace.sandboxMode !== void 0 && !parseSandboxMode(contract.workspace.sandboxMode))
4669
5230
  throw new Error("Invalid workspace.sandboxMode");
4670
5231
  if (contract.workspace.filesystem === "enabled" || contract.workspace.process === "runtime") {
4671
- contract.workspace.root = path13.resolve(
5232
+ contract.workspace.root = path14.resolve(
4672
5233
  contract.workspace.root ?? defaultWorkspaceRoot()
4673
5234
  );
4674
5235
  } else if (contract.workspace.root) {
4675
- contract.workspace.root = path13.resolve(contract.workspace.root);
5236
+ contract.workspace.root = path14.resolve(contract.workspace.root);
4676
5237
  }
4677
5238
  rejectContract(
4678
5239
  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"),
@@ -4912,7 +5473,7 @@ var RuntimeState = class {
4912
5473
  if (scope === "workspace") {
4913
5474
  const root = this.runtimeSandboxRoot ?? this.runtimeWorkingDir;
4914
5475
  return JSON.stringify([
4915
- root === null ? null : realpathSync8(root),
5476
+ root === null ? null : realpathSync9(root),
4916
5477
  this.sandboxMode.value,
4917
5478
  connection,
4918
5479
  authority
@@ -4928,6 +5489,7 @@ var RuntimeState = class {
4928
5489
  authority
4929
5490
  ]);
4930
5491
  }
5492
+ acceptedSteerIds = /* @__PURE__ */ new Map();
4931
5493
  pendingSteersByRun = /* @__PURE__ */ new Map();
4932
5494
  steerClosedRuns = /* @__PURE__ */ new Set();
4933
5495
  uiRequestCounter = 0;
@@ -5062,6 +5624,7 @@ var RuntimeState = class {
5062
5624
  this.lastContextLeftPercent = null;
5063
5625
  this.runSeq.delete(runId);
5064
5626
  this.pendingSteersByRun.delete(runId);
5627
+ this.acceptedSteerIds.delete(runId);
5065
5628
  this.steerClosedRuns.delete(runId);
5066
5629
  if (this.activeRunId === null) {
5067
5630
  this.sessionAppend = null;
@@ -5074,10 +5637,18 @@ var RuntimeState = class {
5074
5637
  canSteerRun(runId) {
5075
5638
  return this.activeRunId === runId && !this.cancelRequested && !this.steerClosedRuns.has(runId);
5076
5639
  }
5640
+ acceptedRunSteerId(runId, clientSteerId) {
5641
+ return this.acceptedSteerIds.get(runId)?.get(clientSteerId);
5642
+ }
5077
5643
  enqueueRunSteer(runId, content, clientSteerId, approvalUserText) {
5078
5644
  this.signalApprovalChange();
5079
5645
  this.runSteerCounter += 1;
5080
5646
  const steerId = `s${this.runSteerCounter}`;
5647
+ if (clientSteerId !== void 0) {
5648
+ const accepted = this.acceptedSteerIds.get(runId) ?? /* @__PURE__ */ new Map();
5649
+ accepted.set(clientSteerId, steerId);
5650
+ this.acceptedSteerIds.set(runId, accepted);
5651
+ }
5081
5652
  if (this.approvalIntent?.runId === runId) {
5082
5653
  this.approvalIntent.steers.push({
5083
5654
  id: steerId,
@@ -5088,7 +5659,7 @@ var RuntimeState = class {
5088
5659
  const queue = this.pendingSteersByRun.get(runId) ?? [];
5089
5660
  queue.push({
5090
5661
  steer_id: steerId,
5091
- ...clientSteerId ? { client_steer_id: clientSteerId } : {},
5662
+ ...clientSteerId !== void 0 ? { client_steer_id: clientSteerId } : {},
5092
5663
  content
5093
5664
  });
5094
5665
  this.pendingSteersByRun.set(runId, queue);
@@ -5212,7 +5783,7 @@ var RuntimeState = class {
5212
5783
  };
5213
5784
 
5214
5785
  // src/subagents/bootstrap.ts
5215
- import path14 from "path";
5786
+ import path15 from "path";
5216
5787
  import { sandboxModes } from "@codelia/shared-types";
5217
5788
  import { z as z3 } from "zod";
5218
5789
 
@@ -5286,8 +5857,8 @@ var subagentBootstrapSchema = z3.object({
5286
5857
  version: z3.literal(1),
5287
5858
  task_id: z3.string().uuid(),
5288
5859
  prompt: z3.string().min(1).max(32768),
5289
- workspace_root: z3.string().refine(path14.isAbsolute),
5290
- protected_paths: z3.array(z3.string().refine(path14.isAbsolute)).optional(),
5860
+ workspace_root: z3.string().refine(path15.isAbsolute),
5861
+ protected_paths: z3.array(z3.string().refine(path15.isAbsolute)).optional(),
5291
5862
  lineage: z3.object({
5292
5863
  name: subagentNameSchema.optional(),
5293
5864
  tree_id: z3.string().min(1),
@@ -6209,7 +6780,7 @@ var redactSubagentJson = (value, secrets = []) => JSON.parse(
6209
6780
 
6210
6781
  // src/subagents/read-tools.ts
6211
6782
  import { promises as fs6 } from "fs";
6212
- import path17 from "path";
6783
+ import path18 from "path";
6213
6784
  import { defineTool } from "@codelia/core";
6214
6785
  import { z as z5 } from "zod";
6215
6786
 
@@ -6218,10 +6789,10 @@ import crypto3 from "crypto";
6218
6789
  import {
6219
6790
  constants as constants6,
6220
6791
  promises as fs4,
6221
- lstatSync as lstatSync9,
6222
- realpathSync as realpathSync9
6792
+ lstatSync as lstatSync10,
6793
+ realpathSync as realpathSync10
6223
6794
  } from "fs";
6224
- import path15 from "path";
6795
+ import path16 from "path";
6225
6796
  var SecurityError = class extends Error {
6226
6797
  constructor(message) {
6227
6798
  super(message);
@@ -6231,22 +6802,22 @@ var SecurityError = class extends Error {
6231
6802
  var identity = (info) => `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
6232
6803
  var directoryIdentity2 = (stat) => `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
6233
6804
  var selectMissingFile = (entry) => {
6234
- let parent = path15.dirname(entry.target);
6805
+ let parent = path16.dirname(entry.target);
6235
6806
  for (; ; ) {
6236
6807
  try {
6237
- const stat = lstatSync9(parent, { bigint: true });
6238
- if (!stat.isDirectory() || realpathSync9(parent) !== parent)
6808
+ const stat = lstatSync10(parent, { bigint: true });
6809
+ if (!stat.isDirectory() || realpathSync10(parent) !== parent)
6239
6810
  throw new SecurityError("Expected a canonical parent directory");
6240
6811
  return Object.freeze({
6241
6812
  ...entry,
6242
6813
  identity: null,
6243
6814
  parent,
6244
6815
  parentIdentity: directoryIdentity2(stat),
6245
- tail: path15.relative(parent, entry.target)
6816
+ tail: path16.relative(parent, entry.target)
6246
6817
  });
6247
6818
  } catch (error) {
6248
6819
  if (error.code !== "ENOENT") throw error;
6249
- const ancestor = path15.dirname(parent);
6820
+ const ancestor = path16.dirname(parent);
6250
6821
  if (ancestor === parent) throw error;
6251
6822
  parent = ancestor;
6252
6823
  }
@@ -6254,15 +6825,15 @@ var selectMissingFile = (entry) => {
6254
6825
  };
6255
6826
  var missingDestinationCurrent = (selection) => {
6256
6827
  try {
6257
- const segments = selection.tail.split(path15.sep);
6828
+ const segments = selection.tail.split(path16.sep);
6258
6829
  if (segments.some(
6259
6830
  (segment) => !segment || segment === "." || segment === ".."
6260
- ) || path15.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
6831
+ ) || path16.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
6261
6832
  return false;
6262
6833
  let current = selection.parent;
6263
6834
  for (const [index, segment] of segments.entries()) {
6264
- current = path15.join(current, segment);
6265
- const stat = lstatSync9(current);
6835
+ current = path16.join(current, segment);
6836
+ const stat = lstatSync10(current);
6266
6837
  if (index === segments.length - 1 || !stat.isDirectory()) return false;
6267
6838
  }
6268
6839
  return false;
@@ -6272,8 +6843,8 @@ var missingDestinationCurrent = (selection) => {
6272
6843
  };
6273
6844
  var directoryBindingCurrent = (selection) => {
6274
6845
  try {
6275
- const stat = lstatSync9(selection.parent, { bigint: true });
6276
- return stat.isDirectory() && directoryIdentity2(stat) === selection.parentIdentity && realpathSync9(selection.parent) === selection.parent;
6846
+ const stat = lstatSync10(selection.parent, { bigint: true });
6847
+ return stat.isDirectory() && directoryIdentity2(stat) === selection.parentIdentity && realpathSync10(selection.parent) === selection.parent;
6277
6848
  } catch {
6278
6849
  return false;
6279
6850
  }
@@ -6286,6 +6857,7 @@ var SandboxContext = class _SandboxContext {
6286
6857
  approvalMode;
6287
6858
  protectedPaths;
6288
6859
  protectedAliasPaths;
6860
+ homeDotDirectory;
6289
6861
  readOnlyPaths;
6290
6862
  readOnlyAliasPaths;
6291
6863
  mutations;
@@ -6298,6 +6870,7 @@ var SandboxContext = class _SandboxContext {
6298
6870
  this.approvalMode = init.approvalMode;
6299
6871
  this.protectedPaths = init.protectedPaths;
6300
6872
  this.protectedAliasPaths = init.protectedAliasPaths;
6873
+ this.homeDotDirectory = init.homeDotDirectory;
6301
6874
  this.readOnlyPaths = init.readOnlyPaths ?? [];
6302
6875
  this.readOnlyAliasPaths = init.readOnlyAliasPaths ?? this.readOnlyPaths;
6303
6876
  this.selections = init.selections;
@@ -6305,7 +6878,7 @@ var SandboxContext = class _SandboxContext {
6305
6878
  }
6306
6879
  static async create(rootDir, options = {}) {
6307
6880
  const sessionId = crypto3.randomUUID().slice(0, 8);
6308
- const root = rootDir ? path15.resolve(rootDir) : process.cwd();
6881
+ const root = rootDir ? path16.resolve(rootDir) : process.cwd();
6309
6882
  if (options.sandboxMode !== "readonly")
6310
6883
  await fs4.mkdir(root, { recursive: true });
6311
6884
  const directory = options.protectResources ? await fs4.realpath(root) : root;
@@ -6318,7 +6891,8 @@ var SandboxContext = class _SandboxContext {
6318
6891
  [],
6319
6892
  options.sandboxMode,
6320
6893
  false,
6321
- options.extraReadOnlyPaths
6894
+ options.extraReadOnlyPaths,
6895
+ { recheckHomeLinksOnWrite: true }
6322
6896
  ) : {},
6323
6897
  sessionId,
6324
6898
  mutations: typeof options.mutations === "function" ? await options.mutations(directory) : options.mutations,
@@ -6329,7 +6903,7 @@ var SandboxContext = class _SandboxContext {
6329
6903
  resolvePath(targetPath, access = "write") {
6330
6904
  if (access === "write" && this.sandboxMode === "readonly")
6331
6905
  throw new SecurityError("Sandbox mode is readonly");
6332
- const resolved = path15.isAbsolute(targetPath) ? path15.resolve(targetPath) : path15.resolve(this.workingDir, targetPath);
6906
+ const resolved = path16.isAbsolute(targetPath) ? path16.resolve(targetPath) : path16.resolve(this.workingDir, targetPath);
6333
6907
  if (this.protectedPaths) return this.resolveProtectedPath(resolved, access);
6334
6908
  if (this.approvalMode === "full-access") {
6335
6909
  return resolved;
@@ -6347,12 +6921,12 @@ var SandboxContext = class _SandboxContext {
6347
6921
  selectFile(operand, access, directoryEntry = false) {
6348
6922
  const target = this.resolvePath(operand, access);
6349
6923
  if (directoryEntry) {
6350
- const lexical = path15.resolve(this.workingDir, operand);
6351
- const name = path15.join(
6352
- resolvePolicyPath(path15.dirname(lexical)),
6353
- path15.basename(lexical)
6924
+ const lexical = path16.resolve(this.workingDir, operand);
6925
+ const name = path16.join(
6926
+ resolvePolicyPath(path16.dirname(lexical)),
6927
+ path16.basename(lexical)
6354
6928
  );
6355
- if (target !== name || lstatSync9(name, { throwIfNoEntry: false })?.isSymbolicLink())
6929
+ if (target !== name || lstatSync10(name, { throwIfNoEntry: false })?.isSymbolicLink())
6356
6930
  throw new SecurityError(
6357
6931
  "Patch deletion and move require a regular directory entry without a symbolic link"
6358
6932
  );
@@ -6364,7 +6938,7 @@ var SandboxContext = class _SandboxContext {
6364
6938
  ...directoryEntry ? { directoryEntry: true } : {}
6365
6939
  };
6366
6940
  try {
6367
- const info = lstatSync9(target, { bigint: true });
6941
+ const info = lstatSync10(target, { bigint: true });
6368
6942
  if (!info.isFile())
6369
6943
  throw new SecurityError("Expected a regular file for this operation");
6370
6944
  return Object.freeze({
@@ -6385,6 +6959,7 @@ var SandboxContext = class _SandboxContext {
6385
6959
  sandboxMode: this.sandboxMode,
6386
6960
  protectedPaths: this.protectedPaths,
6387
6961
  protectedAliasPaths: this.protectedAliasPaths,
6962
+ homeDotDirectory: this.homeDotDirectory,
6388
6963
  readOnlyPaths: this.readOnlyPaths,
6389
6964
  readOnlyAliasPaths: this.readOnlyAliasPaths,
6390
6965
  mutations: this.mutations,
@@ -6505,7 +7080,7 @@ var SandboxContext = class _SandboxContext {
6505
7080
  writeProtection(target, alias = false) {
6506
7081
  const { readOnlyPaths } = gitMetadataPaths(
6507
7082
  this.rootDir,
6508
- path15.dirname(target)
7083
+ path16.dirname(target)
6509
7084
  );
6510
7085
  const projectConfig = workspaceConfigProtection(this.rootDir);
6511
7086
  return [
@@ -6527,7 +7102,7 @@ var SandboxContext = class _SandboxContext {
6527
7102
  if (access !== "write") return;
6528
7103
  if (!isWithin(this.rootDir, value))
6529
7104
  throw new SecurityError("Write path escapes the workspace");
6530
- if (isWorkspaceConfigName(this.rootDir, value) || this.writeProtection(value).some(
7105
+ if (this.homeDotDirectory && isHomeWriteReserved(this.homeDotDirectory, value) || isWorkspaceConfigName(this.rootDir, value) || this.writeProtection(value).some(
6531
7106
  (entry) => resourceContainsPath(entry, value)
6532
7107
  ))
6533
7108
  throw new SecurityError("Path is read-only under the resource policy");
@@ -6537,16 +7112,16 @@ var SandboxContext = class _SandboxContext {
6537
7112
  let probe = resolved;
6538
7113
  for (; ; ) {
6539
7114
  try {
6540
- const actual = realpathSync9(probe);
6541
- const target = path15.resolve(actual, path15.relative(probe, resolved));
7115
+ const actual = realpathSync10(probe);
7116
+ const target = path16.resolve(actual, path16.relative(probe, resolved));
6542
7117
  rejectProtected(target);
6543
7118
  if (target !== resolved) rejectWrite(target);
6544
7119
  if (probe === resolved) {
6545
- const stat = lstatSync9(target);
7120
+ const stat = lstatSync10(target);
6546
7121
  if (!stat.isFile() && !stat.isDirectory())
6547
7122
  throw new SecurityError("Unsupported file type");
6548
7123
  if (stat.isFile() && stat.nlink > 1) {
6549
- const inode2 = lstatSync9(target, { bigint: true });
7124
+ const inode2 = lstatSync10(target, { bigint: true });
6550
7125
  if (isProtectedAlias(inode2, protectedPaths))
6551
7126
  throw new SecurityError("Path aliases a protected file");
6552
7127
  if (access === "write" && this.isReadOnlyAlias(inode2, target))
@@ -6556,10 +7131,10 @@ var SandboxContext = class _SandboxContext {
6556
7131
  return target;
6557
7132
  } catch (error) {
6558
7133
  if (error.code !== "ENOENT") throw error;
6559
- const ancestor = path15.dirname(probe);
7134
+ const ancestor = path16.dirname(probe);
6560
7135
  if (ancestor === probe) throw error;
6561
7136
  try {
6562
- if (lstatSync9(probe).isSymbolicLink())
7137
+ if (lstatSync10(probe).isSymbolicLink())
6563
7138
  throw new SecurityError("Path contains a dangling symlink");
6564
7139
  } catch (entryError) {
6565
7140
  if (entryError.code !== "ENOENT")
@@ -6606,7 +7181,7 @@ var appendReadMetadata = (output, content) => `${output}
6606
7181
 
6607
7182
  // src/subagents/workspace-files.ts
6608
7183
  import { constants as constants7, promises as fs5 } from "fs";
6609
- import path16 from "path";
7184
+ import path17 from "path";
6610
7185
  var MAX_CHILD_FILE_BYTES = 4 * 1024 * 1024;
6611
7186
  var readContent = async (handle) => {
6612
7187
  const buffer = Buffer.alloc(MAX_CHILD_FILE_BYTES + 1);
@@ -6619,6 +7194,7 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
6619
7194
  const {
6620
7195
  protectedPaths,
6621
7196
  protectedAliasPaths,
7197
+ homeDotDirectory: homeDotDirectory2,
6622
7198
  readOnlyPaths = [],
6623
7199
  readOnlyAliasPaths = readOnlyPaths
6624
7200
  } = workspacePathProtection(
@@ -6627,19 +7203,20 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
6627
7203
  [],
6628
7204
  "workspace-write",
6629
7205
  false,
6630
- extraReadOnlyPaths
7206
+ extraReadOnlyPaths,
7207
+ { recheckHomeLinksOnWrite: true }
6631
7208
  );
6632
7209
  const blocked = (target) => protectedPaths.some((entry) => resourceContainsPath(entry, target));
6633
7210
  const resolve = async (name, allowMissing = false) => {
6634
- const candidate = path16.resolve(root, name);
7211
+ const candidate = path17.resolve(root, name);
6635
7212
  if (blocked(candidate))
6636
7213
  throw new Error("Path is protected by the resource policy");
6637
- const relative = path16.relative(root, candidate);
6638
- if (relative === ".." || relative.startsWith(`..${path16.sep}`) || path16.isAbsolute(relative))
7214
+ const relative = path17.relative(root, candidate);
7215
+ if (relative === ".." || relative.startsWith(`..${path17.sep}`) || path17.isAbsolute(relative))
6639
7216
  throw new Error("Path outside delegated workspace");
6640
7217
  let part = root;
6641
- for (const segment of relative.split(path16.sep).filter(Boolean)) {
6642
- part = path16.join(part, segment);
7218
+ for (const segment of relative.split(path17.sep).filter(Boolean)) {
7219
+ part = path17.join(part, segment);
6643
7220
  try {
6644
7221
  if ((await fs5.lstat(part)).isSymbolicLink())
6645
7222
  throw new Error(
@@ -6679,10 +7256,10 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
6679
7256
  const file = await resolve(name, expected === "missing");
6680
7257
  const repositoryReadOnly = gitMetadataPaths(
6681
7258
  root,
6682
- path16.dirname(file)
7259
+ path17.dirname(file)
6683
7260
  ).readOnlyPaths;
6684
7261
  const projectConfig = workspaceConfigProtection(root);
6685
- if (isWorkspaceConfigName(root, file) || [
7262
+ if (homeDotDirectory2 && isHomeWriteReserved(homeDotDirectory2, file) || isWorkspaceConfigName(root, file) || [
6686
7263
  ...readOnlyPaths,
6687
7264
  ...repositoryReadOnly,
6688
7265
  ...projectConfig.readOnlyPaths
@@ -6702,7 +7279,7 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
6702
7279
  if (approval && expected === "missing")
6703
7280
  throw new Error("File already exists");
6704
7281
  if (expected === "missing") {
6705
- await fs5.mkdir(path16.dirname(file), { recursive: true });
7282
+ await fs5.mkdir(path17.dirname(file), { recursive: true });
6706
7283
  await resolve(name, true);
6707
7284
  }
6708
7285
  const handle = await fs5.open(
@@ -6811,17 +7388,17 @@ var createSubagentReadTools = (root, protectedPaths, options = {}) => {
6811
7388
  signal?.throwIfAborted();
6812
7389
  const dir = pending.shift();
6813
7390
  if (!dir) break;
6814
- const entries = await fs6.opendir(await resolve(path17.relative(root2, dir)));
7391
+ const entries = await fs6.opendir(await resolve(path18.relative(root2, dir)));
6815
7392
  for await (const entry of entries) {
6816
7393
  if (entry.isSymbolicLink() || entry.name === ".git" || entry.name === "node_modules")
6817
7394
  continue;
6818
- const child = path17.join(dir, entry.name);
7395
+ const child = path18.join(dir, entry.name);
6819
7396
  if (blocked(child)) continue;
6820
7397
  if (entry.isDirectory()) {
6821
7398
  if (pending.length >= 2e3) return { paths, truncated: true };
6822
7399
  pending.push(child);
6823
7400
  } else if (entry.isFile()) {
6824
- const name = path17.relative(root2, child);
7401
+ const name = path18.relative(root2, child);
6825
7402
  const selected = await selectRead(name, sandbox).catch(
6826
7403
  () => void 0
6827
7404
  );
@@ -7314,7 +7891,10 @@ export {
7314
7891
  openBrowser,
7315
7892
  readEnvValue,
7316
7893
  resolveConfigPath,
7894
+ SHARED_PROJECT_CONFIG_ERROR,
7317
7895
  resolveProjectConfigPath,
7896
+ resolveDistinctProjectConfigPath,
7897
+ resolveConfigLayers,
7318
7898
  resolveImageGenerationConfig,
7319
7899
  updateImageGeneration,
7320
7900
  resolveModelConfig,
@@ -7327,6 +7907,7 @@ export {
7327
7907
  resolveMcpServers,
7328
7908
  updateModel,
7329
7909
  updateTuiTheme,
7910
+ normalizeModelLevel,
7330
7911
  resolveReasoningEffort,
7331
7912
  loadSystemPrompt,
7332
7913
  builtinApiKeyBase,
@@ -7336,16 +7917,25 @@ export {
7336
7917
  sendNotificationAsync,
7337
7918
  send,
7338
7919
  sendError,
7339
- sendResult,
7340
7920
  sendAgentEvent,
7341
7921
  sendRunStatus,
7342
7922
  sendRunContext,
7343
7923
  sendRunDiagnostics,
7344
7924
  sendRunMetrics,
7925
+ parseRequestParams,
7926
+ parseUiNotificationParams,
7927
+ sendRequestResult,
7928
+ notificationMessage,
7929
+ requestMessage,
7930
+ parseUiResult,
7345
7931
  requestUiConfirm,
7346
7932
  requestUiPrompt,
7347
7933
  requestUiPick,
7348
7934
  createOpenAiDeviceCodeSession,
7935
+ getChatProviderAuth,
7936
+ getStoredProviderApiKey,
7937
+ setProviderChatAuth,
7938
+ clearProviderEntry,
7349
7939
  AuthStore,
7350
7940
  SUPPORTED_PROVIDERS,
7351
7941
  configuredProviders,
@@ -7358,6 +7948,10 @@ export {
7358
7948
  AuthResolver,
7359
7949
  isTuiLocalEnvironment,
7360
7950
  isProcessEnabled,
7951
+ comparableResourceName,
7952
+ resourceContainsPath,
7953
+ isHomeDotTarget,
7954
+ isHomeWriteReserved,
7361
7955
  mxcLifecycle,
7362
7956
  singleCommandWords,
7363
7957
  isSimpleAndChain,
@@ -7369,15 +7963,15 @@ export {
7369
7963
  bindKnownSystemExecutable,
7370
7964
  isRootControlledSharedExecutable,
7371
7965
  areAllExecutableLinksOutsideRestrictedPaths,
7372
- comparableResourceName,
7373
- resourceContainsPath,
7374
7966
  resolveSystemBash,
7375
7967
  confinedAutoLaunchDirectoryName,
7376
7968
  supportsProtectedShell,
7377
7969
  platformShellSource,
7378
7970
  resolvePolicyPath,
7379
7971
  canonicalPolicyPaths,
7972
+ runtimeReadOnlyPaths,
7380
7973
  workspacePathProtection,
7974
+ macAdditionalWriteLauncherPaths,
7381
7975
  MacSeatbeltBackend,
7382
7976
  createMacMxcShellBackend,
7383
7977
  UserShellBackend,