@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.
@@ -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");
@@ -47,6 +47,7 @@ var resolveConfigPath = () => {
47
47
  return storage.resolvePaths().configFile;
48
48
  };
49
49
  var resolveProjectConfigPath = (workingDir) => import_node_path.default.resolve(workingDir, ".codelia", "config.json");
50
+ var normalizeModelLevel = (value) => value.trim().toLowerCase();
50
51
  var resolveReasoningEffort = (value) => {
51
52
  return resolveModelLevelOption(value, "model.reasoning", {
52
53
  allowXhigh: true
@@ -59,7 +60,7 @@ var resolveTextVerbosity = (value) => {
59
60
  };
60
61
  function resolveModelLevelOption(value, fieldName, options) {
61
62
  if (!value) return void 0;
62
- const normalized = value.trim().toLowerCase();
63
+ const normalized = normalizeModelLevel(value);
63
64
  if (normalized === "low" || normalized === "medium" || normalized === "high") {
64
65
  return normalized;
65
66
  }
@@ -71,15 +72,16 @@ function resolveModelLevelOption(value, fieldName, options) {
71
72
  }
72
73
 
73
74
  // src/rpc/ui-requests.ts
74
- var import_protocol = require("@codelia/protocol");
75
-
76
- // src/rpc/transport.ts
77
- var import_node_async_hooks = require("async_hooks");
75
+ var import_protocol3 = require("@codelia/protocol");
78
76
 
79
77
  // src/logger.ts
80
78
  var import_logger = require("@codelia/logger");
81
79
 
80
+ // src/rpc/protocol.ts
81
+ var import_protocol2 = require("@codelia/protocol");
82
+
82
83
  // src/rpc/transport.ts
84
+ var import_node_async_hooks = require("async_hooks");
83
85
  var responseContext = new import_node_async_hooks.AsyncLocalStorage();
84
86
  var describeRpcMessage = (msg) => {
85
87
  if ("method" in msg && typeof msg.method === "string") {
@@ -110,16 +112,47 @@ var send = (msg) => {
110
112
  }
111
113
  };
112
114
 
115
+ // src/rpc/protocol.ts
116
+ var MAX_ISSUES = 10;
117
+ var describeIssues = (error) => error.issues.slice(0, MAX_ISSUES).map((issue) => ({
118
+ path: issue.path.map(String).join("."),
119
+ code: issue.code,
120
+ message: issue.message
121
+ }));
122
+ var schemaFor = (method, slot) => {
123
+ const spec = import_protocol2.protocolMethods[method];
124
+ if (slot === "params") return spec.params;
125
+ if (!("result" in spec))
126
+ throw new Error(`${method} is a notification without a result`);
127
+ return spec.result;
128
+ };
129
+ var assertOutgoing = (method, slot, value) => {
130
+ if (process.env.CODELIA_PROTOCOL_ASSERT !== "1") return;
131
+ const result = schemaFor(method, slot).safeParse(value);
132
+ if (!result.success)
133
+ throw new Error(
134
+ `protocol assertion failed for ${method} ${slot}: ${JSON.stringify(describeIssues(result.error))}`
135
+ );
136
+ };
137
+ var notificationMessage = (method, params) => {
138
+ assertOutgoing(method, "params", params);
139
+ return { jsonrpc: "2.0", method, params };
140
+ };
141
+ var requestMessage = (method, id, params) => {
142
+ assertOutgoing(method, "params", params);
143
+ return { jsonrpc: "2.0", id, method, params };
144
+ };
145
+ var parseUiResult = (method, raw) => {
146
+ const result = schemaFor(method, "result").safeParse(raw);
147
+ if (result.success) return { ok: true, result: result.data };
148
+ return { ok: false, issues: describeIssues(result.error) };
149
+ };
150
+
113
151
  // src/rpc/ui-requests.ts
114
152
  var requestUi = async (state, method, params, signal) => {
115
153
  if (signal?.aborted) return null;
116
154
  const id = state.nextUiRequestId();
117
- const request = {
118
- jsonrpc: "2.0",
119
- id,
120
- method,
121
- params
122
- };
155
+ const request = requestMessage(method, id, params);
123
156
  const response = state.waitForUiResponse(id);
124
157
  let sent = false;
125
158
  const abort = () => {
@@ -127,13 +160,12 @@ var requestUi = async (state, method, params, signal) => {
127
160
  jsonrpc: "2.0",
128
161
  id,
129
162
  error: {
130
- code: import_protocol.RPC_ERROR_CODE.RUNTIME_INTERNAL,
163
+ code: import_protocol3.RPC_ERROR_CODE.RUNTIME_INTERNAL,
131
164
  message: "UI request cancelled"
132
165
  }
133
166
  });
134
- if (cancelled && sent && method === "ui.pick.request") {
135
- send({ jsonrpc: "2.0", method: "ui.pick.cancelled", params: { id } });
136
- }
167
+ if (!cancelled || !sent || method !== "ui.pick.request") return;
168
+ send(notificationMessage("ui.pick.cancelled", { id }));
137
169
  };
138
170
  signal?.addEventListener("abort", abort, { once: true });
139
171
  try {
@@ -142,7 +174,12 @@ var requestUi = async (state, method, params, signal) => {
142
174
  send(request);
143
175
  sent = true;
144
176
  }
145
- return await response;
177
+ const parsed = parseUiResult(method, await response);
178
+ if (parsed.ok) return parsed.result;
179
+ (0, import_logger.log)(
180
+ `protocol mismatch: ${method} result: ${JSON.stringify(parsed.issues)}`
181
+ );
182
+ return null;
146
183
  } catch {
147
184
  return null;
148
185
  } finally {
@@ -374,6 +411,7 @@ var startOAuthCallbackServer = (options) => {
374
411
  // src/auth/openai-oauth.ts
375
412
  var import_node_child_process = require("child_process");
376
413
  var import_core2 = require("@codelia/core");
414
+ var import_storage2 = require("@codelia/storage");
377
415
  var DEFAULT_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
378
416
  var ISSUER = "https://auth.openai.com";
379
417
  var DEFAULT_PORT = 1455;
@@ -400,6 +438,32 @@ var buildAuthorizeUrl = (redirectUri, pkce, state) => {
400
438
  });
401
439
  return `${ISSUER}/oauth/authorize?${params.toString()}`;
402
440
  };
441
+ var withSignalAbort = (promise, signal) => {
442
+ if (!signal) return promise;
443
+ if (signal.aborted) {
444
+ return Promise.reject(
445
+ signal.reason instanceof Error ? signal.reason : new Error("Request aborted")
446
+ );
447
+ }
448
+ return new Promise((resolve, reject) => {
449
+ const onAbort = () => {
450
+ reject(
451
+ signal.reason instanceof Error ? signal.reason : new Error("Request aborted")
452
+ );
453
+ };
454
+ signal.addEventListener("abort", onAbort, { once: true });
455
+ promise.then(
456
+ (value) => {
457
+ signal.removeEventListener("abort", onAbort);
458
+ resolve(value);
459
+ },
460
+ (error) => {
461
+ signal.removeEventListener("abort", onAbort);
462
+ reject(error);
463
+ }
464
+ );
465
+ });
466
+ };
403
467
  var requestToken = async (params, operation, signal) => {
404
468
  const response = await fetch(`${ISSUER}/oauth/token`, {
405
469
  method: "POST",
@@ -409,9 +473,9 @@ var requestToken = async (params, operation, signal) => {
409
473
  body: new URLSearchParams(params).toString()
410
474
  });
411
475
  if (!response.ok) {
412
- throw await tokenFailure(response, operation);
476
+ throw await withSignalAbort(tokenFailure(response, operation), signal);
413
477
  }
414
- return response.json();
478
+ return withSignalAbort(response.json(), signal);
415
479
  };
416
480
  var oauthReasons = {
417
481
  refresh_token_reused: "The refresh token has already been used.",
@@ -448,16 +512,40 @@ var exchangeCodeForTokens = async (code, redirectUri, pkce) => {
448
512
  "exchange"
449
513
  );
450
514
  };
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
- );
515
+ var refreshAccessToken = async (refreshToken, signal, options) => {
516
+ const timeoutMs = options?.timeoutMs ?? import_storage2.DEFAULT_OAUTH_REFRESH_TIMEOUT_MS;
517
+ const timeoutController = new AbortController();
518
+ let timedOut = false;
519
+ const timer = setTimeout(() => {
520
+ timedOut = true;
521
+ timeoutController.abort(new Error("OAuth token refresh timed out"));
522
+ }, timeoutMs);
523
+ const effectiveSignal = signal ? AbortSignal.any([signal, timeoutController.signal]) : timeoutController.signal;
524
+ try {
525
+ return await requestToken(
526
+ {
527
+ grant_type: "refresh_token",
528
+ refresh_token: refreshToken,
529
+ client_id: clientId()
530
+ },
531
+ "refresh",
532
+ effectiveSignal
533
+ );
534
+ } catch (error) {
535
+ if (timedOut) {
536
+ throw new import_core2.ProviderFailureError({
537
+ provider: "openai",
538
+ kind: "provider",
539
+ code: "oauth_refresh_timeout",
540
+ safeMessage: "OpenAI OAuth token refresh timed out.",
541
+ detail: "The OAuth token endpoint did not respond before the timeout.",
542
+ retryable: true
543
+ });
544
+ }
545
+ throw error;
546
+ } finally {
547
+ clearTimeout(timer);
548
+ }
461
549
  };
462
550
  var parseJwt = (token) => {
463
551
  const parts = token.split(".");
@@ -739,93 +827,312 @@ var isOfficialApiKeyBase = (provider, base) => Object.hasOwn(bases, provider) &&
739
827
 
740
828
  // src/auth/store.ts
741
829
  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;
830
+ var import_storage3 = require("@codelia/storage");
831
+ var normalizeAuthFileToV2 = (auth) => (0, import_storage3.parseAuthDocument)(JSON.stringify(auth)).normalized;
832
+ var getChatProviderAuth = (auth, provider) => {
833
+ if (!Object.hasOwn(auth.providers, provider)) return void 0;
834
+ const entry = auth.providers[provider];
835
+ if (entry.chat_method === "oauth" && entry.credentials.oauth) {
836
+ return { method: "oauth", oauth: entry.credentials.oauth };
837
+ }
838
+ if (entry.chat_method === "api_key" && entry.credentials.api_key) {
839
+ return { method: "api_key", ...entry.credentials.api_key };
840
+ }
841
+ return void 0;
842
+ };
843
+ var setProviderChatAuth = (auth, provider, next) => {
844
+ const existing = Object.hasOwn(auth.providers, provider) ? auth.providers[provider] : void 0;
845
+ const credentials = {
846
+ ...existing?.credentials ?? {}
847
+ };
848
+ if (next.method === "api_key") {
849
+ credentials.api_key = {
850
+ api_key: next.api_key,
851
+ ...next.api_base ? { api_base: next.api_base } : {}
852
+ };
853
+ } else {
854
+ credentials.oauth = next.oauth;
855
+ }
856
+ auth.providers[provider] = {
857
+ chat_method: next.method,
858
+ credentials
859
+ };
860
+ };
861
+ var updateProviderOAuthTokens = (auth, provider, oauth2) => {
862
+ if (!Object.hasOwn(auth.providers, provider)) return false;
863
+ const entry = auth.providers[provider];
864
+ if (!entry.credentials.oauth) return false;
865
+ auth.providers[provider] = {
866
+ ...entry.chat_method ? { chat_method: entry.chat_method } : {},
867
+ credentials: {
868
+ ...entry.credentials,
869
+ oauth: oauth2
870
+ }
871
+ };
872
+ return true;
873
+ };
874
+ var clearProviderEntry = (auth, provider) => {
875
+ delete auth.providers[provider];
876
+ };
877
+ var projectAuthV2ToV1View = (auth) => {
878
+ const providers = {};
879
+ for (const name of Object.keys(auth.providers)) {
880
+ const chatAuth = getChatProviderAuth(auth, name);
881
+ if (chatAuth) {
882
+ providers[name] = chatAuth;
883
+ }
884
+ }
885
+ return { version: import_storage3.AUTH_VERSION_V1, providers };
886
+ };
887
+ var readTextIfPresent = async (filePath) => {
888
+ if (!await (0, import_storage3.verifyWindowsCredentialFileAcl)(filePath)) return null;
889
+ try {
890
+ return await import_node_fs2.promises.readFile(filePath, "utf8");
891
+ } catch (error) {
892
+ if (error?.code === "ENOENT") return null;
893
+ throw error;
894
+ }
755
895
  };
896
+ var readAuthFileSyncStrict = (filePath, legacy = false) => {
897
+ if (!(0, import_storage3.verifyWindowsCredentialFileAclSync)(filePath, legacy)) return null;
898
+ let fd;
899
+ try {
900
+ fd = (0, import_node_fs2.openSync)(
901
+ filePath,
902
+ import_node_fs2.constants.O_RDONLY | import_node_fs2.constants.O_NONBLOCK | (import_node_fs2.constants.O_NOFOLLOW ?? 0)
903
+ );
904
+ } catch (error) {
905
+ if (error?.code === "ENOENT") return null;
906
+ throw error;
907
+ }
908
+ try {
909
+ const stat = (0, import_node_fs2.fstatSync)(fd);
910
+ if (!stat.isFile() || stat.size > 1024 * 1024) {
911
+ throw new Error("auth.json cannot be read at approval time");
912
+ }
913
+ return (0, import_storage3.parseAuthDocument)((0, import_node_fs2.readFileSync)(fd, "utf8")).normalized;
914
+ } finally {
915
+ (0, import_node_fs2.closeSync)(fd);
916
+ }
917
+ };
918
+ var isAuthNonEmpty = (doc) => doc !== null && Object.keys(doc.providers).length > 0;
756
919
  var AuthStore = class {
757
920
  paths;
758
- constructor(paths) {
759
- this.paths = paths ?? (0, import_storage2.resolveStoragePaths)();
921
+ lockOptions;
922
+ storageMode;
923
+ keychain;
924
+ constructor(paths, options) {
925
+ this.paths = paths ?? (0, import_storage3.resolveStoragePaths)();
926
+ this.lockOptions = options?.lock;
927
+ this.storageMode = options?.storageMode;
928
+ this.keychain = options?.keychain ?? new import_storage3.MacOsKeychainClient({
929
+ credentialsDir: this.paths.credentialsDir
930
+ });
760
931
  }
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
- }
932
+ lockPath() {
933
+ return (0, import_storage3.authLockPathFor)(this.paths.credentialsDir);
767
934
  }
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
935
+ keychainAccount() {
936
+ return (0, import_storage3.keychainAccountForConfigDir)(this.paths.configDir);
937
+ }
938
+ resolveBackendUnlocked() {
939
+ return (0, import_storage3.coordinateCredentialBackendUnlocked)({
940
+ paths: this.paths,
941
+ storageMode: this.storageMode,
942
+ keychain: this.keychain,
943
+ authAdapter: import_storage3.providerAuthStoreAdapter,
944
+ mcpAdapter: import_storage3.mcpAuthStoreAdapter
945
+ });
946
+ }
947
+ async readFromBackend(active) {
948
+ if (active === "keyring") {
949
+ const text2 = await this.keychain.get(
950
+ import_storage3.CODELIA_AUTH_KEYCHAIN_SERVICE,
951
+ this.keychainAccount()
775
952
  );
776
- } catch (error) {
777
- return absentAuthFile(error);
953
+ if (text2 === null) {
954
+ return { version: import_storage3.AUTH_VERSION_V2, providers: {} };
955
+ }
956
+ const parsed2 = (0, import_storage3.parseAuthDocument)(text2);
957
+ if (parsed2.sourceVersion === 1) {
958
+ await this.writeToBackend("keyring", parsed2.normalized);
959
+ }
960
+ return parsed2.normalized;
778
961
  }
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);
962
+ const text = await readTextIfPresent(this.paths.authFile);
963
+ if (text === null) {
964
+ return { version: import_storage3.AUTH_VERSION_V2, providers: {} };
786
965
  }
966
+ const parsed = (0, import_storage3.parseAuthDocument)(text);
967
+ if (parsed.sourceVersion === 1) {
968
+ await this.writeToBackend("file", parsed.normalized);
969
+ }
970
+ return parsed.normalized;
971
+ }
972
+ async writeToBackend(active, auth) {
973
+ if (active === "keyring") {
974
+ await this.keychain.set(
975
+ import_storage3.CODELIA_AUTH_KEYCHAIN_SERVICE,
976
+ this.keychainAccount(),
977
+ JSON.stringify(auth)
978
+ );
979
+ return;
980
+ }
981
+ await (0, import_storage3.ensureStorageDirs)(this.paths);
982
+ const data = JSON.stringify(auth, null, 2);
983
+ await (0, import_storage3.writeFileAtomic)(this.paths.authFile, data, { mode: 384 });
787
984
  }
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
985
+ /**
986
+ * Load normalized v2 credentials from the active backend (macOS Keychain or
987
+ * protected `credentials/` file), running two-phase migration if needed.
988
+ */
989
+ async loadV2() {
990
+ return (0, import_storage3.withAuthStoreLock)(
991
+ this.lockPath(),
992
+ async () => {
993
+ const resolved = await this.resolveBackendUnlocked();
994
+ return this.readFromBackend(resolved.active);
995
+ },
996
+ this.lockOptions
795
997
  );
796
- authWriteQueues.set(key, settled);
797
- try {
798
- return await next;
799
- } finally {
800
- if (authWriteQueues.get(key) === settled) authWriteQueues.delete(key);
998
+ }
999
+ /**
1000
+ * Synchronous v2 snapshot for a one-use local approval consumed immediately
1001
+ * before spawn. Fails closed (throws) on corrupt `storage-state.json`,
1002
+ * in-progress migrations or pending cleanup, dual-store conflicts, or
1003
+ * locked/unavailable/timed-out Keychain access.
1004
+ */
1005
+ loadForApprovalV2() {
1006
+ const configured = (0, import_storage3.resolveConfiguredAuthStorageMode)(
1007
+ this.paths,
1008
+ this.storageMode
1009
+ );
1010
+ const state = (0, import_storage3.readAuthStorageStateSync)(this.paths.authStateFile);
1011
+ if (state?.status === "migrating") {
1012
+ throw new Error(
1013
+ "Credential storage migration is in progress; approval-time auth is unavailable"
1014
+ );
1015
+ }
1016
+ if (configured === "file" && state?.active_backend === "keyring") {
1017
+ throw new Error(
1018
+ "Credential reverse migration to file is pending; approval-time auth is unavailable"
1019
+ );
1020
+ }
1021
+ const useKeychain = configured === "keyring" || configured === "auto" && state?.active_backend === "keyring";
1022
+ const currentFile = readAuthFileSyncStrict(this.paths.authFile);
1023
+ const legacyFile = readAuthFileSyncStrict(this.paths.legacyAuthFile, true);
1024
+ if (isAuthNonEmpty(currentFile) && isAuthNonEmpty(legacyFile) && !(0, import_storage3.canonicalJsonEqual)(currentFile, legacyFile)) {
1025
+ throw new import_storage3.CredentialConflictError("auth");
801
1026
  }
1027
+ if (useKeychain) {
1028
+ const text = this.keychain.getSync(
1029
+ import_storage3.CODELIA_AUTH_KEYCHAIN_SERVICE,
1030
+ this.keychainAccount(),
1031
+ 2e3
1032
+ );
1033
+ const keychainDoc = text === null ? { version: import_storage3.AUTH_VERSION_V2, providers: {} } : (0, import_storage3.parseAuthDocument)(text).normalized;
1034
+ for (const fileCandidate of [currentFile, legacyFile]) {
1035
+ if (isAuthNonEmpty(fileCandidate) && isAuthNonEmpty(keychainDoc) && !(0, import_storage3.canonicalJsonEqual)(keychainDoc, fileCandidate)) {
1036
+ throw new import_storage3.CredentialConflictError("auth");
1037
+ }
1038
+ }
1039
+ return keychainDoc;
1040
+ }
1041
+ if (isAuthNonEmpty(currentFile)) return currentFile;
1042
+ if (isAuthNonEmpty(legacyFile)) return legacyFile;
1043
+ return currentFile ?? legacyFile ?? { version: import_storage3.AUTH_VERSION_V2, providers: {} };
1044
+ }
1045
+ /** Legacy v1-projected read view over the underlying v2 store. */
1046
+ async load() {
1047
+ return projectAuthV2ToV1View(await this.loadV2());
1048
+ }
1049
+ /** Synchronous legacy v1-projected snapshot for approval checks. */
1050
+ loadForApproval() {
1051
+ return projectAuthV2ToV1View(this.loadForApprovalV2());
802
1052
  }
803
1053
  /**
804
- * Reload, mutate and save under a per-file queue. Use this for every
805
- * credential change made outside the cached-resolver flow.
1054
+ * Reload v2, mutate, and atomically save under the interprocess SQLite lock.
1055
+ * Skips writing if the serialized v2 document did not change.
1056
+ */
1057
+ updateV2(mutate) {
1058
+ return (0, import_storage3.withAuthStoreLock)(
1059
+ this.lockPath(),
1060
+ async () => {
1061
+ const resolved = await this.resolveBackendUnlocked();
1062
+ const auth = await this.readFromBackend(resolved.active);
1063
+ const before = JSON.stringify(auth);
1064
+ const result = await mutate(auth);
1065
+ if (JSON.stringify(auth) !== before) {
1066
+ await this.writeToBackend(resolved.active, auth);
1067
+ }
1068
+ return result;
1069
+ },
1070
+ this.lockOptions
1071
+ );
1072
+ }
1073
+ /**
1074
+ * Legacy v1-projected update helper. Applies v1 mutations onto the underlying
1075
+ * v2 document while preserving coexisting credentials on untouched slots.
806
1076
  */
807
1077
  update(mutate) {
808
- return this.enqueue(async () => {
809
- const auth = await this.load();
810
- const result = await mutate(auth);
811
- await this.save(auth);
1078
+ return this.updateV2(async (v2) => {
1079
+ const beforeView = projectAuthV2ToV1View(v2);
1080
+ const workingView = {
1081
+ version: import_storage3.AUTH_VERSION_V1,
1082
+ providers: { ...beforeView.providers }
1083
+ };
1084
+ const result = await mutate(workingView);
1085
+ const touched = /* @__PURE__ */ new Set([
1086
+ ...Object.keys(beforeView.providers),
1087
+ ...Object.keys(workingView.providers)
1088
+ ]);
1089
+ for (const name of touched) {
1090
+ const had = Object.hasOwn(beforeView.providers, name);
1091
+ const has = Object.hasOwn(workingView.providers, name);
1092
+ if (!has && had) {
1093
+ clearProviderEntry(v2, name);
1094
+ } else if (has) {
1095
+ const next = workingView.providers[name];
1096
+ if (!had || !(0, import_storage3.canonicalJsonEqual)(beforeView.providers[name], next)) {
1097
+ setProviderChatAuth(v2, name, next);
1098
+ }
1099
+ }
1100
+ }
812
1101
  return result;
813
1102
  });
814
1103
  }
815
- /** Queued removal of every provider; works even if the file is unreadable. */
1104
+ /**
1105
+ * Locked removal of every provider across all credential locations
1106
+ * (`credentials/auth.json`, legacy `auth.json`, and Keychain if active/reachable).
1107
+ * Succeeds even when an `auth` storage conflict or corrupt file exists so
1108
+ * full logout always gives users a clean recovery path (never touches `mcp-auth`).
1109
+ */
816
1110
  clearAll() {
817
- return this.enqueue(
818
- () => this.save({ version: AUTH_VERSION, providers: {} })
1111
+ return (0, import_storage3.withAuthStoreLock)(
1112
+ this.lockPath(),
1113
+ async () => {
1114
+ await (0, import_storage3.clearStoreAcrossAllLocationsUnlocked)({
1115
+ paths: this.paths,
1116
+ adapter: import_storage3.providerAuthStoreAdapter,
1117
+ keychain: this.keychain
1118
+ });
1119
+ },
1120
+ this.lockOptions
1121
+ );
1122
+ }
1123
+ async saveV2(auth) {
1124
+ await (0, import_storage3.withAuthStoreLock)(
1125
+ this.lockPath(),
1126
+ async () => {
1127
+ const resolved = await this.resolveBackendUnlocked();
1128
+ await this.writeToBackend(resolved.active, auth);
1129
+ },
1130
+ this.lockOptions
819
1131
  );
820
1132
  }
821
1133
  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
- }
1134
+ const normalized = normalizeAuthFileToV2(auth);
1135
+ await this.saveV2(normalized);
829
1136
  }
830
1137
  };
831
1138
 
@@ -881,12 +1188,12 @@ var AuthResolver = class _AuthResolver {
881
1188
  }
882
1189
  static async create(state, log2, providers = {}) {
883
1190
  const store = new AuthStore();
884
- const auth = await store.load();
1191
+ const auth = await store.loadV2();
885
1192
  return new _AuthResolver(state, log2, store, auth, providers);
886
1193
  }
887
1194
  hasAnyAvailableAuth() {
888
1195
  return this.availableProviders.some((provider) => {
889
- if (this.auth.providers[provider]) return true;
1196
+ if (getChatProviderAuth(this.auth, provider)) return true;
890
1197
  return Boolean(this.envApiKey(provider));
891
1198
  });
892
1199
  }
@@ -896,7 +1203,7 @@ var AuthResolver = class _AuthResolver {
896
1203
  throw new Error(`Unsupported model.provider: ${preferred}`);
897
1204
  if (preferredProvider) return preferredProvider;
898
1205
  const providersWithAuth = this.availableProviders.filter(
899
- (provider) => !!this.auth.providers[provider]
1206
+ (provider) => !!getChatProviderAuth(this.auth, provider)
900
1207
  );
901
1208
  if (providersWithAuth.length === 1) {
902
1209
  return providersWithAuth[0];
@@ -927,13 +1234,11 @@ var AuthResolver = class _AuthResolver {
927
1234
  async resolveProviderAuth(provider) {
928
1235
  if (!this.availableProviders.includes(provider))
929
1236
  throw new Error(`Unsupported provider: ${provider}`);
930
- const existing = this.auth.providers[provider];
1237
+ const existing = getChatProviderAuth(this.auth, provider);
931
1238
  if (existing) return existing;
932
1239
  const envValue = this.envApiKey(provider);
933
1240
  if (envValue) {
934
- const auth = configuredApiKeyAuth(provider, envValue);
935
- await this.setProviderAuth(provider, auth);
936
- return auth;
1241
+ return configuredApiKeyAuth(provider, envValue);
937
1242
  }
938
1243
  if (provider === "openai") {
939
1244
  return this.promptOpenAiAuth();
@@ -968,7 +1273,7 @@ var AuthResolver = class _AuthResolver {
968
1273
  if (options?.matches && !options.matches(oauth3))
969
1274
  throw new Error("OpenAI OAuth account changed");
970
1275
  };
971
- const entry = this.auth.providers.openai;
1276
+ const entry = getChatProviderAuth(this.auth, "openai");
972
1277
  if (entry?.method !== "oauth") {
973
1278
  throw new Error("OpenAI OAuth is not configured");
974
1279
  }
@@ -976,15 +1281,15 @@ var AuthResolver = class _AuthResolver {
976
1281
  options?.signal?.throwIfAborted();
977
1282
  checkAccount(oauth2);
978
1283
  if (oauth2.expires_at <= Date.now() + 6e4) {
979
- oauth2 = await this.store.update(async (auth) => {
980
- const current = auth.providers.openai;
1284
+ const updated = await this.store.updateV2(async (auth) => {
1285
+ const current = getChatProviderAuth(auth, "openai");
981
1286
  if (current?.method !== "oauth") {
982
1287
  throw new Error("OpenAI OAuth is not configured");
983
1288
  }
984
1289
  options?.signal?.throwIfAborted();
985
1290
  checkAccount(current.oauth);
986
1291
  if (current.oauth.expires_at > Date.now() + 6e4) {
987
- return current.oauth;
1292
+ return { oauth: current.oauth, auth };
988
1293
  }
989
1294
  this.log("refreshing OpenAI OAuth token");
990
1295
  const tokens = await refreshAccessToken(current.oauth.refresh_token);
@@ -996,10 +1301,13 @@ var AuthResolver = class _AuthResolver {
996
1301
  ...accountId ? { account_id: accountId } : {}
997
1302
  };
998
1303
  checkAccount(refreshed);
999
- auth.providers.openai = { method: "oauth", oauth: refreshed };
1000
- return refreshed;
1304
+ if (!updateProviderOAuthTokens(auth, "openai", refreshed)) {
1305
+ throw new Error("OpenAI OAuth is not configured");
1306
+ }
1307
+ return { oauth: refreshed, auth };
1001
1308
  });
1002
- this.auth.providers.openai = { method: "oauth", oauth: oauth2 };
1309
+ oauth2 = updated.oauth;
1310
+ this.auth = updated.auth;
1003
1311
  }
1004
1312
  options?.signal?.throwIfAborted();
1005
1313
  return { token: oauth2.access_token, accountId: oauth2.account_id };
@@ -1189,8 +1497,8 @@ var AuthResolver = class _AuthResolver {
1189
1497
  return auth;
1190
1498
  }
1191
1499
  async setProviderAuth(provider, auth) {
1192
- this.auth = await this.store.update((latest) => {
1193
- latest.providers[provider] = auth;
1500
+ this.auth = await this.store.updateV2((latest) => {
1501
+ setProviderChatAuth(latest, provider, auth);
1194
1502
  return latest;
1195
1503
  });
1196
1504
  }
@@ -1199,7 +1507,7 @@ var AuthResolver = class _AuthResolver {
1199
1507
  // src/model-factory.ts
1200
1508
  var import_core6 = require("@codelia/core");
1201
1509
  var import_model_metadata = require("@codelia/model-metadata");
1202
- var import_storage3 = require("@codelia/storage");
1510
+ var import_storage4 = require("@codelia/storage");
1203
1511
 
1204
1512
  // src/model-fast.ts
1205
1513
  var import_core3 = require("@codelia/core");
@@ -1858,7 +2166,7 @@ var resolveAnthropicModelMaxTokens = async (model, options) => {
1858
2166
  return resolveAnthropicStaticModelMaxTokens(model);
1859
2167
  }
1860
2168
  const metadataService = new import_model_metadata.ModelMetadataServiceImpl({
1861
- storagePathService: new import_storage3.StoragePathServiceImpl()
2169
+ storagePathService: new import_storage4.StoragePathServiceImpl()
1862
2170
  });
1863
2171
  const direct = await metadataService.getModelEntry("anthropic", model);
1864
2172
  const prefixed = model.startsWith("anthropic/") ? null : await metadataService.getModelEntry("anthropic", `anthropic/${model}`);
@@ -2316,7 +2624,7 @@ var resolveRuntimeEnvironment = (options = {}) => {
2316
2624
  // src/sandbox/mode.ts
2317
2625
  var import_node_fs3 = require("fs");
2318
2626
  var import_shared_types4 = require("@codelia/shared-types");
2319
- var import_storage4 = require("@codelia/storage");
2627
+ var import_storage5 = require("@codelia/storage");
2320
2628
  var defaultSandboxMode = Object.freeze({
2321
2629
  value: "workspace-write",
2322
2630
  source: "fallback"
@@ -2428,6 +2736,7 @@ var RuntimeState = class {
2428
2736
  authority
2429
2737
  ]);
2430
2738
  }
2739
+ acceptedSteerIds = /* @__PURE__ */ new Map();
2431
2740
  pendingSteersByRun = /* @__PURE__ */ new Map();
2432
2741
  steerClosedRuns = /* @__PURE__ */ new Set();
2433
2742
  uiRequestCounter = 0;
@@ -2562,6 +2871,7 @@ var RuntimeState = class {
2562
2871
  this.lastContextLeftPercent = null;
2563
2872
  this.runSeq.delete(runId);
2564
2873
  this.pendingSteersByRun.delete(runId);
2874
+ this.acceptedSteerIds.delete(runId);
2565
2875
  this.steerClosedRuns.delete(runId);
2566
2876
  if (this.activeRunId === null) {
2567
2877
  this.sessionAppend = null;
@@ -2574,10 +2884,18 @@ var RuntimeState = class {
2574
2884
  canSteerRun(runId) {
2575
2885
  return this.activeRunId === runId && !this.cancelRequested && !this.steerClosedRuns.has(runId);
2576
2886
  }
2887
+ acceptedRunSteerId(runId, clientSteerId) {
2888
+ return this.acceptedSteerIds.get(runId)?.get(clientSteerId);
2889
+ }
2577
2890
  enqueueRunSteer(runId, content, clientSteerId, approvalUserText) {
2578
2891
  this.signalApprovalChange();
2579
2892
  this.runSteerCounter += 1;
2580
2893
  const steerId = `s${this.runSteerCounter}`;
2894
+ if (clientSteerId !== void 0) {
2895
+ const accepted = this.acceptedSteerIds.get(runId) ?? /* @__PURE__ */ new Map();
2896
+ accepted.set(clientSteerId, steerId);
2897
+ this.acceptedSteerIds.set(runId, accepted);
2898
+ }
2581
2899
  if (this.approvalIntent?.runId === runId) {
2582
2900
  this.approvalIntent.steers.push({
2583
2901
  id: steerId,
@@ -2588,7 +2906,7 @@ var RuntimeState = class {
2588
2906
  const queue = this.pendingSteersByRun.get(runId) ?? [];
2589
2907
  queue.push({
2590
2908
  steer_id: steerId,
2591
- ...clientSteerId ? { client_steer_id: clientSteerId } : {},
2909
+ ...clientSteerId !== void 0 ? { client_steer_id: clientSteerId } : {},
2592
2910
  content
2593
2911
  });
2594
2912
  this.pendingSteersByRun.set(runId, queue);
@@ -2902,9 +3220,9 @@ var createChildChannel = (send3) => {
2902
3220
 
2903
3221
  // src/subagents/child-runtime.ts
2904
3222
  var import_node_crypto7 = require("crypto");
2905
- var import_node_fs18 = require("fs");
3223
+ var import_node_fs19 = require("fs");
2906
3224
  var import_core12 = require("@codelia/core");
2907
- var import_storage9 = require("@codelia/storage");
3225
+ var import_storage10 = require("@codelia/storage");
2908
3226
 
2909
3227
  // src/permissions/utils.ts
2910
3228
  var SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
@@ -3110,10 +3428,10 @@ var import_node_crypto4 = require("crypto");
3110
3428
 
3111
3429
  // src/tasks/manager.ts
3112
3430
  var import_node_crypto3 = __toESM(require("crypto"), 1);
3113
- var import_storage6 = require("@codelia/storage");
3431
+ var import_storage7 = require("@codelia/storage");
3114
3432
 
3115
3433
  // src/subagents/process-identity.ts
3116
- var import_storage5 = require("@codelia/storage");
3434
+ var import_storage6 = require("@codelia/storage");
3117
3435
 
3118
3436
  // src/subagents/mailbox.ts
3119
3437
  var formatAgentMessages = (messages) => messages.map(
@@ -3207,15 +3525,15 @@ var createTaskProgressTracker = (options) => {
3207
3525
  };
3208
3526
 
3209
3527
  // src/subagents/read-tools.ts
3210
- var import_node_fs17 = require("fs");
3211
- var import_node_path18 = __toESM(require("path"), 1);
3528
+ var import_node_fs18 = require("fs");
3529
+ var import_node_path19 = __toESM(require("path"), 1);
3212
3530
  var import_core10 = require("@codelia/core");
3213
3531
  var import_zod7 = require("zod");
3214
3532
 
3215
3533
  // src/sandbox/context.ts
3216
3534
  var import_node_crypto5 = __toESM(require("crypto"), 1);
3217
- var import_node_fs15 = require("fs");
3218
- var import_node_path16 = __toESM(require("path"), 1);
3535
+ var import_node_fs16 = require("fs");
3536
+ var import_node_path17 = __toESM(require("path"), 1);
3219
3537
 
3220
3538
  // src/permissions/git-metadata.ts
3221
3539
  var import_node_fs5 = require("fs");
@@ -3400,15 +3718,155 @@ var resolveGitMetadata = (directories, includeObjectDirectories) => {
3400
3718
  var gitMetadataPaths = (...directories) => resolveGitMetadata(directories, false);
3401
3719
  var gitMetadataWithObjectDirectories = (...directories) => resolveGitMetadata(directories, true);
3402
3720
 
3403
- // src/permissions/protected-aliases.ts
3721
+ // src/permissions/home-dot-paths.ts
3722
+ var import_node_fs7 = require("fs");
3723
+ var import_node_os = __toESM(require("os"), 1);
3724
+ var import_node_path6 = __toESM(require("path"), 1);
3725
+
3726
+ // src/permissions/resource-paths.ts
3404
3727
  var import_node_fs6 = require("fs");
3405
3728
  var import_node_path5 = __toESM(require("path"), 1);
3729
+ var lookup = (pathname) => (0, import_node_fs6.lstatSync)(pathname, { bigint: true, throwIfNoEntry: false });
3730
+ var sameEntry = (left, right) => left.dev === right.dev && left.ino === right.ino;
3731
+ var comparableResourceName = (pathname) => {
3732
+ const folded = pathname.normalize("NFD").toUpperCase().toLowerCase();
3733
+ return process.platform === "win32" ? folded.replace(/[ .]+(?=[\\/]|$)/gu, "") : folded;
3734
+ };
3735
+ function distinguishesAsciiCase(parent) {
3736
+ try {
3737
+ const directory = (0, import_node_fs6.opendirSync)(parent);
3738
+ try {
3739
+ for (let index = 0; index < 16; index++) {
3740
+ const name = directory.readSync()?.name;
3741
+ if (!name) break;
3742
+ const changed = name.replace(
3743
+ /[A-Za-z]/u,
3744
+ (letter) => letter === letter.toLowerCase() ? letter.toUpperCase() : letter.toLowerCase()
3745
+ );
3746
+ if (name === changed) continue;
3747
+ const original = lookup(import_node_path5.default.join(parent, name));
3748
+ const alternate = lookup(import_node_path5.default.join(parent, changed));
3749
+ if (original) return !alternate || !sameEntry(original, alternate);
3750
+ }
3751
+ } finally {
3752
+ directory.closeSync();
3753
+ }
3754
+ } catch {
3755
+ }
3756
+ return false;
3757
+ }
3758
+ function resourceContainsPath(resource, target) {
3759
+ if (target === resource || target.startsWith(
3760
+ resource.endsWith(import_node_path5.default.sep) ? resource : `${resource}${import_node_path5.default.sep}`
3761
+ ))
3762
+ return true;
3763
+ const root = import_node_path5.default.parse(resource).root;
3764
+ const targetRoot = import_node_path5.default.parse(target).root;
3765
+ if (comparableResourceName(root) !== comparableResourceName(targetRoot))
3766
+ return false;
3767
+ const parts = resource.slice(root.length).split(import_node_path5.default.sep);
3768
+ const overlapping = target.slice(targetRoot.length).split(import_node_path5.default.sep).slice(0, parts.length);
3769
+ if (overlapping.length !== parts.length) return false;
3770
+ const candidate = import_node_path5.default.join(targetRoot, ...overlapping);
3771
+ const namesMayMatch = comparableResourceName(resource) === comparableResourceName(candidate);
3772
+ try {
3773
+ const targetEntry = lookup(candidate);
3774
+ if (!targetEntry && !namesMayMatch) return false;
3775
+ const protectedEntry = lookup(resource);
3776
+ if (protectedEntry || targetEntry)
3777
+ return !!protectedEntry && !!targetEntry && sameEntry(protectedEntry, targetEntry);
3778
+ if (!namesMayMatch) return false;
3779
+ const parent = import_node_path5.default.dirname(resource);
3780
+ 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);
3781
+ } catch {
3782
+ return namesMayMatch;
3783
+ }
3784
+ }
3785
+ var missing = (error) => error.code === "ENOENT";
3786
+ function resolveReservedTarget(target, remaining = 64) {
3787
+ if (!remaining) throw new Error("reserved_path_unresolved");
3788
+ try {
3789
+ return (0, import_node_fs6.realpathSync)(target);
3790
+ } catch (error) {
3791
+ const parent = import_node_path5.default.dirname(target);
3792
+ if (!missing(error) || parent === target) throw error;
3793
+ const canonicalParent = resolveReservedTarget(parent, remaining - 1);
3794
+ if (!(0, import_node_fs6.lstatSync)(target, { throwIfNoEntry: false })?.isSymbolicLink())
3795
+ return import_node_path5.default.join(canonicalParent, import_node_path5.default.basename(target));
3796
+ const referent = (0, import_node_fs6.readlinkSync)(target);
3797
+ let seenName = false;
3798
+ for (const part of referent.split(
3799
+ process.platform === "win32" ? /[\\/]/u : "/"
3800
+ )) {
3801
+ if (part === ".." && seenName)
3802
+ throw new Error("reserved_path_unresolved");
3803
+ if (part && part !== "." && part !== "..") seenName = true;
3804
+ }
3805
+ return resolveReservedTarget(
3806
+ import_node_path5.default.resolve(canonicalParent, referent),
3807
+ remaining - 1
3808
+ );
3809
+ }
3810
+ }
3811
+
3812
+ // src/permissions/home-dot-paths.ts
3813
+ var homeDotDirectory = (writeRoots, home = import_node_os.default.homedir()) => {
3814
+ if (!writeRoots.length) return void 0;
3815
+ const canonicalHome = resolveReservedTarget(home);
3816
+ return writeRoots.some(
3817
+ (root) => resourceContainsPath(resolveReservedTarget(root), canonicalHome)
3818
+ ) ? canonicalHome : void 0;
3819
+ };
3820
+ var isHomeDotTarget = (home, target, platform = process.platform) => {
3821
+ if (!resourceContainsPath(home, target)) return false;
3822
+ const root = import_node_path6.default.parse(home).root;
3823
+ const depth = home.slice(root.length).split(import_node_path6.default.sep).filter(Boolean).length;
3824
+ const first = target.slice(import_node_path6.default.parse(target).root.length).split(import_node_path6.default.sep).filter(Boolean)[depth];
3825
+ return !!first && (first.startsWith(".") || platform === "darwin" && resourceContainsPath(import_node_path6.default.join(home, "Library"), target));
3826
+ };
3827
+ var hasClosedHomeDotCycle = (home, start) => {
3828
+ const seen = /* @__PURE__ */ new Set();
3829
+ let current = start;
3830
+ while (seen.size < 64) {
3831
+ if (seen.has(current)) return true;
3832
+ seen.add(current);
3833
+ let link;
3834
+ try {
3835
+ link = (0, import_node_fs7.readlinkSync)(current);
3836
+ } catch {
3837
+ return false;
3838
+ }
3839
+ const next = import_node_path6.default.resolve(home, link);
3840
+ const name = import_node_path6.default.basename(next);
3841
+ if (import_node_path6.default.dirname(next) !== home || !isHomeDotTarget(home, next) || link !== next && link !== name && link !== `.${import_node_path6.default.sep}${name}`)
3842
+ return false;
3843
+ current = next;
3844
+ }
3845
+ return false;
3846
+ };
3847
+ var homeDotLinkTargets = (home) => (0, import_node_fs7.readdirSync)(home, { withFileTypes: true }).filter(
3848
+ (entry) => entry.isSymbolicLink() && isHomeDotTarget(home, import_node_path6.default.join(home, entry.name))
3849
+ ).flatMap((entry) => {
3850
+ const link = import_node_path6.default.join(home, entry.name);
3851
+ try {
3852
+ return [resolveReservedTarget(link)];
3853
+ } catch (error) {
3854
+ if (error.code === "ELOOP" && hasClosedHomeDotCycle(home, link))
3855
+ return [];
3856
+ throw error;
3857
+ }
3858
+ });
3859
+ var isHomeWriteReserved = (home, target) => isHomeDotTarget(home, target) || homeDotLinkTargets(home).some((link) => resourceContainsPath(link, target));
3860
+
3861
+ // src/permissions/protected-aliases.ts
3862
+ var import_node_fs8 = require("fs");
3863
+ var import_node_path7 = __toESM(require("path"), 1);
3406
3864
  var maxEntries = 4096;
3407
3865
  var inode = (stat) => `${stat.dev}:${stat.ino}`;
3408
3866
  function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifiedHooks = []) {
3409
3867
  const pending = roots.map((entry) => {
3410
3868
  try {
3411
- return (0, import_node_fs6.realpathSync)(entry);
3869
+ return (0, import_node_fs8.realpathSync)(entry);
3412
3870
  } catch (error) {
3413
3871
  if (error.code === "ENOENT") return entry;
3414
3872
  throw error;
@@ -3424,7 +3882,7 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
3424
3882
  const target = hooks.get(file);
3425
3883
  if (!target) return false;
3426
3884
  try {
3427
- return (0, import_node_fs6.realpathSync)(file) === target && (0, import_node_fs6.lstatSync)(target).isFile();
3885
+ return (0, import_node_fs8.realpathSync)(file) === target && (0, import_node_fs8.lstatSync)(target).isFile();
3428
3886
  } catch {
3429
3887
  return false;
3430
3888
  }
@@ -3436,18 +3894,18 @@ function* linkedInodes(roots, entryLimit, ignoredObjectDirectories = [], verifie
3436
3894
  if (visited.size > entryLimit)
3437
3895
  throw new Error("protected_alias_index_unavailable");
3438
3896
  try {
3439
- const metadata = (0, import_node_fs6.lstatSync)(file, { bigint: true });
3897
+ const metadata = (0, import_node_fs8.lstatSync)(file, { bigint: true });
3440
3898
  if (metadata.isFile() && metadata.nlink > 1n) yield inode(metadata);
3441
3899
  if (metadata.isSymbolicLink() && ignored.size) {
3442
3900
  if (verifiedHook(file)) continue;
3443
3901
  pending.push(...ignored);
3444
3902
  ignored.clear();
3445
3903
  } else if (metadata.isDirectory()) {
3446
- const children = (0, import_node_fs6.readdirSync)(file);
3904
+ const children = (0, import_node_fs8.readdirSync)(file);
3447
3905
  if (children.length + pending.length + visited.size > entryLimit)
3448
3906
  throw new Error("protected_alias_index_unavailable");
3449
3907
  for (const name of children) {
3450
- const child = import_node_path5.default.join(file, name);
3908
+ const child = import_node_path7.default.join(file, name);
3451
3909
  if (!ignored.has(child)) pending.push(child);
3452
3910
  }
3453
3911
  }
@@ -3472,130 +3930,70 @@ var hasReadOnlyAliases = (roots, target, ignoredObjectDirectories, verifiedHooks
3472
3930
  };
3473
3931
  var isProtectedAlias = (stat, paths) => stat.nlink > 1n && findProtectedAliases(paths).has(inode(stat));
3474
3932
 
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
3933
  // src/permissions/shell-backend.ts
3536
3934
  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");
3935
+ var import_node_fs15 = require("fs");
3936
+ var import_node_os2 = __toESM(require("os"), 1);
3937
+ var import_node_path16 = __toESM(require("path"), 1);
3938
+ var import_storage9 = require("@codelia/storage");
3541
3939
 
3542
3940
  // src/sandbox/file-mutation-helper.ts
3543
- var import_node_path7 = __toESM(require("path"), 1);
3941
+ var import_node_path8 = __toESM(require("path"), 1);
3544
3942
 
3545
3943
  // src/utils/paths.ts
3546
- var import_node_path8 = __toESM(require("path"), 1);
3944
+ var import_node_path9 = __toESM(require("path"), 1);
3547
3945
  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}`);
3946
+ const relative = import_node_path9.default.relative(root, target);
3947
+ return relative === "" || !import_node_path9.default.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${import_node_path9.default.sep}`);
3550
3948
  };
3551
3949
 
3552
3950
  // src/permissions/linux-shell-backend.ts
3553
3951
  var import_node_child_process2 = require("child_process");
3554
- var import_node_fs10 = require("fs");
3555
- var import_node_path11 = __toESM(require("path"), 1);
3952
+ var import_node_fs11 = require("fs");
3953
+ var import_node_path12 = __toESM(require("path"), 1);
3556
3954
 
3557
3955
  // src/permissions/linux-mountinfo.ts
3558
- var import_node_fs8 = require("fs");
3559
- var import_node_path9 = __toESM(require("path"), 1);
3956
+ var import_node_fs9 = require("fs");
3957
+ var import_node_path10 = __toESM(require("path"), 1);
3560
3958
 
3561
3959
  // src/permissions/shell-analysis.ts
3562
3960
  var MAX_SOURCE_BYTES = 32 * 1024;
3563
3961
 
3564
3962
  // src/permissions/shell-path.ts
3565
- var import_node_fs9 = require("fs");
3566
- var import_node_path10 = __toESM(require("path"), 1);
3963
+ var import_node_fs10 = require("fs");
3964
+ var import_node_path11 = __toESM(require("path"), 1);
3567
3965
 
3568
3966
  // src/permissions/mxc-launcher.ts
3569
3967
  var import_node_child_process3 = require("child_process");
3570
- var import_node_fs11 = require("fs");
3571
- var import_node_path12 = __toESM(require("path"), 1);
3968
+ var import_node_fs12 = require("fs");
3969
+ var import_node_path13 = __toESM(require("path"), 1);
3572
3970
  var import_node_url = require("url");
3573
3971
  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));
3972
+ var packagePath = import_node_path13.default.join("node_modules", "@codelia", "tui-darwin-arm64");
3973
+ var moduleDir = typeof __dirname === "string" ? __dirname : import_node_path13.default.dirname((0, import_node_url.fileURLToPath)(import_meta.url));
3576
3974
 
3577
3975
  // src/permissions/system-bash.ts
3578
- var import_node_fs12 = require("fs");
3579
- var import_node_path13 = require("path");
3976
+ var import_node_fs13 = require("fs");
3977
+ var import_node_path14 = require("path");
3580
3978
 
3581
3979
  // 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");
3980
+ var import_node_fs14 = require("fs");
3981
+ var import_node_path15 = __toESM(require("path"), 1);
3982
+ var import_storage8 = require("@codelia/storage");
3585
3983
  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";
3984
+ var isWorkspaceConfigName = (root, target) => resourceContainsPath(import_node_path15.default.dirname(resolveProjectConfigPath(root)), target);
3985
+ var missing2 = (error) => error.code === "ENOENT";
3588
3986
  function resolveConfigTarget(target, remaining = 64) {
3589
3987
  if (!remaining) throw new Error("workspace_config_path_unresolved");
3590
3988
  try {
3591
- return (0, import_node_fs13.realpathSync)(target);
3989
+ return (0, import_node_fs14.realpathSync)(target);
3592
3990
  } catch (error) {
3593
- const parent = import_node_path14.default.dirname(target);
3594
- if (!missing(error) || parent === target) throw error;
3991
+ const parent = import_node_path15.default.dirname(target);
3992
+ if (!missing2(error) || parent === target) throw error;
3595
3993
  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);
3994
+ if (!(0, import_node_fs14.lstatSync)(target, { throwIfNoEntry: false })?.isSymbolicLink())
3995
+ return import_node_path15.default.join(canonicalParent, import_node_path15.default.basename(target));
3996
+ const referent = (0, import_node_fs14.readlinkSync)(target);
3599
3997
  let seenName = false;
3600
3998
  for (const part of referent.split(
3601
3999
  process.platform === "win32" ? /[\\/]/u : "/"
@@ -3605,14 +4003,14 @@ function resolveConfigTarget(target, remaining = 64) {
3605
4003
  if (part && part !== "." && part !== "..") seenName = true;
3606
4004
  }
3607
4005
  return resolveConfigTarget(
3608
- import_node_path14.default.resolve(canonicalParent, referent),
4006
+ import_node_path15.default.resolve(canonicalParent, referent),
3609
4007
  remaining - 1
3610
4008
  );
3611
4009
  }
3612
4010
  }
3613
4011
  var workspaceConfigProtection = (root) => {
3614
4012
  const config = resolveProjectConfigPath(root);
3615
- const directory = import_node_path14.default.dirname(config);
4013
+ const directory = import_node_path15.default.dirname(config);
3616
4014
  const readOnlyPaths = /* @__PURE__ */ new Set([directory]);
3617
4015
  const readOnlyAliasPaths = /* @__PURE__ */ new Set();
3618
4016
  const reserveTarget = (file) => {
@@ -3620,37 +4018,37 @@ var workspaceConfigProtection = (root) => {
3620
4018
  readOnlyPaths.add(target);
3621
4019
  readOnlyAliasPaths.add(target);
3622
4020
  };
3623
- if ((0, import_node_fs13.lstatSync)(directory, { throwIfNoEntry: false })) {
4021
+ if ((0, import_node_fs14.lstatSync)(directory, { throwIfNoEntry: false })) {
3624
4022
  const canonical = resolveConfigTarget(directory);
3625
4023
  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)();
4024
+ if ((0, import_node_fs14.lstatSync)(canonical, { throwIfNoEntry: false })?.isDirectory()) {
4025
+ const file = import_node_path15.default.join(canonical, import_node_path15.default.basename(config));
4026
+ if ((0, import_node_fs14.lstatSync)(file, { throwIfNoEntry: false })) reserveTarget(file);
4027
+ const storage = (0, import_storage8.resolveStoragePaths)();
3630
4028
  const globalStorage = [
3631
- (0, import_storage7.resolveStoragePaths)({ layout: "home" }).root,
4029
+ (0, import_storage8.resolveStoragePaths)({ layout: "home" }).root,
3632
4030
  storage.root,
3633
4031
  storage.configDir
3634
4032
  ].some((entry) => {
3635
4033
  try {
3636
- return (0, import_node_fs13.realpathSync)(entry) === canonical;
4034
+ return (0, import_node_fs14.realpathSync)(entry) === canonical;
3637
4035
  } catch (error) {
3638
- if (!missing(error)) throw error;
4036
+ if (!missing2(error)) throw error;
3639
4037
  return false;
3640
4038
  }
3641
4039
  });
3642
4040
  if (!globalStorage) {
3643
- const worktrees = import_node_path14.default.join(canonical, "worktrees");
4041
+ const worktrees = import_node_path15.default.join(canonical, "worktrees");
3644
4042
  const pending = [canonical];
3645
4043
  for (const current of pending) {
3646
- const children = (0, import_node_fs13.opendirSync)(current);
4044
+ const children = (0, import_node_fs14.opendirSync)(current);
3647
4045
  try {
3648
4046
  for (let entry = children.readSync(); entry; entry = children.readSync()) {
3649
- const target = import_node_path14.default.join(current, entry.name);
4047
+ const target = import_node_path15.default.join(current, entry.name);
3650
4048
  if (target === file || target === worktrees) continue;
3651
4049
  if (entry.isSymbolicLink()) reserveTarget(target);
3652
4050
  else if (entry.isDirectory()) pending.push(target);
3653
- else if (entry.isFile() && ((0, import_node_fs13.lstatSync)(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
4051
+ else if (entry.isFile() && ((0, import_node_fs14.lstatSync)(target, { throwIfNoEntry: false })?.nlink ?? 0) > 1)
3654
4052
  readOnlyAliasPaths.add(target);
3655
4053
  }
3656
4054
  } finally {
@@ -3669,31 +4067,31 @@ var workspaceConfigProtection = (root) => {
3669
4067
  // src/permissions/shell-backend.ts
3670
4068
  var realOrLexical = (value) => {
3671
4069
  try {
3672
- return (0, import_node_fs14.realpathSync)(value);
4070
+ return (0, import_node_fs15.realpathSync)(value);
3673
4071
  } catch {
3674
- return import_node_path15.default.resolve(value);
4072
+ return import_node_path16.default.resolve(value);
3675
4073
  }
3676
4074
  };
3677
4075
  var resolvePolicyPath = (target) => {
3678
- const absolute = import_node_path15.default.resolve(target);
4076
+ const absolute = import_node_path16.default.resolve(target);
3679
4077
  try {
3680
- return (0, import_node_fs14.realpathSync)(absolute);
4078
+ return (0, import_node_fs15.realpathSync)(absolute);
3681
4079
  } catch (error) {
3682
- const parent = import_node_path15.default.dirname(absolute);
4080
+ const parent = import_node_path16.default.dirname(absolute);
3683
4081
  if (error.code !== "ENOENT" || parent === absolute)
3684
4082
  throw error;
3685
- if ((0, import_node_fs14.lstatSync)(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
4083
+ if ((0, import_node_fs15.lstatSync)(absolute, { throwIfNoEntry: false })?.isSymbolicLink())
3686
4084
  throw error;
3687
- return import_node_path15.default.join(resolvePolicyPath(parent), import_node_path15.default.basename(absolute));
4085
+ return import_node_path16.default.join(resolvePolicyPath(parent), import_node_path16.default.basename(absolute));
3688
4086
  }
3689
4087
  };
3690
4088
  var canonicalPolicyPaths = (paths) => Object.freeze([
3691
4089
  ...new Set(
3692
- paths.flatMap((entry) => [import_node_path15.default.resolve(entry), resolvePolicyPath(entry)])
4090
+ paths.flatMap((entry) => [import_node_path16.default.resolve(entry), resolvePolicyPath(entry)])
3693
4091
  )
3694
4092
  ]);
3695
4093
  var runtimeReadOnlyPaths = () => {
3696
- const storage = (0, import_storage8.resolveStoragePaths)();
4094
+ const storage = (0, import_storage9.resolveStoragePaths)();
3697
4095
  return canonicalPolicyPaths([
3698
4096
  storage.root,
3699
4097
  storage.configDir,
@@ -3701,37 +4099,68 @@ var runtimeReadOnlyPaths = () => {
3701
4099
  resolveConfigPath()
3702
4100
  ]);
3703
4101
  };
4102
+ var runtimeProtectedCredentialPaths = () => {
4103
+ const storage = (0, import_storage9.resolveStoragePaths)();
4104
+ const targets = [];
4105
+ if (process.platform === "linux") {
4106
+ try {
4107
+ (0, import_node_fs15.mkdirSync)(storage.credentialsDir, { recursive: true, mode: 448 });
4108
+ targets.push(storage.credentialsDir);
4109
+ } catch {
4110
+ if ((0, import_node_fs15.lstatSync)(storage.credentialsDir, { throwIfNoEntry: false })) {
4111
+ targets.push(storage.credentialsDir);
4112
+ }
4113
+ }
4114
+ for (const legacy of [storage.legacyAuthFile, storage.legacyMcpAuthFile]) {
4115
+ if ((0, import_node_fs15.lstatSync)(legacy, { throwIfNoEntry: false })) {
4116
+ targets.push(legacy);
4117
+ }
4118
+ }
4119
+ } else {
4120
+ targets.push(
4121
+ storage.credentialsDir,
4122
+ storage.legacyAuthFile,
4123
+ storage.legacyMcpAuthFile
4124
+ );
4125
+ }
4126
+ return canonicalPolicyPaths(targets);
4127
+ };
3704
4128
  var runtimeAuthorityAliasPaths = () => {
3705
- const storage = (0, import_storage8.resolveStoragePaths)();
4129
+ const storage = (0, import_storage9.resolveStoragePaths)();
3706
4130
  const databasePaths = [
3707
- import_node_path15.default.join(storage.configDir, ".projects-policy-lock.sqlite"),
3708
- import_node_path15.default.join(storage.sessionsDir, "state.db")
4131
+ import_node_path16.default.join(storage.configDir, ".projects-policy-lock.sqlite"),
4132
+ import_node_path16.default.join(storage.sessionsDir, "state.db")
3709
4133
  ];
3710
4134
  return canonicalPolicyPaths([
3711
4135
  resolveConfigPath(),
3712
4136
  storage.configFile,
3713
4137
  storage.projectsFile,
3714
- storage.authFile,
3715
- storage.mcpAuthFile,
3716
4138
  ...[
3717
4139
  "launch-approvals",
3718
4140
  "auto-review.json",
3719
4141
  confinedAutoLaunchDirectoryName
3720
- ].map((entry) => import_node_path15.default.join(storage.configDir, entry)),
4142
+ ].map((entry) => import_node_path16.default.join(storage.configDir, entry)),
3721
4143
  ...databasePaths.flatMap(
3722
4144
  (file) => ["", "-wal", "-shm", "-journal"].map((suffix) => `${file}${suffix}`)
3723
4145
  )
3724
4146
  ]);
3725
4147
  };
3726
- var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectories = [], sandboxMode = "workspace-write", allowSharedGitObjects = false, extraReadOnlyPaths = []) => {
4148
+ var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectories = [], sandboxMode = "workspace-write", allowSharedGitObjects = false, extraReadOnlyPaths = [], homeScope = {}) => {
3727
4149
  const discover = allowSharedGitObjects && sandboxMode === "workspace-write" ? gitMetadataWithObjectDirectories : gitMetadataPaths;
3728
4150
  const { readOnlyPaths, reservedMarkers, objectDirectories, hookAliases } = discover(root, ...relatedDirectories);
3729
- const protectedPaths = canonicalPolicyPaths(extraProtectedPaths);
4151
+ const protectedPaths = canonicalPolicyPaths([
4152
+ ...extraProtectedPaths,
4153
+ ...runtimeProtectedCredentialPaths()
4154
+ ]);
3730
4155
  const projectConfig = workspaceConfigProtection(root);
3731
4156
  const hostReadOnlyPaths = canonicalPolicyPaths(extraReadOnlyPaths);
3732
4157
  const runtimeRoots = runtimeReadOnlyPaths();
3733
4158
  const runtimeAuthority = runtimeAuthorityAliasPaths();
4159
+ const protectedHome = homeDotDirectory(
4160
+ homeScope.writeRoots ?? (sandboxMode === "readonly" ? [] : [root])
4161
+ );
3734
4162
  const additionalReadOnlyPaths = [
4163
+ ...protectedHome && !homeScope.recheckHomeLinksOnWrite ? homeDotLinkTargets(protectedHome) : [],
3735
4164
  ...reservedMarkers,
3736
4165
  ...projectConfig.readOnlyPaths,
3737
4166
  ...hostReadOnlyPaths,
@@ -3744,13 +4173,14 @@ var workspacePathProtection = (root, extraProtectedPaths = [], relatedDirectorie
3744
4173
  const objectDirectoriesWithSharedFiles = objectDirectories.filter(
3745
4174
  (directory) => {
3746
4175
  const overlaps = (other) => resourceContainsPath(other, directory.path) || resourceContainsPath(directory.path, other);
3747
- const commonDirectory = import_node_path15.default.dirname(directory.path);
4176
+ const commonDirectory = import_node_path16.default.dirname(directory.path);
3748
4177
  return !strongerPaths.some(overlaps) && !readOnlyPaths.some(
3749
4178
  (other) => overlaps(other) && realOrLexical(other) !== commonDirectory
3750
4179
  );
3751
4180
  }
3752
4181
  );
3753
4182
  return {
4183
+ ...protectedHome ? { homeDotDirectory: protectedHome } : {},
3754
4184
  protectedPaths,
3755
4185
  protectedAliasPaths: protectedPaths,
3756
4186
  readOnlyPaths: Object.freeze(
@@ -3784,22 +4214,22 @@ var SecurityError = class extends Error {
3784
4214
  var identity = (info) => `${info.dev}:${info.ino}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`;
3785
4215
  var directoryIdentity = (stat) => `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
3786
4216
  var selectMissingFile = (entry) => {
3787
- let parent = import_node_path16.default.dirname(entry.target);
4217
+ let parent = import_node_path17.default.dirname(entry.target);
3788
4218
  for (; ; ) {
3789
4219
  try {
3790
- const stat = (0, import_node_fs15.lstatSync)(parent, { bigint: true });
3791
- if (!stat.isDirectory() || (0, import_node_fs15.realpathSync)(parent) !== parent)
4220
+ const stat = (0, import_node_fs16.lstatSync)(parent, { bigint: true });
4221
+ if (!stat.isDirectory() || (0, import_node_fs16.realpathSync)(parent) !== parent)
3792
4222
  throw new SecurityError("Expected a canonical parent directory");
3793
4223
  return Object.freeze({
3794
4224
  ...entry,
3795
4225
  identity: null,
3796
4226
  parent,
3797
4227
  parentIdentity: directoryIdentity(stat),
3798
- tail: import_node_path16.default.relative(parent, entry.target)
4228
+ tail: import_node_path17.default.relative(parent, entry.target)
3799
4229
  });
3800
4230
  } catch (error) {
3801
4231
  if (error.code !== "ENOENT") throw error;
3802
- const ancestor = import_node_path16.default.dirname(parent);
4232
+ const ancestor = import_node_path17.default.dirname(parent);
3803
4233
  if (ancestor === parent) throw error;
3804
4234
  parent = ancestor;
3805
4235
  }
@@ -3807,15 +4237,15 @@ var selectMissingFile = (entry) => {
3807
4237
  };
3808
4238
  var missingDestinationCurrent = (selection) => {
3809
4239
  try {
3810
- const segments = selection.tail.split(import_node_path16.default.sep);
4240
+ const segments = selection.tail.split(import_node_path17.default.sep);
3811
4241
  if (segments.some(
3812
4242
  (segment) => !segment || segment === "." || segment === ".."
3813
- ) || import_node_path16.default.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
4243
+ ) || import_node_path17.default.join(selection.parent, selection.tail) !== selection.target || !directoryBindingCurrent(selection))
3814
4244
  return false;
3815
4245
  let current = selection.parent;
3816
4246
  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);
4247
+ current = import_node_path17.default.join(current, segment);
4248
+ const stat = (0, import_node_fs16.lstatSync)(current);
3819
4249
  if (index === segments.length - 1 || !stat.isDirectory()) return false;
3820
4250
  }
3821
4251
  return false;
@@ -3825,8 +4255,8 @@ var missingDestinationCurrent = (selection) => {
3825
4255
  };
3826
4256
  var directoryBindingCurrent = (selection) => {
3827
4257
  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;
4258
+ const stat = (0, import_node_fs16.lstatSync)(selection.parent, { bigint: true });
4259
+ return stat.isDirectory() && directoryIdentity(stat) === selection.parentIdentity && (0, import_node_fs16.realpathSync)(selection.parent) === selection.parent;
3830
4260
  } catch {
3831
4261
  return false;
3832
4262
  }
@@ -3839,6 +4269,7 @@ var SandboxContext = class _SandboxContext {
3839
4269
  approvalMode;
3840
4270
  protectedPaths;
3841
4271
  protectedAliasPaths;
4272
+ homeDotDirectory;
3842
4273
  readOnlyPaths;
3843
4274
  readOnlyAliasPaths;
3844
4275
  mutations;
@@ -3851,6 +4282,7 @@ var SandboxContext = class _SandboxContext {
3851
4282
  this.approvalMode = init.approvalMode;
3852
4283
  this.protectedPaths = init.protectedPaths;
3853
4284
  this.protectedAliasPaths = init.protectedAliasPaths;
4285
+ this.homeDotDirectory = init.homeDotDirectory;
3854
4286
  this.readOnlyPaths = init.readOnlyPaths ?? [];
3855
4287
  this.readOnlyAliasPaths = init.readOnlyAliasPaths ?? this.readOnlyPaths;
3856
4288
  this.selections = init.selections;
@@ -3858,10 +4290,10 @@ var SandboxContext = class _SandboxContext {
3858
4290
  }
3859
4291
  static async create(rootDir, options = {}) {
3860
4292
  const sessionId = import_node_crypto5.default.randomUUID().slice(0, 8);
3861
- const root = rootDir ? import_node_path16.default.resolve(rootDir) : process.cwd();
4293
+ const root = rootDir ? import_node_path17.default.resolve(rootDir) : process.cwd();
3862
4294
  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;
4295
+ await import_node_fs16.promises.mkdir(root, { recursive: true });
4296
+ const directory = options.protectResources ? await import_node_fs16.promises.realpath(root) : root;
3865
4297
  return new _SandboxContext({
3866
4298
  rootDir: directory,
3867
4299
  workingDir: directory,
@@ -3871,7 +4303,8 @@ var SandboxContext = class _SandboxContext {
3871
4303
  [],
3872
4304
  options.sandboxMode,
3873
4305
  false,
3874
- options.extraReadOnlyPaths
4306
+ options.extraReadOnlyPaths,
4307
+ { recheckHomeLinksOnWrite: true }
3875
4308
  ) : {},
3876
4309
  sessionId,
3877
4310
  mutations: typeof options.mutations === "function" ? await options.mutations(directory) : options.mutations,
@@ -3882,7 +4315,7 @@ var SandboxContext = class _SandboxContext {
3882
4315
  resolvePath(targetPath, access = "write") {
3883
4316
  if (access === "write" && this.sandboxMode === "readonly")
3884
4317
  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);
4318
+ const resolved = import_node_path17.default.isAbsolute(targetPath) ? import_node_path17.default.resolve(targetPath) : import_node_path17.default.resolve(this.workingDir, targetPath);
3886
4319
  if (this.protectedPaths) return this.resolveProtectedPath(resolved, access);
3887
4320
  if (this.approvalMode === "full-access") {
3888
4321
  return resolved;
@@ -3900,12 +4333,12 @@ var SandboxContext = class _SandboxContext {
3900
4333
  selectFile(operand, access, directoryEntry = false) {
3901
4334
  const target = this.resolvePath(operand, access);
3902
4335
  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)
4336
+ const lexical = import_node_path17.default.resolve(this.workingDir, operand);
4337
+ const name = import_node_path17.default.join(
4338
+ resolvePolicyPath(import_node_path17.default.dirname(lexical)),
4339
+ import_node_path17.default.basename(lexical)
3907
4340
  );
3908
- if (target !== name || (0, import_node_fs15.lstatSync)(name, { throwIfNoEntry: false })?.isSymbolicLink())
4341
+ if (target !== name || (0, import_node_fs16.lstatSync)(name, { throwIfNoEntry: false })?.isSymbolicLink())
3909
4342
  throw new SecurityError(
3910
4343
  "Patch deletion and move require a regular directory entry without a symbolic link"
3911
4344
  );
@@ -3917,7 +4350,7 @@ var SandboxContext = class _SandboxContext {
3917
4350
  ...directoryEntry ? { directoryEntry: true } : {}
3918
4351
  };
3919
4352
  try {
3920
- const info = (0, import_node_fs15.lstatSync)(target, { bigint: true });
4353
+ const info = (0, import_node_fs16.lstatSync)(target, { bigint: true });
3921
4354
  if (!info.isFile())
3922
4355
  throw new SecurityError("Expected a regular file for this operation");
3923
4356
  return Object.freeze({
@@ -3938,6 +4371,7 @@ var SandboxContext = class _SandboxContext {
3938
4371
  sandboxMode: this.sandboxMode,
3939
4372
  protectedPaths: this.protectedPaths,
3940
4373
  protectedAliasPaths: this.protectedAliasPaths,
4374
+ homeDotDirectory: this.homeDotDirectory,
3941
4375
  readOnlyPaths: this.readOnlyPaths,
3942
4376
  readOnlyAliasPaths: this.readOnlyAliasPaths,
3943
4377
  mutations: this.mutations,
@@ -3964,8 +4398,8 @@ var SandboxContext = class _SandboxContext {
3964
4398
  error.code = "ENOENT";
3965
4399
  throw error;
3966
4400
  }
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);
4401
+ const flags = (mode === "read" ? import_node_fs16.constants.O_RDONLY : import_node_fs16.constants.O_RDWR) | (import_node_fs16.constants.O_NOFOLLOW ?? 0) | (import_node_fs16.constants.O_NONBLOCK ?? 0);
4402
+ const handle = await import_node_fs16.promises.open(selected.target, flags);
3969
4403
  try {
3970
4404
  const opened = await handle.stat({ bigint: true });
3971
4405
  if (!opened.isFile() || identity(opened) !== selected.identity || isProtectedAlias(
@@ -4058,7 +4492,7 @@ var SandboxContext = class _SandboxContext {
4058
4492
  writeProtection(target, alias = false) {
4059
4493
  const { readOnlyPaths } = gitMetadataPaths(
4060
4494
  this.rootDir,
4061
- import_node_path16.default.dirname(target)
4495
+ import_node_path17.default.dirname(target)
4062
4496
  );
4063
4497
  const projectConfig = workspaceConfigProtection(this.rootDir);
4064
4498
  return [
@@ -4080,7 +4514,7 @@ var SandboxContext = class _SandboxContext {
4080
4514
  if (access !== "write") return;
4081
4515
  if (!isWithin(this.rootDir, value))
4082
4516
  throw new SecurityError("Write path escapes the workspace");
4083
- if (isWorkspaceConfigName(this.rootDir, value) || this.writeProtection(value).some(
4517
+ if (this.homeDotDirectory && isHomeWriteReserved(this.homeDotDirectory, value) || isWorkspaceConfigName(this.rootDir, value) || this.writeProtection(value).some(
4084
4518
  (entry) => resourceContainsPath(entry, value)
4085
4519
  ))
4086
4520
  throw new SecurityError("Path is read-only under the resource policy");
@@ -4090,16 +4524,16 @@ var SandboxContext = class _SandboxContext {
4090
4524
  let probe = resolved;
4091
4525
  for (; ; ) {
4092
4526
  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));
4527
+ const actual = (0, import_node_fs16.realpathSync)(probe);
4528
+ const target = import_node_path17.default.resolve(actual, import_node_path17.default.relative(probe, resolved));
4095
4529
  rejectProtected(target);
4096
4530
  if (target !== resolved) rejectWrite(target);
4097
4531
  if (probe === resolved) {
4098
- const stat = (0, import_node_fs15.lstatSync)(target);
4532
+ const stat = (0, import_node_fs16.lstatSync)(target);
4099
4533
  if (!stat.isFile() && !stat.isDirectory())
4100
4534
  throw new SecurityError("Unsupported file type");
4101
4535
  if (stat.isFile() && stat.nlink > 1) {
4102
- const inode2 = (0, import_node_fs15.lstatSync)(target, { bigint: true });
4536
+ const inode2 = (0, import_node_fs16.lstatSync)(target, { bigint: true });
4103
4537
  if (isProtectedAlias(inode2, protectedPaths))
4104
4538
  throw new SecurityError("Path aliases a protected file");
4105
4539
  if (access === "write" && this.isReadOnlyAlias(inode2, target))
@@ -4109,10 +4543,10 @@ var SandboxContext = class _SandboxContext {
4109
4543
  return target;
4110
4544
  } catch (error) {
4111
4545
  if (error.code !== "ENOENT") throw error;
4112
- const ancestor = import_node_path16.default.dirname(probe);
4546
+ const ancestor = import_node_path17.default.dirname(probe);
4113
4547
  if (ancestor === probe) throw error;
4114
4548
  try {
4115
- if ((0, import_node_fs15.lstatSync)(probe).isSymbolicLink())
4549
+ if ((0, import_node_fs16.lstatSync)(probe).isSymbolicLink())
4116
4550
  throw new SecurityError("Path contains a dangling symlink");
4117
4551
  } catch (entryError) {
4118
4552
  if (entryError.code !== "ENOENT")
@@ -4140,8 +4574,8 @@ var appendReadMetadata = (output, content) => `${output}
4140
4574
  [read_metadata] content_sha256=${hashUtf8Content(content)}`;
4141
4575
 
4142
4576
  // src/subagents/workspace-files.ts
4143
- var import_node_fs16 = require("fs");
4144
- var import_node_path17 = __toESM(require("path"), 1);
4577
+ var import_node_fs17 = require("fs");
4578
+ var import_node_path18 = __toESM(require("path"), 1);
4145
4579
  var MAX_CHILD_FILE_BYTES = 4 * 1024 * 1024;
4146
4580
  var readContent = async (handle) => {
4147
4581
  const buffer = Buffer.alloc(MAX_CHILD_FILE_BYTES + 1);
@@ -4154,6 +4588,7 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
4154
4588
  const {
4155
4589
  protectedPaths,
4156
4590
  protectedAliasPaths,
4591
+ homeDotDirectory: homeDotDirectory2,
4157
4592
  readOnlyPaths = [],
4158
4593
  readOnlyAliasPaths = readOnlyPaths
4159
4594
  } = workspacePathProtection(
@@ -4162,21 +4597,22 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
4162
4597
  [],
4163
4598
  "workspace-write",
4164
4599
  false,
4165
- extraReadOnlyPaths
4600
+ extraReadOnlyPaths,
4601
+ { recheckHomeLinksOnWrite: true }
4166
4602
  );
4167
4603
  const blocked = (target) => protectedPaths.some((entry) => resourceContainsPath(entry, target));
4168
4604
  const resolve = async (name, allowMissing = false) => {
4169
- const candidate = import_node_path17.default.resolve(root, name);
4605
+ const candidate = import_node_path18.default.resolve(root, name);
4170
4606
  if (blocked(candidate))
4171
4607
  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))
4608
+ const relative = import_node_path18.default.relative(root, candidate);
4609
+ if (relative === ".." || relative.startsWith(`..${import_node_path18.default.sep}`) || import_node_path18.default.isAbsolute(relative))
4174
4610
  throw new Error("Path outside delegated workspace");
4175
4611
  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);
4612
+ for (const segment of relative.split(import_node_path18.default.sep).filter(Boolean)) {
4613
+ part = import_node_path18.default.join(part, segment);
4178
4614
  try {
4179
- if ((await import_node_fs16.promises.lstat(part)).isSymbolicLink())
4615
+ if ((await import_node_fs17.promises.lstat(part)).isSymbolicLink())
4180
4616
  throw new Error(
4181
4617
  "Symbolic links are not available to delegated tools"
4182
4618
  );
@@ -4214,10 +4650,10 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
4214
4650
  const file = await resolve(name, expected === "missing");
4215
4651
  const repositoryReadOnly = gitMetadataPaths(
4216
4652
  root,
4217
- import_node_path17.default.dirname(file)
4653
+ import_node_path18.default.dirname(file)
4218
4654
  ).readOnlyPaths;
4219
4655
  const projectConfig = workspaceConfigProtection(root);
4220
- if (isWorkspaceConfigName(root, file) || [
4656
+ if (homeDotDirectory2 && isHomeWriteReserved(homeDotDirectory2, file) || isWorkspaceConfigName(root, file) || [
4221
4657
  ...readOnlyPaths,
4222
4658
  ...repositoryReadOnly,
4223
4659
  ...projectConfig.readOnlyPaths
@@ -4232,17 +4668,17 @@ var createWorkspaceFiles = (root, extraProtectedPaths, extraReadOnlyPaths) => {
4232
4668
  await approval.bound.writeSelectedFile(name, value);
4233
4669
  return hashUtf8Content(value);
4234
4670
  }
4235
- if (approval && (!selection?.identity || selection.target !== await import_node_fs16.promises.realpath(file)))
4671
+ if (approval && (!selection?.identity || selection.target !== await import_node_fs17.promises.realpath(file)))
4236
4672
  throw new Error("File selection changed after approval");
4237
4673
  if (approval && expected === "missing")
4238
4674
  throw new Error("File already exists");
4239
4675
  if (expected === "missing") {
4240
- await import_node_fs16.promises.mkdir(import_node_path17.default.dirname(file), { recursive: true });
4676
+ await import_node_fs17.promises.mkdir(import_node_path18.default.dirname(file), { recursive: true });
4241
4677
  await resolve(name, true);
4242
4678
  }
4243
- const handle = await import_node_fs16.promises.open(
4679
+ const handle = await import_node_fs17.promises.open(
4244
4680
  file,
4245
- expected === "missing" ? "wx" : import_node_fs16.constants.O_RDWR | (import_node_fs16.constants.O_NOFOLLOW ?? 0)
4681
+ expected === "missing" ? "wx" : import_node_fs17.constants.O_RDWR | (import_node_fs17.constants.O_NOFOLLOW ?? 0)
4246
4682
  );
4247
4683
  try {
4248
4684
  const stat = await handle.stat({ bigint: true });
@@ -4318,7 +4754,7 @@ var clipJsonString = (text, limit) => {
4318
4754
  var createSubagentReadTools = (root, protectedPaths, options = {}) => {
4319
4755
  const permits = options.permits ?? (() => true);
4320
4756
  const resolveWorkspace = async () => {
4321
- const sandbox = await SandboxContext.create(await import_node_fs17.promises.realpath(root), {
4757
+ const sandbox = await SandboxContext.create(await import_node_fs18.promises.realpath(root), {
4322
4758
  protectResources: true,
4323
4759
  extraProtectedPaths: protectedPaths
4324
4760
  });
@@ -4346,17 +4782,17 @@ var createSubagentReadTools = (root, protectedPaths, options = {}) => {
4346
4782
  signal?.throwIfAborted();
4347
4783
  const dir = pending.shift();
4348
4784
  if (!dir) break;
4349
- const entries = await import_node_fs17.promises.opendir(await resolve(import_node_path18.default.relative(root2, dir)));
4785
+ const entries = await import_node_fs18.promises.opendir(await resolve(import_node_path19.default.relative(root2, dir)));
4350
4786
  for await (const entry of entries) {
4351
4787
  if (entry.isSymbolicLink() || entry.name === ".git" || entry.name === "node_modules")
4352
4788
  continue;
4353
- const child = import_node_path18.default.join(dir, entry.name);
4789
+ const child = import_node_path19.default.join(dir, entry.name);
4354
4790
  if (blocked(child)) continue;
4355
4791
  if (entry.isDirectory()) {
4356
4792
  if (pending.length >= 2e3) return { paths, truncated: true };
4357
4793
  pending.push(child);
4358
4794
  } else if (entry.isFile()) {
4359
- const name = import_node_path18.default.relative(root2, child);
4795
+ const name = import_node_path19.default.relative(root2, child);
4360
4796
  const selected = await selectRead(name, sandbox).catch(
4361
4797
  () => void 0
4362
4798
  );
@@ -4587,13 +5023,13 @@ var createSubagentWriteTools = (root, channel, protection, protectedPaths) => {
4587
5023
 
4588
5024
  // src/subagents/child-runtime.ts
4589
5025
  var createChildRun = async (input, llm, options = {}) => {
4590
- const workspace = await import_node_fs18.promises.realpath(input.workspace_root);
5026
+ const workspace = await import_node_fs19.promises.realpath(input.workspace_root);
4591
5027
  const session_id = (0, import_node_crypto7.randomUUID)();
4592
5028
  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 } : {}
5029
+ const sessions = options.sessions ?? new import_storage10.SessionStateStoreImpl();
5030
+ const cache = options.cache ?? new import_storage10.ToolOutputCacheStoreImpl();
5031
+ const eventStore = options.append ? void 0 : new import_storage10.RunEventStoreFactoryImpl(
5032
+ sessions instanceof import_storage10.SessionStateStoreImpl ? { runIndex: sessions } : {}
4597
5033
  ).create({
4598
5034
  runId: run_id,
4599
5035
  startedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -4811,7 +5247,7 @@ var createChildRun = async (input, llm, options = {}) => {
4811
5247
  };
4812
5248
 
4813
5249
  // src/subagents/child-entry.ts
4814
- var bootstrap = (0, import_node_fs19.createReadStream)("", { fd: 3, autoClose: false });
5250
+ var bootstrap = (0, import_node_fs20.createReadStream)("", { fd: 3, autoClose: false });
4815
5251
  bootstrap.setEncoding("utf8");
4816
5252
  var controller = new AbortController();
4817
5253
  var exitTimer;