@codelia/runtime 0.1.86 → 0.1.89

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,7 +23,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  ));
24
24
 
25
25
  // src/subagents/child-entry.ts
26
- var import_node_fs19 = require("fs");
26
+ var import_node_fs20 = require("fs");
27
27
 
28
28
  // src/config.ts
29
29
  var import_node_fs = require("fs");
@@ -374,6 +374,7 @@ var startOAuthCallbackServer = (options) => {
374
374
  // src/auth/openai-oauth.ts
375
375
  var import_node_child_process = require("child_process");
376
376
  var import_core2 = require("@codelia/core");
377
+ var import_storage2 = require("@codelia/storage");
377
378
  var DEFAULT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
378
379
  var ISSUER = "https://auth.openai.com";
379
380
  var DEFAULT_PORT = 1455;
@@ -400,6 +401,32 @@ var buildAuthorizeUrl = (redirectUri, pkce, state) => {
400
401
  });
401
402
  return `${ISSUER}/oauth/authorize?${params.toString()}`;
402
403
  };
404
+ var withSignalAbort = (promise, signal) => {
405
+ if (!signal) return promise;
406
+ if (signal.aborted) {
407
+ return Promise.reject(
408
+ signal.reason instanceof Error ? signal.reason : new Error("Request aborted")
409
+ );
410
+ }
411
+ return new Promise((resolve, reject) => {
412
+ const onAbort = () => {
413
+ reject(
414
+ signal.reason instanceof Error ? signal.reason : new Error("Request aborted")
415
+ );
416
+ };
417
+ signal.addEventListener("abort", onAbort, { once: true });
418
+ promise.then(
419
+ (value) => {
420
+ signal.removeEventListener("abort", onAbort);
421
+ resolve(value);
422
+ },
423
+ (error) => {
424
+ signal.removeEventListener("abort", onAbort);
425
+ reject(error);
426
+ }
427
+ );
428
+ });
429
+ };
403
430
  var requestToken = async (params, operation, signal) => {
404
431
  const response = await fetch(`${ISSUER}/oauth/token`, {
405
432
  method: "POST",
@@ -409,9 +436,9 @@ var requestToken = async (params, operation, signal) => {
409
436
  body: new URLSearchParams(params).toString()
410
437
  });
411
438
  if (!response.ok) {
412
- throw await tokenFailure(response, operation);
439
+ throw await withSignalAbort(tokenFailure(response, operation), signal);
413
440
  }
414
- return response.json();
441
+ return withSignalAbort(response.json(), signal);
415
442
  };
416
443
  var oauthReasons = {
417
444
  refresh_token_reused: "The refresh token has already been used.",
@@ -448,16 +475,40 @@ var exchangeCodeForTokens = async (code, redirectUri, pkce) => {
448
475
  "exchange"
449
476
  );
450
477
  };
451
- var refreshAccessToken = async (refreshToken, signal) => {
452
- return requestToken(
453
- {
454
- grant_type: "refresh_token",
455
- refresh_token: refreshToken,
456
- client_id: clientId()
457
- },
458
- "refresh",
459
- signal
460
- );
478
+ var refreshAccessToken = async (refreshToken, signal, options) => {
479
+ const timeoutMs = options?.timeoutMs ?? import_storage2.DEFAULT_OAUTH_REFRESH_TIMEOUT_MS;
480
+ const timeoutController = new AbortController();
481
+ let timedOut = false;
482
+ const timer = setTimeout(() => {
483
+ timedOut = true;
484
+ timeoutController.abort(new Error("OAuth token refresh timed out"));
485
+ }, timeoutMs);
486
+ const effectiveSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
487
+ try {
488
+ return await requestToken(
489
+ {
490
+ grant_type: "refresh_token",
491
+ refresh_token: refreshToken,
492
+ client_id: clientId()
493
+ },
494
+ "refresh",
495
+ effectiveSignal
496
+ );
497
+ } catch (error) {
498
+ if (timedOut) {
499
+ throw new import_core2.ProviderFailureError({
500
+ provider: "openai",
501
+ kind: "provider",
502
+ code: "oauth_refresh_timeout",
503
+ safeMessage: "OpenAI OAuth token refresh timed out.",
504
+ detail: "The OAuth token endpoint did not respond before the timeout.",
505
+ retryable: true
506
+ });
507
+ }
508
+ throw error;
509
+ } finally {
510
+ clearTimeout(timer);
511
+ }
461
512
  };
462
513
  var parseJwt = (token) => {
463
514
  const parts = token.split(".");
@@ -739,93 +790,312 @@ var isOfficialApiKeyBase = (provider, base) => Object.hasOwn(bases, provider) &&
739
790
 
740
791
  // src/auth/store.ts
741
792
  var import_node_fs2 = require("fs");
742
- var import_storage2 = require("@codelia/storage");
743
- var AUTH_VERSION = 1;
744
- var authWriteQueues = /* @__PURE__ */ new Map();
745
- var parseAuthFile = (text) => {
746
- const parsed = JSON.parse(text);
747
- if (!parsed || parsed.version !== AUTH_VERSION)
748
- throw new Error("auth.json has unsupported version");
749
- return { version: AUTH_VERSION, providers: parsed.providers ?? {} };
750
- };
751
- var absentAuthFile = (error) => {
752
- if (error?.code === "ENOENT")
753
- return { version: AUTH_VERSION, providers: {} };
754
- throw error;
793
+ var import_storage3 = require("@codelia/storage");
794
+ var normalizeAuthFileToV2 = (auth) => (0, import_storage3.parseAuthDocument)(JSON.stringify(auth)).normalized;
795
+ var getChatProviderAuth = (auth, provider) => {
796
+ if (!Object.hasOwn(auth.providers, provider)) return void 0;
797
+ const entry = auth.providers[provider];
798
+ if (entry.chat_method === "oauth" && entry.credentials.oauth) {
799
+ return { method: "oauth", oauth: entry.credentials.oauth };
800
+ }
801
+ if (entry.chat_method === "api_key" && entry.credentials.api_key) {
802
+ return { method: "api_key", ...entry.credentials.api_key };
803
+ }
804
+ return void 0;
805
+ };
806
+ var setProviderChatAuth = (auth, provider, next) => {
807
+ const existing = Object.hasOwn(auth.providers, provider) ? auth.providers[provider] : void 0;
808
+ const credentials = {
809
+ ...existing?.credentials ?? {}
810
+ };
811
+ if (next.method === "api_key") {
812
+ credentials.api_key = {
813
+ api_key: next.api_key,
814
+ ...next.api_base ? { api_base: next.api_base } : {}
815
+ };
816
+ } else {
817
+ credentials.oauth = next.oauth;
818
+ }
819
+ auth.providers[provider] = {
820
+ chat_method: next.method,
821
+ credentials
822
+ };
823
+ };
824
+ var updateProviderOAuthTokens = (auth, provider, oauth2) => {
825
+ if (!Object.hasOwn(auth.providers, provider)) return false;
826
+ const entry = auth.providers[provider];
827
+ if (!entry.credentials.oauth) return false;
828
+ auth.providers[provider] = {
829
+ ...entry.chat_method ? { chat_method: entry.chat_method } : {},
830
+ credentials: {
831
+ ...entry.credentials,
832
+ oauth: oauth2
833
+ }
834
+ };
835
+ return true;
836
+ };
837
+ var clearProviderEntry = (auth, provider) => {
838
+ delete auth.providers[provider];
755
839
  };
840
+ var projectAuthV2ToV1View = (auth) => {
841
+ const providers = {};
842
+ for (const name of Object.keys(auth.providers)) {
843
+ const chatAuth = getChatProviderAuth(auth, name);
844
+ if (chatAuth) {
845
+ providers[name] = chatAuth;
846
+ }
847
+ }
848
+ return { version: import_storage3.AUTH_VERSION_V1, providers };
849
+ };
850
+ var readTextIfPresent = async (filePath) => {
851
+ if (!await (0, import_storage3.verifyWindowsCredentialFileAcl)(filePath)) return null;
852
+ try {
853
+ return await import_node_fs2.promises.readFile(filePath, "utf8");
854
+ } catch (error) {
855
+ if (error?.code === "ENOENT") return null;
856
+ throw error;
857
+ }
858
+ };
859
+ var readAuthFileSyncStrict = (filePath, legacy = false) => {
860
+ if (!(0, import_storage3.verifyWindowsCredentialFileAclSync)(filePath, legacy)) return null;
861
+ let fd;
862
+ try {
863
+ fd = (0, import_node_fs2.openSync)(
864
+ filePath,
865
+ import_node_fs2.constants.O_RDONLY | import_node_fs2.constants.O_NONBLOCK | (import_node_fs2.constants.O_NOFOLLOW ?? 0)
866
+ );
867
+ } catch (error) {
868
+ if (error?.code === "ENOENT") return null;
869
+ throw error;
870
+ }
871
+ try {
872
+ const stat = (0, import_node_fs2.fstatSync)(fd);
873
+ if (!stat.isFile() || stat.size > 1024 * 1024) {
874
+ throw new Error("auth.json cannot be read at approval time");
875
+ }
876
+ return (0, import_storage3.parseAuthDocument)((0, import_node_fs2.readFileSync)(fd, "utf8")).normalized;
877
+ } finally {
878
+ (0, import_node_fs2.closeSync)(fd);
879
+ }
880
+ };
881
+ var isAuthNonEmpty = (doc) => doc !== null && Object.keys(doc.providers).length > 0;
756
882
  var AuthStore = class {
757
883
  paths;
758
- constructor(paths) {
759
- this.paths = paths ?? (0, import_storage2.resolveStoragePaths)();
884
+ lockOptions;
885
+ storageMode;
886
+ keychain;
887
+ constructor(paths, options) {
888
+ this.paths = paths ?? (0, import_storage3.resolveStoragePaths)();
889
+ this.lockOptions = options?.lock;
890
+ this.storageMode = options?.storageMode;
891
+ this.keychain = options?.keychain ?? new import_storage3.MacOsKeychainClient({
892
+ credentialsDir: this.paths.credentialsDir
893
+ });
760
894
  }
761
- async load() {
762
- try {
763
- return parseAuthFile(await import_node_fs2.promises.readFile(this.paths.authFile, "utf8"));
764
- } catch (error) {
765
- return absentAuthFile(error);
766
- }
895
+ lockPath() {
896
+ return (0, import_storage3.authLockPathFor)(this.paths.credentialsDir);
767
897
  }
768
- /** Synchronous snapshot for a one-use local approval consumed immediately before spawn. */
769
- loadForApproval() {
770
- let fd;
771
- try {
772
- fd = (0, import_node_fs2.openSync)(
773
- this.paths.authFile,
774
- import_node_fs2.constants.O_RDONLY | import_node_fs2.constants.O_NONBLOCK
898
+ keychainAccount() {
899
+ return (0, import_storage3.keychainAccountForConfigDir)(this.paths.configDir);
900
+ }
901
+ resolveBackendUnlocked() {
902
+ return (0, import_storage3.coordinateCredentialBackendUnlocked)({
903
+ paths: this.paths,
904
+ storageMode: this.storageMode,
905
+ keychain: this.keychain,
906
+ authAdapter: import_storage3.providerAuthStoreAdapter,
907
+ mcpAdapter: import_storage3.mcpAuthStoreAdapter
908
+ });
909
+ }
910
+ async readFromBackend(active) {
911
+ if (active === "keyring") {
912
+ const text2 = await this.keychain.get(
913
+ import_storage3.CODELIA_AUTH_KEYCHAIN_SERVICE,
914
+ this.keychainAccount()
775
915
  );
776
- } catch (error) {
777
- return absentAuthFile(error);
916
+ if (text2 === null) {
917
+ return { version: import_storage3.AUTH_VERSION_V2, providers: {} };
918
+ }
919
+ const parsed2 = (0, import_storage3.parseAuthDocument)(text2);
920
+ if (parsed2.sourceVersion === 1) {
921
+ await this.writeToBackend("keyring", parsed2.normalized);
922
+ }
923
+ return parsed2.normalized;
778
924
  }
779
- try {
780
- const stat = (0, import_node_fs2.fstatSync)(fd);
781
- if (!stat.isFile() || stat.size > 1024 * 1024)
782
- throw new Error("auth.json cannot be read at approval time");
783
- return parseAuthFile((0, import_node_fs2.readFileSync)(fd, "utf8"));
784
- } finally {
785
- (0, import_node_fs2.closeSync)(fd);
925
+ const text = await readTextIfPresent(this.paths.authFile);
926
+ if (text === null) {
927
+ return { version: import_storage3.AUTH_VERSION_V2, providers: {} };
786
928
  }
929
+ const parsed = (0, import_storage3.parseAuthDocument)(text);
930
+ if (parsed.sourceVersion === 1) {
931
+ await this.writeToBackend("file", parsed.normalized);
932
+ }
933
+ return parsed.normalized;
934
+ }
935
+ async writeToBackend(active, auth) {
936
+ if (active === "keyring") {
937
+ await this.keychain.set(
938
+ import_storage3.CODELIA_AUTH_KEYCHAIN_SERVICE,
939
+ this.keychainAccount(),
940
+ JSON.stringify(auth)
941
+ );
942
+ return;
943
+ }
944
+ await (0, import_storage3.ensureStorageDirs)(this.paths);
945
+ const data = JSON.stringify(auth, null, 2);
946
+ await (0, import_storage3.writeFileAtomic)(this.paths.authFile, data, { mode: 384 });
787
947
  }
788
- async enqueue(fn) {
789
- const key = this.paths.authFile;
790
- const previous = authWriteQueues.get(key) ?? Promise.resolve();
791
- const next = previous.then(fn, fn);
792
- const settled = next.then(
793
- () => void 0,
794
- () => void 0
948
+ /**
949
+ * Load normalized v2 credentials from the active backend (macOS Keychain or
950
+ * protected `credentials/` file), running two-phase migration if needed.
951
+ */
952
+ async loadV2() {
953
+ return (0, import_storage3.withAuthStoreLock)(
954
+ this.lockPath(),
955
+ async () => {
956
+ const resolved = await this.resolveBackendUnlocked();
957
+ return this.readFromBackend(resolved.active);
958
+ },
959
+ this.lockOptions
795
960
  );
796
- authWriteQueues.set(key, settled);
797
- try {
798
- return await next;
799
- } finally {
800
- if (authWriteQueues.get(key) === settled) authWriteQueues.delete(key);
961
+ }
962
+ /**
963
+ * Synchronous v2 snapshot for a one-use local approval consumed immediately
964
+ * before spawn. Fails closed (throws) on corrupt `storage-state.json`,
965
+ * in-progress migrations or pending cleanup, dual-store conflicts, or
966
+ * locked/unavailable/timed-out Keychain access.
967
+ */
968
+ loadForApprovalV2() {
969
+ const configured = (0, import_storage3.resolveConfiguredAuthStorageMode)(
970
+ this.paths,
971
+ this.storageMode
972
+ );
973
+ const state = (0, import_storage3.readAuthStorageStateSync)(this.paths.authStateFile);
974
+ if (state?.status === "migrating") {
975
+ throw new Error(
976
+ "Credential storage migration is in progress; approval-time auth is unavailable"
977
+ );
978
+ }
979
+ if (configured === "file" && state?.active_backend === "keyring") {
980
+ throw new Error(
981
+ "Credential reverse migration to file is pending; approval-time auth is unavailable"
982
+ );
801
983
  }
984
+ const useKeychain = configured === "keyring" || configured === "auto" && state?.active_backend === "keyring";
985
+ const currentFile = readAuthFileSyncStrict(this.paths.authFile);
986
+ const legacyFile = readAuthFileSyncStrict(this.paths.legacyAuthFile, true);
987
+ if (isAuthNonEmpty(currentFile) && isAuthNonEmpty(legacyFile) && !(0, import_storage3.canonicalJsonEqual)(currentFile, legacyFile)) {
988
+ throw new import_storage3.CredentialConflictError("auth");
989
+ }
990
+ if (useKeychain) {
991
+ const text = this.keychain.getSync(
992
+ import_storage3.CODELIA_AUTH_KEYCHAIN_SERVICE,
993
+ this.keychainAccount(),
994
+ 2e3
995
+ );
996
+ const keychainDoc = text === null ? { version: import_storage3.AUTH_VERSION_V2, providers: {} } : (0, import_storage3.parseAuthDocument)(text).normalized;
997
+ for (const fileCandidate of [currentFile, legacyFile]) {
998
+ if (isAuthNonEmpty(fileCandidate) && isAuthNonEmpty(keychainDoc) && !(0, import_storage3.canonicalJsonEqual)(keychainDoc, fileCandidate)) {
999
+ throw new import_storage3.CredentialConflictError("auth");
1000
+ }
1001
+ }
1002
+ return keychainDoc;
1003
+ }
1004
+ if (isAuthNonEmpty(currentFile)) return currentFile;
1005
+ if (isAuthNonEmpty(legacyFile)) return legacyFile;
1006
+ return currentFile ?? legacyFile ?? { version: import_storage3.AUTH_VERSION_V2, providers: {} };
1007
+ }
1008
+ /** Legacy v1-projected read view over the underlying v2 store. */
1009
+ async load() {
1010
+ return projectAuthV2ToV1View(await this.loadV2());
1011
+ }
1012
+ /** Synchronous legacy v1-projected snapshot for approval checks. */
1013
+ loadForApproval() {
1014
+ return projectAuthV2ToV1View(this.loadForApprovalV2());
802
1015
  }
803
1016
  /**
804
- * Reload, mutate and save under a per-file queue. Use this for every
805
- * credential change made outside the cached-resolver flow.
1017
+ * Reload v2, mutate, and atomically save under the interprocess SQLite lock.
1018
+ * Skips writing if the serialized v2 document did not change.
1019
+ */
1020
+ updateV2(mutate) {
1021
+ return (0, import_storage3.withAuthStoreLock)(
1022
+ this.lockPath(),
1023
+ async () => {
1024
+ const resolved = await this.resolveBackendUnlocked();
1025
+ const auth = await this.readFromBackend(resolved.active);
1026
+ const before = JSON.stringify(auth);
1027
+ const result = await mutate(auth);
1028
+ if (JSON.stringify(auth) !== before) {
1029
+ await this.writeToBackend(resolved.active, auth);
1030
+ }
1031
+ return result;
1032
+ },
1033
+ this.lockOptions
1034
+ );
1035
+ }
1036
+ /**
1037
+ * Legacy v1-projected update helper. Applies v1 mutations onto the underlying
1038
+ * v2 document while preserving coexisting credentials on untouched slots.
806
1039
  */
807
1040
  update(mutate) {
808
- return this.enqueue(async () => {
809
- const auth = await this.load();
810
- const result = await mutate(auth);
811
- await this.save(auth);
1041
+ return this.updateV2(async (v2) => {
1042
+ const beforeView = projectAuthV2ToV1View(v2);
1043
+ const workingView = {
1044
+ version: import_storage3.AUTH_VERSION_V1,
1045
+ providers: { ...beforeView.providers }
1046
+ };
1047
+ const result = await mutate(workingView);
1048
+ const touched = /* @__PURE__ */ new Set([
1049
+ ...Object.keys(beforeView.providers),
1050
+ ...Object.keys(workingView.providers)
1051
+ ]);
1052
+ for (const name of touched) {
1053
+ const had = Object.hasOwn(beforeView.providers, name);
1054
+ const has = Object.hasOwn(workingView.providers, name);
1055
+ if (!has && had) {
1056
+ clearProviderEntry(v2, name);
1057
+ } else if (has) {
1058
+ const next = workingView.providers[name];
1059
+ if (!had || !(0, import_storage3.canonicalJsonEqual)(beforeView.providers[name], next)) {
1060
+ setProviderChatAuth(v2, name, next);
1061
+ }
1062
+ }
1063
+ }
812
1064
  return result;
813
1065
  });
814
1066
  }
815
- /** Queued removal of every provider; works even if the file is unreadable. */
1067
+ /**
1068
+ * Locked removal of every provider across all credential locations
1069
+ * (`credentials/auth.json`, legacy `auth.json`, and Keychain if active/reachable).
1070
+ * Succeeds even when an `auth` storage conflict or corrupt file exists so
1071
+ * full logout always gives users a clean recovery path (never touches `mcp-auth`).
1072
+ */
816
1073
  clearAll() {
817
- return this.enqueue(
818
- () => this.save({ version: AUTH_VERSION, providers: {} })
1074
+ return (0, import_storage3.withAuthStoreLock)(
1075
+ this.lockPath(),
1076
+ async () => {
1077
+ await (0, import_storage3.clearStoreAcrossAllLocationsUnlocked)({
1078
+ paths: this.paths,
1079
+ adapter: import_storage3.providerAuthStoreAdapter,
1080
+ keychain: this.keychain
1081
+ });
1082
+ },
1083
+ this.lockOptions
1084
+ );
1085
+ }
1086
+ async saveV2(auth) {
1087
+ await (0, import_storage3.withAuthStoreLock)(
1088
+ this.lockPath(),
1089
+ async () => {
1090
+ const resolved = await this.resolveBackendUnlocked();
1091
+ await this.writeToBackend(resolved.active, auth);
1092
+ },
1093
+ this.lockOptions
819
1094
  );
820
1095
  }
821
1096
  async save(auth) {
822
- await (0, import_storage2.ensureStorageDirs)(this.paths);
823
- const data = JSON.stringify(auth, null, 2);
824
- await import_node_fs2.promises.writeFile(this.paths.authFile, data, { mode: 384 });
825
- try {
826
- await import_node_fs2.promises.chmod(this.paths.authFile, 384);
827
- } catch {
828
- }
1097
+ const normalized = normalizeAuthFileToV2(auth);
1098
+ await this.saveV2(normalized);
829
1099
  }
830
1100
  };
831
1101
 
@@ -881,12 +1151,12 @@ var AuthResolver = class _AuthResolver {
881
1151
  }
882
1152
  static async create(state, log2, providers = {}) {
883
1153
  const store = new AuthStore();
884
- const auth = await store.load();
1154
+ const auth = await store.loadV2();
885
1155
  return new _AuthResolver(state, log2, store, auth, providers);
886
1156
  }
887
1157
  hasAnyAvailableAuth() {
888
1158
  return this.availableProviders.some((provider) => {
889
- if (this.auth.providers[provider]) return true;
1159
+ if (getChatProviderAuth(this.auth, provider)) return true;
890
1160
  return Boolean(this.envApiKey(provider));
891
1161
  });
892
1162
  }
@@ -896,7 +1166,7 @@ var AuthResolver = class _AuthResolver {
896
1166
  throw new Error(`Unsupported model.provider: ${preferred}`);
897
1167
  if (preferredProvider) return preferredProvider;
898
1168
  const providersWithAuth = this.availableProviders.filter(
899
- (provider) => !!this.auth.providers[provider]
1169
+ (provider) => !!getChatProviderAuth(this.auth, provider)
900
1170
  );
901
1171
  if (providersWithAuth.length === 1) {
902
1172
  return providersWithAuth[0];
@@ -927,13 +1197,11 @@ var AuthResolver = class _AuthResolver {
927
1197
  async resolveProviderAuth(provider) {
928
1198
  if (!this.availableProviders.includes(provider))
929
1199
  throw new Error(`Unsupported provider: ${provider}`);
930
- const existing = this.auth.providers[provider];
1200
+ const existing = getChatProviderAuth(this.auth, provider);
931
1201
  if (existing) return existing;
932
1202
  const envValue = this.envApiKey(provider);
933
1203
  if (envValue) {
934
- const auth = configuredApiKeyAuth(provider, envValue);
935
- await this.setProviderAuth(provider, auth);
936
- return auth;
1204
+ return configuredApiKeyAuth(provider, envValue);
937
1205
  }
938
1206
  if (provider === "openai") {
939
1207
  return this.promptOpenAiAuth();
@@ -968,7 +1236,7 @@ var AuthResolver = class _AuthResolver {
968
1236
  if (options?.matches && !options.matches(oauth3))
969
1237
  throw new Error("OpenAI OAuth account changed");
970
1238
  };
971
- const entry = this.auth.providers.openai;
1239
+ const entry = getChatProviderAuth(this.auth, "openai");
972
1240
  if (entry?.method !== "oauth") {
973
1241
  throw new Error("OpenAI OAuth is not configured");
974
1242
  }
@@ -976,15 +1244,15 @@ var AuthResolver = class _AuthResolver {
976
1244
  options?.signal?.throwIfAborted();
977
1245
  checkAccount(oauth2);
978
1246
  if (oauth2.expires_at <= Date.now() + 6e4) {
979
- oauth2 = await this.store.update(async (auth) => {
980
- const current = auth.providers.openai;
1247
+ const updated = await this.store.updateV2(async (auth) => {
1248
+ const current = getChatProviderAuth(auth, "openai");
981
1249
  if (current?.method !== "oauth") {
982
1250
  throw new Error("OpenAI OAuth is not configured");
983
1251
  }
984
1252
  options?.signal?.throwIfAborted();
985
1253
  checkAccount(current.oauth);
986
1254
  if (current.oauth.expires_at > Date.now() + 6e4) {
987
- return current.oauth;
1255
+ return { oauth: current.oauth, auth };
988
1256
  }
989
1257
  this.log("refreshing OpenAI OAuth token");
990
1258
  const tokens = await refreshAccessToken(current.oauth.refresh_token);
@@ -996,10 +1264,13 @@ var AuthResolver = class _AuthResolver {
996
1264
  ...accountId ? { account_id: accountId } : {}
997
1265
  };
998
1266
  checkAccount(refreshed);
999
- auth.providers.openai = { method: "oauth", oauth: refreshed };
1000
- return refreshed;
1267
+ if (!updateProviderOAuthTokens(auth, "openai", refreshed)) {
1268
+ throw new Error("OpenAI OAuth is not configured");
1269
+ }
1270
+ return { oauth: refreshed, auth };
1001
1271
  });
1002
- this.auth.providers.openai = { method: "oauth", oauth: oauth2 };
1272
+ oauth2 = updated.oauth;
1273
+ this.auth = updated.auth;
1003
1274
  }
1004
1275
  options?.signal?.throwIfAborted();
1005
1276
  return { token: oauth2.access_token, accountId: oauth2.account_id };
@@ -1189,8 +1460,8 @@ var AuthResolver = class _AuthResolver {
1189
1460
  return auth;
1190
1461
  }
1191
1462
  async setProviderAuth(provider, auth) {
1192
- this.auth = await this.store.update((latest) => {
1193
- latest.providers[provider] = auth;
1463
+ this.auth = await this.store.updateV2((latest) => {
1464
+ setProviderChatAuth(latest, provider, auth);
1194
1465
  return latest;
1195
1466
  });
1196
1467
  }
@@ -1199,7 +1470,7 @@ var AuthResolver = class _AuthResolver {
1199
1470
  // src/model-factory.ts
1200
1471
  var import_core6 = require("@codelia/core");
1201
1472
  var import_model_metadata = require("@codelia/model-metadata");
1202
- var import_storage3 = require("@codelia/storage");
1473
+ var import_storage4 = require("@codelia/storage");
1203
1474
 
1204
1475
  // src/model-fast.ts
1205
1476
  var import_core3 = require("@codelia/core");
@@ -1858,7 +2129,7 @@ var resolveAnthropicModelMaxTokens = async (model, options) => {
1858
2129
  return resolveAnthropicStaticModelMaxTokens(model);
1859
2130
  }
1860
2131
  const metadataService = new import_model_metadata.ModelMetadataServiceImpl({
1861
- storagePathService: new import_storage3.StoragePathServiceImpl()
2132
+ storagePathService: new import_storage4.StoragePathServiceImpl()
1862
2133
  });
1863
2134
  const direct = await metadataService.getModelEntry("anthropic", model);
1864
2135
  const prefixed = model.startsWith("anthropic/") ? null : await metadataService.getModelEntry("anthropic", `anthropic/${model}`);
@@ -2316,7 +2587,7 @@ var resolveRuntimeEnvironment = (options = {}) => {
2316
2587
  // src/sandbox/mode.ts
2317
2588
  var import_node_fs3 = require("fs");
2318
2589
  var import_shared_types4 = require("@codelia/shared-types");
2319
- var import_storage4 = require("@codelia/storage");
2590
+ var import_storage5 = require("@codelia/storage");
2320
2591
  var defaultSandboxMode = Object.freeze({
2321
2592
  value: "workspace-write",
2322
2593
  source: "fallback"
@@ -2902,9 +3173,9 @@ var createChildChannel = (send3) => {
2902
3173
 
2903
3174
  // src/subagents/child-runtime.ts
2904
3175
  var import_node_crypto7 = require("crypto");
2905
- var import_node_fs18 = require("fs");
3176
+ var import_node_fs19 = require("fs");
2906
3177
  var import_core12 = require("@codelia/core");
2907
- var import_storage9 = require("@codelia/storage");
3178
+ var import_storage10 = require("@codelia/storage");
2908
3179
 
2909
3180
  // src/permissions/utils.ts
2910
3181
  var SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -3110,10 +3381,10 @@ var import_node_crypto4 = require("crypto");
3110
3381
 
3111
3382
  // src/tasks/manager.ts
3112
3383
  var import_node_crypto3 = __toESM(require("crypto"), 1);
3113
- var import_storage6 = require("@codelia/storage");
3384
+ var import_storage7 = require("@codelia/storage");
3114
3385
 
3115
3386
  // src/subagents/process-identity.ts
3116
- var import_storage5 = require("@codelia/storage");
3387
+ var import_storage6 = require("@codelia/storage");
3117
3388
 
3118
3389
  // src/subagents/mailbox.ts
3119
3390
  var formatAgentMessages = (messages) => messages.map(
@@ -3207,15 +3478,15 @@ var createTaskProgressTracker = (options) => {
3207
3478
  };
3208
3479
 
3209
3480
  // src/subagents/read-tools.ts
3210
- var import_node_fs17 = require("fs");
3211
- var import_node_path18 = __toESM(require("path"), 1);
3481
+ var import_node_fs18 = require("fs");
3482
+ var import_node_path19 = __toESM(require("path"), 1);
3212
3483
  var import_core10 = require("@codelia/core");
3213
3484
  var import_zod7 = require("zod");
3214
3485
 
3215
3486
  // src/sandbox/context.ts
3216
3487
  var import_node_crypto5 = __toESM(require("crypto"), 1);
3217
- var import_node_fs15 = require("fs");
3218
- var import_node_path16 = __toESM(require("path"), 1);
3488
+ var import_node_fs16 = require("fs");
3489
+ var import_node_path17 = __toESM(require("path"), 1);
3219
3490
 
3220
3491
  // src/permissions/git-metadata.ts
3221
3492
  var import_node_fs5 = require("fs");
@@ -3400,15 +3671,155 @@ var resolveGitMetadata = (directories, includeObjectDirectories) => {
3400
3671
  var gitMetadataPaths = (...directories) => resolveGitMetadata(directories, false);
3401
3672
  var gitMetadataWithObjectDirectories = (...directories) => resolveGitMetadata(directories, true);
3402
3673
 
3403
- // src/permissions/protected-aliases.ts
3674
+ // src/permissions/home-dot-paths.ts
3675
+ var import_node_fs7 = require("fs");
3676
+ var import_node_os = __toESM(require("os"), 1);
3677
+ var import_node_path6 = __toESM(require("path"), 1);
3678
+
3679
+ // src/permissions/resource-paths.ts
3404
3680
  var import_node_fs6 = require("fs");
3405
3681
  var import_node_path5 = __toESM(require("path"), 1);
3682
+ var lookup = (pathname) => (0, import_node_fs6.lstatSync)(pathname, { bigint: true, throwIfNoEntry: false });
3683
+ var sameEntry = (left, right) => left.dev === right.dev && left.ino === right.ino;
3684
+ var comparableResourceName = (pathname) => {
3685
+ const folded = pathname.normalize("NFD").toUpperCase().toLowerCase();
3686
+ return process.platform === "win32" ? folded.replace(/[ .]+(?=[\\/]|$)/gu, "") : folded;
3687
+ };
3688
+ function distinguishesAsciiCase(parent) {
3689
+ try {
3690
+ const directory = (0, import_node_fs6.opendirSync)(parent);
3691
+ try {
3692
+ for (let index = 0; index < 16; index++) {
3693
+ const name = directory.readSync()?.name;
3694
+ if (!name) break;
3695
+ const changed = name.replace(
3696
+ /[A-Za-z]/u,
3697
+ (letter) => letter === letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase()
3698
+ );
3699
+ if (name === changed) continue;
3700
+ const original = lookup(import_node_path5.default.join(parent, name));
3701
+ const alternate = lookup(import_node_path5.default.join(parent, changed));
3702
+ if (original) return !alternate || !sameEntry(original, alternate);
3703
+ }
3704
+ } finally {
3705
+ directory.closeSync();
3706
+ }
3707
+ } catch {
3708
+ }
3709
+ return false;
3710
+ }
3711
+ function resourceContainsPath(resource, target) {
3712
+ if (target === resource || target.startsWith(
3713
+ resource.endsWith(import_node_path5.default.sep) ? resource : `${resource}${import_node_path5.default.sep}`
3714
+ ))
3715
+ return true;
3716
+ const root = import_node_path5.default.parse(resource).root;
3717
+ const targetRoot = import_node_path5.default.parse(target).root;
3718
+ if (comparableResourceName(root) !== comparableResourceName(targetRoot))
3719
+ return false;
3720
+ const parts = resource.slice(root.length).split(import_node_path5.default.sep);
3721
+ const overlapping = target.slice(targetRoot.length).split(import_node_path5.default.sep).slice(0, parts.length);
3722
+ if (overlapping.length !== parts.length) return false;
3723
+ const candidate = import_node_path5.default.join(targetRoot, ...overlapping);
3724
+ const namesMayMatch = comparableResourceName(resource) === comparableResourceName(candidate);
3725
+ try {
3726
+ const targetEntry = lookup(candidate);
3727
+ if (!targetEntry && !namesMayMatch) return false;
3728
+ const protectedEntry = lookup(resource);
3729
+ if (protectedEntry || targetEntry)
3730
+ return !!protectedEntry && !!targetEntry && sameEntry(protectedEntry, targetEntry);
3731
+ if (!namesMayMatch) return false;
3732
+ const parent = import_node_path5.default.dirname(resource);
3733
+ return import_node_path5.default.dirname(candidate) !== parent || !/^[\x20-\x7e]+$/u.test(import_node_path5.default.basename(resource)) || !/^[\x20-\x7e]+$/u.test(import_node_path5.default.basename(candidate)) || import_node_path5.default.basename(resource).toLowerCase() !== import_node_path5.default.basename(candidate).toLowerCase() || !distinguishesAsciiCase(parent);
3734
+ } catch {
3735
+ return namesMayMatch;
3736
+ }
3737
+ }
3738
+ var missing = (error) => error.code === "ENOENT";
3739
+ function resolveReservedTarget(target, remaining = 64) {
3740
+ if (!remaining) throw new Error("reserved_path_unresolved");
3741
+ try {
3742
+ return (0, import_node_fs6.realpathSync)(target);
3743
+ } catch (error) {
3744
+ const parent = import_node_path5.default.dirname(target);
3745
+ if (!missing(error) || parent === target) throw error;
3746
+ const canonicalParent = resolveReservedTarget(parent, remaining - 1);
3747
+ if (!(0, import_node_fs6.lstatSync)(target, { throwIfNoEntry: false })?.isSymbolicLink())
3748
+ return import_node_path5.default.join(canonicalParent, import_node_path5.default.basename(target));
3749
+ const referent = (0, import_node_fs6.readlinkSync)(target);
3750
+ let seenName = false;
3751
+ for (const part of referent.split(
3752
+ process.platform === "win32" ? /[\\/]/u : "/"
3753
+ )) {
3754
+ if (part === ".." && seenName)
3755
+ throw new Error("reserved_path_unresolved");
3756
+ if (part && part !== "." && part !== "..") seenName = true;
3757
+ }
3758
+ return resolveReservedTarget(
3759
+ import_node_path5.default.resolve(canonicalParent, referent),
3760
+ remaining - 1
3761
+ );
3762
+ }
3763
+ }
3764
+
3765
+ // src/permissions/home-dot-paths.ts
3766
+ var homeDotDirectory = (writeRoots, home = import_node_os.default.homedir()) => {
3767
+ if (!writeRoots.length) return void 0;
3768
+ const canonicalHome = resolveReservedTarget(home);
3769
+ return writeRoots.some(
3770
+ (root) => resourceContainsPath(resolveReservedTarget(root), canonicalHome)
3771
+ ) ? canonicalHome : void 0;
3772
+ };
3773
+ var isHomeDotTarget = (home, target, platform = process.platform) => {
3774
+ if (!resourceContainsPath(home, target)) return false;
3775
+ const root = import_node_path6.default.parse(home).root;
3776
+ const depth = home.slice(root.length).split(import_node_path6.default.sep).filter(Boolean).length;
3777
+ const first = target.slice(import_node_path6.default.parse(target).root.length).split(import_node_path6.default.sep).filter(Boolean)[depth];
3778
+ return !!first && (first.startsWith(".") || platform === "darwin" && resourceContainsPath(import_node_path6.default.join(home, "Library"), target));
3779
+ };
3780
+ var hasClosedHomeDotCycle = (home, start) => {
3781
+ const seen = /* @__PURE__ */ new Set();
3782
+ let current = start;
3783
+ while (seen.size < 64) {
3784
+ if (seen.has(current)) return true;
3785
+ seen.add(current);
3786
+ let link;
3787
+ try {
3788
+ link = (0, import_node_fs7.readlinkSync)(current);
3789
+ } catch {
3790
+ return false;
3791
+ }
3792
+ const next = import_node_path6.default.resolve(home, link);
3793
+ const name = import_node_path6.default.basename(next);
3794
+ if (import_node_path6.default.dirname(next) !== home || !isHomeDotTarget(home, next) || link !== next && link !== name && link !== `.${import_node_path6.default.sep}${name}`)
3795
+ return false;
3796
+ current = next;
3797
+ }
3798
+ return false;
3799
+ };
3800
+ var homeDotLinkTargets = (home) => (0, import_node_fs7.readdirSync)(home, { withFileTypes: true }).filter(
3801
+ (entry) => entry.isSymbolicLink() && isHomeDotTarget(home, import_node_path6.default.join(home, entry.name))
3802
+ ).flatMap((entry) => {
3803
+ const link = import_node_path6.default.join(home, entry.name);
3804
+ try {
3805
+ return [resolveReservedTarget(link)];
3806
+ } catch (error) {
3807
+ if (error.code === "ELOOP" && hasClosedHomeDotCycle(home, link))
3808
+ return [];
3809
+ throw error;
3810
+ }
3811
+ });
3812
+ var isHomeWriteReserved = (home, target) => isHomeDotTarget(home, target) || homeDotLinkTargets(home).some((link) => resourceContainsPath(link, target));
3813
+
3814
+ // src/permissions/protected-aliases.ts
3815
+ var import_node_fs8 = require("fs");
3816
+ var import_node_path7 = __toESM(require("path"), 1);
3406
3817
  var maxEntries = 4096;
3407
3818
  var inode = (stat) => `${stat.dev}:${stat.ino}`;
3408
3819
  function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifiedHooks = []) {
3409
3820
  const pending = roots.map((entry) => {
3410
3821
  try {
3411
- return (0, import_node_fs6.realpathSync)(entry);
3822
+ return (0, import_node_fs8.realpathSync)(entry);
3412
3823
  } catch (error) {
3413
3824
  if (error.code === "ENOENT") return entry;
3414
3825
  throw error;
@@ -3424,7 +3835,7 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
3424
3835
  const target = hooks.get(file);
3425
3836
  if (!target) return false;
3426
3837
  try {
3427
- return (0, import_node_fs6.realpathSync)(file) === target && (0, import_node_fs6.lstatSync)(target).isFile();
3838
+ return (0, import_node_fs8.realpathSync)(file) === target && (0, import_node_fs8.lstatSync)(target).isFile();
3428
3839
  } catch {
3429
3840
  return false;
3430
3841
  }
@@ -3436,18 +3847,18 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
3436
3847
  if (visited.size > entryLimit)
3437
3848
  throw new Error("protected_alias_index_unavailable");
3438
3849
  try {
3439
- const metadata = (0, import_node_fs6.lstatSync)(file, { bigint: true });
3850
+ const metadata = (0, import_node_fs8.lstatSync)(file, { bigint: true });
3440
3851
  if (metadata.isFile() && metadata.nlink > 1n) yield inode(metadata);
3441
3852
  if (metadata.isSymbolicLink() && ignored.size) {
3442
3853
  if (verifiedHook(file)) continue;
3443
3854
  pending.push(...ignored);
3444
3855
  ignored.clear();
3445
3856
  } else if (metadata.isDirectory()) {
3446
- const children = (0, import_node_fs6.readdirSync)(file);
3857
+ const children = (0, import_node_fs8.readdirSync)(file);
3447
3858
  if (children.length + pending.length + visited.size > entryLimit)
3448
3859
  throw new Error("protected_alias_index_unavailable");
3449
3860
  for (const name of children) {
3450
- const child = import_node_path5.default.join(file, name);
3861
+ const child = import_node_path7.default.join(file, name);
3451
3862
  if (!ignored.has(child)) pending.push(child);
3452
3863
  }
3453
3864
  }
@@ -3472,130 +3883,70 @@ var hasReadOnlyAliases = (roots, target, ignoredObjectDirectories, verifiedHooks
3472
3883
  };
3473
3884
  var isProtectedAlias = (stat, paths) => stat.nlink > 1n && findProtectedAliases(paths).has(inode(stat));
3474
3885
 
3475
- // src/permissions/resource-paths.ts
3476
- var import_node_fs7 = require("fs");
3477
- var import_node_path6 = __toESM(require("path"), 1);
3478
- var lookup = (pathname) => (0, import_node_fs7.lstatSync)(pathname, { bigint: true, throwIfNoEntry: false });
3479
- var sameEntry = (left, right) => left.dev === right.dev && left.ino === right.ino;
3480
- var comparableResourceName = (pathname) => {
3481
- const folded = pathname.normalize("NFD").toUpperCase().toLowerCase();
3482
- return process.platform === "win32" ? folded.replace(/[ .]+(?=[\\/]|$)/gu, "") : folded;
3483
- };
3484
- function distinguishesAsciiCase(parent) {
3485
- try {
3486
- const directory = (0, import_node_fs7.opendirSync)(parent);
3487
- try {
3488
- for (let index = 0; index < 16; index++) {
3489
- const name = directory.readSync()?.name;
3490
- if (!name) break;
3491
- const changed = name.replace(
3492
- /[A-Za-z]/u,
3493
- (letter) => letter === letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase()
3494
- );
3495
- if (name === changed) continue;
3496
- const original = lookup(import_node_path6.default.join(parent, name));
3497
- const alternate = lookup(import_node_path6.default.join(parent, changed));
3498
- if (original) return !alternate || !sameEntry(original, alternate);
3499
- }
3500
- } finally {
3501
- directory.closeSync();
3502
- }
3503
- } catch {
3504
- }
3505
- return false;
3506
- }
3507
- function resourceContainsPath(resource, target) {
3508
- if (target === resource || target.startsWith(
3509
- resource.endsWith(import_node_path6.default.sep) ? resource : `${resource}${import_node_path6.default.sep}`
3510
- ))
3511
- return true;
3512
- const root = import_node_path6.default.parse(resource).root;
3513
- const targetRoot = import_node_path6.default.parse(target).root;
3514
- if (comparableResourceName(root) !== comparableResourceName(targetRoot))
3515
- return false;
3516
- const parts = resource.slice(root.length).split(import_node_path6.default.sep);
3517
- const overlapping = target.slice(targetRoot.length).split(import_node_path6.default.sep).slice(0, parts.length);
3518
- if (overlapping.length !== parts.length) return false;
3519
- const candidate = import_node_path6.default.join(targetRoot, ...overlapping);
3520
- const namesMayMatch = comparableResourceName(resource) === comparableResourceName(candidate);
3521
- try {
3522
- const targetEntry = lookup(candidate);
3523
- if (!targetEntry && !namesMayMatch) return false;
3524
- const protectedEntry = lookup(resource);
3525
- if (protectedEntry || targetEntry)
3526
- return !!protectedEntry && !!targetEntry && sameEntry(protectedEntry, targetEntry);
3527
- if (!namesMayMatch) return false;
3528
- const parent = import_node_path6.default.dirname(resource);
3529
- return import_node_path6.default.dirname(candidate) !== parent || !/^[\x20-\x7e]+$/u.test(import_node_path6.default.basename(resource)) || !/^[\x20-\x7e]+$/u.test(import_node_path6.default.basename(candidate)) || import_node_path6.default.basename(resource).toLowerCase() !== import_node_path6.default.basename(candidate).toLowerCase() || !distinguishesAsciiCase(parent);
3530
- } catch {
3531
- return namesMayMatch;
3532
- }
3533
- }
3534
-
3535
3886
  // src/permissions/shell-backend.ts
3536
3887
  var import_node_child_process4 = require("child_process");
3537
- var import_node_fs14 = require("fs");
3538
- var import_node_os = __toESM(require("os"), 1);
3539
- var import_node_path15 = __toESM(require("path"), 1);
3540
- var import_storage8 = require("@codelia/storage");
3888
+ var import_node_fs15 = require("fs");
3889
+ var import_node_os2 = __toESM(require("os"), 1);
3890
+ var import_node_path16 = __toESM(require("path"), 1);
3891
+ var import_storage9 = require("@codelia/storage");
3541
3892
 
3542
3893
  // src/sandbox/file-mutation-helper.ts
3543
- var import_node_path7 = __toESM(require("path"), 1);
3894
+ var import_node_path8 = __toESM(require("path"), 1);
3544
3895
 
3545
3896
  // src/utils/paths.ts
3546
- var import_node_path8 = __toESM(require("path"), 1);
3897
+ var import_node_path9 = __toESM(require("path"), 1);
3547
3898
  var isWithin = (root, target) => {
3548
- const relative = import_node_path8.default.relative(root, target);
3549
- return relative === "" || !import_node_path8.default.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${import_node_path8.default.sep}`);
3899
+ const relative = import_node_path9.default.relative(root, target);
3900
+ return relative === "" || !import_node_path9.default.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${import_node_path9.default.sep}`);
3550
3901
  };
3551
3902
 
3552
3903
  // src/permissions/linux-shell-backend.ts
3553
3904
  var import_node_child_process2 = require("child_process");
3554
- var import_node_fs10 = require("fs");
3555
- var import_node_path11 = __toESM(require("path"), 1);
3905
+ var import_node_fs11 = require("fs");
3906
+ var import_node_path12 = __toESM(require("path"), 1);
3556
3907
 
3557
3908
  // src/permissions/linux-mountinfo.ts
3558
- var import_node_fs8 = require("fs");
3559
- var import_node_path9 = __toESM(require("path"), 1);
3909
+ var import_node_fs9 = require("fs");
3910
+ var import_node_path10 = __toESM(require("path"), 1);
3560
3911
 
3561
3912
  // src/permissions/shell-analysis.ts
3562
3913
  var MAX_SOURCE_BYTES = 32 * 1024;
3563
3914
 
3564
3915
  // src/permissions/shell-path.ts
3565
- var import_node_fs9 = require("fs");
3566
- var import_node_path10 = __toESM(require("path"), 1);
3916
+ var import_node_fs10 = require("fs");
3917
+ var import_node_path11 = __toESM(require("path"), 1);
3567
3918
 
3568
3919
  // src/permissions/mxc-launcher.ts
3569
3920
  var import_node_child_process3 = require("child_process");
3570
- var import_node_fs11 = require("fs");
3571
- var import_node_path12 = __toESM(require("path"), 1);
3921
+ var import_node_fs12 = require("fs");
3922
+ var import_node_path13 = __toESM(require("path"), 1);
3572
3923
  var import_node_url = require("url");
3573
3924
  var import_meta = {};
3574
- var packagePath = import_node_path12.default.join("node_modules", "@codelia", "tui-darwin-arm64");
3575
- var moduleDir = typeof __dirname === "string" ? __dirname : import_node_path12.default.dirname((0, import_node_url.fileURLToPath)(import_meta.url));
3925
+ var packagePath = import_node_path13.default.join("node_modules", "@codelia", "tui-darwin-arm64");
3926
+ var moduleDir = typeof __dirname === "string" ? __dirname : import_node_path13.default.dirname((0, import_node_url.fileURLToPath)(import_meta.url));
3576
3927
 
3577
3928
  // src/permissions/system-bash.ts
3578
- var import_node_fs12 = require("fs");
3579
- var import_node_path13 = require("path");
3929
+ var import_node_fs13 = require("fs");
3930
+ var import_node_path14 = require("path");
3580
3931
 
3581
3932
  // src/permissions/workspace-config-paths.ts
3582
- var import_node_fs13 = require("fs");
3583
- var import_node_path14 = __toESM(require("path"), 1);
3584
- var import_storage7 = require("@codelia/storage");
3933
+ var import_node_fs14 = require("fs");
3934
+ var import_node_path15 = __toESM(require("path"), 1);
3935
+ var import_storage8 = require("@codelia/storage");
3585
3936
  var confinedAutoLaunchDirectoryName = "confined-auto-launch";
3586
- var isWorkspaceConfigName = (root, target) => resourceContainsPath(import_node_path14.default.dirname(resolveProjectConfigPath(root)), target);
3587
- var missing = (error) => error.code === "ENOENT";
3937
+ var isWorkspaceConfigName = (root, target) => resourceContainsPath(import_node_path15.default.dirname(resolveProjectConfigPath(root)), target);
3938
+ var missing2 = (error) => error.code === "ENOENT";
3588
3939
  function resolveConfigTarget(target, remaining = 64) {
3589
3940
  if (!remaining) throw new Error("workspace_config_path_unresolved");
3590
3941
  try {
3591
- return (0, import_node_fs13.realpathSync)(target);
3942
+ return (0, import_node_fs14.realpathSync)(target);
3592
3943
  } catch (error) {
3593
- const parent = import_node_path14.default.dirname(target);
3594
- if (!missing(error) || parent === target) throw error;
3944
+ const parent = import_node_path15.default.dirname(target);
3945
+ if (!missing2(error) || parent === target) throw error;
3595
3946
  const canonicalParent = resolveConfigTarget(parent, remaining - 1);
3596
- if (!(0, import_node_fs13.lstatSync)(target, { throwIfNoEntry: false })?.isSymbolicLink())
3597
- return import_node_path14.default.join(canonicalParent, import_node_path14.default.basename(target));
3598
- const referent = (0, import_node_fs13.readlinkSync)(target);
3947
+ if (!(0, import_node_fs14.lstatSync)(target, { throwIfNoEntry: false })?.isSymbolicLink())
3948
+ return import_node_path15.default.join(canonicalParent, import_node_path15.default.basename(target));
3949
+ const referent = (0, import_node_fs14.readlinkSync)(target);
3599
3950
  let seenName = false;
3600
3951
  for (const part of referent.split(
3601
3952
  process.platform === "win32" ? /[\\/]/u : "/"
@@ -3605,14 +3956,14 @@ function resolveConfigTarget(target, remaining = 64) {
3605
3956
  if (part && part !== "." && part !== "..") seenName = true;
3606
3957
  }
3607
3958
  return resolveConfigTarget(
3608
- import_node_path14.default.resolve(canonicalParent, referent),
3959
+ import_node_path15.default.resolve(canonicalParent, referent),
3609
3960
  remaining - 1
3610
3961
  );
3611
3962
  }
3612
3963
  }
3613
3964
  var workspaceConfigProtection = (root) => {
3614
3965
  const config = resolveProjectConfigPath(root);
3615
- const directory = import_node_path14.default.dirname(config);
3966
+ const directory = import_node_path15.default.dirname(config);
3616
3967
  const readOnlyPaths = /* @__PURE__ */ new Set([directory]);
3617
3968
  const readOnlyAliasPaths = /* @__PURE__ */ new Set();
3618
3969
  const reserveTarget = (file) => {
@@ -3620,37 +3971,37 @@ var workspaceConfigProtection = (root) => {
3620
3971
  readOnlyPaths.add(target);
3621
3972
  readOnlyAliasPaths.add(target);
3622
3973
  };
3623
- if ((0, import_node_fs13.lstatSync)(directory, { throwIfNoEntry: false })) {
3974
+ if ((0, import_node_fs14.lstatSync)(directory, { throwIfNoEntry: false })) {
3624
3975
  const canonical = resolveConfigTarget(directory);
3625
3976
  readOnlyPaths.add(canonical);
3626
- if ((0, import_node_fs13.lstatSync)(canonical, { throwIfNoEntry: false })?.isDirectory()) {
3627
- const file = import_node_path14.default.join(canonical, import_node_path14.default.basename(config));
3628
- if ((0, import_node_fs13.lstatSync)(file, { throwIfNoEntry: false })) reserveTarget(file);
3629
- const storage = (0, import_storage7.resolveStoragePaths)();
3977
+ if ((0, import_node_fs14.lstatSync)(canonical, { throwIfNoEntry: false })?.isDirectory()) {
3978
+ const file = import_node_path15.default.join(canonical, import_node_path15.default.basename(config));
3979
+ if ((0, import_node_fs14.lstatSync)(file, { throwIfNoEntry: false })) reserveTarget(file);
3980
+ const storage = (0, import_storage8.resolveStoragePaths)();
3630
3981
  const globalStorage = [
3631
- (0, import_storage7.resolveStoragePaths)({ layout: "home" }).root,
3982
+ (0, import_storage8.resolveStoragePaths)({ layout: "home" }).root,
3632
3983
  storage.root,
3633
3984
  storage.configDir
3634
3985
  ].some((entry) => {
3635
3986
  try {
3636
- return (0, import_node_fs13.realpathSync)(entry) === canonical;
3987
+ return (0, import_node_fs14.realpathSync)(entry) === canonical;
3637
3988
  } catch (error) {
3638
- if (!missing(error)) throw error;
3989
+ if (!missing2(error)) throw error;
3639
3990
  return false;
3640
3991
  }
3641
3992
  });
3642
3993
  if (!globalStorage) {
3643
- const worktrees = import_node_path14.default.join(canonical, "worktrees");
3994
+ const worktrees = import_node_path15.default.join(canonical, "worktrees");
3644
3995
  const pending = [canonical];
3645
3996
  for (const current of pending) {
3646
- const children = (0, import_node_fs13.opendirSync)(current);
3997
+ const children = (0, import_node_fs14.opendirSync)(current);
3647
3998
  try {
3648
3999
  for (let entry = children.readSync(); entry; entry = children.readSync()) {
3649
- const target = import_node_path14.default.join(current, entry.name);
4000
+ const target = import_node_path15.default.join(current, entry.name);
3650
4001
  if (target === file || target === worktrees) continue;
3651
4002
  if (entry.isSymbolicLink()) reserveTarget(target);
3652
4003
  else if (entry.isDirectory()) pending.push(target);
3653
- else if (entry.isFile() && ((0, import_node_fs13.lstatSync)(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
4004
+ else if (entry.isFile() && ((0, import_node_fs14.lstatSync)(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
3654
4005
  readOnlyAliasPaths.add(target);
3655
4006
  }
3656
4007
  } finally {
@@ -3669,31 +4020,31 @@ var workspaceConfigProtection = (root) => {
3669
4020
  // src/permissions/shell-backend.ts
3670
4021
  var realOrLexical = (value) => {
3671
4022
  try {
3672
- return (0, import_node_fs14.realpathSync)(value);
4023
+ return (0, import_node_fs15.realpathSync)(value);
3673
4024
  } catch {
3674
- return import_node_path15.default.resolve(value);
4025
+ return import_node_path16.default.resolve(value);
3675
4026
  }
3676
4027
  };
3677
4028
  var resolvePolicyPath = (target) => {
3678
- const absolute = import_node_path15.default.resolve(target);
4029
+ const absolute = import_node_path16.default.resolve(target);
3679
4030
  try {
3680
- return (0, import_node_fs14.realpathSync)(absolute);
4031
+ return (0, import_node_fs15.realpathSync)(absolute);
3681
4032
  } catch (error) {
3682
- const parent = import_node_path15.default.dirname(absolute);
4033
+ const parent = import_node_path16.default.dirname(absolute);
3683
4034
  if (error.code !== "ENOENT" || parent === absolute)
3684
4035
  throw error;
3685
- if ((0, import_node_fs14.lstatSync)(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
4036
+ if ((0, import_node_fs15.lstatSync)(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
3686
4037
  throw error;
3687
- return import_node_path15.default.join(resolvePolicyPath(parent), import_node_path15.default.basename(absolute));
4038
+ return import_node_path16.default.join(resolvePolicyPath(parent), import_node_path16.default.basename(absolute));
3688
4039
  }
3689
4040
  };
3690
4041
  var canonicalPolicyPaths = (paths) => Object.freeze([
3691
4042
  ...new Set(
3692
- paths.flatMap((entry) => [import_node_path15.default.resolve(entry), resolvePolicyPath(entry)])
4043
+ paths.flatMap((entry) => [import_node_path16.default.resolve(entry), resolvePolicyPath(entry)])
3693
4044
  )
3694
4045
  ]);
3695
4046
  var runtimeReadOnlyPaths = () => {
3696
- const storage = (0, import_storage8.resolveStoragePaths)();
4047
+ const storage = (0, import_storage9.resolveStoragePaths)();
3697
4048
  return canonicalPolicyPaths([
3698
4049
  storage.root,
3699
4050
  storage.configDir,
@@ -3701,37 +4052,68 @@ var runtimeReadOnlyPaths = () => {
3701
4052
  resolveConfigPath()
3702
4053
  ]);
3703
4054
  };
4055
+ var runtimeProtectedCredentialPaths = () => {
4056
+ const storage = (0, import_storage9.resolveStoragePaths)();
4057
+ const targets = [];
4058
+ if (process.platform === "linux") {
4059
+ try {
4060
+ (0, import_node_fs15.mkdirSync)(storage.credentialsDir, { recursive: true, mode: 448 });
4061
+ targets.push(storage.credentialsDir);
4062
+ } catch {
4063
+ if ((0, import_node_fs15.lstatSync)(storage.credentialsDir, { throwIfNoEntry: false })) {
4064
+ targets.push(storage.credentialsDir);
4065
+ }
4066
+ }
4067
+ for (const legacy of [storage.legacyAuthFile, storage.legacyMcpAuthFile]) {
4068
+ if ((0, import_node_fs15.lstatSync)(legacy, { throwIfNoEntry: false })) {
4069
+ targets.push(legacy);
4070
+ }
4071
+ }
4072
+ } else {
4073
+ targets.push(
4074
+ storage.credentialsDir,
4075
+ storage.legacyAuthFile,
4076
+ storage.legacyMcpAuthFile
4077
+ );
4078
+ }
4079
+ return canonicalPolicyPaths(targets);
4080
+ };
3704
4081
  var runtimeAuthorityAliasPaths = () => {
3705
- const storage = (0, import_storage8.resolveStoragePaths)();
4082
+ const storage = (0, import_storage9.resolveStoragePaths)();
3706
4083
  const databasePaths = [
3707
- import_node_path15.default.join(storage.configDir, ".projects-policy-lock.sqlite"),
3708
- import_node_path15.default.join(storage.sessionsDir, "state.db")
4084
+ import_node_path16.default.join(storage.configDir, ".projects-policy-lock.sqlite"),
4085
+ import_node_path16.default.join(storage.sessionsDir, "state.db")
3709
4086
  ];
3710
4087
  return canonicalPolicyPaths([
3711
4088
  resolveConfigPath(),
3712
4089
  storage.configFile,
3713
4090
  storage.projectsFile,
3714
- storage.authFile,
3715
- storage.mcpAuthFile,
3716
4091
  ...[
3717
4092
  "launch-approvals",
3718
4093
  "auto-review.json",
3719
4094
  confinedAutoLaunchDirectoryName
3720
- ].map((entry) => import_node_path15.default.join(storage.configDir, entry)),
4095
+ ].map((entry) => import_node_path16.default.join(storage.configDir, entry)),
3721
4096
  ...databasePaths.flatMap(
3722
4097
  (file) => ["", "-wal", "-shm", "-journal"].map((suffix) => `${file}${suffix}`)
3723
4098
  )
3724
4099
  ]);
3725
4100
  };
3726
- var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectories = [], sandboxMode = "workspace-write", allowSharedGitObjects = false, extraReadOnlyPaths = []) => {
4101
+ var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectories = [], sandboxMode = "workspace-write", allowSharedGitObjects = false, extraReadOnlyPaths = [], homeScope = {}) => {
3727
4102
  const discover = allowSharedGitObjects && sandboxMode === "workspace-write" ? gitMetadataWithObjectDirectories : gitMetadataPaths;
3728
4103
  const { readOnlyPaths, reservedMarkers, objectDirectories, hookAliases } = discover(root, ...relatedDirectories);
3729
- const protectedPaths = canonicalPolicyPaths(extraProtectedPaths);
4104
+ const protectedPaths = canonicalPolicyPaths([
4105
+ ...extraProtectedPaths,
4106
+ ...runtimeProtectedCredentialPaths()
4107
+ ]);
3730
4108
  const projectConfig = workspaceConfigProtection(root);
3731
4109
  const hostReadOnlyPaths = canonicalPolicyPaths(extraReadOnlyPaths);
3732
4110
  const runtimeRoots = runtimeReadOnlyPaths();
3733
4111
  const runtimeAuthority = runtimeAuthorityAliasPaths();
4112
+ const protectedHome = homeDotDirectory(
4113
+ homeScope.writeRoots ?? (sandboxMode === "readonly" ? [] : [root])
4114
+ );
3734
4115
  const additionalReadOnlyPaths = [
4116
+ ...protectedHome && !homeScope.recheckHomeLinksOnWrite ? homeDotLinkTargets(protectedHome) : [],
3735
4117
  ...reservedMarkers,
3736
4118
  ...projectConfig.readOnlyPaths,
3737
4119
  ...hostReadOnlyPaths,
@@ -3744,13 +4126,14 @@ var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectorie
3744
4126
  const objectDirectoriesWithSharedFiles = objectDirectories.filter(
3745
4127
  (directory) => {
3746
4128
  const overlaps = (other) => resourceContainsPath(other, directory.path) || resourceContainsPath(directory.path, other);
3747
- const commonDirectory = import_node_path15.default.dirname(directory.path);
4129
+ const commonDirectory = import_node_path16.default.dirname(directory.path);
3748
4130
  return !strongerPaths.some(overlaps) && !readOnlyPaths.some(
3749
4131
  (other) => overlaps(other) && realOrLexical(other) !== commonDirectory
3750
4132
  );
3751
4133
  }
3752
4134
  );
3753
4135
  return {
4136
+ ...protectedHome ? { homeDotDirectory: protectedHome } : {},
3754
4137
  protectedPaths,
3755
4138
  protectedAliasPaths: protectedPaths,
3756
4139
  readOnlyPaths: Object.freeze(
@@ -3784,22 +4167,22 @@ var SecurityError = class extends Error {
3784
4167
  var identity = (info) => `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
3785
4168
  var directoryIdentity = (stat) => `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
3786
4169
  var selectMissingFile = (entry) => {
3787
- let parent = import_node_path16.default.dirname(entry.target);
4170
+ let parent = import_node_path17.default.dirname(entry.target);
3788
4171
  for (; ; ) {
3789
4172
  try {
3790
- const stat = (0, import_node_fs15.lstatSync)(parent, { bigint: true });
3791
- if (!stat.isDirectory() || (0, import_node_fs15.realpathSync)(parent) !== parent)
4173
+ const stat = (0, import_node_fs16.lstatSync)(parent, { bigint: true });
4174
+ if (!stat.isDirectory() || (0, import_node_fs16.realpathSync)(parent) !== parent)
3792
4175
  throw new SecurityError("Expected a canonical parent directory");
3793
4176
  return Object.freeze({
3794
4177
  ...entry,
3795
4178
  identity: null,
3796
4179
  parent,
3797
4180
  parentIdentity: directoryIdentity(stat),
3798
- tail: import_node_path16.default.relative(parent, entry.target)
4181
+ tail: import_node_path17.default.relative(parent, entry.target)
3799
4182
  });
3800
4183
  } catch (error) {
3801
4184
  if (error.code !== "ENOENT") throw error;
3802
- const ancestor = import_node_path16.default.dirname(parent);
4185
+ const ancestor = import_node_path17.default.dirname(parent);
3803
4186
  if (ancestor === parent) throw error;
3804
4187
  parent = ancestor;
3805
4188
  }
@@ -3807,15 +4190,15 @@ var selectMissingFile = (entry) => {
3807
4190
  };
3808
4191
  var missingDestinationCurrent = (selection) => {
3809
4192
  try {
3810
- const segments = selection.tail.split(import_node_path16.default.sep);
4193
+ const segments = selection.tail.split(import_node_path17.default.sep);
3811
4194
  if (segments.some(
3812
4195
  (segment) => !segment || segment === "." || segment === ".."
3813
- ) || import_node_path16.default.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
4196
+ ) || import_node_path17.default.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
3814
4197
  return false;
3815
4198
  let current = selection.parent;
3816
4199
  for (const [index, segment] of segments.entries()) {
3817
- current = import_node_path16.default.join(current, segment);
3818
- const stat = (0, import_node_fs15.lstatSync)(current);
4200
+ current = import_node_path17.default.join(current, segment);
4201
+ const stat = (0, import_node_fs16.lstatSync)(current);
3819
4202
  if (index === segments.length - 1 || !stat.isDirectory()) return false;
3820
4203
  }
3821
4204
  return false;
@@ -3825,8 +4208,8 @@ var missingDestinationCurrent = (selection) => {
3825
4208
  };
3826
4209
  var directoryBindingCurrent = (selection) => {
3827
4210
  try {
3828
- const stat = (0, import_node_fs15.lstatSync)(selection.parent, { bigint: true });
3829
- return stat.isDirectory() && directoryIdentity(stat) === selection.parentIdentity && (0, import_node_fs15.realpathSync)(selection.parent) === selection.parent;
4211
+ const stat = (0, import_node_fs16.lstatSync)(selection.parent, { bigint: true });
4212
+ return stat.isDirectory() && directoryIdentity(stat) === selection.parentIdentity && (0, import_node_fs16.realpathSync)(selection.parent) === selection.parent;
3830
4213
  } catch {
3831
4214
  return false;
3832
4215
  }
@@ -3839,6 +4222,7 @@ var SandboxContext = class _SandboxContext {
3839
4222
  approvalMode;
3840
4223
  protectedPaths;
3841
4224
  protectedAliasPaths;
4225
+ homeDotDirectory;
3842
4226
  readOnlyPaths;
3843
4227
  readOnlyAliasPaths;
3844
4228
  mutations;
@@ -3851,6 +4235,7 @@ var SandboxContext = class _SandboxContext {
3851
4235
  this.approvalMode = init.approvalMode;
3852
4236
  this.protectedPaths = init.protectedPaths;
3853
4237
  this.protectedAliasPaths = init.protectedAliasPaths;
4238
+ this.homeDotDirectory = init.homeDotDirectory;
3854
4239
  this.readOnlyPaths = init.readOnlyPaths ?? [];
3855
4240
  this.readOnlyAliasPaths = init.readOnlyAliasPaths ?? this.readOnlyPaths;
3856
4241
  this.selections = init.selections;
@@ -3858,10 +4243,10 @@ var SandboxContext = class _SandboxContext {
3858
4243
  }
3859
4244
  static async create(rootDir, options = {}) {
3860
4245
  const sessionId = import_node_crypto5.default.randomUUID().slice(0, 8);
3861
- const root = rootDir ? import_node_path16.default.resolve(rootDir) : process.cwd();
4246
+ const root = rootDir ? import_node_path17.default.resolve(rootDir) : process.cwd();
3862
4247
  if (options.sandboxMode !== "readonly")
3863
- await import_node_fs15.promises.mkdir(root, { recursive: true });
3864
- const directory = options.protectResources ? await import_node_fs15.promises.realpath(root) : root;
4248
+ await import_node_fs16.promises.mkdir(root, { recursive: true });
4249
+ const directory = options.protectResources ? await import_node_fs16.promises.realpath(root) : root;
3865
4250
  return new _SandboxContext({
3866
4251
  rootDir: directory,
3867
4252
  workingDir: directory,
@@ -3871,7 +4256,8 @@ var SandboxContext = class _SandboxContext {
3871
4256
  [],
3872
4257
  options.sandboxMode,
3873
4258
  false,
3874
- options.extraReadOnlyPaths
4259
+ options.extraReadOnlyPaths,
4260
+ { recheckHomeLinksOnWrite: true }
3875
4261
  ) : {},
3876
4262
  sessionId,
3877
4263
  mutations: typeof options.mutations === "function" ? await options.mutations(directory) : options.mutations,
@@ -3882,7 +4268,7 @@ var SandboxContext = class _SandboxContext {
3882
4268
  resolvePath(targetPath, access = "write") {
3883
4269
  if (access === "write" && this.sandboxMode === "readonly")
3884
4270
  throw new SecurityError("Sandbox mode is readonly");
3885
- const resolved = import_node_path16.default.isAbsolute(targetPath) ? import_node_path16.default.resolve(targetPath) : import_node_path16.default.resolve(this.workingDir, targetPath);
4271
+ const resolved = import_node_path17.default.isAbsolute(targetPath) ? import_node_path17.default.resolve(targetPath) : import_node_path17.default.resolve(this.workingDir, targetPath);
3886
4272
  if (this.protectedPaths) return this.resolveProtectedPath(resolved, access);
3887
4273
  if (this.approvalMode === "full-access") {
3888
4274
  return resolved;
@@ -3900,12 +4286,12 @@ var SandboxContext = class _SandboxContext {
3900
4286
  selectFile(operand, access, directoryEntry = false) {
3901
4287
  const target = this.resolvePath(operand, access);
3902
4288
  if (directoryEntry) {
3903
- const lexical = import_node_path16.default.resolve(this.workingDir, operand);
3904
- const name = import_node_path16.default.join(
3905
- resolvePolicyPath(import_node_path16.default.dirname(lexical)),
3906
- import_node_path16.default.basename(lexical)
4289
+ const lexical = import_node_path17.default.resolve(this.workingDir, operand);
4290
+ const name = import_node_path17.default.join(
4291
+ resolvePolicyPath(import_node_path17.default.dirname(lexical)),
4292
+ import_node_path17.default.basename(lexical)
3907
4293
  );
3908
- if (target !== name || (0, import_node_fs15.lstatSync)(name, { throwIfNoEntry: false })?.isSymbolicLink())
4294
+ if (target !== name || (0, import_node_fs16.lstatSync)(name, { throwIfNoEntry: false })?.isSymbolicLink())
3909
4295
  throw new SecurityError(
3910
4296
  "Patch deletion and move require a regular directory entry without a symbolic link"
3911
4297
  );
@@ -3917,7 +4303,7 @@ var SandboxContext = class _SandboxContext {
3917
4303
  ...directoryEntry ? { directoryEntry: true } : {}
3918
4304
  };
3919
4305
  try {
3920
- const info = (0, import_node_fs15.lstatSync)(target, { bigint: true });
4306
+ const info = (0, import_node_fs16.lstatSync)(target, { bigint: true });
3921
4307
  if (!info.isFile())
3922
4308
  throw new SecurityError("Expected a regular file for this operation");
3923
4309
  return Object.freeze({
@@ -3938,6 +4324,7 @@ var SandboxContext = class _SandboxContext {
3938
4324
  sandboxMode: this.sandboxMode,
3939
4325
  protectedPaths: this.protectedPaths,
3940
4326
  protectedAliasPaths: this.protectedAliasPaths,
4327
+ homeDotDirectory: this.homeDotDirectory,
3941
4328
  readOnlyPaths: this.readOnlyPaths,
3942
4329
  readOnlyAliasPaths: this.readOnlyAliasPaths,
3943
4330
  mutations: this.mutations,
@@ -3964,8 +4351,8 @@ var SandboxContext = class _SandboxContext {
3964
4351
  error.code = "ENOENT";
3965
4352
  throw error;
3966
4353
  }
3967
- const flags = (mode === "read" ? import_node_fs15.constants.O_RDONLY : import_node_fs15.constants.O_RDWR) | (import_node_fs15.constants.O_NOFOLLOW ?? 0) | (import_node_fs15.constants.O_NONBLOCK ?? 0);
3968
- const handle = await import_node_fs15.promises.open(selected.target, flags);
4354
+ const flags = (mode === "read" ? import_node_fs16.constants.O_RDONLY : import_node_fs16.constants.O_RDWR) | (import_node_fs16.constants.O_NOFOLLOW ?? 0) | (import_node_fs16.constants.O_NONBLOCK ?? 0);
4355
+ const handle = await import_node_fs16.promises.open(selected.target, flags);
3969
4356
  try {
3970
4357
  const opened = await handle.stat({ bigint: true });
3971
4358
  if (!opened.isFile() || identity(opened) !== selected.identity || isProtectedAlias(
@@ -4058,7 +4445,7 @@ var SandboxContext = class _SandboxContext {
4058
4445
  writeProtection(target, alias = false) {
4059
4446
  const { readOnlyPaths } = gitMetadataPaths(
4060
4447
  this.rootDir,
4061
- import_node_path16.default.dirname(target)
4448
+ import_node_path17.default.dirname(target)
4062
4449
  );
4063
4450
  const projectConfig = workspaceConfigProtection(this.rootDir);
4064
4451
  return [
@@ -4080,7 +4467,7 @@ var SandboxContext = class _SandboxContext {
4080
4467
  if (access !== "write") return;
4081
4468
  if (!isWithin(this.rootDir, value))
4082
4469
  throw new SecurityError("Write path escapes the workspace");
4083
- if (isWorkspaceConfigName(this.rootDir, value) || this.writeProtection(value).some(
4470
+ if (this.homeDotDirectory && isHomeWriteReserved(this.homeDotDirectory, value) || isWorkspaceConfigName(this.rootDir, value) || this.writeProtection(value).some(
4084
4471
  (entry) => resourceContainsPath(entry, value)
4085
4472
  ))
4086
4473
  throw new SecurityError("Path is read-only under the resource policy");
@@ -4090,16 +4477,16 @@ var SandboxContext = class _SandboxContext {
4090
4477
  let probe = resolved;
4091
4478
  for (; ; ) {
4092
4479
  try {
4093
- const actual = (0, import_node_fs15.realpathSync)(probe);
4094
- const target = import_node_path16.default.resolve(actual, import_node_path16.default.relative(probe, resolved));
4480
+ const actual = (0, import_node_fs16.realpathSync)(probe);
4481
+ const target = import_node_path17.default.resolve(actual, import_node_path17.default.relative(probe, resolved));
4095
4482
  rejectProtected(target);
4096
4483
  if (target !== resolved) rejectWrite(target);
4097
4484
  if (probe === resolved) {
4098
- const stat = (0, import_node_fs15.lstatSync)(target);
4485
+ const stat = (0, import_node_fs16.lstatSync)(target);
4099
4486
  if (!stat.isFile() && !stat.isDirectory())
4100
4487
  throw new SecurityError("Unsupported file type");
4101
4488
  if (stat.isFile() && stat.nlink > 1) {
4102
- const inode2 = (0, import_node_fs15.lstatSync)(target, { bigint: true });
4489
+ const inode2 = (0, import_node_fs16.lstatSync)(target, { bigint: true });
4103
4490
  if (isProtectedAlias(inode2, protectedPaths))
4104
4491
  throw new SecurityError("Path aliases a protected file");
4105
4492
  if (access === "write" && this.isReadOnlyAlias(inode2, target))
@@ -4109,10 +4496,10 @@ var SandboxContext = class _SandboxContext {
4109
4496
  return target;
4110
4497
  } catch (error) {
4111
4498
  if (error.code !== "ENOENT") throw error;
4112
- const ancestor = import_node_path16.default.dirname(probe);
4499
+ const ancestor = import_node_path17.default.dirname(probe);
4113
4500
  if (ancestor === probe) throw error;
4114
4501
  try {
4115
- if ((0, import_node_fs15.lstatSync)(probe).isSymbolicLink())
4502
+ if ((0, import_node_fs16.lstatSync)(probe).isSymbolicLink())
4116
4503
  throw new SecurityError("Path contains a dangling symlink");
4117
4504
  } catch (entryError) {
4118
4505
  if (entryError.code !== "ENOENT")
@@ -4140,8 +4527,8 @@ var appendReadMetadata = (output, content) => `${output}
4140
4527
  [read_metadata] content_sha256=${hashUtf8Content(content)}`;
4141
4528
 
4142
4529
  // src/subagents/workspace-files.ts
4143
- var import_node_fs16 = require("fs");
4144
- var import_node_path17 = __toESM(require("path"), 1);
4530
+ var import_node_fs17 = require("fs");
4531
+ var import_node_path18 = __toESM(require("path"), 1);
4145
4532
  var MAX_CHILD_FILE_BYTES = 4 * 1024 * 1024;
4146
4533
  var readContent = async (handle) => {
4147
4534
  const buffer = Buffer.alloc(MAX_CHILD_FILE_BYTES + 1);
@@ -4154,6 +4541,7 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
4154
4541
  const {
4155
4542
  protectedPaths,
4156
4543
  protectedAliasPaths,
4544
+ homeDotDirectory: homeDotDirectory2,
4157
4545
  readOnlyPaths = [],
4158
4546
  readOnlyAliasPaths = readOnlyPaths
4159
4547
  } = workspacePathProtection(
@@ -4162,21 +4550,22 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
4162
4550
  [],
4163
4551
  "workspace-write",
4164
4552
  false,
4165
- extraReadOnlyPaths
4553
+ extraReadOnlyPaths,
4554
+ { recheckHomeLinksOnWrite: true }
4166
4555
  );
4167
4556
  const blocked = (target) => protectedPaths.some((entry) => resourceContainsPath(entry, target));
4168
4557
  const resolve = async (name, allowMissing = false) => {
4169
- const candidate = import_node_path17.default.resolve(root, name);
4558
+ const candidate = import_node_path18.default.resolve(root, name);
4170
4559
  if (blocked(candidate))
4171
4560
  throw new Error("Path is protected by the resource policy");
4172
- const relative = import_node_path17.default.relative(root, candidate);
4173
- if (relative === ".." || relative.startsWith(`..${import_node_path17.default.sep}`) || import_node_path17.default.isAbsolute(relative))
4561
+ const relative = import_node_path18.default.relative(root, candidate);
4562
+ if (relative === ".." || relative.startsWith(`..${import_node_path18.default.sep}`) || import_node_path18.default.isAbsolute(relative))
4174
4563
  throw new Error("Path outside delegated workspace");
4175
4564
  let part = root;
4176
- for (const segment of relative.split(import_node_path17.default.sep).filter(Boolean)) {
4177
- part = import_node_path17.default.join(part, segment);
4565
+ for (const segment of relative.split(import_node_path18.default.sep).filter(Boolean)) {
4566
+ part = import_node_path18.default.join(part, segment);
4178
4567
  try {
4179
- if ((await import_node_fs16.promises.lstat(part)).isSymbolicLink())
4568
+ if ((await import_node_fs17.promises.lstat(part)).isSymbolicLink())
4180
4569
  throw new Error(
4181
4570
  "Symbolic links are not available to delegated tools"
4182
4571
  );
@@ -4214,10 +4603,10 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
4214
4603
  const file = await resolve(name, expected === "missing");
4215
4604
  const repositoryReadOnly = gitMetadataPaths(
4216
4605
  root,
4217
- import_node_path17.default.dirname(file)
4606
+ import_node_path18.default.dirname(file)
4218
4607
  ).readOnlyPaths;
4219
4608
  const projectConfig = workspaceConfigProtection(root);
4220
- if (isWorkspaceConfigName(root, file) || [
4609
+ if (homeDotDirectory2 && isHomeWriteReserved(homeDotDirectory2, file) || isWorkspaceConfigName(root, file) || [
4221
4610
  ...readOnlyPaths,
4222
4611
  ...repositoryReadOnly,
4223
4612
  ...projectConfig.readOnlyPaths
@@ -4232,17 +4621,17 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
4232
4621
  await approval.bound.writeSelectedFile(name, value);
4233
4622
  return hashUtf8Content(value);
4234
4623
  }
4235
- if (approval && (!selection?.identity || selection.target !== await import_node_fs16.promises.realpath(file)))
4624
+ if (approval && (!selection?.identity || selection.target !== await import_node_fs17.promises.realpath(file)))
4236
4625
  throw new Error("File selection changed after approval");
4237
4626
  if (approval && expected === "missing")
4238
4627
  throw new Error("File already exists");
4239
4628
  if (expected === "missing") {
4240
- await import_node_fs16.promises.mkdir(import_node_path17.default.dirname(file), { recursive: true });
4629
+ await import_node_fs17.promises.mkdir(import_node_path18.default.dirname(file), { recursive: true });
4241
4630
  await resolve(name, true);
4242
4631
  }
4243
- const handle = await import_node_fs16.promises.open(
4632
+ const handle = await import_node_fs17.promises.open(
4244
4633
  file,
4245
- expected === "missing" ? "wx" : import_node_fs16.constants.O_RDWR | (import_node_fs16.constants.O_NOFOLLOW ?? 0)
4634
+ expected === "missing" ? "wx" : import_node_fs17.constants.O_RDWR | (import_node_fs17.constants.O_NOFOLLOW ?? 0)
4246
4635
  );
4247
4636
  try {
4248
4637
  const stat = await handle.stat({ bigint: true });
@@ -4318,7 +4707,7 @@ var clipJsonString = (text, limit) => {
4318
4707
  var createSubagentReadTools = (root, protectedPaths, options = {}) => {
4319
4708
  const permits = options.permits ?? (() => true);
4320
4709
  const resolveWorkspace = async () => {
4321
- const sandbox = await SandboxContext.create(await import_node_fs17.promises.realpath(root), {
4710
+ const sandbox = await SandboxContext.create(await import_node_fs18.promises.realpath(root), {
4322
4711
  protectResources: true,
4323
4712
  extraProtectedPaths: protectedPaths
4324
4713
  });
@@ -4346,17 +4735,17 @@ var createSubagentReadTools = (root, protectedPaths, options = {}) => {
4346
4735
  signal?.throwIfAborted();
4347
4736
  const dir = pending.shift();
4348
4737
  if (!dir) break;
4349
- const entries = await import_node_fs17.promises.opendir(await resolve(import_node_path18.default.relative(root2, dir)));
4738
+ const entries = await import_node_fs18.promises.opendir(await resolve(import_node_path19.default.relative(root2, dir)));
4350
4739
  for await (const entry of entries) {
4351
4740
  if (entry.isSymbolicLink() || entry.name === ".git" || entry.name === "node_modules")
4352
4741
  continue;
4353
- const child = import_node_path18.default.join(dir, entry.name);
4742
+ const child = import_node_path19.default.join(dir, entry.name);
4354
4743
  if (blocked(child)) continue;
4355
4744
  if (entry.isDirectory()) {
4356
4745
  if (pending.length >= 2e3) return { paths, truncated: true };
4357
4746
  pending.push(child);
4358
4747
  } else if (entry.isFile()) {
4359
- const name = import_node_path18.default.relative(root2, child);
4748
+ const name = import_node_path19.default.relative(root2, child);
4360
4749
  const selected = await selectRead(name, sandbox).catch(
4361
4750
  () => void 0
4362
4751
  );
@@ -4587,13 +4976,13 @@ var createSubagentWriteTools = (root, channel, protection, protectedPaths) => {
4587
4976
 
4588
4977
  // src/subagents/child-runtime.ts
4589
4978
  var createChildRun = async (input, llm, options = {}) => {
4590
- const workspace = await import_node_fs18.promises.realpath(input.workspace_root);
4979
+ const workspace = await import_node_fs19.promises.realpath(input.workspace_root);
4591
4980
  const session_id = (0, import_node_crypto7.randomUUID)();
4592
4981
  const run_id = (0, import_node_crypto7.randomUUID)();
4593
- const sessions = options.sessions ?? new import_storage9.SessionStateStoreImpl();
4594
- const cache = options.cache ?? new import_storage9.ToolOutputCacheStoreImpl();
4595
- const eventStore = options.append ? void 0 : new import_storage9.RunEventStoreFactoryImpl(
4596
- sessions instanceof import_storage9.SessionStateStoreImpl ? { runIndex: sessions } : {}
4982
+ const sessions = options.sessions ?? new import_storage10.SessionStateStoreImpl();
4983
+ const cache = options.cache ?? new import_storage10.ToolOutputCacheStoreImpl();
4984
+ const eventStore = options.append ? void 0 : new import_storage10.RunEventStoreFactoryImpl(
4985
+ sessions instanceof import_storage10.SessionStateStoreImpl ? { runIndex: sessions } : {}
4597
4986
  ).create({
4598
4987
  runId: run_id,
4599
4988
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -4811,7 +5200,7 @@ var createChildRun = async (input, llm, options = {}) => {
4811
5200
  };
4812
5201
 
4813
5202
  // src/subagents/child-entry.ts
4814
- var bootstrap = (0, import_node_fs19.createReadStream)("", { fd: 3, autoClose: false });
5203
+ var bootstrap = (0, import_node_fs20.createReadStream)("", { fd: 3, autoClose: false });
4815
5204
  bootstrap.setEncoding("utf8");
4816
5205
  var controller = new AbortController();
4817
5206
  var exitTimer;