codexuse-cli 6.0.5 → 6.1.0

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.
package/dist/index.js CHANGED
@@ -2026,8 +2026,8 @@ var require_toml = __commonJS({
2026
2026
  });
2027
2027
 
2028
2028
  // src/commands/accountPool.ts
2029
- var import_node_crypto13 = require("crypto");
2030
- var import_node_path13 = __toESM(require("path"));
2029
+ var import_node_crypto14 = require("crypto");
2030
+ var import_node_path14 = __toESM(require("path"));
2031
2031
 
2032
2032
  // ../../packages/contracts/src/settings/types.ts
2033
2033
  var DEFAULT_ACCOUNT_POOL_EXPOSED_MODELS = [
@@ -2077,9 +2077,9 @@ function migrateLegacyAccountPoolExposedReasoningDefaults(efforts) {
2077
2077
  }
2078
2078
 
2079
2079
  // ../../packages/runtime-app-state/src/app/state.ts
2080
- var import_node_async_hooks = require("async_hooks");
2080
+ var import_node_async_hooks2 = require("async_hooks");
2081
2081
  var import_node_crypto2 = require("crypto");
2082
- var import_node_path3 = __toESM(require("path"), 1);
2082
+ var import_node_path4 = __toESM(require("path"), 1);
2083
2083
  var import_node_os = __toESM(require("os"), 1);
2084
2084
 
2085
2085
  // ../../packages/contracts/src/desktop/llm-compatibility.ts
@@ -2097,6 +2097,47 @@ var DESKTOP_LLM_CAPABILITY_NAMES = [
2097
2097
  "standaloneWebSearch",
2098
2098
  "imageGeneration"
2099
2099
  ];
2100
+ var MAX_DESKTOP_LLM_CONTEXT_TOKENS = 1e8;
2101
+ function boundedCatalogInteger(value3, minimum, maximum) {
2102
+ return typeof value3 === "number" && Number.isInteger(value3) && value3 >= minimum && value3 <= maximum ? value3 : null;
2103
+ }
2104
+ function normalizeDesktopLlmModelCatalogMetadata(value3) {
2105
+ const record2 = value3 && typeof value3 === "object" && !Array.isArray(value3) ? value3 : {};
2106
+ const description = typeof record2.description === "string" ? record2.description.slice(0, 2e3).trim() || null : null;
2107
+ const contextWindow = boundedCatalogInteger(
2108
+ record2.contextWindow,
2109
+ 1,
2110
+ MAX_DESKTOP_LLM_CONTEXT_TOKENS
2111
+ );
2112
+ const requestedMaxContextWindow = boundedCatalogInteger(
2113
+ record2.maxContextWindow,
2114
+ 1,
2115
+ MAX_DESKTOP_LLM_CONTEXT_TOKENS
2116
+ );
2117
+ const maxContextWindow = contextWindow !== null && requestedMaxContextWindow !== null && requestedMaxContextWindow < contextWindow ? contextWindow : requestedMaxContextWindow;
2118
+ const effectiveContextWindowPercent = boundedCatalogInteger(
2119
+ record2.effectiveContextWindowPercent,
2120
+ 1,
2121
+ 100
2122
+ );
2123
+ const requestedAutoCompactTokenLimit = boundedCatalogInteger(
2124
+ record2.autoCompactTokenLimit,
2125
+ 1,
2126
+ MAX_DESKTOP_LLM_CONTEXT_TOKENS
2127
+ );
2128
+ const compactContextWindow = contextWindow ?? maxContextWindow;
2129
+ const maximumAutoCompactTokenLimit = compactContextWindow ? Math.max(
2130
+ 1,
2131
+ Math.floor(compactContextWindow * 0.9)
2132
+ ) : MAX_DESKTOP_LLM_CONTEXT_TOKENS;
2133
+ return {
2134
+ description,
2135
+ contextWindow,
2136
+ maxContextWindow,
2137
+ autoCompactTokenLimit: requestedAutoCompactTokenLimit !== null && requestedAutoCompactTokenLimit <= maximumAutoCompactTokenLimit ? requestedAutoCompactTokenLimit : null,
2138
+ effectiveContextWindowPercent
2139
+ };
2140
+ }
2100
2141
  var POLICY_CAPABILITIES = /* @__PURE__ */ new Set([
2101
2142
  "inputImage",
2102
2143
  "reasoning",
@@ -3242,6 +3283,78 @@ async function deleteDocument(dbPath, namespace) {
3242
3283
  );
3243
3284
  }
3244
3285
 
3286
+ // ../../packages/runtime-app-state/src/storage/cloudSyncTransaction.ts
3287
+ var import_node_async_hooks = require("async_hooks");
3288
+ var import_node_path3 = __toESM(require("path"), 1);
3289
+ var CloudSyncTransactionLockError = class extends Error {
3290
+ constructor(reason, options = {}) {
3291
+ super(
3292
+ reason === "busy" ? "Another CodexUse process is changing Cloud Sync data. Wait for it to finish, then try again." : "CodexUse could not open the Cloud Sync transaction lock.",
3293
+ options
3294
+ );
3295
+ this.reason = reason;
3296
+ this.name = "CloudSyncTransactionLockError";
3297
+ }
3298
+ };
3299
+ var TRANSACTION_LOCK_NAME = "cloud-sync-transaction";
3300
+ var heldLocks = new import_node_async_hooks.AsyncLocalStorage();
3301
+ var operationTails = /* @__PURE__ */ new Map();
3302
+ function getCloudSyncTransactionLockPath(userDataDir) {
3303
+ return import_node_path3.default.join(userDataDir, TRANSACTION_LOCK_NAME);
3304
+ }
3305
+ async function acquireTransactionLock(target, mode) {
3306
+ const acquire = mode === "write" ? acquireCrossProcessFileLock : acquireCrossProcessFileReadLock;
3307
+ let release;
3308
+ try {
3309
+ release = await acquire(target);
3310
+ } catch (error) {
3311
+ throw new CloudSyncTransactionLockError("unavailable", { cause: error });
3312
+ }
3313
+ if (release) {
3314
+ return release;
3315
+ }
3316
+ throw new CloudSyncTransactionLockError("busy");
3317
+ }
3318
+ async function withCloudSyncTransaction(userDataDir, mode, operation) {
3319
+ const target = import_node_path3.default.resolve(getCloudSyncTransactionLockPath(userDataDir));
3320
+ const held = heldLocks.getStore();
3321
+ const heldTransaction = held?.get(target);
3322
+ if (heldTransaction?.active) {
3323
+ if (heldTransaction.mode === "read" && mode === "write") {
3324
+ throw new Error("A Cloud Sync read transaction cannot be upgraded to a write transaction.");
3325
+ }
3326
+ return operation();
3327
+ }
3328
+ const previous = operationTails.get(target) ?? Promise.resolve();
3329
+ let finish;
3330
+ const turn = new Promise((resolve2) => {
3331
+ finish = resolve2;
3332
+ });
3333
+ operationTails.set(target, turn);
3334
+ await previous;
3335
+ let release = null;
3336
+ let transaction = null;
3337
+ try {
3338
+ release = await acquireTransactionLock(target, mode);
3339
+ const nextHeld = new Map(held ?? []);
3340
+ transaction = { active: true, mode };
3341
+ nextHeld.set(target, transaction);
3342
+ return await heldLocks.run(nextHeld, operation);
3343
+ } finally {
3344
+ if (transaction) {
3345
+ transaction.active = false;
3346
+ }
3347
+ try {
3348
+ await release?.();
3349
+ } finally {
3350
+ finish();
3351
+ if (operationTails.get(target) === turn) {
3352
+ operationTails.delete(target);
3353
+ }
3354
+ }
3355
+ }
3356
+ }
3357
+
3245
3358
  // ../../packages/runtime-app-state/src/app/state.ts
3246
3359
  var APP_STATE_DOCUMENT = "desktop.app-state";
3247
3360
  var APP_NAME = "codexuse-desktop";
@@ -3255,7 +3368,7 @@ var persistenceFailure = null;
3255
3368
  var pendingRendererUiPatch = null;
3256
3369
  var nextPersistenceRetryAt = 0;
3257
3370
  var writeLock = Promise.resolve();
3258
- var writeLockContext = new import_node_async_hooks.AsyncLocalStorage();
3371
+ var writeLockContext = new import_node_async_hooks2.AsyncLocalStorage();
3259
3372
  function isRecord2(value3) {
3260
3373
  return Boolean(value3) && typeof value3 === "object" && !Array.isArray(value3);
3261
3374
  }
@@ -3284,7 +3397,7 @@ function resolveDefaultUserDataDir() {
3284
3397
  if (!home) {
3285
3398
  throw new Error("Unable to resolve home directory for app state.");
3286
3399
  }
3287
- return import_node_path3.default.join(home, "Library", "Application Support", APP_NAME);
3400
+ return import_node_path4.default.join(home, "Library", "Application Support", APP_NAME);
3288
3401
  }
3289
3402
  function getUserDataDir() {
3290
3403
  return configuredUserDataDir ?? resolveDefaultUserDataDir();
@@ -3369,23 +3482,12 @@ function createDefaultAppState() {
3369
3482
  runtimeSettings: {},
3370
3483
  ui: {
3371
3484
  themeMode: null,
3372
- layout: {
3373
- sidebarCollapsed: null
3374
- },
3375
3485
  profiles: {
3376
- viewMode: null,
3377
- sortBy: null,
3378
- groupBy: null,
3379
- planFilter: null,
3380
- healthFilter: null,
3381
- customGroupFilter: null,
3382
- toolbarOpen: null,
3383
3486
  collapsedSections: {}
3384
3487
  },
3385
3488
  onboarding: {
3386
3489
  welcomeCompleted: false,
3387
3490
  welcomeCompletedAt: null,
3388
- welcomeResumeStep: null,
3389
3491
  milestones: {
3390
3492
  firstProfileAdded: false,
3391
3493
  secondProfileAdded: false
@@ -3648,6 +3750,7 @@ function migrateDesktopLlmRegistry(profiles) {
3648
3750
  enabled: true,
3649
3751
  baseUrl: apiRoot,
3650
3752
  modelsPath: `${apiRoot}/models`,
3753
+ modelsDevId: null,
3651
3754
  authMode: "bearer",
3652
3755
  credentialRef: `CODEXUSE_RELAY_${profile.id}`,
3653
3756
  hasCredential: profile.hasApiKey,
@@ -3687,6 +3790,7 @@ function migrateDesktopLlmRegistry(profiles) {
3687
3790
  displayName: profile.model,
3688
3791
  adapter: profile.protocol === "chat-completions" ? "openai-chat" : "openai-responses",
3689
3792
  path: profile.protocol === "chat-completions" ? `${apiRoot}/chat/completions` : `${apiRoot}/responses`,
3793
+ catalogMetadata: normalizeDesktopLlmModelCatalogMetadata(null),
3690
3794
  capabilities: {
3691
3795
  streamingText: capability("streamingText", true),
3692
3796
  inputImage: capability("inputImage", false),
@@ -3779,6 +3883,7 @@ function normalizeDesktopLlmRegistry(value3, profiles) {
3779
3883
  enabled: entry.enabled === true,
3780
3884
  baseUrl,
3781
3885
  modelsPath: asString(entry.modelsPath),
3886
+ modelsDevId: typeof entry.modelsDevId === "string" && /^[a-z0-9][a-z0-9-]{0,127}$/.test(entry.modelsDevId) ? entry.modelsDevId : null,
3782
3887
  authMode,
3783
3888
  credentialRef: asString(entry.credentialRef),
3784
3889
  hasCredential: entry.hasCredential === true,
@@ -3855,6 +3960,9 @@ function normalizeDesktopLlmRegistry(value3, profiles) {
3855
3960
  displayName,
3856
3961
  adapter,
3857
3962
  path: routePath,
3963
+ catalogMetadata: normalizeDesktopLlmModelCatalogMetadata(
3964
+ entry.catalogMetadata
3965
+ ),
3858
3966
  capabilities,
3859
3967
  requestProfile: {
3860
3968
  reasoningStyle,
@@ -3932,6 +4040,7 @@ function normalizeDesktopLlmRegistry(value3, profiles) {
3932
4040
  enabled: provider.enabled,
3933
4041
  baseUrl: provider.baseUrl,
3934
4042
  modelsPath: provider.modelsPath,
4043
+ modelsDevId: provider.modelsDevId,
3935
4044
  authMode: provider.authMode,
3936
4045
  credentialRef: provider.credentialRef,
3937
4046
  hasCredential: provider.hasCredential,
@@ -3948,6 +4057,7 @@ function normalizeDesktopLlmRegistry(value3, profiles) {
3948
4057
  displayName: route.displayName,
3949
4058
  adapter: route.adapter,
3950
4059
  path: route.path,
4060
+ catalogMetadata: route.catalogMetadata,
3951
4061
  capabilities: route.capabilities,
3952
4062
  requestProfile: route.requestProfile,
3953
4063
  reasoningEffort: route.reasoningEffort,
@@ -4379,41 +4489,18 @@ function normalizeAppState(raw) {
4379
4489
  merged.ui = clone2(defaults.ui);
4380
4490
  }
4381
4491
  merged.ui.themeMode = merged.ui.themeMode === "light" || merged.ui.themeMode === "dark" ? merged.ui.themeMode : null;
4382
- if (!isRecord2(merged.ui.layout)) {
4383
- merged.ui.layout = clone2(defaults.ui.layout);
4384
- }
4385
- if (typeof merged.ui.layout.sidebarCollapsed !== "boolean") {
4386
- merged.ui.layout.sidebarCollapsed = null;
4387
- }
4388
- if (!isRecord2(merged.ui.profiles)) {
4389
- merged.ui.profiles = clone2(defaults.ui.profiles);
4390
- }
4391
- merged.ui.profiles.viewMode = merged.ui.profiles.viewMode === "cards" || merged.ui.profiles.viewMode === "compact" ? merged.ui.profiles.viewMode : null;
4392
- merged.ui.profiles.sortBy = asString(merged.ui.profiles.sortBy);
4393
- merged.ui.profiles.groupBy = asString(merged.ui.profiles.groupBy);
4394
- merged.ui.profiles.planFilter = asString(merged.ui.profiles.planFilter);
4395
- merged.ui.profiles.healthFilter = asString(merged.ui.profiles.healthFilter);
4396
- merged.ui.profiles.customGroupFilter = asString(
4397
- merged.ui.profiles.customGroupFilter
4398
- );
4399
- if (typeof merged.ui.profiles.toolbarOpen !== "boolean") {
4400
- merged.ui.profiles.toolbarOpen = null;
4401
- }
4402
- if (!isRecord2(merged.ui.profiles.collapsedSections)) {
4403
- merged.ui.profiles.collapsedSections = {};
4404
- } else {
4405
- merged.ui.profiles.collapsedSections = Object.fromEntries(
4406
- Object.entries(merged.ui.profiles.collapsedSections).flatMap(
4407
- ([key, value3]) => {
4408
- const normalizedKey = asString(key);
4409
- if (!normalizedKey || typeof value3 !== "boolean") {
4410
- return [];
4411
- }
4412
- return [[normalizedKey, value3]];
4413
- }
4414
- )
4415
- );
4416
- }
4492
+ const collapsedProfileSections = isRecord2(merged.ui.profiles) ? merged.ui.profiles.collapsedSections : null;
4493
+ merged.ui.profiles = {
4494
+ collapsedSections: isRecord2(collapsedProfileSections) ? Object.fromEntries(
4495
+ Object.entries(collapsedProfileSections).flatMap(([key, value3]) => {
4496
+ const normalizedKey = asString(key);
4497
+ if (!normalizedKey || typeof value3 !== "boolean") {
4498
+ return [];
4499
+ }
4500
+ return [[normalizedKey, value3]];
4501
+ })
4502
+ ) : {}
4503
+ };
4417
4504
  if (!isRecord2(merged.ui.onboarding)) {
4418
4505
  merged.ui.onboarding = clone2(defaults.ui.onboarding);
4419
4506
  }
@@ -4423,7 +4510,7 @@ function normalizeAppState(raw) {
4423
4510
  if (!Number.isFinite(merged.ui.onboarding.welcomeCompletedAt)) {
4424
4511
  merged.ui.onboarding.welcomeCompletedAt = null;
4425
4512
  }
4426
- merged.ui.onboarding.welcomeResumeStep = merged.ui.onboarding.welcomeResumeStep === 2 ? 2 : null;
4513
+ delete merged.ui.onboarding.welcomeResumeStep;
4427
4514
  if (!isRecord2(merged.ui.onboarding.milestones)) {
4428
4515
  merged.ui.onboarding.milestones = clone2(defaults.ui.onboarding.milestones);
4429
4516
  }
@@ -4565,10 +4652,10 @@ function normalizeAppState(raw) {
4565
4652
  ([rootPath, profileName]) => {
4566
4653
  const normalizedRoot = asString(rootPath);
4567
4654
  const normalizedProfile = asString(profileName);
4568
- if (!normalizedRoot || !import_node_path3.default.isAbsolute(normalizedRoot) || !normalizedProfile) {
4655
+ if (!normalizedRoot || !import_node_path4.default.isAbsolute(normalizedRoot) || !normalizedProfile) {
4569
4656
  return [];
4570
4657
  }
4571
- return [[import_node_path3.default.normalize(normalizedRoot), normalizedProfile]];
4658
+ return [[import_node_path4.default.normalize(normalizedRoot), normalizedProfile]];
4572
4659
  }
4573
4660
  )
4574
4661
  );
@@ -4659,7 +4746,11 @@ async function ensureInitialized() {
4659
4746
  if (memoryState && Date.now() < nextPersistenceRetryAt) {
4660
4747
  return memoryState;
4661
4748
  }
4662
- const attempt = readStoredAppStateForInit();
4749
+ const attempt = withCloudSyncTransaction(
4750
+ getUserDataDir(),
4751
+ "write",
4752
+ readStoredAppStateForInit
4753
+ );
4663
4754
  attempt.catch(() => void 0);
4664
4755
  let deadlineTimer;
4665
4756
  const deadline = new Promise((resolve2) => {
@@ -4724,56 +4815,77 @@ async function getAppState() {
4724
4815
  return state;
4725
4816
  }
4726
4817
  async function refreshAppStateCache() {
4727
- return withWriteLock(async () => {
4728
- const stored = await readStoredAppStateOrNull();
4729
- if (!stored) {
4730
- return ensureInitialized();
4818
+ try {
4819
+ return await withCloudSyncTransaction(
4820
+ getUserDataDir(),
4821
+ "write",
4822
+ () => withWriteLock(async () => {
4823
+ const stored = await readStoredAppStateOrNull();
4824
+ if (!stored) {
4825
+ return ensureInitialized();
4826
+ }
4827
+ appStateCache = freezeDeep(stored);
4828
+ ephemeralAppState = null;
4829
+ persistenceFailure = null;
4830
+ return appStateCache;
4831
+ })
4832
+ );
4833
+ } catch (error) {
4834
+ const busyLock = error instanceof CloudSyncTransactionLockError && error.reason === "busy";
4835
+ if (!busyLock) {
4836
+ const cause = error instanceof CloudSyncTransactionLockError ? error.cause ?? error : error;
4837
+ persistenceFailure = {
4838
+ kind: classifyAppStorageFailure(cause),
4839
+ message: cause instanceof Error ? cause.message : String(cause)
4840
+ };
4841
+ nextPersistenceRetryAt = Date.now() + PERSISTENCE_RETRY_COOLDOWN_MS;
4731
4842
  }
4732
- appStateCache = freezeDeep(stored);
4733
- ephemeralAppState = null;
4734
- persistenceFailure = null;
4735
- return appStateCache;
4736
- });
4843
+ return withWriteLock(() => ensureInitialized());
4844
+ }
4737
4845
  }
4738
4846
  async function updateAppState(transform3, options = {}) {
4739
4847
  const mode = options.mode ?? "patch";
4740
- return withWriteLock(async () => {
4741
- const shouldNormalize = options.normalize !== false;
4742
- const pendingUiPatch = pendingRendererUiPatch;
4743
- try {
4744
- const stored = await updateDocument({
4745
- dbPath: resolveStorageDbPath(),
4746
- namespace: APP_STATE_DOCUMENT,
4747
- normalize: normalizeAppState,
4748
- fallback: () => normalizeAppState(null),
4749
- cloneBeforeTransform: false,
4750
- normalizeResult: shouldNormalize,
4751
- cloneResult: false,
4752
- strictExisting: true,
4753
- transform: (current) => {
4754
- const transformed = transform3(
4755
- options.cloneCurrent === false ? current : clone2(current)
4756
- );
4757
- const next = mode === "replace" ? transformed : deepMerge(current, transformed);
4758
- return pendingUiPatch ? deepMerge(next, { ui: pendingUiPatch }) : next;
4848
+ return withCloudSyncTransaction(
4849
+ getUserDataDir(),
4850
+ "write",
4851
+ () => withWriteLock(async () => {
4852
+ const shouldNormalize = options.normalize !== false;
4853
+ const pendingUiPatch = pendingRendererUiPatch;
4854
+ try {
4855
+ const stored = await updateDocument({
4856
+ dbPath: resolveStorageDbPath(),
4857
+ namespace: APP_STATE_DOCUMENT,
4858
+ normalize: normalizeAppState,
4859
+ fallback: () => normalizeAppState(null),
4860
+ cloneBeforeTransform: false,
4861
+ normalizeResult: shouldNormalize,
4862
+ cloneResult: false,
4863
+ strictExisting: true,
4864
+ transform: (current) => {
4865
+ const transformed = transform3(
4866
+ options.cloneCurrent === false ? current : clone2(current)
4867
+ );
4868
+ const next = mode === "replace" ? transformed : deepMerge(current, transformed);
4869
+ return pendingUiPatch ? deepMerge(next, { ui: pendingUiPatch }) : next;
4870
+ }
4871
+ });
4872
+ if (pendingRendererUiPatch === pendingUiPatch) {
4873
+ pendingRendererUiPatch = null;
4759
4874
  }
4760
- });
4761
- if (pendingRendererUiPatch === pendingUiPatch) {
4762
- pendingRendererUiPatch = null;
4875
+ appStateCache = freezeDeep(stored);
4876
+ ephemeralAppState = null;
4877
+ persistenceFailure = null;
4878
+ return appStateCache;
4879
+ } catch (error) {
4880
+ persistenceFailure = {
4881
+ kind: classifyAppStorageFailure(error),
4882
+ message: error instanceof Error ? error.message : String(error)
4883
+ };
4884
+ nextPersistenceRetryAt = Date.now() + PERSISTENCE_RETRY_COOLDOWN_MS;
4885
+ throw error;
4763
4886
  }
4764
- appStateCache = freezeDeep(stored);
4765
- ephemeralAppState = null;
4766
- persistenceFailure = null;
4767
- return appStateCache;
4768
- } catch (error) {
4769
- persistenceFailure = {
4770
- kind: classifyAppStorageFailure(error),
4771
- message: error instanceof Error ? error.message : String(error)
4772
- };
4773
- nextPersistenceRetryAt = Date.now() + PERSISTENCE_RETRY_COOLDOWN_MS;
4774
- throw error;
4775
- }
4776
- });
4887
+ })
4888
+ );
4777
4889
  }
4778
4890
  async function patchAppState(patch) {
4779
4891
  return updateAppState(() => patch, {
@@ -4833,10 +4945,6 @@ function withCurrentRuntimeDefaults(settings, options = {}) {
4833
4945
  changed = true;
4834
4946
  }
4835
4947
  }
4836
- if (next.rateLimitPercentMode !== "remaining" && next.rateLimitPercentMode !== "used") {
4837
- next.rateLimitPercentMode = "remaining";
4838
- changed = true;
4839
- }
4840
4948
  if (next.officialCodexRelayMode !== "official" && next.officialCodexRelayMode !== "off" && next.officialCodexRelayMode !== void 0) {
4841
4949
  next.officialCodexRelayMode = "off";
4842
4950
  changed = true;
@@ -4949,7 +5057,6 @@ function parseStoredTrial(raw) {
4949
5057
  }
4950
5058
  var CLOUD_SYNC_RUNTIME_SETTING_KEYS = /* @__PURE__ */ new Set([
4951
5059
  "keepAppRunningAfterWindowClose",
4952
- "rateLimitPercentMode",
4953
5060
  "officialCodexWideViewEnabled",
4954
5061
  "officialCodexWideViewMaxWidth",
4955
5062
  "officialCodexScrollRestoreEnabled",
@@ -5461,6 +5568,9 @@ function buildTrialInfo(stored, now2) {
5461
5568
  daysLeft
5462
5569
  };
5463
5570
  }
5571
+ function lockReasonFor(info) {
5572
+ return info.expired ? "trial-ended" : null;
5573
+ }
5464
5574
  function buildLockedTrialInfo(stored) {
5465
5575
  return {
5466
5576
  active: false,
@@ -5604,7 +5714,7 @@ function readServerVerifiedTrial(now2) {
5604
5714
  }
5605
5715
  async function resolveTrialState(now2 = Date.now(), options = {}) {
5606
5716
  if (!isTrialEnforcementEnabled()) {
5607
- return { info: null, locked: false };
5717
+ return { info: null, locked: false, lockReason: null };
5608
5718
  }
5609
5719
  const allowNetwork = options.allowNetwork !== false;
5610
5720
  const secret = await getLicenseSecret();
@@ -5619,16 +5729,20 @@ async function resolveTrialState(now2 = Date.now(), options = {}) {
5619
5729
  if (hasLocalClockRollback(cached2, now2)) {
5620
5730
  const refreshed2 = allowNetwork ? await syncAndPersistTrial({ stored: cached2, secret, now: now2 }) : null;
5621
5731
  if (!refreshed2) {
5622
- return { info: buildLockedTrialInfo(cached2), locked: true };
5732
+ return {
5733
+ info: buildLockedTrialInfo(cached2),
5734
+ locked: true,
5735
+ lockReason: "unverified"
5736
+ };
5623
5737
  }
5624
5738
  const info3 = buildTrialInfo(refreshed2, trustedTrialNow(refreshed2, now2));
5625
- return { info: info3, locked: info3.expired };
5739
+ return { info: info3, locked: info3.expired, lockReason: lockReasonFor(info3) };
5626
5740
  }
5627
5741
  if (shouldRefreshInBackground(cached2, now2)) {
5628
5742
  void syncTrialWithServer({ force: true }).catch(() => void 0);
5629
5743
  }
5630
5744
  const info2 = buildTrialInfo(cached2, trustedTrialNow(cached2, now2));
5631
- return { info: info2, locked: info2.expired };
5745
+ return { info: info2, locked: info2.expired, lockReason: lockReasonFor(info2) };
5632
5746
  }
5633
5747
  }
5634
5748
  if (stored && (!currentDeviceId || !hasTrustedServerRecord(stored, secret, currentDeviceId))) {
@@ -5642,15 +5756,19 @@ async function resolveTrialState(now2 = Date.now(), options = {}) {
5642
5756
  startTrialSyncInBackground();
5643
5757
  }
5644
5758
  const info2 = buildTrialInfo(next, trustedTrialNow(next, now2));
5645
- return { info: info2, locked: info2.expired };
5759
+ return { info: info2, locked: info2.expired, lockReason: lockReasonFor(info2) };
5646
5760
  }
5647
5761
  if (options.refreshInBackground === true) {
5648
5762
  startTrialSyncInBackground();
5649
5763
  }
5650
5764
  if (!hadStoredTrial && options.refreshInBackground === true) {
5651
- return { info: null, locked: false };
5765
+ return { info: null, locked: false, lockReason: null };
5652
5766
  }
5653
- return { info: buildLockedTrialInfo(stored), locked: true };
5767
+ return {
5768
+ info: buildLockedTrialInfo(stored),
5769
+ locked: true,
5770
+ lockReason: "unverified"
5771
+ };
5654
5772
  }
5655
5773
  const refreshed = await syncAndPersistTrial({ stored, secret, now: now2 });
5656
5774
  if (!refreshed) {
@@ -5658,12 +5776,16 @@ async function resolveTrialState(now2 = Date.now(), options = {}) {
5658
5776
  const next = await persistLocalSeenIfNeeded(stored, secret, now2).catch(() => stored);
5659
5777
  rememberServerVerifiedTrial(next, now2);
5660
5778
  const info2 = buildTrialInfo(next, trustedTrialNow(next, now2));
5661
- return { info: info2, locked: info2.expired };
5779
+ return { info: info2, locked: info2.expired, lockReason: lockReasonFor(info2) };
5662
5780
  }
5663
- return { info: buildLockedTrialInfo(stored), locked: true };
5781
+ return {
5782
+ info: buildLockedTrialInfo(stored),
5783
+ locked: true,
5784
+ lockReason: "unverified"
5785
+ };
5664
5786
  }
5665
5787
  const info = buildTrialInfo(refreshed, trustedTrialNow(refreshed, now2));
5666
- return { info, locked: info.expired };
5788
+ return { info, locked: info.expired, lockReason: lockReasonFor(info) };
5667
5789
  }
5668
5790
  async function syncTrialWithServer(opts = {}) {
5669
5791
  if (!isTrialEnforcementEnabled()) {
@@ -5696,7 +5818,8 @@ var BASE_PRICE_DISPLAY = offer.basePriceDisplay;
5696
5818
  var PROMO_CODE = offer.couponCode;
5697
5819
  var PROMO_PERCENT = offer.discountPercent;
5698
5820
  var PROMO_ACTIVE = offer.isActive;
5699
- var LICENSE_MAX_USES = 5;
5821
+ var LICENSE_MAX_DEVICES = 5;
5822
+ var DEFAULT_ACTIVATION_API_URL = "https://api.codexuse.com/v1/activation";
5700
5823
  var FREE_PROFILE_LIMIT = 2;
5701
5824
  var LICENSE_REFRESH_INTERVAL_MS = 5 * 60 * 1e3;
5702
5825
  var MAX_NEXT_CHECK_MS = 60 * 60 * 1e3;
@@ -5764,7 +5887,7 @@ function isSignatureValid2(license, secret) {
5764
5887
  const expected = signLicense(license, secret);
5765
5888
  return expected === license.signature;
5766
5889
  }
5767
- async function requestGumroadVerify(licenseKey, mode) {
5890
+ async function requestGumroadVerify(licenseKey) {
5768
5891
  const controller = new AbortController();
5769
5892
  const timeout2 = setTimeout(() => controller.abort(), 1e4);
5770
5893
  try {
@@ -5772,7 +5895,7 @@ async function requestGumroadVerify(licenseKey, mode) {
5772
5895
  product_permalink: PRODUCT_PERMALINK,
5773
5896
  product_id: PRODUCT_ID,
5774
5897
  license_key: licenseKey,
5775
- increment_uses_count: mode === "activation" ? "true" : "false"
5898
+ increment_uses_count: "false"
5776
5899
  });
5777
5900
  const response = await fetch("https://api.gumroad.com/v2/licenses/verify", {
5778
5901
  method: "POST",
@@ -5804,6 +5927,41 @@ async function requestGumroadVerify(licenseKey, mode) {
5804
5927
  clearTimeout(timeout2);
5805
5928
  }
5806
5929
  }
5930
+ async function requestDeviceActivation(licenseKey) {
5931
+ const controller = new AbortController();
5932
+ const timeout2 = setTimeout(() => controller.abort(), 1e4);
5933
+ try {
5934
+ const baseUrl = (process.env.CODEXUSE_ACTIVATION_API_URL?.trim() || DEFAULT_ACTIVATION_API_URL).replace(/\/+$/, "");
5935
+ const response = await fetch(`${baseUrl}/device`, {
5936
+ method: "POST",
5937
+ headers: { "Content-Type": "application/json" },
5938
+ body: JSON.stringify({ licenseKey, deviceId: await getDeviceId() }),
5939
+ signal: controller.signal
5940
+ });
5941
+ const payload = await response.json().catch(() => null);
5942
+ if (!response.ok) {
5943
+ const message = typeof payload?.error === "string" && payload.error.trim() ? payload.error.trim() : `License activation failed (${response.status}).`;
5944
+ const code = response.status >= 500 ? "network" : isExplicitRevocationMessage(message) ? "revoked" : "invalid";
5945
+ throw new LicenseError(message, code);
5946
+ }
5947
+ return {
5948
+ email: typeof payload?.purchaseEmail === "string" ? payload.purchaseEmail.trim() || null : null
5949
+ };
5950
+ } catch (error) {
5951
+ if (error instanceof LicenseError) {
5952
+ throw error;
5953
+ }
5954
+ if (error instanceof Error && error.name === "AbortError") {
5955
+ throw new LicenseError("License activation timed out.", "network");
5956
+ }
5957
+ throw new LicenseError(
5958
+ error instanceof Error ? error.message : "Unable to reach the license server.",
5959
+ "network"
5960
+ );
5961
+ } finally {
5962
+ clearTimeout(timeout2);
5963
+ }
5964
+ }
5807
5965
  function isExplicitRevocationMessage(message) {
5808
5966
  if (!message) {
5809
5967
  return false;
@@ -5811,10 +5969,10 @@ function isExplicitRevocationMessage(message) {
5811
5969
  const normalized = message.toLowerCase();
5812
5970
  return normalized.includes("revoked") || normalized.includes("refunded") || normalized.includes("chargeback") || normalized.includes("disabled") || normalized.includes("subscription") || normalized.includes("no longer active");
5813
5971
  }
5814
- function normalizeVerificationResult(response, mode) {
5972
+ function normalizeVerificationResult(response) {
5815
5973
  if (!response.success) {
5816
5974
  const message = response.message ?? "License key is invalid.";
5817
- if (mode === "refresh" && !isExplicitRevocationMessage(message)) {
5975
+ if (!isExplicitRevocationMessage(message)) {
5818
5976
  throw new LicenseError(message, "network");
5819
5977
  }
5820
5978
  throw new LicenseError(message, "invalid");
@@ -5831,20 +5989,6 @@ function normalizeVerificationResult(response, mode) {
5831
5989
  const email = response.purchase.email ?? null;
5832
5990
  return { email };
5833
5991
  }
5834
- function ensureWithinUseLimit(response) {
5835
- if (!response.success) {
5836
- return;
5837
- }
5838
- if (typeof response.uses !== "number") {
5839
- return;
5840
- }
5841
- if (response.uses > LICENSE_MAX_USES) {
5842
- throw new LicenseError(
5843
- `This license has reached the activation limit (${LICENSE_MAX_USES}). Contact support to move it to another device.`,
5844
- "invalid"
5845
- );
5846
- }
5847
- }
5848
5992
  function computeCapabilities(opts) {
5849
5993
  return {
5850
5994
  unlimitedProfiles: opts.entitled,
@@ -5858,7 +6002,7 @@ function applyTrial(base2, trial) {
5858
6002
  if (base2.isPro) {
5859
6003
  return { ...base2, trial: null };
5860
6004
  }
5861
- const { info, locked } = trial;
6005
+ const { info, locked, lockReason } = trial;
5862
6006
  if (!info) {
5863
6007
  return base2;
5864
6008
  }
@@ -5878,6 +6022,10 @@ function applyTrial(base2, trial) {
5878
6022
  ...base2,
5879
6023
  tier: "free",
5880
6024
  state: "locked",
6025
+ // From the boundary that knows. The frontend used to read expiresAt and
6026
+ // call any lock an ended trial, but buildLockedTrialInfo keeps a stored
6027
+ // expiresAt that can be in the future.
6028
+ lockReason: lockReason ?? "unverified",
5881
6029
  capabilities: computeCapabilities({ licensed: false, entitled: false }),
5882
6030
  profileLimit: 0,
5883
6031
  profilesRemaining: 0,
@@ -5893,6 +6041,9 @@ function toLicenseStatus(stored, overrides = {}) {
5893
6041
  const base2 = {
5894
6042
  tier,
5895
6043
  state,
6044
+ // applyTrial sets this when it moves the state to "locked". Nothing else
6045
+ // locks, so nothing else has a reason.
6046
+ lockReason: null,
5896
6047
  isPro,
5897
6048
  capabilities: computeCapabilities({ licensed: isPro, entitled: isPro }),
5898
6049
  trial: null,
@@ -5912,7 +6063,7 @@ function toLicenseStatus(stored, overrides = {}) {
5912
6063
  basePriceDisplay: BASE_PRICE_DISPLAY,
5913
6064
  promoCode: PROMO_ACTIVE ? PROMO_CODE : null,
5914
6065
  promoPercent: PROMO_ACTIVE ? PROMO_PERCENT : null,
5915
- maxDevices: LICENSE_MAX_USES
6066
+ maxDevices: LICENSE_MAX_DEVICES
5916
6067
  };
5917
6068
  return { ...base2, ...overrides };
5918
6069
  }
@@ -5999,9 +6150,8 @@ var LicenseService = class {
5999
6150
  }
6000
6151
  const verify = async () => {
6001
6152
  try {
6002
- const result2 = await requestGumroadVerify(workingStored.licenseKey, "refresh");
6003
- ensureWithinUseLimit(result2);
6004
- const normalized = normalizeVerificationResult(result2, "refresh");
6153
+ const result2 = await requestGumroadVerify(workingStored.licenseKey);
6154
+ const normalized = normalizeVerificationResult(result2);
6005
6155
  const updated = {
6006
6156
  licenseKey: workingStored.licenseKey,
6007
6157
  purchaseEmail: normalized.email,
@@ -6058,9 +6208,7 @@ var LicenseService = class {
6058
6208
  }
6059
6209
  const secret = await getLicenseSecret();
6060
6210
  const digest = import_node_crypto7.default.createHash("sha256").update(trimmed).digest("hex");
6061
- const result2 = await requestGumroadVerify(trimmed, "activation");
6062
- ensureWithinUseLimit(result2);
6063
- const normalized = normalizeVerificationResult(result2, "activation");
6211
+ const normalized = await requestDeviceActivation(trimmed);
6064
6212
  const stored = {
6065
6213
  licenseKey: trimmed,
6066
6214
  purchaseEmail: normalized.email,
@@ -6120,7 +6268,7 @@ function shouldEnforceProfileLimit(status) {
6120
6268
  }
6121
6269
 
6122
6270
  // ../../packages/runtime-profiles/src/profiles/profile-manager.ts
6123
- var import_node_crypto12 = require("crypto");
6271
+ var import_node_crypto13 = require("crypto");
6124
6272
  var import_fs = require("fs");
6125
6273
  var import_node_os5 = __toESM(require("os"), 1);
6126
6274
  var import_path = __toESM(require("path"), 1);
@@ -6178,30 +6326,32 @@ function resolveProfileIdentityKeyFromProfile(profile) {
6178
6326
  }
6179
6327
 
6180
6328
  // ../../packages/runtime-codex/src/codex/rpc.ts
6181
- var import_node_child_process5 = require("child_process");
6182
- var import_node_crypto9 = require("crypto");
6329
+ var import_node_child_process6 = require("child_process");
6330
+ var import_node_crypto10 = require("crypto");
6183
6331
  var import_node_readline = __toESM(require("readline"), 1);
6184
6332
  var import_node_fs6 = require("fs");
6185
6333
  var import_node_os3 = __toESM(require("os"), 1);
6186
- var import_node_path9 = __toESM(require("path"), 1);
6334
+ var import_node_path10 = __toESM(require("path"), 1);
6187
6335
 
6188
6336
  // ../../packages/runtime-codex/src/codex/cli.ts
6337
+ var import_node_child_process3 = require("child_process");
6189
6338
  var import_node_fs4 = require("fs");
6190
- var import_node_path4 = __toESM(require("path"), 1);
6339
+ var import_node_path5 = __toESM(require("path"), 1);
6191
6340
  var STABLE_CHANNEL = "stable";
6192
6341
  var ENV_HINTS = ["CODEX_BINARY", "CODEX_CLI_PATH", "CODEX_PATH"];
6193
6342
  var cachedStatus = null;
6343
+ var cachedVersion = null;
6194
6344
  function getPathHintEntries() {
6195
6345
  const homeDir = process.env.HOME ?? "";
6196
6346
  const homeEntries = homeDir ? [
6197
- import_node_path4.default.join(homeDir, ".local", "bin"),
6198
- import_node_path4.default.join(homeDir, ".fnm", "aliases", "default", "bin"),
6199
- import_node_path4.default.join(homeDir, ".fnm", "current", "bin"),
6200
- import_node_path4.default.join(homeDir, ".volta", "bin"),
6201
- import_node_path4.default.join(homeDir, ".asdf", "shims"),
6202
- import_node_path4.default.join(homeDir, ".bun", "bin")
6347
+ import_node_path5.default.join(homeDir, ".local", "bin"),
6348
+ import_node_path5.default.join(homeDir, ".fnm", "aliases", "default", "bin"),
6349
+ import_node_path5.default.join(homeDir, ".fnm", "current", "bin"),
6350
+ import_node_path5.default.join(homeDir, ".volta", "bin"),
6351
+ import_node_path5.default.join(homeDir, ".asdf", "shims"),
6352
+ import_node_path5.default.join(homeDir, ".bun", "bin")
6203
6353
  ] : [];
6204
- const configuredHints = (process.env.CODEX_PATH_HINTS ?? "").split(import_node_path4.default.delimiter).map((entry) => entry.trim()).filter(Boolean);
6354
+ const configuredHints = (process.env.CODEX_PATH_HINTS ?? "").split(import_node_path5.default.delimiter).map((entry) => entry.trim()).filter(Boolean);
6205
6355
  return [
6206
6356
  "/opt/homebrew/bin",
6207
6357
  "/usr/local/bin",
@@ -6213,7 +6363,7 @@ function fileExists(candidate) {
6213
6363
  if (!candidate) {
6214
6364
  return null;
6215
6365
  }
6216
- const normalized = import_node_path4.default.resolve(candidate);
6366
+ const normalized = import_node_path5.default.resolve(candidate);
6217
6367
  try {
6218
6368
  const stats = (0, import_node_fs4.statSync)(normalized);
6219
6369
  if (stats.isFile()) {
@@ -6242,12 +6392,12 @@ function resolveCodexFromPath() {
6242
6392
  new Set(
6243
6393
  [
6244
6394
  ...getPathHintEntries(),
6245
- ...pathValue.split(import_node_path4.default.delimiter).map((entry) => entry.trim()).filter(Boolean)
6395
+ ...pathValue.split(import_node_path5.default.delimiter).map((entry) => entry.trim()).filter(Boolean)
6246
6396
  ].filter(Boolean)
6247
6397
  )
6248
6398
  );
6249
6399
  for (const entry of entries3) {
6250
- const candidate = fileExists(import_node_path4.default.join(entry, "codex"));
6400
+ const candidate = fileExists(import_node_path5.default.join(entry, "codex"));
6251
6401
  if (candidate) {
6252
6402
  return candidate;
6253
6403
  }
@@ -6289,8 +6439,59 @@ function evaluateExternalStatus() {
6289
6439
  function evaluateCodexCliStatus() {
6290
6440
  return evaluateExternalStatus();
6291
6441
  }
6442
+ function runVersionPreflight(cliPath) {
6443
+ return new Promise((resolve2) => {
6444
+ const useNode = /\.(?:c|m)?js$/i.test(cliPath);
6445
+ const child = (0, import_node_child_process3.spawn)(
6446
+ useNode ? process.execPath : cliPath,
6447
+ useNode ? [cliPath, "--version"] : ["--version"],
6448
+ {
6449
+ env: process.env,
6450
+ stdio: ["ignore", "pipe", "pipe"]
6451
+ }
6452
+ );
6453
+ let output = "";
6454
+ let settled = false;
6455
+ const finish = (version) => {
6456
+ if (settled) {
6457
+ return;
6458
+ }
6459
+ settled = true;
6460
+ clearTimeout(timeout2);
6461
+ resolve2(version);
6462
+ };
6463
+ const collect = (chunk) => {
6464
+ if (output.length < 1024) {
6465
+ output += chunk.toString();
6466
+ }
6467
+ };
6468
+ child.stdout?.on("data", collect);
6469
+ child.stderr?.on("data", collect);
6470
+ child.on("error", () => finish(null));
6471
+ child.on("close", (code) => {
6472
+ const trimmed = output.trim();
6473
+ const version = trimmed.match(/\b\d+\.\d+\.\d+(?:[-+][\w.-]+)?\b/)?.[0] ?? null;
6474
+ finish(code === 0 ? version : null);
6475
+ });
6476
+ const timeout2 = setTimeout(() => {
6477
+ child.kill();
6478
+ finish(null);
6479
+ }, 5e3);
6480
+ });
6481
+ }
6292
6482
  async function refreshCodexStatus() {
6293
- cachedStatus = evaluateCodexCliStatus();
6483
+ const discovered = evaluateCodexCliStatus();
6484
+ cachedVersion = null;
6485
+ if (discovered.available && discovered.path) {
6486
+ cachedVersion = await runVersionPreflight(discovered.path);
6487
+ cachedStatus = cachedVersion ? discovered : {
6488
+ ...discovered,
6489
+ available: false,
6490
+ reason: "Codex CLI was found but cannot run. Repair the Codex CLI, then try again."
6491
+ };
6492
+ } else {
6493
+ cachedStatus = discovered;
6494
+ }
6294
6495
  return { ...cachedStatus };
6295
6496
  }
6296
6497
  var CodexCliMissingError = class extends Error {
@@ -6310,8 +6511,8 @@ async function requireCodexCli() {
6310
6511
  }
6311
6512
 
6312
6513
  // ../../packages/runtime-codex/src/codex/command.ts
6313
- var import_node_child_process3 = require("child_process");
6314
- var import_node_path5 = __toESM(require("path"), 1);
6514
+ var import_node_child_process4 = require("child_process");
6515
+ var import_node_path6 = __toESM(require("path"), 1);
6315
6516
  var cachedNodeRuntime = null;
6316
6517
  function isJavaScriptEntrypoint(binaryPath) {
6317
6518
  const normalized = binaryPath.trim().toLowerCase();
@@ -6327,19 +6528,19 @@ function resolveNodeRuntime(env) {
6327
6528
  }
6328
6529
  const runtimeEnv = { ...process.env, ...env };
6329
6530
  const homeDir = runtimeEnv.HOME ?? "";
6330
- const pathHints = (runtimeEnv.CODEX_PATH_HINTS ?? process.env.CODEX_PATH_HINTS ?? "").split(import_node_path5.default.delimiter).map((entry) => entry.trim()).filter(Boolean);
6531
+ const pathHints = (runtimeEnv.CODEX_PATH_HINTS ?? process.env.CODEX_PATH_HINTS ?? "").split(import_node_path6.default.delimiter).map((entry) => entry.trim()).filter(Boolean);
6331
6532
  const extraPathEntries = [
6332
6533
  "/usr/local/bin",
6333
6534
  "/opt/homebrew/bin",
6334
- import_node_path5.default.join(homeDir, ".local", "bin"),
6335
- import_node_path5.default.join(homeDir, ".fnm", "aliases", "default", "bin"),
6336
- import_node_path5.default.join(homeDir, ".fnm", "current", "bin"),
6535
+ import_node_path6.default.join(homeDir, ".local", "bin"),
6536
+ import_node_path6.default.join(homeDir, ".fnm", "aliases", "default", "bin"),
6537
+ import_node_path6.default.join(homeDir, ".fnm", "current", "bin"),
6337
6538
  ...pathHints
6338
6539
  ].filter(Boolean);
6339
6540
  const currentPath = runtimeEnv.PATH ?? "";
6340
6541
  runtimeEnv.PATH = Array.from(
6341
- /* @__PURE__ */ new Set([...extraPathEntries, ...currentPath.split(import_node_path5.default.delimiter).filter(Boolean)])
6342
- ).join(import_node_path5.default.delimiter);
6542
+ /* @__PURE__ */ new Set([...extraPathEntries, ...currentPath.split(import_node_path6.default.delimiter).filter(Boolean)])
6543
+ ).join(import_node_path6.default.delimiter);
6343
6544
  const candidates = Array.from(
6344
6545
  new Set(
6345
6546
  [
@@ -6353,7 +6554,7 @@ function resolveNodeRuntime(env) {
6353
6554
  )
6354
6555
  );
6355
6556
  for (const candidate of candidates) {
6356
- const probe = (0, import_node_child_process3.spawnSync)(candidate, ["-v"], { env: runtimeEnv, stdio: "ignore" });
6557
+ const probe = (0, import_node_child_process4.spawnSync)(candidate, ["-v"], { env: runtimeEnv, stdio: "ignore" });
6357
6558
  if (!probe.error && probe.status === 0) {
6358
6559
  cachedNodeRuntime = candidate;
6359
6560
  return candidate;
@@ -6382,7 +6583,7 @@ var import_node_crypto8 = require("crypto");
6382
6583
  var import_node_fs5 = require("fs");
6383
6584
  var import_promises2 = require("fs/promises");
6384
6585
  var import_node_os2 = __toESM(require("os"), 1);
6385
- var import_node_path6 = __toESM(require("path"), 1);
6586
+ var import_node_path7 = __toESM(require("path"), 1);
6386
6587
  function resolveHomeDir() {
6387
6588
  return process.env.HOME || import_node_os2.default.homedir();
6388
6589
  }
@@ -6391,7 +6592,7 @@ function expandHomePrefix(input, homeDir) {
6391
6592
  return homeDir;
6392
6593
  }
6393
6594
  if (input.startsWith("~/") || input.startsWith("~\\")) {
6394
- return import_node_path6.default.join(homeDir, input.slice(2));
6595
+ return import_node_path7.default.join(homeDir, input.slice(2));
6395
6596
  }
6396
6597
  return input;
6397
6598
  }
@@ -6407,23 +6608,23 @@ function normalizeCodexHomePath(input) {
6407
6608
  if (!configured) {
6408
6609
  return null;
6409
6610
  }
6410
- return import_node_path6.default.resolve(expandHomePrefix(configured, resolveHomeDir()));
6611
+ return import_node_path7.default.resolve(expandHomePrefix(configured, resolveHomeDir()));
6411
6612
  }
6412
6613
  function resolveDefaultCodexHomeDir() {
6413
- return normalizeCodexHomePath(process.env.CODEX_HOME) ?? import_node_path6.default.join(resolveHomeDir(), ".codex");
6614
+ return normalizeCodexHomePath(process.env.CODEX_HOME) ?? import_node_path7.default.join(resolveHomeDir(), ".codex");
6414
6615
  }
6415
6616
  function resolveCodexSqliteHomeDir(codexHomePath) {
6416
6617
  return normalizeCodexHomePath(process.env.CODEX_SQLITE_HOME) ?? resolveCodexHomeDir({ codexHomePath });
6417
6618
  }
6418
6619
  function resolveCurrentProfileCodexHomeDir(profileHomeId) {
6419
- return import_node_path6.default.join(
6620
+ return import_node_path7.default.join(
6420
6621
  resolveProfileCodexHomesRoot(),
6421
6622
  (0, import_node_crypto8.createHash)("sha256").update(profileHomeId).digest("hex").slice(0, 20)
6422
6623
  );
6423
6624
  }
6424
6625
  function resolveProfileCodexHomeDir(profileHomeId) {
6425
6626
  const current = resolveCurrentProfileCodexHomeDir(profileHomeId);
6426
- const legacy = import_node_path6.default.join(resolveLegacyProfileCodexHomesRoot(), profileHomeId);
6627
+ const legacy = import_node_path7.default.join(resolveLegacyProfileCodexHomesRoot(), profileHomeId);
6427
6628
  const currentExists = (0, import_node_fs5.existsSync)(current);
6428
6629
  const legacyExists = (0, import_node_fs5.existsSync)(legacy);
6429
6630
  if (currentExists && legacyExists) {
@@ -6433,15 +6634,15 @@ function resolveProfileCodexHomeDir(profileHomeId) {
6433
6634
  }
6434
6635
  function findProfileCodexHomeLocationConflict(profileHomeId) {
6435
6636
  const current = resolveCurrentProfileCodexHomeDir(profileHomeId);
6436
- const legacy = import_node_path6.default.join(resolveLegacyProfileCodexHomesRoot(), profileHomeId);
6637
+ const legacy = import_node_path7.default.join(resolveLegacyProfileCodexHomesRoot(), profileHomeId);
6437
6638
  return (0, import_node_fs5.existsSync)(current) && (0, import_node_fs5.existsSync)(legacy) ? { current, legacy } : null;
6438
6639
  }
6439
6640
  function resolveProfileCodexHomesRoot() {
6440
- return import_node_path6.default.join(resolveHomeDir(), ".codexuse", "p");
6641
+ return import_node_path7.default.join(resolveHomeDir(), ".codexuse", "p");
6441
6642
  }
6442
6643
  async function ensureProfileCodexHomesRoot() {
6443
6644
  const root = resolveProfileCodexHomesRoot();
6444
- const parent = import_node_path6.default.dirname(root);
6645
+ const parent = import_node_path7.default.dirname(root);
6445
6646
  await (0, import_promises2.mkdir)(parent, { recursive: true, mode: 448 });
6446
6647
  await (0, import_promises2.mkdir)(root, { recursive: true, mode: 448 });
6447
6648
  if (process.platform !== "win32") {
@@ -6451,10 +6652,10 @@ async function ensureProfileCodexHomesRoot() {
6451
6652
  return root;
6452
6653
  }
6453
6654
  function resolveLegacyProfileCodexHomesRoot() {
6454
- return import_node_path6.default.join(getUserDataDir(), "profile-homes");
6655
+ return import_node_path7.default.join(getUserDataDir(), "profile-homes");
6455
6656
  }
6456
6657
  async function migrateProfileCodexHomeDir(profileHomeId) {
6457
- const legacy = import_node_path6.default.join(resolveLegacyProfileCodexHomesRoot(), profileHomeId);
6658
+ const legacy = import_node_path7.default.join(resolveLegacyProfileCodexHomesRoot(), profileHomeId);
6458
6659
  const current = resolveCurrentProfileCodexHomeDir(profileHomeId);
6459
6660
  const currentExists = (0, import_node_fs5.existsSync)(current);
6460
6661
  const legacyExists = (0, import_node_fs5.existsSync)(legacy);
@@ -6531,9 +6732,9 @@ function buildCodexChildEnv(overrides = {}) {
6531
6732
  var import_toml = __toESM(require_toml(), 1);
6532
6733
 
6533
6734
  // ../../packages/runtime-codex/src/codex/config-metadata.ts
6534
- var import_node_child_process4 = require("child_process");
6735
+ var import_node_child_process5 = require("child_process");
6535
6736
  var import_promises3 = require("fs/promises");
6536
- var import_node_path7 = __toESM(require("path"), 1);
6737
+ var import_node_path8 = __toESM(require("path"), 1);
6537
6738
  var CONFIG_SCHEMA_URL = "https://raw.githubusercontent.com/openai/codex/main/codex-rs/core/config.schema.json";
6538
6739
  var METADATA_CACHE_TTL_MS = 6e4;
6539
6740
  var FALLBACK_SCHEMA_TOP_LEVEL_KEYS = [
@@ -6643,7 +6844,7 @@ function uniqueSorted(values2) {
6643
6844
  }
6644
6845
  async function runCommand(command, args2, timeoutMs = 3e3) {
6645
6846
  return new Promise((resolve2, reject) => {
6646
- const child = (0, import_node_child_process4.spawn)(command, args2, {
6847
+ const child = (0, import_node_child_process5.spawn)(command, args2, {
6647
6848
  stdio: ["ignore", "pipe", "pipe"],
6648
6849
  env: buildCodexChildEnv()
6649
6850
  });
@@ -6719,8 +6920,8 @@ function parseSchemaKeys(schemaRaw) {
6719
6920
  async function readSchemaFromLocal() {
6720
6921
  const candidates = [
6721
6922
  process.env.CODEX_CONFIG_SCHEMA_PATH,
6722
- import_node_path7.default.join(process.cwd(), "codex-rs", "core", "config.schema.json"),
6723
- import_node_path7.default.join(process.cwd(), "node_modules", "@openai", "codex", "codex-rs", "core", "config.schema.json")
6923
+ import_node_path8.default.join(process.cwd(), "codex-rs", "core", "config.schema.json"),
6924
+ import_node_path8.default.join(process.cwd(), "node_modules", "@openai", "codex", "codex-rs", "core", "config.schema.json")
6724
6925
  ].filter((candidate) => Boolean(candidate));
6725
6926
  for (const candidate of candidates) {
6726
6927
  try {
@@ -6824,8 +7025,9 @@ async function getCodexConfigMetadata(forceRefresh = false) {
6824
7025
  }
6825
7026
 
6826
7027
  // ../../packages/runtime-codex/src/codex/config-io.ts
7028
+ var import_node_crypto9 = require("crypto");
6827
7029
  var import_promises4 = require("fs/promises");
6828
- var import_node_path8 = __toESM(require("path"), 1);
7030
+ var import_node_path9 = __toESM(require("path"), 1);
6829
7031
 
6830
7032
  // ../../packages/runtime-codex/src/codex/config-presets.ts
6831
7033
  var DEFAULT_CONFIG_TEMPLATE = [
@@ -6868,12 +7070,55 @@ var YOLO_PRESET = {
6868
7070
 
6869
7071
  // ../../packages/runtime-codex/src/codex/config-io.ts
6870
7072
  function getConfigPath(options) {
6871
- return import_node_path8.default.join(resolveCodexHomeDir(options), "config.toml");
7073
+ return import_node_path9.default.join(resolveCodexHomeDir(options), "config.toml");
6872
7074
  }
6873
7075
  async function ensureConfigDirExists(filePath) {
6874
- const dir = import_node_path8.default.dirname(filePath);
7076
+ const dir = import_node_path9.default.dirname(filePath);
6875
7077
  await (0, import_promises4.mkdir)(dir, { recursive: true });
6876
7078
  }
7079
+ async function resolveConfigWriteTarget(configPath) {
7080
+ try {
7081
+ if (!(await (0, import_promises4.lstat)(configPath)).isSymbolicLink()) {
7082
+ return configPath;
7083
+ }
7084
+ try {
7085
+ return await (0, import_promises4.realpath)(configPath);
7086
+ } catch (error) {
7087
+ if (error.code !== "ENOENT") {
7088
+ throw error;
7089
+ }
7090
+ return import_node_path9.default.resolve(import_node_path9.default.dirname(configPath), await (0, import_promises4.readlink)(configPath));
7091
+ }
7092
+ } catch (error) {
7093
+ if (error.code === "ENOENT") {
7094
+ return configPath;
7095
+ }
7096
+ throw error;
7097
+ }
7098
+ }
7099
+ async function removeStaleConfigStagingFiles(targetPath) {
7100
+ const directory = import_node_path9.default.dirname(targetPath);
7101
+ const prefix = `${import_node_path9.default.basename(targetPath)}.tmp-`;
7102
+ const entries3 = await (0, import_promises4.readdir)(directory).catch((error) => {
7103
+ if (error.code === "ENOENT") {
7104
+ return [];
7105
+ }
7106
+ throw error;
7107
+ });
7108
+ await Promise.all(
7109
+ entries3.filter((entry) => entry.startsWith(prefix)).map((entry) => (0, import_promises4.rm)(import_node_path9.default.join(directory, entry), { force: true }))
7110
+ );
7111
+ }
7112
+ async function resolveConfigWriteMode(targetPath) {
7113
+ try {
7114
+ return (await (0, import_promises4.stat)(targetPath)).mode & 511;
7115
+ } catch (error) {
7116
+ if (error.code === "ENOENT") {
7117
+ return 384;
7118
+ }
7119
+ throw error;
7120
+ }
7121
+ }
6877
7122
  function normalizeLineEndings(content) {
6878
7123
  return content.replace(/\r\n/g, "\n");
6879
7124
  }
@@ -6882,29 +7127,76 @@ function ensureTrailingNewline(content) {
6882
7127
  `;
6883
7128
  }
6884
7129
  async function readConfigContent(options) {
6885
- const configPath = getConfigPath(options);
6886
- try {
6887
- const content = await (0, import_promises4.readFile)(configPath, "utf8");
6888
- return {
6889
- exists: true,
6890
- content: normalizeLineEndings(content)
6891
- };
6892
- } catch (error) {
6893
- const nodeError = error;
6894
- if (nodeError.code === "ENOENT") {
7130
+ return withCloudSyncTransaction(getUserDataDir(), "read", async () => {
7131
+ const configPath = getConfigPath(options);
7132
+ try {
7133
+ const content = await (0, import_promises4.readFile)(configPath, "utf8");
6895
7134
  return {
6896
- exists: false,
6897
- content: DEFAULT_CONFIG_TEMPLATE
7135
+ exists: true,
7136
+ content: normalizeLineEndings(content)
6898
7137
  };
7138
+ } catch (error) {
7139
+ const nodeError = error;
7140
+ if (nodeError.code === "ENOENT") {
7141
+ return {
7142
+ exists: false,
7143
+ content: DEFAULT_CONFIG_TEMPLATE
7144
+ };
7145
+ }
7146
+ throw error;
6899
7147
  }
6900
- throw error;
6901
- }
7148
+ });
6902
7149
  }
6903
7150
  async function writeConfigContent(content, options) {
6904
- const configPath = getConfigPath(options);
6905
- await ensureConfigDirExists(configPath);
6906
- const normalized = ensureTrailingNewline(normalizeLineEndings(content));
6907
- await (0, import_promises4.writeFile)(configPath, normalized, "utf8");
7151
+ await withCloudSyncTransaction(getUserDataDir(), "write", async () => {
7152
+ const configPath = getConfigPath(options);
7153
+ await ensureConfigDirExists(configPath);
7154
+ const targetPath = await resolveConfigWriteTarget(configPath);
7155
+ await removeStaleConfigStagingFiles(targetPath);
7156
+ const mode = await resolveConfigWriteMode(targetPath);
7157
+ const normalized = ensureTrailingNewline(normalizeLineEndings(content));
7158
+ const stagingPath = `${targetPath}.tmp-${process.pid}-${(0, import_node_crypto9.randomUUID)()}`;
7159
+ try {
7160
+ const handle = await (0, import_promises4.open)(stagingPath, "wx", mode);
7161
+ try {
7162
+ await handle.writeFile(normalized, "utf8");
7163
+ await handle.sync();
7164
+ } finally {
7165
+ await handle.close();
7166
+ }
7167
+ await (0, import_promises4.rename)(stagingPath, targetPath);
7168
+ if (process.platform !== "win32") {
7169
+ await (0, import_promises4.chmod)(targetPath, mode);
7170
+ const directory = await (0, import_promises4.open)(import_node_path9.default.dirname(targetPath), "r");
7171
+ try {
7172
+ await directory.sync();
7173
+ } finally {
7174
+ await directory.close();
7175
+ }
7176
+ }
7177
+ } finally {
7178
+ await (0, import_promises4.rm)(stagingPath, { force: true });
7179
+ }
7180
+ });
7181
+ }
7182
+ async function removeConfigContent(options) {
7183
+ await withCloudSyncTransaction(getUserDataDir(), "write", async () => {
7184
+ const configPath = getConfigPath(options);
7185
+ try {
7186
+ await (0, import_promises4.unlink)(configPath);
7187
+ } catch (error) {
7188
+ if (error.code === "ENOENT") {
7189
+ return;
7190
+ }
7191
+ throw error;
7192
+ }
7193
+ const directory = await (0, import_promises4.open)(import_node_path9.default.dirname(configPath), "r");
7194
+ try {
7195
+ await directory.sync();
7196
+ } finally {
7197
+ await directory.close();
7198
+ }
7199
+ });
6908
7200
  }
6909
7201
  async function getUpdatedAt(configPath, exists) {
6910
7202
  if (!exists) {
@@ -6922,191 +7214,6 @@ async function getUpdatedAt(configPath, exists) {
6922
7214
  }
6923
7215
  }
6924
7216
 
6925
- // ../../packages/shared/src/core/errors.ts
6926
- var ANSI_PATTERN = /\u001B\[[0-9;]*m/g;
6927
- function stripAnsi(value3) {
6928
- return value3.replace(ANSI_PATTERN, "");
6929
- }
6930
- function normalizeWhitespace(value3) {
6931
- return value3.replace(/\s+/g, " ").trim();
6932
- }
6933
- function compactErrorText(value3, maxLength = 220) {
6934
- if (!value3) {
6935
- return "";
6936
- }
6937
- const cleaned = normalizeWhitespace(stripAnsi(String(value3)));
6938
- if (!cleaned) {
6939
- return "";
6940
- }
6941
- if (cleaned.length <= maxLength) {
6942
- return cleaned;
6943
- }
6944
- return `${cleaned.slice(0, maxLength).trimEnd()}\u2026`;
6945
- }
6946
- function createErrorReferenceId() {
6947
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`.toUpperCase();
6948
- }
6949
- function serializeUnknownError(value3) {
6950
- if (typeof value3 === "string") {
6951
- return value3;
6952
- }
6953
- if (value3 instanceof Error) {
6954
- return value3.stack ?? value3.message;
6955
- }
6956
- try {
6957
- return JSON.stringify(value3);
6958
- } catch {
6959
- return String(value3);
6960
- }
6961
- }
6962
- function extractRawMessage(error) {
6963
- if (error === null || typeof error === "undefined") {
6964
- return "";
6965
- }
6966
- if (typeof error === "string") {
6967
- return error;
6968
- }
6969
- if (error instanceof Error) {
6970
- return error.message;
6971
- }
6972
- return String(error);
6973
- }
6974
- function normalizeRawMessage(rawMessage) {
6975
- let cleaned = normalizeWhitespace(stripAnsi(rawMessage));
6976
- if (!cleaned) {
6977
- return "";
6978
- }
6979
- if (cleaned.startsWith("Error invoking remote method")) {
6980
- cleaned = cleaned.replace(/^Error invoking remote method '[^']+': Error: /, "");
6981
- }
6982
- if (cleaned.toLowerCase().includes("openai codex") && cleaned.toLowerCase().includes("workdir:")) {
6983
- const parts = cleaned.split(/error:/i);
6984
- if (parts.length > 1) {
6985
- return parts[parts.length - 1]?.trim() ?? cleaned;
6986
- }
6987
- }
6988
- return cleaned;
6989
- }
6990
- function resolveCategory(cleaned, options) {
6991
- const lower = cleaned.toLowerCase();
6992
- if (options.notFoundFallback && (lower.includes("enoent") || lower.includes("not found"))) {
6993
- return {
6994
- code: "ERR_NOT_FOUND",
6995
- title: "We couldn't find that item",
6996
- message: options.notFoundFallback,
6997
- recovery: "Check the path or selection, then try again.",
6998
- retryable: true
6999
- };
7000
- }
7001
- if (lower.includes("rate limit") || lower.includes("quota exceeded") || lower.includes("too many requests") || lower.includes("429")) {
7002
- return {
7003
- code: "ERR_RATE_LIMIT",
7004
- title: "Rate limit reached",
7005
- message: "The provider is rate limited right now.",
7006
- recovery: "Wait a moment, switch profiles, or try again.",
7007
- retryable: true
7008
- };
7009
- }
7010
- if (lower.includes("timeout") || lower.includes("timed out")) {
7011
- return {
7012
- code: "ERR_TIMEOUT",
7013
- title: "Request timed out",
7014
- message: "The operation took too long to finish.",
7015
- recovery: "Check the connection and try again.",
7016
- retryable: true
7017
- };
7018
- }
7019
- if (lower.includes("network") || lower.includes("econn") || lower.includes("networkerror") || lower.includes("connection refused") || lower.includes("socket hang up")) {
7020
- return {
7021
- code: "ERR_NETWORK",
7022
- title: "Can't reach the service",
7023
- message: "CodexUse couldn't connect to the required service.",
7024
- recovery: "Check your internet or local server connection, then retry.",
7025
- retryable: true
7026
- };
7027
- }
7028
- if (lower.includes("token_invalidated") || lower.includes("session invalidated") || lower.includes("session expired") || lower.includes("refresh token") || lower.includes("unauthorized") || lower.includes("401")) {
7029
- return {
7030
- code: "ERR_AUTH",
7031
- title: "Sign-in expired",
7032
- message: "This account needs to sign in again.",
7033
- recovery: "Reconnect the profile, then retry the action.",
7034
- retryable: true
7035
- };
7036
- }
7037
- if (lower.includes("permission") || lower.includes("eacces") || lower.includes("operation not permitted")) {
7038
- return {
7039
- code: "ERR_PERMISSION",
7040
- title: "Permission denied",
7041
- message: "CodexUse doesn't have permission to do that.",
7042
- recovery: "Check the file permissions or restart the app and try again.",
7043
- retryable: true
7044
- };
7045
- }
7046
- if (lower.includes("enospc") || lower.includes("disk full") || lower.includes("no space left")) {
7047
- return {
7048
- code: "ERR_DISK_FULL",
7049
- title: "Disk is full",
7050
- message: "CodexUse couldn't save data because the disk is full.",
7051
- recovery: "Free up disk space, then try again.",
7052
- retryable: true
7053
- };
7054
- }
7055
- if (lower.includes("codex cli") || lower.includes("command not found") || lower.includes("spawn codex") || lower.includes("could not find codex")) {
7056
- return {
7057
- code: "ERR_CLI_UNAVAILABLE",
7058
- title: "Codex CLI unavailable",
7059
- message: "CodexUse couldn't start the Codex CLI.",
7060
- recovery: "Check Runtime > Codex and confirm the CLI is installed correctly.",
7061
- retryable: true
7062
- };
7063
- }
7064
- if (lower.includes("provider") || lower.includes("model") || lower.includes("openai") || lower.includes("anthropic")) {
7065
- return {
7066
- code: "ERR_PROVIDER",
7067
- title: "Provider request failed",
7068
- message: "The AI provider rejected or failed the request.",
7069
- recovery: "Try again, or switch the active profile or model.",
7070
- retryable: true
7071
- };
7072
- }
7073
- return {
7074
- code: "ERR_UNKNOWN",
7075
- title: "That did not work",
7076
- message: options.fallback,
7077
- recovery: "Try again. If it keeps happening, report the error with the reference below.",
7078
- retryable: true
7079
- };
7080
- }
7081
- function resolveUserFacingError(error, options = {}) {
7082
- const fallback = options.fallback ?? "That action did not complete.";
7083
- const rawMessage = extractRawMessage(error);
7084
- const cleaned = normalizeRawMessage(rawMessage);
7085
- const category = resolveCategory(cleaned, {
7086
- fallback,
7087
- ...options.notFoundFallback ? { notFoundFallback: options.notFoundFallback } : {}
7088
- });
7089
- return {
7090
- ...category,
7091
- referenceId: createErrorReferenceId(),
7092
- technicalMessage: compactErrorText(cleaned || rawMessage || fallback, 400),
7093
- technicalDetails: compactErrorText(serializeUnknownError(error), 4e3)
7094
- };
7095
- }
7096
- function formatUserFacingError(error, options = {}) {
7097
- const info = resolveUserFacingError(error, options);
7098
- const maxLength = typeof options.maxLength === "number" ? options.maxLength : 220;
7099
- const withRecovery = info.recovery && !/try again/i.test(info.message) ? `${info.message} ${info.recovery}` : info.message;
7100
- if (withRecovery.length <= maxLength) {
7101
- return withRecovery;
7102
- }
7103
- let cleaned = info.message;
7104
- if (cleaned.length > maxLength) {
7105
- cleaned = `${cleaned.slice(0, maxLength).trimEnd()}\u2026`;
7106
- }
7107
- return cleaned;
7108
- }
7109
-
7110
7217
  // ../../packages/runtime-codex/src/codex/config.ts
7111
7218
  function tryParseToml(content) {
7112
7219
  try {
@@ -7114,14 +7221,10 @@ function tryParseToml(content) {
7114
7221
  return { data: parsed ?? {}, error: null };
7115
7222
  } catch (error) {
7116
7223
  const maybe = error;
7117
- const line = typeof maybe?.line === "number" ? maybe.line : null;
7118
- const column = typeof maybe?.column === "number" ? maybe.column : typeof maybe?.col === "number" ? maybe.col : null;
7224
+ const line = typeof maybe?.line === "number" ? maybe.line + 1 : null;
7225
+ const column = typeof maybe?.col === "number" ? maybe.col + 1 : null;
7119
7226
  const location = line !== null ? `line ${line}${column !== null ? `, column ${column}` : ""}` : null;
7120
- const friendly = formatUserFacingError(error, {
7121
- fallback: "Invalid config.toml syntax. Fix it and try again.",
7122
- maxLength: 180
7123
- });
7124
- const message = location ? `${friendly} (near ${location}).` : friendly;
7227
+ const message = location ? `Invalid config.toml syntax near ${location}. Fix it and try again.` : "Invalid config.toml syntax. Fix it and try again.";
7125
7228
  return { data: null, error: message };
7126
7229
  }
7127
7230
  }
@@ -7419,12 +7522,16 @@ async function getCodexConfigSnapshot(options) {
7419
7522
  const { content, exists } = await readConfigContent(options);
7420
7523
  return buildSnapshot(content, exists, options);
7421
7524
  }
7422
- async function saveCodexConfigContent(content, options) {
7525
+ function assertValidCodexConfigContent(content) {
7423
7526
  const normalized = ensureTrailingNewline(normalizeLineEndings(content));
7424
7527
  const parsed = tryParseToml(normalized);
7425
7528
  if (!parsed.data) {
7426
7529
  throw new Error(parsed.error ?? "config.toml contains invalid TOML syntax.");
7427
7530
  }
7531
+ return normalized;
7532
+ }
7533
+ async function saveCodexConfigContent(content, options) {
7534
+ const normalized = assertValidCodexConfigContent(content);
7428
7535
  await writeConfigContent(normalized, options);
7429
7536
  return buildSnapshot(normalized, true, options);
7430
7537
  }
@@ -8108,8 +8215,8 @@ var CIRCULAR = "[Circular]";
8108
8215
  function formatPropertyKey(name) {
8109
8216
  return typeof name === "string" ? JSON.stringify(name) : String(name);
8110
8217
  }
8111
- function formatPath(path19) {
8112
- return path19.map((key) => `[${formatPropertyKey(key)}]`).join("");
8218
+ function formatPath(path21) {
8219
+ return path21.map((key) => `[${formatPropertyKey(key)}]`).join("");
8113
8220
  }
8114
8221
  function formatDate(date) {
8115
8222
  try {
@@ -11620,9 +11727,9 @@ var Pointer = class extends Base {
11620
11727
  * The issue that occurred.
11621
11728
  */
11622
11729
  issue;
11623
- constructor(path19, issue) {
11730
+ constructor(path21, issue) {
11624
11731
  super();
11625
- this.path = path19;
11732
+ this.path = path21;
11626
11733
  this.issue = issue;
11627
11734
  }
11628
11735
  };
@@ -11807,43 +11914,43 @@ function getExpectedMessage(expected, issue) {
11807
11914
  const input = formatInput(issue);
11808
11915
  return input === void 0 ? `Expected ${expected}` : `Expected ${expected}, got ${input}`;
11809
11916
  }
11810
- function toDefaultIssues(issue, path19, leafHook, checkHook) {
11917
+ function toDefaultIssues(issue, path21, leafHook, checkHook) {
11811
11918
  switch (issue._tag) {
11812
11919
  case "Filter": {
11813
11920
  const message = checkHook(issue);
11814
11921
  if (message !== void 0) {
11815
11922
  return [{
11816
- path: path19,
11923
+ path: path21,
11817
11924
  message
11818
11925
  }];
11819
11926
  }
11820
11927
  if (issue.issue._tag !== "InvalidValue") {
11821
- return toDefaultIssues(issue.issue, path19, leafHook, checkHook);
11928
+ return toDefaultIssues(issue.issue, path21, leafHook, checkHook);
11822
11929
  }
11823
11930
  const expected = findExpected(issue.issue);
11824
11931
  return [{
11825
- path: path19,
11932
+ path: path21,
11826
11933
  message: expected === void 0 ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue)
11827
11934
  }];
11828
11935
  }
11829
11936
  case "Encoding":
11830
- return toDefaultIssues(issue.issue, path19, leafHook, checkHook);
11937
+ return toDefaultIssues(issue.issue, path21, leafHook, checkHook);
11831
11938
  case "Pointer":
11832
- return toDefaultIssues(issue.issue, [...path19, ...issue.path], leafHook, checkHook);
11939
+ return toDefaultIssues(issue.issue, [...path21, ...issue.path], leafHook, checkHook);
11833
11940
  case "Composite":
11834
- return issue.issues.flatMap((issue2) => toDefaultIssues(issue2, path19, leafHook, checkHook));
11941
+ return issue.issues.flatMap((issue2) => toDefaultIssues(issue2, path21, leafHook, checkHook));
11835
11942
  case "AnyOf": {
11836
11943
  if (issue.issues.length === 0) {
11837
11944
  return [{
11838
- path: path19,
11945
+ path: path21,
11839
11946
  message: findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue)
11840
11947
  }];
11841
11948
  }
11842
- return issue.issues.flatMap((issue2) => toDefaultIssues(issue2, path19, leafHook, checkHook));
11949
+ return issue.issues.flatMap((issue2) => toDefaultIssues(issue2, path21, leafHook, checkHook));
11843
11950
  }
11844
11951
  default:
11845
11952
  return [{
11846
- path: path19,
11953
+ path: path21,
11847
11954
  message: leafHook(issue)
11848
11955
  }];
11849
11956
  }
@@ -11862,7 +11969,7 @@ function makeFormatterDefault() {
11862
11969
  return (issue) => formatIssue(issue, "");
11863
11970
  }
11864
11971
  var defaultFormatter = /* @__PURE__ */ makeFormatterDefault();
11865
- function formatIssue(issue, path19) {
11972
+ function formatIssue(issue, path21) {
11866
11973
  let message;
11867
11974
  switch (issue._tag) {
11868
11975
  case "Filter": {
@@ -11871,7 +11978,7 @@ function formatIssue(issue, path19) {
11871
11978
  message = annotated;
11872
11979
  } else {
11873
11980
  if (issue.issue._tag !== "InvalidValue") {
11874
- return formatIssue(issue.issue, path19);
11981
+ return formatIssue(issue.issue, path21);
11875
11982
  }
11876
11983
  const expected = findExpected(issue.issue);
11877
11984
  message = expected === void 0 ? getExpectedMessage(formatCheck(issue.filter), issue) : getExpectedMessage(expected, issue.issue);
@@ -11879,13 +11986,13 @@ function formatIssue(issue, path19) {
11879
11986
  break;
11880
11987
  }
11881
11988
  case "Encoding":
11882
- return formatIssue(issue.issue, path19);
11989
+ return formatIssue(issue.issue, path21);
11883
11990
  case "Pointer":
11884
- return formatIssue(issue.issue, path19 + formatPath(issue.path));
11991
+ return formatIssue(issue.issue, path21 + formatPath(issue.path));
11885
11992
  case "Composite":
11886
11993
  case "AnyOf": {
11887
11994
  if (issue._tag === "Composite" || issue.issues.length > 0) {
11888
- return issue.issues.map((issue2) => formatIssue(issue2, path19)).join("\n");
11995
+ return issue.issues.map((issue2) => formatIssue(issue2, path21)).join("\n");
11889
11996
  }
11890
11997
  message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue);
11891
11998
  break;
@@ -11894,8 +12001,8 @@ function formatIssue(issue, path19) {
11894
12001
  message = defaultLeafHook(issue);
11895
12002
  break;
11896
12003
  }
11897
- return path19 ? `${message}
11898
- at ${path19}` : message;
12004
+ return path21 ? `${message}
12005
+ at ${path21}` : message;
11899
12006
  }
11900
12007
  function findMessage(issue) {
11901
12008
  if (issue._tag === "Pointer") return;
@@ -16316,10 +16423,10 @@ function makeReducer2(combiner2) {
16316
16423
  }
16317
16424
 
16318
16425
  // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/errors.js
16319
- function errorWithPath(message, path19) {
16320
- if (path19.length > 0) {
16426
+ function errorWithPath(message, path21) {
16427
+ if (path21.length > 0) {
16321
16428
  message += `
16322
- at ${formatPath(path19)}`;
16429
+ at ${formatPath(path21)}`;
16323
16430
  }
16324
16431
  return new Error(message);
16325
16432
  }
@@ -16660,26 +16767,26 @@ function filterLayer(ast, checks, normalBase, terminalBase) {
16660
16767
  });
16661
16768
  }
16662
16769
  var memoized = /* @__PURE__ */ memoize((ast) => recur(ast, []));
16663
- function recur(ast, path19) {
16770
+ function recur(ast, path21) {
16664
16771
  const annotation = resolve(ast)?.toArbitrary;
16665
16772
  if (annotation) {
16666
- const typeParameters = isDeclaration(ast) ? ast.typeParameters.map((tp) => recur(tp, path19)) : [];
16773
+ const typeParameters = isDeclaration(ast) ? ast.typeParameters.map((tp) => recur(tp, path21)) : [];
16667
16774
  const checks = collectChecks(ast.checks);
16668
16775
  const derive = (lazyNormal) => (fc, ctx, nextCtx, recursionStack) => normalizeDerivation(annotation(makeTypeParameters(typeParameters, fc, resetContext(ctx), recursionStack, lazyNormal))(fc, nextCtx), typeParameters.length > 0)[lazyNormal ? "terminal" : "arbitrary"];
16669
16776
  return filterLayer(ast, checks, derive(false), derive(true));
16670
16777
  }
16671
16778
  if (ast.checks) {
16672
16779
  const checks = collectChecks(ast.checks);
16673
- const lawc = recur(replaceChecks(ast, void 0), path19);
16780
+ const lawc = recur(replaceChecks(ast, void 0), path21);
16674
16781
  return filterLayer(ast, checks, (fc, _ctx, nextCtx, recursionStack) => lawc(fc, nextCtx, recursionStack), (fc, _ctx, nextCtx, recursionStack) => lawc.terminal(fc, nextCtx, recursionStack));
16675
16782
  }
16676
- return base(ast, path19);
16783
+ return base(ast, path21);
16677
16784
  }
16678
- function base(ast, path19) {
16785
+ function base(ast, path21) {
16679
16786
  switch (ast._tag) {
16680
16787
  case "Never":
16681
16788
  case "Declaration":
16682
- throw errorWithPath(`Unsupported AST ${ast._tag}`, path19);
16789
+ throw errorWithPath(`Unsupported AST ${ast._tag}`, path21);
16683
16790
  case "Null":
16684
16791
  return same((fc) => fc.constant(null));
16685
16792
  case "Void":
@@ -16716,20 +16823,20 @@ function base(ast, path19) {
16716
16823
  case "ObjectKeyword":
16717
16824
  return same((fc) => fc.oneof(fc.object(), fc.array(fc.anything())));
16718
16825
  case "Enum":
16719
- return recur(enumsToLiterals(ast), path19);
16826
+ return recur(enumsToLiterals(ast), path21);
16720
16827
  case "TemplateLiteral": {
16721
- const parts = ast.parts.map((part, i) => recur(toEncoded(part), [...path19, i]));
16828
+ const parts = ast.parts.map((part, i) => recur(toEncoded(part), [...path21, i]));
16722
16829
  return same((fc, ctx, recursionStack) => fc.tuple(...parts.map((part) => part(fc, finiteNumberContext(ctx), recursionStack))).map((segments) => segments.map((segment) => globalThis.String(segment)).join("")));
16723
16830
  }
16724
16831
  case "Arrays": {
16725
16832
  const elements = ast.elements.map((ast2, i) => ({
16726
16833
  ast: ast2,
16727
- arbitrary: recur(ast2, [...path19, i])
16834
+ arbitrary: recur(ast2, [...path21, i])
16728
16835
  }));
16729
16836
  const len = ast.elements.length;
16730
16837
  const rest = ast.rest.map((ast2, i) => ({
16731
16838
  ast: ast2,
16732
- arbitrary: recur(ast2, [...path19, len + i])
16839
+ arbitrary: recur(ast2, [...path21, len + i])
16733
16840
  }));
16734
16841
  const terminal = (fc, ctx, recursionStack) => {
16735
16842
  const reset = resetContext(ctx);
@@ -16829,12 +16936,12 @@ function base(ast, path19) {
16829
16936
  case "Objects": {
16830
16937
  const propertySignatures = ast.propertySignatures.map((ps) => ({
16831
16938
  ps,
16832
- arbitrary: recur(ps.type, [...path19, ps.name])
16939
+ arbitrary: recur(ps.type, [...path21, ps.name])
16833
16940
  }));
16834
16941
  const indexSignatures = ast.indexSignatures.map((is3) => ({
16835
16942
  is: is3,
16836
- parameter: recur(is3.parameter, path19),
16837
- type: recur(is3.type, path19)
16943
+ parameter: recur(is3.parameter, path21),
16944
+ type: recur(is3.type, path21)
16838
16945
  }));
16839
16946
  const terminal = (fc, ctx, recursionStack) => {
16840
16947
  const reset = resetContext(ctx);
@@ -16937,7 +17044,7 @@ function base(ast, path19) {
16937
17044
  }, terminal);
16938
17045
  }
16939
17046
  case "Union": {
16940
- const types = ast.types.map((ast2) => recur(ast2, path19));
17047
+ const types = ast.types.map((ast2) => recur(ast2, path21));
16941
17048
  const terminal = (fc, ctx, recursionStack) => oneOf(fc, types.map((type) => type.terminal(fc, ctx, recursionStack)).filter(isNotUndefined));
16942
17049
  return makeLazy((fc, ctx, recursionStack) => {
16943
17050
  const arbitraries = types.map((type) => type(fc, ctx, recursionStack));
@@ -16957,7 +17064,7 @@ function base(ast, path19) {
16957
17064
  case "Suspend": {
16958
17065
  const memo = arbitraryMemoMap.get(ast);
16959
17066
  if (memo) return memo;
16960
- const get5 = memoizeThunk(() => recur(ast.thunk(), path19));
17067
+ const get5 = memoizeThunk(() => recur(ast.thunk(), path21));
16961
17068
  const out = makeLazy((fc, ctx, recursionStack) => {
16962
17069
  const recursion = getSuspendRecursion(fc, ast);
16963
17070
  const nextCtx = {
@@ -16967,7 +17074,7 @@ function base(ast, path19) {
16967
17074
  const nextStack = recursionStack.includes(ast) ? recursionStack : [...recursionStack, ast];
16968
17075
  const terminal = get5().terminal(fc, nextCtx, nextStack);
16969
17076
  if (terminal === void 0) {
16970
- throw errorWithPath("Unable to derive an arbitrary for a recursive schema without a finite generation path", path19);
17077
+ throw errorWithPath("Unable to derive an arbitrary for a recursive schema without a finite generation path", path21);
16971
17078
  }
16972
17079
  return fc.oneof(recursion, terminal, fc.constant(null).chain(() => get5()(fc, nextCtx, nextStack)));
16973
17080
  }, (fc, ctx, recursionStack) => {
@@ -16990,10 +17097,10 @@ function base(ast, path19) {
16990
17097
  var toEquivalence = /* @__PURE__ */ memoize((ast) => {
16991
17098
  return recur2(ast, []);
16992
17099
  });
16993
- function recur2(ast, path19) {
17100
+ function recur2(ast, path21) {
16994
17101
  const annotation = resolve(ast)?.["toEquivalence"];
16995
17102
  if (annotation) {
16996
- return annotation(isDeclaration(ast) ? ast.typeParameters.map((tp) => recur2(tp, path19)) : []);
17103
+ return annotation(isDeclaration(ast) ? ast.typeParameters.map((tp) => recur2(tp, path21)) : []);
16997
17104
  }
16998
17105
  switch (ast._tag) {
16999
17106
  case "Never":
@@ -17016,9 +17123,9 @@ function recur2(ast, path19) {
17016
17123
  case "TemplateLiteral":
17017
17124
  return equals;
17018
17125
  case "Arrays": {
17019
- const elements = ast.elements.map((e, i) => recur2(e, [...path19, i]));
17126
+ const elements = ast.elements.map((e, i) => recur2(e, [...path21, i]));
17020
17127
  const len = ast.elements.length;
17021
- const rest = ast.rest.map((r, i) => recur2(r, [...path19, len + i]));
17128
+ const rest = ast.rest.map((r, i) => recur2(r, [...path21, len + i]));
17022
17129
  return make2((a, b) => {
17023
17130
  if (!Array.isArray(a) || !Array.isArray(b)) {
17024
17131
  return false;
@@ -17053,8 +17160,8 @@ function recur2(ast, path19) {
17053
17160
  if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) {
17054
17161
  return equals;
17055
17162
  }
17056
- const propertySignatures = ast.propertySignatures.map((ps) => recur2(ps.type, [...path19, ps.name]));
17057
- const indexSignatures = ast.indexSignatures.map((is3) => recur2(is3.type, path19));
17163
+ const propertySignatures = ast.propertySignatures.map((ps) => recur2(ps.type, [...path21, ps.name]));
17164
+ const indexSignatures = ast.indexSignatures.map((is3) => recur2(is3.type, path21));
17058
17165
  return make2((a, b) => {
17059
17166
  if (!isObject(a) || !isObject(b)) {
17060
17167
  return false;
@@ -17090,7 +17197,7 @@ function recur2(ast, path19) {
17090
17197
  }
17091
17198
  case "Union": {
17092
17199
  const types = toType(ast).types;
17093
- const compiled = new Map(types.map((candidate, i) => [candidate, [_is(candidate), recur2(ast.types[i], path19)]]));
17200
+ const compiled = new Map(types.map((candidate, i) => [candidate, [_is(candidate), recur2(ast.types[i], path21)]]));
17094
17201
  return make2((a, b) => {
17095
17202
  const candidates = getCandidates(a, types);
17096
17203
  for (let i = 0; i < candidates.length; i++) {
@@ -17103,7 +17210,7 @@ function recur2(ast, path19) {
17103
17210
  });
17104
17211
  }
17105
17212
  case "Suspend": {
17106
- const get5 = memoizeThunk(() => recur2(ast.thunk(), path19));
17213
+ const get5 = memoizeThunk(() => recur2(ast.thunk(), path21));
17107
17214
  return make2((a, b) => get5()(a, b));
17108
17215
  }
17109
17216
  }
@@ -17389,11 +17496,11 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17389
17496
  schemas,
17390
17497
  definitions
17391
17498
  };
17392
- function compileDefinition(key, path19) {
17499
+ function compileDefinition(key, path21) {
17393
17500
  const compiled = definitionStates.get(key);
17394
17501
  if (compiled !== void 0) return typeof compiled === "string" ? compiled : key;
17395
17502
  if (!Object.hasOwn(references, key)) {
17396
- throw errorWithPath(`Invalid reference ${key}`, [...path19, "$ref"]);
17503
+ throw errorWithPath(`Invalid reference ${key}`, [...path21, "$ref"]);
17397
17504
  }
17398
17505
  definitionStates.set(key, null);
17399
17506
  const representation = references[key];
@@ -17426,14 +17533,14 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17426
17533
  const annotations = representation.checks.length === 0 ? representation.annotations : representation.checks[representation.checks.length - 1].annotations;
17427
17534
  return typeof annotations?.identifier !== "string" && typeof annotations?.[IDENTIFIER_FALLBACK_KEY] === "string" ? annotations[IDENTIFIER_FALLBACK_KEY] : void 0;
17428
17535
  }
17429
- function annotationSchemas(representation, path19) {
17430
- return representation?.schemas?.map((schema, index2) => recur3(schema, [...path19, "schemas", index2])) ?? [];
17536
+ function annotationSchemas(representation, path21) {
17537
+ return representation?.schemas?.map((schema, index2) => recur3(schema, [...path21, "schemas", index2])) ?? [];
17431
17538
  }
17432
- function compileCheck(check2, type, path19) {
17539
+ function compileCheck(check2, type, path21) {
17433
17540
  const annotations = check2.annotations;
17434
17541
  const callback2 = annotations?.toJsonSchema;
17435
17542
  if (callback2 !== void 0) {
17436
- const schemas2 = annotationSchemas(check2.representation, [...path19, "representation"]);
17543
+ const schemas2 = annotationSchemas(check2.representation, [...path21, "representation"]);
17437
17544
  const fragment = callback2({
17438
17545
  type,
17439
17546
  schemas: schemas2
@@ -17447,7 +17554,7 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17447
17554
  return check2._tag === "Filter" && hasOnlyKeywords(schema, allowed) && (ordinary2 === void 0 || hasOnlyKeywords(ordinary2, promotableAnnotationKeywords)) ? [schema, true] : [schema];
17448
17555
  }
17449
17556
  if (check2._tag === "Filter") return void 0;
17450
- const children = check2.checks.map((child, index2) => compileCheck(child, type, [...path19, "checks", index2])).filter((child) => child !== void 0);
17557
+ const children = check2.checks.map((child, index2) => compileCheck(child, type, [...path21, "checks", index2])).filter((child) => child !== void 0);
17451
17558
  if (children.length === 0) return void 0;
17452
17559
  const ordinary = collectJsonSchemaAnnotations(annotations, options);
17453
17560
  const allOf = children.map(([schema]) => schema);
@@ -17458,16 +17565,16 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17458
17565
  ...ordinary
17459
17566
  }];
17460
17567
  }
17461
- function recur3(representation, path19) {
17568
+ function recur3(representation, path21) {
17462
17569
  if (representation._tag === "Reference") {
17463
- const canonical = compileDefinition(representation.$ref, path19);
17570
+ const canonical = compileDefinition(representation.$ref, path21);
17464
17571
  return {
17465
17572
  $ref: `#/$defs/${escapeToken(canonical)}`
17466
17573
  };
17467
17574
  }
17468
17575
  const cached2 = compiledRepresentations.get(representation);
17469
17576
  if (cached2 !== void 0) return cached2;
17470
- let output = on(representation, path19);
17577
+ let output = on(representation, path21);
17471
17578
  const ordinary = collectJsonSchemaAnnotations(representation.annotations, options);
17472
17579
  if (ordinary !== void 0) {
17473
17580
  output = {
@@ -17477,7 +17584,7 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17477
17584
  }
17478
17585
  for (let index2 = 0; index2 < representation.checks.length; index2++) {
17479
17586
  const type = typeof output.type === "string" && isJsonSchemaType(output.type) ? output.type : void 0;
17480
- const check2 = compileCheck(representation.checks[index2], type, [...path19, "checks", index2]);
17587
+ const check2 = compileCheck(representation.checks[index2], type, [...path21, "checks", index2]);
17481
17588
  if (check2 !== void 0) {
17482
17589
  output = appendJsonSchema(output, ...check2);
17483
17590
  }
@@ -17485,7 +17592,7 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17485
17592
  compiledRepresentations.set(representation, output);
17486
17593
  return output;
17487
17594
  }
17488
- function on(representation, path19) {
17595
+ function on(representation, path21) {
17489
17596
  switch (representation._tag) {
17490
17597
  case "Any":
17491
17598
  case "Unknown":
@@ -17523,7 +17630,7 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17523
17630
  return {};
17524
17631
  }
17525
17632
  case "Suspend":
17526
- return recur3(representation.thunk, [...path19, "thunk"]);
17633
+ return recur3(representation.thunk, [...path21, "thunk"]);
17527
17634
  case "Never":
17528
17635
  return {
17529
17636
  not: {}
@@ -17584,7 +17691,7 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17584
17691
  };
17585
17692
  case "Arrays": {
17586
17693
  if (representation.rest.length > 1) {
17587
- throw errorWithPath("Invalid schema representation document", [...path19, "rest"]);
17694
+ throw errorWithPath("Invalid schema representation document", [...path21, "rest"]);
17588
17695
  }
17589
17696
  const out = {
17590
17697
  type: "array"
@@ -17592,7 +17699,7 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17592
17699
  let minItems = representation.elements.length;
17593
17700
  const prefixItems = representation.elements.map((element, index2) => {
17594
17701
  if (element.isOptional) minItems--;
17595
- const compiled = recur3(element.type, [...path19, "elements", index2, "type"]);
17702
+ const compiled = recur3(element.type, [...path21, "elements", index2, "type"]);
17596
17703
  const annotations = collectJsonSchemaAnnotations(element.annotations, options);
17597
17704
  return annotations === void 0 ? compiled : appendJsonSchema(compiled, annotations);
17598
17705
  });
@@ -17605,7 +17712,7 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17605
17712
  }
17606
17713
  if (representation.rest.length === 1) {
17607
17714
  delete out.maxItems;
17608
- const rest = recur3(representation.rest[0], [...path19, "rest", 0]);
17715
+ const rest = recur3(representation.rest[0], [...path21, "rest", 0]);
17609
17716
  if (Object.keys(rest).length > 0) out.items = rest;
17610
17717
  else delete out.items;
17611
17718
  }
@@ -17629,10 +17736,10 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17629
17736
  for (let index2 = 0; index2 < representation.propertySignatures.length; index2++) {
17630
17737
  const property = representation.propertySignatures[index2];
17631
17738
  if (typeof property.name !== "string") {
17632
- throw errorWithPath("Invalid schema representation document", [...path19, "propertySignatures", index2, "name"]);
17739
+ throw errorWithPath("Invalid schema representation document", [...path21, "propertySignatures", index2, "name"]);
17633
17740
  }
17634
17741
  const name = property.name;
17635
- const compiled = recur3(property.type, [...path19, "propertySignatures", index2, "type"]);
17742
+ const compiled = recur3(property.type, [...path21, "propertySignatures", index2, "type"]);
17636
17743
  const annotations = collectJsonSchemaAnnotations(property.annotations, options);
17637
17744
  assignProperty(properties, name, annotations === void 0 ? compiled : appendJsonSchema(compiled, annotations));
17638
17745
  if (!property.isOptional) required2.push(name);
@@ -17643,9 +17750,9 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17643
17750
  const additionalProperties = [];
17644
17751
  for (let index2 = 0; index2 < representation.indexSignatures.length; index2++) {
17645
17752
  const signature = representation.indexSignatures[index2];
17646
- let type = recur3(signature.type, [...path19, "indexSignatures", index2, "type"]);
17753
+ let type = recur3(signature.type, [...path21, "indexSignatures", index2, "type"]);
17647
17754
  if (Object.keys(type).length === 1 && "not" in type) type = false;
17648
- const patterns = getParameterPatterns(signature.parameter, [...path19, "indexSignatures", index2, "parameter"], /* @__PURE__ */ new Set());
17755
+ const patterns = getParameterPatterns(signature.parameter, [...path21, "indexSignatures", index2, "parameter"], /* @__PURE__ */ new Set());
17649
17756
  if (patterns.length === 0) {
17650
17757
  additionalProperties.push(type);
17651
17758
  } else {
@@ -17675,7 +17782,7 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17675
17782
  return out;
17676
17783
  }
17677
17784
  case "Union": {
17678
- const types = representation.types.map((type, index2) => recur3(type, [...path19, "types", index2]));
17785
+ const types = representation.types.map((type, index2) => recur3(type, [...path21, "types", index2]));
17679
17786
  if (types.length === 0) return {
17680
17787
  not: {}
17681
17788
  };
@@ -17691,25 +17798,25 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17691
17798
  }
17692
17799
  }
17693
17800
  }
17694
- function getParameterPatterns(parameter, path19, seenReferences) {
17801
+ function getParameterPatterns(parameter, path21, seenReferences) {
17695
17802
  switch (parameter._tag) {
17696
17803
  case "Reference": {
17697
17804
  if (!Object.hasOwn(references, parameter.$ref)) {
17698
- throw errorWithPath(`Invalid reference ${parameter.$ref}`, [...path19, "$ref"]);
17805
+ throw errorWithPath(`Invalid reference ${parameter.$ref}`, [...path21, "$ref"]);
17699
17806
  }
17700
- compileDefinition(parameter.$ref, path19);
17807
+ compileDefinition(parameter.$ref, path21);
17701
17808
  if (seenReferences.has(parameter.$ref)) return [];
17702
17809
  const next = new Set(seenReferences).add(parameter.$ref);
17703
17810
  return getParameterPatterns(references[parameter.$ref], ["references", parameter.$ref], next);
17704
17811
  }
17705
17812
  case "String":
17706
- return collectPatterns(recur3(parameter, path19));
17813
+ return collectPatterns(recur3(parameter, path21));
17707
17814
  case "TemplateLiteral":
17708
17815
  return [`^${parameter.parts.map(getPartPattern).join("")}$`];
17709
17816
  case "Union":
17710
- return parameter.types.flatMap((type, index2) => getParameterPatterns(type, [...path19, "types", index2], seenReferences));
17817
+ return parameter.types.flatMap((type, index2) => getParameterPatterns(type, [...path21, "types", index2], seenReferences));
17711
17818
  default:
17712
- throw errorWithPath("Invalid schema representation document", path19);
17819
+ throw errorWithPath("Invalid schema representation document", path21);
17713
17820
  }
17714
17821
  }
17715
17822
  }
@@ -18094,25 +18201,25 @@ function get4(oldValue, newValue) {
18094
18201
  getLoop(oldValue, newValue, "", patches);
18095
18202
  return patches;
18096
18203
  }
18097
- function getLoop(oldValue, newValue, path19, patches) {
18204
+ function getLoop(oldValue, newValue, path21, patches) {
18098
18205
  if (Object.is(oldValue, newValue)) return;
18099
18206
  if (Array.isArray(oldValue) && Array.isArray(newValue)) {
18100
18207
  const len1 = oldValue.length;
18101
18208
  const len2 = newValue.length;
18102
18209
  const shared = Math.min(len1, len2);
18103
18210
  for (let i = 0; i < shared; i++) {
18104
- getLoop(oldValue[i], newValue[i], `${path19}/${i}`, patches);
18211
+ getLoop(oldValue[i], newValue[i], `${path21}/${i}`, patches);
18105
18212
  }
18106
18213
  for (let i = len1 - 1; i >= len2; i--) {
18107
18214
  patches.push({
18108
18215
  op: "remove",
18109
- path: `${path19}/${i}`
18216
+ path: `${path21}/${i}`
18110
18217
  });
18111
18218
  }
18112
18219
  for (let i = len1; i < len2; i++) {
18113
18220
  patches.push({
18114
18221
  op: "add",
18115
- path: `${path19}/${i}`,
18222
+ path: `${path21}/${i}`,
18116
18223
  value: newValue[i]
18117
18224
  });
18118
18225
  }
@@ -18123,7 +18230,7 @@ function getLoop(oldValue, newValue, path19, patches) {
18123
18230
  const keys22 = Object.keys(newValue);
18124
18231
  const allKeys = Array.from(/* @__PURE__ */ new Set([...keys1, ...keys22])).sort();
18125
18232
  for (const key of allKeys) {
18126
- const keyPath = `${path19}/${escapeToken(key)}`;
18233
+ const keyPath = `${path21}/${escapeToken(key)}`;
18127
18234
  const hasKey1 = Object.hasOwn(oldValue, key);
18128
18235
  const hasKey2 = Object.hasOwn(newValue, key);
18129
18236
  if (hasKey1 && hasKey2) {
@@ -18145,7 +18252,7 @@ function getLoop(oldValue, newValue, path19, patches) {
18145
18252
  }
18146
18253
  patches.push({
18147
18254
  op: "replace",
18148
- path: path19,
18255
+ path: path21,
18149
18256
  value: newValue
18150
18257
  });
18151
18258
  }
@@ -18295,12 +18402,12 @@ var PathNode = class {
18295
18402
  path;
18296
18403
  get;
18297
18404
  set;
18298
- constructor(path19) {
18299
- this.path = path19;
18405
+ constructor(path21) {
18406
+ this.path = path21;
18300
18407
  this.get = (s) => {
18301
18408
  let out = s;
18302
- for (let i = 0; i < path19.length; i++) {
18303
- out = out[path19[i]];
18409
+ for (let i = 0; i < path21.length; i++) {
18410
+ out = out[path21[i]];
18304
18411
  }
18305
18412
  return out;
18306
18413
  };
@@ -18308,12 +18415,12 @@ var PathNode = class {
18308
18415
  const out = cloneShallow(s);
18309
18416
  let current = out;
18310
18417
  let i = 0;
18311
- for (; i < path19.length - 1; i++) {
18312
- const key = path19[i];
18418
+ for (; i < path21.length - 1; i++) {
18419
+ const key = path21[i];
18313
18420
  assignProperty(current, key, cloneShallow(current[key]));
18314
18421
  current = current[key];
18315
18422
  }
18316
- assignProperty(current, path19[i], a);
18423
+ assignProperty(current, path21[i], a);
18317
18424
  return out;
18318
18425
  };
18319
18426
  }
@@ -23170,82 +23277,12 @@ var ProviderEvent = Schema_exports.Struct({
23170
23277
  payload: Schema_exports.optional(Schema_exports.Unknown)
23171
23278
  });
23172
23279
 
23173
- // ../../packages/contracts/src/filesystem.ts
23174
- var FILESYSTEM_PATH_MAX_LENGTH = 512;
23175
- var FilesystemBrowseInput = Schema_exports.Struct({
23176
- partialPath: TrimmedNonEmptyString.check(Schema_exports.isMaxLength(FILESYSTEM_PATH_MAX_LENGTH)),
23177
- cwd: Schema_exports.optional(TrimmedNonEmptyString.check(Schema_exports.isMaxLength(FILESYSTEM_PATH_MAX_LENGTH)))
23178
- });
23179
- var FilesystemBrowseEntry = Schema_exports.Struct({
23180
- name: TrimmedNonEmptyString,
23181
- fullPath: TrimmedNonEmptyString
23182
- });
23183
- var FilesystemBrowseResult = Schema_exports.Struct({
23184
- parentPath: TrimmedNonEmptyString,
23185
- entries: Schema_exports.Array(FilesystemBrowseEntry)
23186
- });
23187
-
23188
- // ../../packages/contracts/src/editor.ts
23189
- var EDITORS = [
23190
- { id: "cursor", label: "Cursor", commands: ["cursor"], supportsGoto: true },
23191
- { id: "vscode", label: "VS Code", commands: ["code"], supportsGoto: true },
23192
- {
23193
- id: "vscode-insiders",
23194
- label: "VS Code Insiders",
23195
- commands: ["code-insiders"],
23196
- supportsGoto: true
23197
- },
23198
- { id: "vscodium", label: "VSCodium", commands: ["codium"], supportsGoto: true },
23199
- { id: "zed", label: "Zed", commands: ["zed", "zeditor"], supportsGoto: false },
23200
- { id: "antigravity", label: "Antigravity", commands: ["agy"], supportsGoto: false },
23201
- { id: "file-manager", label: "File Manager", commands: null, supportsGoto: false }
23202
- ];
23203
- var EditorId = Schema_exports.Literals(EDITORS.map((e) => e.id));
23204
- var OpenInEditorInput = Schema_exports.Struct({
23205
- cwd: TrimmedNonEmptyString,
23206
- editor: EditorId
23207
- });
23208
-
23209
- // ../../packages/contracts/src/runtime.ts
23210
- var RuntimeConfigIssue = Schema_exports.Struct({
23211
- kind: TrimmedNonEmptyString,
23212
- message: TrimmedNonEmptyString
23213
- });
23214
- var RuntimeConfigIssues = Schema_exports.Array(RuntimeConfigIssue);
23215
- var RuntimeProviderStatusState = Schema_exports.Literals(["ready", "warning", "error"]);
23216
- var RuntimeProviderAuthStatus = Schema_exports.Literals([
23217
- "authenticated",
23218
- "unauthenticated",
23219
- "unknown"
23220
- ]);
23221
- var RuntimeProviderStatus = Schema_exports.Struct({
23222
- provider: ProviderKind,
23223
- status: RuntimeProviderStatusState,
23224
- available: Schema_exports.Boolean,
23225
- authStatus: RuntimeProviderAuthStatus,
23226
- checkedAt: IsoDateTime,
23227
- message: Schema_exports.optional(TrimmedNonEmptyString)
23228
- });
23229
- var RuntimeProviderStatuses = Schema_exports.Array(RuntimeProviderStatus);
23230
- var RuntimeConfig = Schema_exports.Struct({
23231
- cwd: TrimmedNonEmptyString,
23232
- issues: RuntimeConfigIssues,
23233
- providers: RuntimeProviderStatuses,
23234
- availableEditors: Schema_exports.Array(EditorId)
23235
- });
23236
- var RuntimeProviderUpdatedPayload = Schema_exports.Struct({
23237
- providers: RuntimeProviderStatuses
23238
- });
23239
-
23240
- // ../../packages/contracts/src/rpc.ts
23280
+ // ../../packages/contracts/src/desktop/rpc-types.ts
23241
23281
  var RPC_METHODS = {
23242
23282
  filesystemBrowse: "filesystem.browse",
23243
- // Shell methods
23244
23283
  shellOpenInEditor: "shell.openInEditor",
23245
- // Runtime meta
23246
23284
  runtimeGetConfig: "runtime.getConfig",
23247
23285
  runtimeRefreshProviders: "runtime.refreshProviders",
23248
- // Desktop dashboard/runtime methods
23249
23286
  appStateGet: "appState.get",
23250
23287
  appStatePatch: "appState.patch",
23251
23288
  appSettingsGet: "appSettings.get",
@@ -23314,6 +23351,7 @@ var RPC_METHODS = {
23314
23351
  desktopLlmSetProviderEnabled: "desktopLlm.setProviderEnabled",
23315
23352
  desktopLlmSetRoutePublished: "desktopLlm.setRoutePublished",
23316
23353
  desktopLlmProbeRoute: "desktopLlm.probeRoute",
23354
+ desktopLlmCreateGuidedProfile: "desktopLlm.createGuidedProfile",
23317
23355
  desktopLlmUpsertExternalProfile: "desktopLlm.upsertExternalProfile",
23318
23356
  desktopLlmDeleteExternalProfile: "desktopLlm.deleteExternalProfile",
23319
23357
  desktopLlmLaunchExternalProfile: "desktopLlm.launchExternalProfile",
@@ -23346,6 +23384,75 @@ var RPC_CHANNELS = {
23346
23384
  officialCodexActivityUpdated: "officialCodex.activityUpdated",
23347
23385
  officialCodexStatusUpdated: "officialCodex.statusUpdated"
23348
23386
  };
23387
+
23388
+ // ../../packages/contracts/src/filesystem.ts
23389
+ var FILESYSTEM_PATH_MAX_LENGTH = 512;
23390
+ var FilesystemBrowseInput = Schema_exports.Struct({
23391
+ partialPath: TrimmedNonEmptyString.check(Schema_exports.isMaxLength(FILESYSTEM_PATH_MAX_LENGTH)),
23392
+ cwd: Schema_exports.optional(TrimmedNonEmptyString.check(Schema_exports.isMaxLength(FILESYSTEM_PATH_MAX_LENGTH)))
23393
+ });
23394
+ var FilesystemBrowseEntry = Schema_exports.Struct({
23395
+ name: TrimmedNonEmptyString,
23396
+ fullPath: TrimmedNonEmptyString
23397
+ });
23398
+ var FilesystemBrowseResult = Schema_exports.Struct({
23399
+ parentPath: TrimmedNonEmptyString,
23400
+ entries: Schema_exports.Array(FilesystemBrowseEntry)
23401
+ });
23402
+
23403
+ // ../../packages/contracts/src/editor.ts
23404
+ var EDITORS = [
23405
+ { id: "cursor", label: "Cursor", commands: ["cursor"], supportsGoto: true },
23406
+ { id: "vscode", label: "VS Code", commands: ["code"], supportsGoto: true },
23407
+ {
23408
+ id: "vscode-insiders",
23409
+ label: "VS Code Insiders",
23410
+ commands: ["code-insiders"],
23411
+ supportsGoto: true
23412
+ },
23413
+ { id: "vscodium", label: "VSCodium", commands: ["codium"], supportsGoto: true },
23414
+ { id: "zed", label: "Zed", commands: ["zed", "zeditor"], supportsGoto: false },
23415
+ { id: "antigravity", label: "Antigravity", commands: ["agy"], supportsGoto: false },
23416
+ { id: "file-manager", label: "File Manager", commands: null, supportsGoto: false }
23417
+ ];
23418
+ var EditorId = Schema_exports.Literals(EDITORS.map((e) => e.id));
23419
+ var OpenInEditorInput = Schema_exports.Struct({
23420
+ cwd: TrimmedNonEmptyString,
23421
+ editor: EditorId
23422
+ });
23423
+
23424
+ // ../../packages/contracts/src/runtime.ts
23425
+ var RuntimeConfigIssue = Schema_exports.Struct({
23426
+ kind: TrimmedNonEmptyString,
23427
+ message: TrimmedNonEmptyString
23428
+ });
23429
+ var RuntimeConfigIssues = Schema_exports.Array(RuntimeConfigIssue);
23430
+ var RuntimeProviderStatusState = Schema_exports.Literals(["ready", "warning", "error"]);
23431
+ var RuntimeProviderAuthStatus = Schema_exports.Literals([
23432
+ "authenticated",
23433
+ "unauthenticated",
23434
+ "unknown"
23435
+ ]);
23436
+ var RuntimeProviderStatus = Schema_exports.Struct({
23437
+ provider: ProviderKind,
23438
+ status: RuntimeProviderStatusState,
23439
+ available: Schema_exports.Boolean,
23440
+ authStatus: RuntimeProviderAuthStatus,
23441
+ checkedAt: IsoDateTime,
23442
+ message: Schema_exports.optional(TrimmedNonEmptyString)
23443
+ });
23444
+ var RuntimeProviderStatuses = Schema_exports.Array(RuntimeProviderStatus);
23445
+ var RuntimeConfig = Schema_exports.Struct({
23446
+ cwd: TrimmedNonEmptyString,
23447
+ issues: RuntimeConfigIssues,
23448
+ providers: RuntimeProviderStatuses,
23449
+ availableEditors: Schema_exports.Array(EditorId)
23450
+ });
23451
+ var RuntimeProviderUpdatedPayload = Schema_exports.Struct({
23452
+ providers: RuntimeProviderStatuses
23453
+ });
23454
+
23455
+ // ../../packages/contracts/src/rpc.ts
23349
23456
  var tagRequestBody = (tag2, schema) => schema.mapFields(
23350
23457
  Struct_exports.assign({ _tag: Schema_exports.tag(tag2) }),
23351
23458
  // PreserveChecks is safe here. No existing schema should have checks depending on the tag
@@ -23449,6 +23556,7 @@ var DesktopRpcRequestBody = Schema_exports.Union([
23449
23556
  Schema_exports.Union([Schema_exports.Literal("manual"), Schema_exports.Literal("auto-roll")])
23450
23557
  ),
23451
23558
  carryDraft: Schema_exports.optional(Schema_exports.Boolean),
23559
+ continueThreadId: Schema_exports.optional(Schema_exports.Union([Schema_exports.String, Schema_exports.Null])),
23452
23560
  forceAdopt: Schema_exports.optional(Schema_exports.Boolean),
23453
23561
  launchIfNotRunning: Schema_exports.optional(Schema_exports.Boolean),
23454
23562
  awaitCodexFollowUp: Schema_exports.optional(Schema_exports.Boolean)
@@ -23758,6 +23866,10 @@ var DesktopRpcRequestBody = Schema_exports.Union([
23758
23866
  RPC_METHODS.desktopLlmProbeRoute,
23759
23867
  Schema_exports.Struct({ publicSlug: TrimmedNonEmptyString })
23760
23868
  ),
23869
+ tagRequestBody(
23870
+ RPC_METHODS.desktopLlmCreateGuidedProfile,
23871
+ Schema_exports.Struct({ input: Schema_exports.Unknown })
23872
+ ),
23761
23873
  tagRequestBody(
23762
23874
  RPC_METHODS.desktopLlmUpsertExternalProfile,
23763
23875
  Schema_exports.Struct({ profile: Schema_exports.Unknown })
@@ -24223,7 +24335,7 @@ function authWritebackPaths(filePath) {
24223
24335
  };
24224
24336
  }
24225
24337
  function fingerprintAuth(content) {
24226
- return (0, import_node_crypto9.createHash)("sha256").update(content).digest("hex");
24338
+ return (0, import_node_crypto10.createHash)("sha256").update(content).digest("hex");
24227
24339
  }
24228
24340
  async function readOptionalFile(filePath) {
24229
24341
  try {
@@ -24235,10 +24347,10 @@ async function readOptionalFile(filePath) {
24235
24347
  }
24236
24348
  }
24237
24349
  async function writeAtomicPath(filePath, content) {
24238
- const dir = import_node_path9.default.dirname(filePath);
24239
- const tempPath = import_node_path9.default.join(
24350
+ const dir = import_node_path10.default.dirname(filePath);
24351
+ const tempPath = import_node_path10.default.join(
24240
24352
  dir,
24241
- `.${import_node_path9.default.basename(filePath)}.${process.pid}.${(0, import_node_crypto9.randomUUID)()}.tmp`
24353
+ `.${import_node_path10.default.basename(filePath)}.${process.pid}.${(0, import_node_crypto10.randomUUID)()}.tmp`
24242
24354
  );
24243
24355
  const handle = await import_node_fs6.promises.open(tempPath, "wx", 384);
24244
24356
  try {
@@ -24262,10 +24374,10 @@ async function writeAtomicPath(filePath, content) {
24262
24374
  }
24263
24375
  }
24264
24376
  async function installAuthFileIfAbsent(filePath, content) {
24265
- const dir = import_node_path9.default.dirname(filePath);
24266
- const tempPath = import_node_path9.default.join(
24377
+ const dir = import_node_path10.default.dirname(filePath);
24378
+ const tempPath = import_node_path10.default.join(
24267
24379
  dir,
24268
- `.${import_node_path9.default.basename(filePath)}.${process.pid}.${(0, import_node_crypto9.randomUUID)()}.install`
24380
+ `.${import_node_path10.default.basename(filePath)}.${process.pid}.${(0, import_node_crypto10.randomUUID)()}.install`
24269
24381
  );
24270
24382
  const handle = await import_node_fs6.promises.open(tempPath, "wx", 384);
24271
24383
  try {
@@ -24336,7 +24448,7 @@ async function hasExternalOpenFileHandle(filePath) {
24336
24448
  }
24337
24449
  const lsofCommand = process.platform === "darwin" ? "/usr/sbin/lsof" : "lsof";
24338
24450
  return new Promise((resolve2) => {
24339
- const child = (0, import_node_child_process5.spawn)(lsofCommand, ["-F", "p", "--", filePath], {
24451
+ const child = (0, import_node_child_process6.spawn)(lsofCommand, ["-F", "p", "--", filePath], {
24340
24452
  stdio: ["ignore", "pipe", "ignore"]
24341
24453
  });
24342
24454
  let output = "";
@@ -24479,7 +24591,7 @@ async function acquireCodexAuthFileSystemLock(filePath) {
24479
24591
  }
24480
24592
  }
24481
24593
  async function acquireCodexAuthFileLock(filePath) {
24482
- const queueKey = import_node_path9.default.resolve(filePath);
24594
+ const queueKey = import_node_path10.default.resolve(filePath);
24483
24595
  const predecessor = authFileLockQueues.get(queueKey) ?? Promise.resolve();
24484
24596
  let finishTurn;
24485
24597
  const turn = new Promise((resolve2) => {
@@ -24512,7 +24624,7 @@ async function acquireCodexAuthFileLock(filePath) {
24512
24624
  }
24513
24625
  }
24514
24626
  async function acquireCodexAuthFileReadLock(filePath) {
24515
- const queueKey = import_node_path9.default.resolve(filePath);
24627
+ const queueKey = import_node_path10.default.resolve(filePath);
24516
24628
  await (authFileLockQueues.get(queueKey) ?? Promise.resolve());
24517
24629
  const releaseReadLock = await acquireCrossProcessFileReadLock(filePath);
24518
24630
  if (!releaseReadLock) {
@@ -24686,9 +24798,9 @@ function parseRateLimitSnapshotFromRpcMessage(message) {
24686
24798
  return snapshot2;
24687
24799
  }
24688
24800
  function resolveRpcAuthPath(envOverride, authPath) {
24689
- return authPath ?? import_node_path9.default.join(
24801
+ return authPath ?? import_node_path10.default.join(
24690
24802
  resolveCodexHomeDir({
24691
- codexHomePath: envOverride?.CODEX_HOME ?? (envOverride?.HOME ? import_node_path9.default.join(envOverride.HOME, ".codex") : void 0)
24803
+ codexHomePath: envOverride?.CODEX_HOME ?? (envOverride?.HOME ? import_node_path10.default.join(envOverride.HOME, ".codex") : void 0)
24692
24804
  }),
24693
24805
  "auth.json"
24694
24806
  );
@@ -24696,8 +24808,8 @@ function resolveRpcAuthPath(envOverride, authPath) {
24696
24808
  async function fetchRateLimitsViaRpc(envOverride, options = {}) {
24697
24809
  const binaryPath = options.codexPath ?? await requireCodexCli();
24698
24810
  const sourceAuthPath = resolveRpcAuthPath(envOverride, options.authPath);
24699
- const tempHome = await import_node_fs6.promises.mkdtemp(import_node_path9.default.join(import_node_os3.default.tmpdir(), "codex-rpc-"));
24700
- const tempAuthPath = import_node_path9.default.join(tempHome, "auth.json");
24811
+ const tempHome = await import_node_fs6.promises.mkdtemp(import_node_path10.default.join(import_node_os3.default.tmpdir(), "codex-rpc-"));
24812
+ const tempAuthPath = import_node_path10.default.join(tempHome, "auth.json");
24701
24813
  let initialSourceAuth;
24702
24814
  try {
24703
24815
  const authLock = await acquireCodexAuthFileReadLock(sourceAuthPath);
@@ -24736,7 +24848,7 @@ async function fetchRateLimitsViaRpc(envOverride, options = {}) {
24736
24848
  ["-s", "read-only", "-a", "never", "app-server"],
24737
24849
  childEnv
24738
24850
  );
24739
- const child = (0, import_node_child_process5.spawn)(command.command, command.args, {
24851
+ const child = (0, import_node_child_process6.spawn)(command.command, command.args, {
24740
24852
  stdio: ["pipe", "pipe", "pipe"],
24741
24853
  env: childEnv,
24742
24854
  shell: command.shell
@@ -24830,9 +24942,9 @@ async function activateResetWindowViaRpc(envOverride, options = {}) {
24830
24942
  async function activateResetWindowViaRpcIsolated(envOverride, options, sourceAuthPath) {
24831
24943
  const binaryPath = options.codexPath ?? await requireCodexCli();
24832
24944
  const tempHome = await import_node_fs6.promises.mkdtemp(
24833
- import_node_path9.default.join(import_node_os3.default.tmpdir(), "codex-activation-")
24945
+ import_node_path10.default.join(import_node_os3.default.tmpdir(), "codex-activation-")
24834
24946
  );
24835
- const tempAuthPath = import_node_path9.default.join(tempHome, "auth.json");
24947
+ const tempAuthPath = import_node_path10.default.join(tempHome, "auth.json");
24836
24948
  let initialSourceAuth;
24837
24949
  try {
24838
24950
  const authLock = await acquireCodexAuthFileReadLock(sourceAuthPath);
@@ -24862,14 +24974,14 @@ async function activateResetWindowViaRpcIsolated(envOverride, options, sourceAut
24862
24974
  let configuredModel = null;
24863
24975
  try {
24864
24976
  const snapshot2 = await getCodexConfigSnapshot({
24865
- codexHomePath: import_node_path9.default.dirname(sourceAuthPath)
24977
+ codexHomePath: import_node_path10.default.dirname(sourceAuthPath)
24866
24978
  });
24867
24979
  configuredModel = snapshot2.settings.model;
24868
24980
  } catch {
24869
24981
  }
24870
24982
  const activationModel = resolveActivationModel(configuredModel);
24871
24983
  await import_node_fs6.promises.writeFile(
24872
- import_node_path9.default.join(tempHome, "config.toml"),
24984
+ import_node_path10.default.join(tempHome, "config.toml"),
24873
24985
  `model = ${JSON.stringify(activationModel)}
24874
24986
  `,
24875
24987
  "utf8"
@@ -24888,7 +25000,7 @@ async function activateResetWindowViaRpcIsolated(envOverride, options, sourceAut
24888
25000
  ["-s", "read-only", "-a", "never", "app-server"],
24889
25001
  childEnv
24890
25002
  );
24891
- const child = (0, import_node_child_process5.spawn)(command.command, command.args, {
25003
+ const child = (0, import_node_child_process6.spawn)(command.command, command.args, {
24892
25004
  stdio: ["pipe", "pipe", "pipe"],
24893
25005
  env: childEnv,
24894
25006
  shell: command.shell
@@ -25063,15 +25175,15 @@ async function activateResetWindowViaRpcIsolated(envOverride, options, sourceAut
25063
25175
  }
25064
25176
 
25065
25177
  // ../../packages/runtime-codex/src/codex/officialAppRestart.ts
25066
- var import_node_child_process6 = require("child_process");
25067
- var import_node_crypto10 = require("crypto");
25178
+ var import_node_child_process7 = require("child_process");
25179
+ var import_node_crypto11 = require("crypto");
25068
25180
  var import_node_fs8 = require("fs");
25069
25181
  var import_node_os4 = require("os");
25070
- var import_node_path11 = __toESM(require("path"), 1);
25182
+ var import_node_path12 = __toESM(require("path"), 1);
25071
25183
 
25072
25184
  // ../../packages/runtime-codex/src/codex/threadUsage.ts
25073
25185
  var import_node_fs7 = require("fs");
25074
- var import_node_path10 = __toESM(require("path"), 1);
25186
+ var import_node_path11 = __toESM(require("path"), 1);
25075
25187
  var ROLLOUT_DIRS = ["sessions", "archived_sessions"];
25076
25188
  var SQLITE_EXTENSIONS = /* @__PURE__ */ new Set([".db", ".sqlite", ".sqlite3"]);
25077
25189
  var SILENT_TAKEOVER_HOT_WINDOW_MS = 6e4;
@@ -25093,7 +25205,7 @@ async function collectRolloutFiles(root) {
25093
25205
  const childVisits = [];
25094
25206
  for (const entry of entries3) {
25095
25207
  const entryName = String(entry.name);
25096
- const entryPath = import_node_path10.default.join(dir, entryName);
25208
+ const entryPath = import_node_path11.default.join(dir, entryName);
25097
25209
  if (entry.isDirectory()) {
25098
25210
  childVisits.push(visit(entryPath));
25099
25211
  continue;
@@ -25118,7 +25230,7 @@ async function collectRolloutFilesStrict(root) {
25118
25230
  await Promise.all(
25119
25231
  entries3.map(async (entry) => {
25120
25232
  const entryName = String(entry.name);
25121
- const entryPath = import_node_path10.default.join(dir, entryName);
25233
+ const entryPath = import_node_path11.default.join(dir, entryName);
25122
25234
  if (entry.isDirectory()) {
25123
25235
  await visit(entryPath);
25124
25236
  } else if (entry.isFile() && entryName.startsWith("rollout-") && entryName.endsWith(".jsonl")) {
@@ -25134,7 +25246,7 @@ async function readOfficialCodexRolloutActivityHeat(profileHome) {
25134
25246
  let latestUpdatedAtMs = null;
25135
25247
  try {
25136
25248
  for (const dirname of ROLLOUT_DIRS) {
25137
- const root = import_node_path10.default.join(profileHome, dirname);
25249
+ const root = import_node_path11.default.join(profileHome, dirname);
25138
25250
  try {
25139
25251
  await import_node_fs7.promises.access(root);
25140
25252
  } catch (error) {
@@ -25166,10 +25278,10 @@ async function findRolloutFileByScan(profileHome, threadId) {
25166
25278
  let best = null;
25167
25279
  const variants = threadIdVariants(threadId);
25168
25280
  for (const dirname of ROLLOUT_DIRS) {
25169
- const root = import_node_path10.default.join(profileHome, dirname);
25281
+ const root = import_node_path11.default.join(profileHome, dirname);
25170
25282
  const files = await collectRolloutFiles(root);
25171
25283
  for (const file of files) {
25172
- const basename = import_node_path10.default.basename(file);
25284
+ const basename = import_node_path11.default.basename(file);
25173
25285
  if (!variants.some((variant) => basename.includes(variant))) {
25174
25286
  continue;
25175
25287
  }
@@ -25245,11 +25357,11 @@ function resolveRolloutPath(profileHome, rolloutPath) {
25245
25357
  if (!rolloutPath) {
25246
25358
  return null;
25247
25359
  }
25248
- return import_node_path10.default.isAbsolute(rolloutPath) ? rolloutPath : import_node_path10.default.join(profileHome, rolloutPath);
25360
+ return import_node_path11.default.isAbsolute(rolloutPath) ? rolloutPath : import_node_path11.default.join(profileHome, rolloutPath);
25249
25361
  }
25250
25362
  async function collectSessionDatabasePaths(profileHome, sqliteHome = profileHome) {
25251
25363
  const paths = [];
25252
- const sqliteDir = import_node_path10.default.join(sqliteHome, "sqlite");
25364
+ const sqliteDir = import_node_path11.default.join(sqliteHome, "sqlite");
25253
25365
  try {
25254
25366
  const entries3 = await import_node_fs7.promises.readdir(sqliteDir, {
25255
25367
  withFileTypes: true,
@@ -25260,20 +25372,20 @@ async function collectSessionDatabasePaths(profileHome, sqliteHome = profileHome
25260
25372
  continue;
25261
25373
  }
25262
25374
  const entryName = String(entry.name);
25263
- if (SQLITE_EXTENSIONS.has(import_node_path10.default.extname(entryName))) {
25264
- paths.push(import_node_path10.default.join(sqliteDir, entryName));
25375
+ if (SQLITE_EXTENSIONS.has(import_node_path11.default.extname(entryName))) {
25376
+ paths.push(import_node_path11.default.join(sqliteDir, entryName));
25265
25377
  }
25266
25378
  }
25267
25379
  } catch {
25268
25380
  }
25269
25381
  paths.sort((left, right) => {
25270
- const leftName = import_node_path10.default.basename(left);
25271
- const rightName = import_node_path10.default.basename(right);
25382
+ const leftName = import_node_path11.default.basename(left);
25383
+ const rightName = import_node_path11.default.basename(right);
25272
25384
  if (leftName === "codex-dev.db" && rightName !== "codex-dev.db") return -1;
25273
25385
  if (rightName === "codex-dev.db" && leftName !== "codex-dev.db") return 1;
25274
25386
  return leftName.localeCompare(rightName);
25275
25387
  });
25276
- const legacy = import_node_path10.default.join(sqliteHome, "state_5.sqlite");
25388
+ const legacy = import_node_path11.default.join(sqliteHome, "state_5.sqlite");
25277
25389
  if (!paths.includes(legacy)) {
25278
25390
  paths.push(legacy);
25279
25391
  }
@@ -25753,7 +25865,7 @@ function hashProfileKey(profileKey) {
25753
25865
  if (!profileKey) {
25754
25866
  return null;
25755
25867
  }
25756
- return (0, import_node_crypto10.createHash)("sha256").update(profileKey).digest("hex").slice(0, 12);
25868
+ return (0, import_node_crypto11.createHash)("sha256").update(profileKey).digest("hex").slice(0, 12);
25757
25869
  }
25758
25870
  function sanitizeOfficialCodexOverlayActionTargetsForRenderer(targets) {
25759
25871
  const sanitized = [];
@@ -27434,7 +27546,7 @@ function createBridgeApplyQolExpression(settings) {
27434
27546
  if (customModelCount === 0) {
27435
27547
  const promo = document.createElement("p");
27436
27548
  promo.className = "codexuse-promo";
27437
- promo.textContent = "CodexUse can also run OpenRouter, DeepSeek, or a local model right here. Add one under Connect \u203A Model Providers.";
27549
+ promo.textContent = "CodexUse can also run OpenRouter, DeepSeek, or a local model right here. Add one under Settings \u203A Model Providers.";
27438
27550
  section.appendChild(promo);
27439
27551
  }
27440
27552
  const divider = mount.firstElementChild?.nextElementSibling;
@@ -29365,7 +29477,7 @@ async function runCdpCommandSequence(debuggerUrl, commands, timeoutMs = CODEX_CD
29365
29477
  });
29366
29478
  }
29367
29479
  async function verifyCdpBindingRoundTrip(debuggerUrl) {
29368
- const nonce = (0, import_node_crypto10.randomUUID)();
29480
+ const nonce = (0, import_node_crypto11.randomUUID)();
29369
29481
  const expression = `(() => {
29370
29482
  const binding = window[${JSON.stringify(CODEXUSE_BRIDGE_BINDING_NAME)}];
29371
29483
  if (typeof binding !== "function") return false;
@@ -29788,7 +29900,7 @@ async function startOfficialCodexBridgeActionListenerOnce(args2) {
29788
29900
  let closeNotified = false;
29789
29901
  let echoReceived = false;
29790
29902
  const requiredCommandIds = /* @__PURE__ */ new Set();
29791
- const echoId = (0, import_node_crypto10.randomUUID)();
29903
+ const echoId = (0, import_node_crypto11.randomUUID)();
29792
29904
  const readyTimeout = setTimeout(() => {
29793
29905
  settleReady(false);
29794
29906
  try {
@@ -29862,7 +29974,7 @@ async function startOfficialCodexBridgeActionListenerOnce(args2) {
29862
29974
  }
29863
29975
  };
29864
29976
  bridgeActionListenerVerifiers.set(args2.debuggerUrl, async () => {
29865
- const id2 = (0, import_node_crypto10.randomUUID)();
29977
+ const id2 = (0, import_node_crypto11.randomUUID)();
29866
29978
  return await new Promise((resolve2) => {
29867
29979
  const waiters = bridgeActionListenerHealthWaiters.get(args2.debuggerUrl) ?? /* @__PURE__ */ new Map();
29868
29980
  bridgeActionListenerHealthWaiters.set(args2.debuggerUrl, waiters);
@@ -29973,18 +30085,18 @@ async function startOfficialCodexBridgeActionListenerOnce(args2) {
29973
30085
  if (!requestId || !rememberBridgeActionId(requestId)) {
29974
30086
  return;
29975
30087
  }
29976
- const path19 = typeof payload.path === "string" ? payload.path.trim().slice(0, 64) : "";
30088
+ const path21 = typeof payload.path === "string" ? payload.path.trim().slice(0, 64) : "";
29977
30089
  const requestHandler = officialCodexBridgeRequestHandler;
29978
30090
  void (async () => {
29979
30091
  let result2;
29980
- if (!path19) {
30092
+ if (!path21) {
29981
30093
  result2 = { status: "failed", reason: "missing-path" };
29982
30094
  } else if (!requestHandler) {
29983
30095
  result2 = { status: "failed", reason: "no-request-handler" };
29984
30096
  } else {
29985
30097
  try {
29986
30098
  result2 = await requestHandler({
29987
- path: path19,
30099
+ path: path21,
29988
30100
  payload: payload.payload ?? null,
29989
30101
  sourceProfileName: bridgeActionListenerProfiles.get(args2.debuggerUrl) ?? profileName
29990
30102
  });
@@ -30410,7 +30522,7 @@ async function recordOfficialCodexActivity(input) {
30410
30522
  };
30411
30523
  const finite2 = (value3, min4, max4) => typeof value3 === "number" && Number.isFinite(value3) ? Math.max(min4, Math.min(max4, value3)) : null;
30412
30524
  const entry = {
30413
- id: (0, import_node_crypto10.randomUUID)(),
30525
+ id: (0, import_node_crypto11.randomUUID)(),
30414
30526
  at: now2.toISOString(),
30415
30527
  kind: input.kind,
30416
30528
  status: bounded(input.status, 80) ?? "unknown",
@@ -30480,7 +30592,7 @@ async function recordOfficialCodexActivity(input) {
30480
30592
  }
30481
30593
  function runCommand2(command, args2, timeoutMs = COMMAND_TIMEOUT_MS) {
30482
30594
  return new Promise((resolve2) => {
30483
- const child = (0, import_node_child_process6.spawn)(command, args2, {
30595
+ const child = (0, import_node_child_process7.spawn)(command, args2, {
30484
30596
  stdio: ["ignore", "pipe", "pipe"]
30485
30597
  });
30486
30598
  let stdout = "";
@@ -30559,7 +30671,7 @@ async function readProcessRows() {
30559
30671
  return rows;
30560
30672
  }
30561
30673
  function getMainExecutablePath(candidate) {
30562
- return import_node_path11.default.join(candidate.appPath, "Contents", "MacOS", candidate.executableName);
30674
+ return import_node_path12.default.join(candidate.appPath, "Contents", "MacOS", candidate.executableName);
30563
30675
  }
30564
30676
  function isMainProcessRow(row, candidate) {
30565
30677
  return row.args.includes(getMainExecutablePath(candidate));
@@ -31404,12 +31516,12 @@ async function resolveOfficialCodexBridgeTarget(args2) {
31404
31516
  }
31405
31517
  var devToolsActivePortPaths = (appUserDataDir) => {
31406
31518
  const roots = appUserDataDir ? [appUserDataDir] : [
31407
- import_node_path11.default.join((0, import_node_os4.homedir)(), "Library", "Application Support", "OpenAI", "Codex"),
31408
- import_node_path11.default.join((0, import_node_os4.homedir)(), "Library", "Application Support", "Codex"),
31409
- import_node_path11.default.join((0, import_node_os4.homedir)(), "Library", "Application Support", "com.openai.codex"),
31410
- import_node_path11.default.join((0, import_node_os4.homedir)(), "Library", "Application Support", "com.openai.chat")
31519
+ import_node_path12.default.join((0, import_node_os4.homedir)(), "Library", "Application Support", "OpenAI", "Codex"),
31520
+ import_node_path12.default.join((0, import_node_os4.homedir)(), "Library", "Application Support", "Codex"),
31521
+ import_node_path12.default.join((0, import_node_os4.homedir)(), "Library", "Application Support", "com.openai.codex"),
31522
+ import_node_path12.default.join((0, import_node_os4.homedir)(), "Library", "Application Support", "com.openai.chat")
31411
31523
  ];
31412
- return roots.map((root) => import_node_path11.default.join(root, "DevToolsActivePort"));
31524
+ return roots.map((root) => import_node_path12.default.join(root, "DevToolsActivePort"));
31413
31525
  };
31414
31526
  var readDevToolsActivePort = async (filePath) => {
31415
31527
  try {
@@ -31462,7 +31574,7 @@ async function openCodexWithProfileHome(candidate, profileHome, profileName, pre
31462
31574
  }
31463
31575
  const telemetryLabel = `codexuse-profile-${encodeURIComponent(profileName)}`;
31464
31576
  const launchHome = resolveCodexLaunchHome(profileHome);
31465
- const appUserDataDir = options.useDefaultUserData === true ? null : options.userDataDir ?? import_node_path11.default.join(profileHome, "codex-app-user-data");
31577
+ const appUserDataDir = options.useDefaultUserData === true ? null : options.userDataDir ?? import_node_path12.default.join(profileHome, "codex-app-user-data");
31466
31578
  const sqliteHome = options.sqliteHome ?? profileHome;
31467
31579
  const activePortPaths = devToolsActivePortPaths(appUserDataDir);
31468
31580
  let child;
@@ -31470,7 +31582,7 @@ async function openCodexWithProfileHome(candidate, profileHome, profileName, pre
31470
31582
  if (appUserDataDir) {
31471
31583
  (0, import_node_fs8.mkdirSync)(appUserDataDir, { recursive: true });
31472
31584
  }
31473
- child = (0, import_node_child_process6.spawn)(
31585
+ child = (0, import_node_child_process7.spawn)(
31474
31586
  "/usr/bin/open",
31475
31587
  [
31476
31588
  "-n",
@@ -31616,13 +31728,13 @@ async function openCodexWithProfileHome(candidate, profileHome, profileName, pre
31616
31728
  };
31617
31729
  }
31618
31730
  function resolveCodexLaunchHome(profileHome) {
31619
- if (Buffer.byteLength(import_node_path11.default.join(profileHome, "ipc", "ipc.sock")) >= 100) {
31731
+ if (Buffer.byteLength(import_node_path12.default.join(profileHome, "ipc", "ipc.sock")) >= 100) {
31620
31732
  throw new Error("codex-home-path-too-long");
31621
31733
  }
31622
31734
  return profileHome;
31623
31735
  }
31624
31736
  async function readBundleString(appPath, key) {
31625
- const plistPath = import_node_path11.default.join(appPath, "Contents", "Info.plist");
31737
+ const plistPath = import_node_path12.default.join(appPath, "Contents", "Info.plist");
31626
31738
  if (!(0, import_node_fs8.existsSync)(plistPath)) {
31627
31739
  return null;
31628
31740
  }
@@ -31642,18 +31754,18 @@ async function readBundleString(appPath, key) {
31642
31754
  }
31643
31755
  function addStandardOfficialCodexAppPaths(rawPaths) {
31644
31756
  for (const appName of OFFICIAL_CODEX_APP_NAMES) {
31645
- rawPaths.add(import_node_path11.default.join("/Applications", appName));
31646
- rawPaths.add(import_node_path11.default.join((0, import_node_os4.homedir)(), "Applications", appName));
31757
+ rawPaths.add(import_node_path12.default.join("/Applications", appName));
31758
+ rawPaths.add(import_node_path12.default.join((0, import_node_os4.homedir)(), "Applications", appName));
31647
31759
  }
31648
31760
  }
31649
31761
  function officialCodexAppPriority(appPath) {
31650
- const priority = OFFICIAL_CODEX_APP_NAMES.indexOf(import_node_path11.default.basename(appPath));
31762
+ const priority = OFFICIAL_CODEX_APP_NAMES.indexOf(import_node_path12.default.basename(appPath));
31651
31763
  return priority >= 0 ? priority : OFFICIAL_CODEX_APP_NAMES.length;
31652
31764
  }
31653
31765
  async function collectCodexAppCandidates(rawPaths) {
31654
31766
  const candidates = [];
31655
31767
  for (const appPath of rawPaths) {
31656
- if (!(0, import_node_fs8.existsSync)(appPath) || !OFFICIAL_CODEX_APP_NAMES.includes(import_node_path11.default.basename(appPath)) || !(0, import_node_fs8.existsSync)(import_node_path11.default.join(appPath, "Contents", "Resources", "codex"))) {
31768
+ if (!(0, import_node_fs8.existsSync)(appPath) || !OFFICIAL_CODEX_APP_NAMES.includes(import_node_path12.default.basename(appPath)) || !(0, import_node_fs8.existsSync)(import_node_path12.default.join(appPath, "Contents", "Resources", "codex"))) {
31657
31769
  continue;
31658
31770
  }
31659
31771
  const bundleId = await readBundleString(appPath, "CFBundleIdentifier");
@@ -31664,7 +31776,7 @@ async function collectCodexAppCandidates(rawPaths) {
31664
31776
  appPath,
31665
31777
  bundleId,
31666
31778
  version: await readBundleString(appPath, "CFBundleShortVersionString"),
31667
- executableName: await readBundleString(appPath, "CFBundleExecutable") ?? import_node_path11.default.basename(appPath, ".app")
31779
+ executableName: await readBundleString(appPath, "CFBundleExecutable") ?? import_node_path12.default.basename(appPath, ".app")
31668
31780
  });
31669
31781
  }
31670
31782
  return candidates.sort(
@@ -31673,7 +31785,7 @@ async function collectCodexAppCandidates(rawPaths) {
31673
31785
  }
31674
31786
  function getRunningCodexPidsFromRows(candidate, rows) {
31675
31787
  const pids = /* @__PURE__ */ new Set();
31676
- const appContentsRoot = `${import_node_path11.default.join(candidate.appPath, "Contents")}${import_node_path11.default.sep}`;
31788
+ const appContentsRoot = `${import_node_path12.default.join(candidate.appPath, "Contents")}${import_node_path12.default.sep}`;
31677
31789
  for (const row of rows) {
31678
31790
  if (row.args.includes(appContentsRoot)) {
31679
31791
  pids.add(row.pid);
@@ -31683,7 +31795,7 @@ function getRunningCodexPidsFromRows(candidate, rows) {
31683
31795
  }
31684
31796
  function getRunningCodexMainPidsFromRows(candidate, rows) {
31685
31797
  const pids = /* @__PURE__ */ new Set();
31686
- const executablePath = import_node_path11.default.join(
31798
+ const executablePath = import_node_path12.default.join(
31687
31799
  candidate.appPath,
31688
31800
  "Contents",
31689
31801
  "MacOS",
@@ -31721,7 +31833,7 @@ async function resolveCodexAppTarget() {
31721
31833
  mainPids: getRunningCodexMainPidsFromRows(candidate, rows)
31722
31834
  })).filter((entry) => entry.mainPids.length > 0);
31723
31835
  const explicit = explicitPath ? runningCandidates.find(
31724
- (entry) => import_node_path11.default.resolve(entry.candidate.appPath) === import_node_path11.default.resolve(explicitPath)
31836
+ (entry) => import_node_path12.default.resolve(entry.candidate.appPath) === import_node_path12.default.resolve(explicitPath)
31725
31837
  ) : null;
31726
31838
  if (runningCandidates.length > 1) {
31727
31839
  return {
@@ -31762,10 +31874,10 @@ function resolveOfficialCodexThreadSqliteHome(profileHome) {
31762
31874
  return profileHome === SHARED_CODEX_HOME ? resolveCodexSqliteHomeDir(profileHome) : profileHome;
31763
31875
  }
31764
31876
  function sharedCodexLaunchOptions(useDefaultUserData, profileIdentity) {
31765
- const userDataDir = !useDefaultUserData && profileIdentity ? import_node_path11.default.join(
31877
+ const userDataDir = !useDefaultUserData && profileIdentity ? import_node_path12.default.join(
31766
31878
  SHARED_CODEX_HOME,
31767
31879
  "codex-app-user-data",
31768
- (0, import_node_crypto10.createHash)("sha256").update(profileIdentity).digest("hex").slice(0, 16)
31880
+ (0, import_node_crypto11.createHash)("sha256").update(profileIdentity).digest("hex").slice(0, 16)
31769
31881
  ) : void 0;
31770
31882
  return {
31771
31883
  useDefaultUserData,
@@ -31962,7 +32074,7 @@ function isSharedHomeMainProcessRow(row, candidate) {
31962
32074
  resolveProfileCodexHomesRoot(),
31963
32075
  resolveLegacyProfileCodexHomesRoot()
31964
32076
  ];
31965
- return isMainProcessRow(row, candidate) && managedRoots.every((root) => !row.args.includes(`${root}${import_node_path11.default.sep}`));
32077
+ return isMainProcessRow(row, candidate) && managedRoots.every((root) => !row.args.includes(`${root}${import_node_path12.default.sep}`));
31966
32078
  }
31967
32079
  async function hydrateSharedHomeCdpWindow(rows, candidate) {
31968
32080
  const isRunningCandidate = async (value3) => {
@@ -34176,7 +34288,7 @@ async function attemptOfficialCodexManagedLiveLogin(args2) {
34176
34288
  }
34177
34289
  }
34178
34290
  async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTrace = {
34179
- operationId: (0, import_node_crypto10.randomUUID)(),
34291
+ operationId: (0, import_node_crypto11.randomUUID)(),
34180
34292
  attempt: 1
34181
34293
  }) {
34182
34294
  let expectedWindowPreflight = options.expectedWindowPreflight;
@@ -35244,7 +35356,7 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
35244
35356
  }
35245
35357
  function applyOfficialCodexLiveAccountSwitch(options = {}) {
35246
35358
  return enqueueProfileAction("shared-window", async () => {
35247
- const operationId = (0, import_node_crypto10.randomUUID)();
35359
+ const operationId = (0, import_node_crypto11.randomUUID)();
35248
35360
  let result2 = await applyOfficialCodexLiveAccountSwitchOnce(options, {
35249
35361
  operationId,
35250
35362
  attempt: 1
@@ -35969,16 +36081,16 @@ async function launchOfficialCodexProfileInstanceOnce(options) {
35969
36081
  }
35970
36082
 
35971
36083
  // ../../packages/runtime-app-state/src/app/profileHomeMutationCoordinator.ts
35972
- var import_node_crypto11 = require("crypto");
36084
+ var import_node_crypto12 = require("crypto");
35973
36085
 
35974
36086
  // ../../packages/runtime-app-state/src/app/processOwner.ts
35975
- var import_node_child_process7 = require("child_process");
36087
+ var import_node_child_process8 = require("child_process");
35976
36088
  function readProcessStartedAt(pid) {
35977
36089
  if (!Number.isSafeInteger(pid) || pid <= 0) {
35978
36090
  return null;
35979
36091
  }
35980
36092
  try {
35981
- const output = (0, import_node_child_process7.execFileSync)("/bin/ps", ["-p", String(pid), "-o", "lstart="], {
36093
+ const output = (0, import_node_child_process8.execFileSync)("/bin/ps", ["-p", String(pid), "-o", "lstart="], {
35982
36094
  encoding: "utf8",
35983
36095
  timeout: 2e3
35984
36096
  }).trim();
@@ -36007,12 +36119,12 @@ function isProcessEpochAlive(pid, expectedStartedAt) {
36007
36119
  // ../../packages/runtime-app-state/src/app/profileHomeMutationCoordinator.ts
36008
36120
  var PROFILE_HOME_MUTATION_TTL_MS = 10 * 60 * 1e3;
36009
36121
  var PROFILE_HOME_MUTATION_RENEW_MS = 30 * 1e3;
36010
- var PROCESS_OWNER_ID = (0, import_node_crypto11.randomUUID)();
36122
+ var PROCESS_OWNER_ID = (0, import_node_crypto12.randomUUID)();
36011
36123
  var PROCESS_STARTED_AT = readProcessStartedAt(process.pid);
36012
36124
  var activeRenewals = /* @__PURE__ */ new Map();
36013
36125
  async function acquireProfileHomeMutationIntent(input) {
36014
36126
  const now2 = Date.now();
36015
- const operationId = (0, import_node_crypto11.randomUUID)();
36127
+ const operationId = (0, import_node_crypto12.randomUUID)();
36016
36128
  const renewal = {
36017
36129
  timer: void 0,
36018
36130
  pending: Promise.resolve(),
@@ -36095,7 +36207,7 @@ async function releaseProfileHomeMutationIntent(homeId, operationId) {
36095
36207
 
36096
36208
  // ../../packages/runtime-profiles/src/profiles/rate-limit-cache.ts
36097
36209
  var import_node_fs9 = require("fs");
36098
- var import_node_path12 = __toESM(require("path"), 1);
36210
+ var import_node_path13 = __toESM(require("path"), 1);
36099
36211
  var memorySnapshots = /* @__PURE__ */ new Map();
36100
36212
  var persistedSnapshotWriteLock = Promise.resolve();
36101
36213
  var RATE_LIMIT_SNAPSHOT_CACHE_FILE = "rate-limit-snapshots.json";
@@ -36103,7 +36215,7 @@ function cloneSnapshot(snapshot2) {
36103
36215
  return JSON.parse(JSON.stringify(snapshot2));
36104
36216
  }
36105
36217
  function snapshotCachePath() {
36106
- return import_node_path12.default.join(getUserDataDir(), RATE_LIMIT_SNAPSHOT_CACHE_FILE);
36218
+ return import_node_path13.default.join(getUserDataDir(), RATE_LIMIT_SNAPSHOT_CACHE_FILE);
36107
36219
  }
36108
36220
  async function loadPersistedSnapshots() {
36109
36221
  let raw;
@@ -36152,7 +36264,7 @@ async function writePersistedSnapshots(snapshots) {
36152
36264
  2
36153
36265
  );
36154
36266
  try {
36155
- await import_node_fs9.promises.mkdir(import_node_path12.default.dirname(filePath), { recursive: true });
36267
+ await import_node_fs9.promises.mkdir(import_node_path13.default.dirname(filePath), { recursive: true });
36156
36268
  await import_node_fs9.promises.writeFile(tmpPath, `${payload}
36157
36269
  `, "utf8");
36158
36270
  await import_node_fs9.promises.rename(tmpPath, filePath);
@@ -36209,9 +36321,20 @@ async function pruneRateLimitSnapshots(allowedKeys) {
36209
36321
 
36210
36322
  // ../../packages/shared/src/core/profile-home-id.ts
36211
36323
  var PROFILE_HOME_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
36324
+ function isSafeProfileHomePathSegment(value3) {
36325
+ if (typeof value3 !== "string" || value3 !== value3.trim()) {
36326
+ return false;
36327
+ }
36328
+ return Boolean(
36329
+ value3 && value3 !== "." && value3 !== ".." && value3.length <= 128 && !/[\\/]/.test(value3) && !Array.from(value3).some((character) => {
36330
+ const code = character.charCodeAt(0);
36331
+ return code < 32 || code === 127;
36332
+ })
36333
+ );
36334
+ }
36212
36335
  function normalizeProfileHomeId(value3) {
36213
36336
  const candidate = typeof value3 === "string" ? value3.trim() : "";
36214
- return candidate && candidate !== "." && candidate !== ".." && candidate.length <= 128 && PROFILE_HOME_ID_PATTERN.test(candidate) ? candidate : null;
36337
+ return isSafeProfileHomePathSegment(candidate) && PROFILE_HOME_ID_PATTERN.test(candidate) ? candidate : null;
36215
36338
  }
36216
36339
 
36217
36340
  // ../../packages/runtime-profiles/src/profiles/profile-manager.ts
@@ -36223,7 +36346,7 @@ var AUTH_MUTATION_MANIFEST_NAME = ".codexuse-auth-transaction.json";
36223
36346
  var AUTH_MUTATION_BACKUP_NAME = ".codexuse-auth-transaction.backup";
36224
36347
  var AUTH_MUTATION_REPLACED_NAME = ".codexuse-auth-transaction.replaced";
36225
36348
  var PROFILE_HOME_MUTATION_MARKER_TTL_MS = 10 * 60 * 1e3;
36226
- var PROCESS_OWNER_ID2 = (0, import_node_crypto12.randomUUID)();
36349
+ var PROCESS_OWNER_ID2 = (0, import_node_crypto13.randomUUID)();
36227
36350
  var PROCESS_STARTED_AT2 = readProcessStartedAt(process.pid);
36228
36351
  var globalAuthSwapLock = Promise.resolve();
36229
36352
  var profileOperationLocks = /* @__PURE__ */ new Map();
@@ -37033,7 +37156,14 @@ var ProfileManager = class {
37033
37156
  }
37034
37157
  await this.credentialsMigrationPromise;
37035
37158
  }
37036
- async migrateCredentialsToProfileHomes() {
37159
+ migrateCredentialsToProfileHomes() {
37160
+ return withCloudSyncTransaction(
37161
+ getUserDataDir(),
37162
+ "write",
37163
+ () => this.migrateCredentialsToProfileHomesUnlocked()
37164
+ );
37165
+ }
37166
+ async migrateCredentialsToProfileHomesUnlocked() {
37037
37167
  const source = await this.readProfilesStateSource();
37038
37168
  await this.reconcileProfileHomeLocationConflicts(source);
37039
37169
  const homeIdsByProfileName = /* @__PURE__ */ new Map();
@@ -37069,7 +37199,7 @@ var ProfileManager = class {
37069
37199
  let attempt = 0;
37070
37200
  let homeId;
37071
37201
  do {
37072
- homeId = `legacy-${(0, import_node_crypto12.createHash)("sha256").update(profileName).update("\0").update(String(attempt)).digest("hex").slice(0, 32)}`;
37202
+ homeId = `legacy-${(0, import_node_crypto13.createHash)("sha256").update(profileName).update("\0").update(String(attempt)).digest("hex").slice(0, 32)}`;
37073
37203
  attempt += 1;
37074
37204
  } while (profileNamesByHomeId.has(homeId.toLowerCase()));
37075
37205
  homeIdsByProfileName.set(profileName, homeId);
@@ -37279,7 +37409,7 @@ var ProfileManager = class {
37279
37409
  const dir = import_path.default.dirname(filePath);
37280
37410
  const tempPath = import_path.default.join(
37281
37411
  dir,
37282
- `.${import_path.default.basename(filePath)}.${process.pid}.${(0, import_node_crypto12.randomUUID)()}.tmp`
37412
+ `.${import_path.default.basename(filePath)}.${process.pid}.${(0, import_node_crypto13.randomUUID)()}.tmp`
37283
37413
  );
37284
37414
  await import_fs.promises.mkdir(dir, { recursive: true, mode: 448 });
37285
37415
  if (process.platform !== "win32") {
@@ -37566,7 +37696,7 @@ var ProfileManager = class {
37566
37696
  if (content === null) {
37567
37697
  return null;
37568
37698
  }
37569
- return (0, import_node_crypto12.createHash)("sha256").update(content).digest("hex");
37699
+ return (0, import_node_crypto13.createHash)("sha256").update(content).digest("hex");
37570
37700
  }
37571
37701
  async readOptionalFile(filePath) {
37572
37702
  try {
@@ -37624,7 +37754,7 @@ var ProfileManager = class {
37624
37754
  const dir = import_path.default.dirname(filePath);
37625
37755
  const tempPath = import_path.default.join(
37626
37756
  dir,
37627
- `.${import_path.default.basename(filePath)}.${process.pid}.${(0, import_node_crypto12.randomUUID)()}.install`
37757
+ `.${import_path.default.basename(filePath)}.${process.pid}.${(0, import_node_crypto13.randomUUID)()}.install`
37628
37758
  );
37629
37759
  const handle = await import_fs.promises.open(tempPath, "wx", 384);
37630
37760
  try {
@@ -37709,29 +37839,31 @@ var ProfileManager = class {
37709
37839
  );
37710
37840
  }
37711
37841
  async withAuthMutationLock(task) {
37712
- const release = await this.acquireAuthMutationLock();
37713
- let result2;
37714
- let taskError = null;
37715
- let taskFailed = false;
37716
- try {
37717
- await this.recoverAuthMutationIfNeeded();
37718
- result2 = await task();
37719
- } catch (error) {
37720
- taskFailed = true;
37721
- taskError = error;
37722
- }
37723
- try {
37724
- await release();
37725
- } catch (releaseError) {
37726
- throw errorWithCause(
37727
- "Codex auth transaction lock could not be released.",
37728
- { taskError, releaseError }
37729
- );
37730
- }
37731
- if (taskFailed) {
37732
- throw taskError;
37733
- }
37734
- return result2;
37842
+ return withCloudSyncTransaction(getUserDataDir(), "write", async () => {
37843
+ const release = await this.acquireAuthMutationLock();
37844
+ let result2;
37845
+ let taskError = null;
37846
+ let taskFailed = false;
37847
+ try {
37848
+ await this.recoverAuthMutationIfNeeded();
37849
+ result2 = await task();
37850
+ } catch (error) {
37851
+ taskFailed = true;
37852
+ taskError = error;
37853
+ }
37854
+ try {
37855
+ await release();
37856
+ } catch (releaseError) {
37857
+ throw errorWithCause(
37858
+ "Codex auth transaction lock could not be released.",
37859
+ { taskError, releaseError }
37860
+ );
37861
+ }
37862
+ if (taskFailed) {
37863
+ throw taskError;
37864
+ }
37865
+ return result2;
37866
+ });
37735
37867
  }
37736
37868
  async beginAuthMutation(operation, targetFingerprint) {
37737
37869
  const sourceRaw = await this.readOptionalFile(this.activeAuth);
@@ -37742,7 +37874,7 @@ var ProfileManager = class {
37742
37874
  });
37743
37875
  const manifest = {
37744
37876
  version: 1,
37745
- id: (0, import_node_crypto12.randomUUID)(),
37877
+ id: (0, import_node_crypto13.randomUUID)(),
37746
37878
  operation,
37747
37879
  phase: "prepared",
37748
37880
  sourceFingerprint: this.fingerprintAuthContent(sourceRaw),
@@ -38414,7 +38546,14 @@ var ProfileManager = class {
38414
38546
  normalizeWorkspaceId(value3) {
38415
38547
  return typeof value3 === "string" && value3.trim().length > 0 ? value3.trim() : DEFAULT_WORKSPACE_ID;
38416
38548
  }
38417
- async persistProfileRecord(name, data, metadata, options) {
38549
+ persistProfileRecord(name, data, metadata, options) {
38550
+ return withCloudSyncTransaction(
38551
+ getUserDataDir(),
38552
+ "write",
38553
+ () => this.persistProfileRecordUnlocked(name, data, metadata, options)
38554
+ );
38555
+ }
38556
+ async persistProfileRecordUnlocked(name, data, metadata, options) {
38418
38557
  const resolvedName = this.normalizeProfileName(name);
38419
38558
  this.assertProfileHomeUsable(resolvedName);
38420
38559
  const initialMap = await this.readProfilesStateMap();
@@ -38464,7 +38603,7 @@ var ProfileManager = class {
38464
38603
  const displayName = typeof options?.displayName === "string" && options.displayName.trim().length > 0 ? options.displayName.trim() : existingRecord?.displayName ?? resolvedName;
38465
38604
  const record2 = {
38466
38605
  name: resolvedName,
38467
- homeId: existingRecord?.homeId ?? (options?.homeId ? this.normalizeProfileHomeId(options.homeId, resolvedName) : (0, import_node_crypto12.randomUUID)()),
38606
+ homeId: existingRecord?.homeId ?? (options?.homeId ? this.normalizeProfileHomeId(options.homeId, resolvedName) : (0, import_node_crypto13.randomUUID)()),
38468
38607
  cloudHomeId: existingRecord?.cloudHomeId ?? null,
38469
38608
  displayName,
38470
38609
  data,
@@ -38569,7 +38708,7 @@ var ProfileManager = class {
38569
38708
  const safeName = record2.name.replace(/[^A-Za-z0-9._-]+/g, "-").slice(0, 48) || "profile";
38570
38709
  const destination = import_path.default.join(
38571
38710
  trashRoot,
38572
- `CodexUse-${safeName}-${(0, import_node_crypto12.randomUUID)()}`
38711
+ `CodexUse-${safeName}-${(0, import_node_crypto13.randomUUID)()}`
38573
38712
  );
38574
38713
  await import_fs.promises.rename(profileHome, destination);
38575
38714
  return destination;
@@ -38997,7 +39136,7 @@ var ProfileManager = class {
38997
39136
  async acquireProfileRuntimeLease(record2) {
38998
39137
  const leaseDir = this.getProfileRuntimeLeaseDir(record2.homeId);
38999
39138
  const deletingPath = (0, import_path2.join)(leaseDir, ".deleting");
39000
- const leaseId = (0, import_node_crypto12.randomUUID)();
39139
+ const leaseId = (0, import_node_crypto13.randomUUID)();
39001
39140
  const leasePath = (0, import_path2.join)(leaseDir, `${leaseId}.json`);
39002
39141
  const backupPath = (0, import_path2.join)(leaseDir, `${leaseId}.auth.backup`);
39003
39142
  const releaseIntent = await this.acquireProfileHomeWriteIntent(record2);
@@ -39208,7 +39347,7 @@ var ProfileManager = class {
39208
39347
  async acquireProfileHomeMutationGuard(record2) {
39209
39348
  const leaseDir = this.getProfileRuntimeLeaseDir(record2.homeId);
39210
39349
  const deletingPath = (0, import_path2.join)(leaseDir, ".deleting");
39211
- const mutationId = (0, import_node_crypto12.randomUUID)();
39350
+ const mutationId = (0, import_node_crypto13.randomUUID)();
39212
39351
  const mutationIntent = await acquireProfileHomeMutationIntent({
39213
39352
  homeId: record2.homeId,
39214
39353
  profileName: record2.name
@@ -40468,32 +40607,39 @@ var ProfileManager = class {
40468
40607
  */
40469
40608
  async exportProfilesForCloudSync() {
40470
40609
  await this.initialize();
40471
- const records = await this.listProfileRecords();
40472
- const exported = [];
40473
- for (const storedRecord of records) {
40474
- const record2 = await this.hydrateProfileRecordStrict(storedRecord);
40475
- exported.push({
40476
- name: record2.name,
40477
- homeId: record2.cloudHomeId ?? record2.homeId,
40478
- displayName: record2.displayName,
40479
- data: record2.data,
40480
- metadata: record2.metadata,
40481
- accountId: record2.accountId,
40482
- workspaceId: record2.workspaceId,
40483
- workspaceName: record2.workspaceName,
40484
- email: record2.email,
40485
- authMethod: record2.authMethod,
40486
- createdAt: record2.createdAt,
40487
- updatedAt: record2.updatedAt
40488
- });
40489
- }
40490
- return exported;
40610
+ return withCloudSyncTransaction(getUserDataDir(), "write", async () => {
40611
+ const records = await this.listProfileRecords();
40612
+ const exported = [];
40613
+ for (const storedRecord of records) {
40614
+ const record2 = await this.hydrateProfileRecordStrict(storedRecord);
40615
+ exported.push({
40616
+ name: record2.name,
40617
+ homeId: record2.cloudHomeId ?? record2.homeId,
40618
+ displayName: record2.displayName,
40619
+ data: record2.data,
40620
+ metadata: record2.metadata,
40621
+ accountId: record2.accountId,
40622
+ workspaceId: record2.workspaceId,
40623
+ workspaceName: record2.workspaceName,
40624
+ email: record2.email,
40625
+ authMethod: record2.authMethod,
40626
+ createdAt: record2.createdAt,
40627
+ updatedAt: record2.updatedAt
40628
+ });
40629
+ }
40630
+ return exported;
40631
+ });
40491
40632
  }
40492
- /**
40493
- * Replace local profiles with a full snapshot from cloud sync.
40494
- */
40495
- async replaceProfilesFromCloudSync(records) {
40633
+ /** Replaces profiles, optionally deferring stale-home removal until commit. */
40634
+ async replaceProfilesFromCloudSync(records, options = {}) {
40496
40635
  await this.initialize();
40636
+ return withCloudSyncTransaction(
40637
+ getUserDataDir(),
40638
+ "write",
40639
+ () => this.replaceProfilesFromCloudSyncUnlocked(records, options)
40640
+ );
40641
+ }
40642
+ async replaceProfilesFromCloudSyncUnlocked(records, options) {
40497
40643
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
40498
40644
  const normalized = /* @__PURE__ */ new Map();
40499
40645
  const existingMap = await this.readProfilesStateMap();
@@ -40560,8 +40706,12 @@ var ProfileManager = class {
40560
40706
  }
40561
40707
  cloudRenamesByOldName.set(renamedExisting.name, name);
40562
40708
  }
40563
- const homeId = (0, import_node_crypto12.randomUUID)();
40564
- const cloudHomeId = remoteHomeId || existing?.cloudHomeId || existing?.homeId || renamedExisting?.cloudHomeId || renamedExisting?.homeId || (0, import_node_crypto12.randomUUID)();
40709
+ const mappedHomeId = options.homeIdByProfileName?.[name];
40710
+ if (mappedHomeId !== void 0 && !isSafeProfileHomePathSegment(mappedHomeId)) {
40711
+ throw new Error(`Cloud Sync restore contains an invalid profile home id.`);
40712
+ }
40713
+ const homeId = mappedHomeId ?? (0, import_node_crypto13.randomUUID)();
40714
+ const cloudHomeId = remoteHomeId || existing?.cloudHomeId || existing?.homeId || renamedExisting?.cloudHomeId || renamedExisting?.homeId || (0, import_node_crypto13.randomUUID)();
40565
40715
  const sourceRecord = renamedExisting ?? existing;
40566
40716
  if (sourceRecord) {
40567
40717
  sourceHomeIdByTargetHomeId.set(homeId, sourceRecord.homeId);
@@ -40599,6 +40749,9 @@ var ProfileManager = class {
40599
40749
  for (const record2 of normalized.values()) {
40600
40750
  nextMap[record2.name] = this.toStateRecord(record2);
40601
40751
  }
40752
+ await options.onPreparedHomeIds?.(
40753
+ Array.from(normalized.values(), (record2) => record2.homeId)
40754
+ );
40602
40755
  const nextHomeIds = new Set(
40603
40756
  Array.from(normalized.values(), (record2) => record2.homeId)
40604
40757
  );
@@ -40612,6 +40765,7 @@ var ProfileManager = class {
40612
40765
  const preparedHomeIds = /* @__PURE__ */ new Set();
40613
40766
  let stateCommitted = false;
40614
40767
  let removed = 0;
40768
+ let pendingStaleRemovals = [];
40615
40769
  const releaseAuthMutation = await this.acquireAuthMutationLock();
40616
40770
  let cloudSyncError = null;
40617
40771
  let cloudSyncFailed = false;
@@ -40647,18 +40801,21 @@ var ProfileManager = class {
40647
40801
  }
40648
40802
  homeExisted = false;
40649
40803
  }
40650
- if (homeExisted) {
40804
+ const reusingExistingHome = options.homeIdByProfileName?.[record2.name] === record2.homeId;
40805
+ if (homeExisted && !reusingExistingHome) {
40651
40806
  throw new Error(
40652
40807
  `Generated profile home '${record2.homeId}' already exists. Retry Cloud Sync.`
40653
40808
  );
40654
40809
  }
40655
- preparedHomeIds.add(record2.homeId);
40810
+ if (!reusingExistingHome) {
40811
+ preparedHomeIds.add(record2.homeId);
40812
+ }
40656
40813
  const writtenAuth = JSON.stringify(
40657
40814
  this.convertToCodexFormat(record2.data),
40658
40815
  null,
40659
40816
  2
40660
40817
  );
40661
- const sourceHomeId = sourceHomeIdByTargetHomeId.get(record2.homeId);
40818
+ const sourceHomeId = reusingExistingHome ? null : sourceHomeIdByTargetHomeId.get(record2.homeId);
40662
40819
  if (sourceHomeId) {
40663
40820
  const sourceHome = this.getProfileHomePath(sourceHomeId);
40664
40821
  let sourceHomeExists = true;
@@ -40720,16 +40877,13 @@ var ProfileManager = class {
40720
40877
  ).catch((error) => {
40721
40878
  logWarn("Failed to prune rate-limit snapshots after Cloud Sync:", error);
40722
40879
  });
40723
- for (const record2 of existingRecords.values()) {
40724
- if (nextHomeIds.has(record2.homeId)) {
40725
- continue;
40726
- }
40727
- try {
40728
- await this.removeProfileHome(record2, true);
40729
- removed += 1;
40730
- } catch (error) {
40731
- logWarn(`Failed to move stale profile '${record2.name}' to Trash after cloud sync:`, error);
40732
- }
40880
+ const staleRecords = Array.from(existingRecords.values()).filter(
40881
+ (record2) => !nextHomeIds.has(record2.homeId)
40882
+ );
40883
+ if (options.deferStaleHomeRemoval) {
40884
+ pendingStaleRemovals = staleRecords;
40885
+ } else {
40886
+ removed = await this.removeStaleProfileHomes(staleRecords);
40733
40887
  }
40734
40888
  } catch (error) {
40735
40889
  cloudSyncFailed = true;
@@ -40783,9 +40937,61 @@ var ProfileManager = class {
40783
40937
  }
40784
40938
  return {
40785
40939
  imported: normalized.size,
40786
- removed
40940
+ removed,
40941
+ pendingStaleRemovals
40787
40942
  };
40788
40943
  }
40944
+ /** Returns the physical home currently backing each profile. */
40945
+ async getProfileHomeIdsByName() {
40946
+ await this.initialize();
40947
+ return withCloudSyncTransaction(getUserDataDir(), "write", async () => {
40948
+ const stateMap = await this.readProfilesStateMap();
40949
+ return Object.fromEntries(
40950
+ Object.entries(stateMap).flatMap(([name, raw]) => {
40951
+ const record2 = this.fromStateRecord(name, raw);
40952
+ return record2?.homeId ? [[name, record2.homeId]] : [];
40953
+ })
40954
+ );
40955
+ });
40956
+ }
40957
+ /** Permanently deletes unreferenced credential homes created by a failed pull. */
40958
+ async deleteAbandonedPullProfileHomes(homeIds) {
40959
+ if (homeIds.some((homeId) => normalizeProfileHomeId(homeId) !== homeId)) {
40960
+ throw new Error("Cloud Sync cleanup contains an invalid profile home id.");
40961
+ }
40962
+ let deleted = 0;
40963
+ for (const homeId of homeIds) {
40964
+ try {
40965
+ await import_fs.promises.rm(this.getProfileHomePath(homeId), {
40966
+ recursive: true,
40967
+ force: true
40968
+ });
40969
+ deleted += 1;
40970
+ } catch (error) {
40971
+ logWarn(
40972
+ `Failed to delete the home an abandoned cloud pull created ('${homeId}'):`,
40973
+ error
40974
+ );
40975
+ }
40976
+ }
40977
+ return deleted;
40978
+ }
40979
+ /** Moves stale user homes to Trash after every synced store commits. */
40980
+ async removeStaleProfileHomes(records) {
40981
+ let removed = 0;
40982
+ for (const record2 of records) {
40983
+ try {
40984
+ await this.removeProfileHome(record2, true);
40985
+ removed += 1;
40986
+ } catch (error) {
40987
+ logWarn(
40988
+ `Failed to move stale profile '${record2.name}' to Trash after cloud sync:`,
40989
+ error
40990
+ );
40991
+ }
40992
+ }
40993
+ return removed;
40994
+ }
40789
40995
  };
40790
40996
 
40791
40997
  // ../../packages/runtime-profiles/src/profiles/managed-profile.ts
@@ -40998,8 +41204,8 @@ Flags:
40998
41204
  --take-control Allow verified replacement of an unmanaged ChatGPT/Codex window
40999
41205
  --profile=NAME Explicitly override a workspace binding for codexuse run
41000
41206
  --strict Reject a --profile override that conflicts with a workspace binding
41001
- --runtime=NAME Accounts Pool runtime store: desktop
41002
- --state-dir=PATH Override the runtime state dir for Accounts Pool inspection
41207
+ --runtime=NAME Account Pool runtime store: desktop
41208
+ --state-dir=PATH Override the runtime state dir for Account Pool inspection
41003
41209
  --passphrase-stdin Read Cloud Sync passphrase from stdin
41004
41210
  Note: profile autoroll requires Pro or an active trial.
41005
41211
  Cloud Sync: set CODEXUSE_SYNC_PASSPHRASE or use --passphrase-stdin unless the passphrase is saved in Keychain.
@@ -41068,7 +41274,7 @@ function parseStringFlag(flags, name) {
41068
41274
 
41069
41275
  // src/commands/accountPool.ts
41070
41276
  var ACCOUNT_POOL_DOCUMENT = "desktop.account-pool.v2";
41071
- var ACCOUNT_POOL_PRO_REQUIRED_MESSAGE = "Accounts Pool requires a Pro license or an active trial.";
41277
+ var ACCOUNT_POOL_PRO_REQUIRED_MESSAGE = "Account Pool requires a Pro license or an active trial.";
41072
41278
  var DESKTOP_RPC_STATE_DIR = "desktop-rpc";
41073
41279
  var ACCOUNT_POOL_STORE_VERSION = 3;
41074
41280
  var MAX_RESPONSE_IDS_PER_SESSION = 64;
@@ -41372,7 +41578,7 @@ function normalizeAccountPoolStore(value3) {
41372
41578
  }
41373
41579
  function normalizeAccountPoolStoreStrict(value3) {
41374
41580
  if (!value3 || typeof value3 !== "object" || Array.isArray(value3)) {
41375
- throw new Error("Accounts Pool store must be a JSON object.");
41581
+ throw new Error("Account Pool store must be a JSON object.");
41376
41582
  }
41377
41583
  return normalizeAccountPoolStore(value3);
41378
41584
  }
@@ -41422,7 +41628,7 @@ function pruneStore(store) {
41422
41628
  return store;
41423
41629
  }
41424
41630
  function resolveAccountPoolDbPath(stateDir) {
41425
- return import_node_path13.default.join(stateDir, "state.sqlite");
41631
+ return import_node_path14.default.join(stateDir, "state.sqlite");
41426
41632
  }
41427
41633
  async function readStore(stateDir) {
41428
41634
  const dbPath = resolveAccountPoolDbPath(stateDir);
@@ -41462,13 +41668,13 @@ async function listApiKeys(stateDir) {
41462
41668
  return Object.values(store.apiKeysById).filter((key) => key.revokedAt === null).sort((left, right) => right.createdAt.localeCompare(left.createdAt)).map(accountPoolApiKeyView);
41463
41669
  }
41464
41670
  function hashToken(token) {
41465
- return (0, import_node_crypto13.createHash)("sha256").update(token).digest("hex");
41671
+ return (0, import_node_crypto14.createHash)("sha256").update(token).digest("hex");
41466
41672
  }
41467
41673
  async function createApiKey(stateDir) {
41468
- const plaintextToken = `cux_pool_${(0, import_node_crypto13.randomBytes)(24).toString("hex")}`;
41674
+ const plaintextToken = `cux_pool_${(0, import_node_crypto14.randomBytes)(24).toString("hex")}`;
41469
41675
  const now2 = (/* @__PURE__ */ new Date()).toISOString();
41470
41676
  const keyRecord = {
41471
- id: (0, import_node_crypto13.randomUUID)(),
41677
+ id: (0, import_node_crypto14.randomUUID)(),
41472
41678
  tokenHash: hashToken(plaintextToken),
41473
41679
  tokenPreview: `${plaintextToken.slice(0, 8)}...${plaintextToken.slice(-6)}`,
41474
41680
  createdAt: now2,
@@ -41523,9 +41729,9 @@ async function listSessions(stateDir) {
41523
41729
  }
41524
41730
  function resolveRuntimeStateDir(runtime, explicitStateDir) {
41525
41731
  if (explicitStateDir) {
41526
- return import_node_path13.default.resolve(explicitStateDir);
41732
+ return import_node_path14.default.resolve(explicitStateDir);
41527
41733
  }
41528
- return import_node_path13.default.join(getUserDataDir(), DESKTOP_RPC_STATE_DIR);
41734
+ return import_node_path14.default.join(getUserDataDir(), DESKTOP_RPC_STATE_DIR);
41529
41735
  }
41530
41736
  function resolveStateDir(flags) {
41531
41737
  const runtimeFlag = parseStringFlag(flags, "--runtime")?.trim().toLowerCase();
@@ -41685,7 +41891,7 @@ async function handleStatus(flags) {
41685
41891
  if (baseUrl) {
41686
41892
  console.log(`Base URL: ${baseUrl}`);
41687
41893
  } else {
41688
- console.log("Base URL: check the running desktop app for the current Accounts Pool URL.");
41894
+ console.log("Base URL: check the running desktop app for the current Account Pool URL.");
41689
41895
  }
41690
41896
  printStringList("Selected profiles", selectedProfiles);
41691
41897
  if (missingSelectedProfiles.length > 0) {
@@ -41704,7 +41910,7 @@ async function handleEnable() {
41704
41910
  accountPoolEnableExistingMigrationApplied: true,
41705
41911
  accountPoolEnabled: true
41706
41912
  }));
41707
- console.log(`Accounts Pool ${result2.settings.accountPoolEnabled ? "enabled" : "disabled"}.`);
41913
+ console.log(`Account Pool ${result2.settings.accountPoolEnabled ? "enabled" : "disabled"}.`);
41708
41914
  }
41709
41915
  async function handleDisable() {
41710
41916
  const result2 = await updateSettings((current) => ({
@@ -41712,7 +41918,7 @@ async function handleDisable() {
41712
41918
  accountPoolEnableExistingMigrationApplied: true,
41713
41919
  accountPoolEnabled: false
41714
41920
  }));
41715
- console.log(`Accounts Pool ${result2.settings.accountPoolEnabled ? "enabled" : "disabled"}.`);
41921
+ console.log(`Account Pool ${result2.settings.accountPoolEnabled ? "enabled" : "disabled"}.`);
41716
41922
  }
41717
41923
  async function handleRouting(params) {
41718
41924
  const value3 = parseRoutingStrategy(params[1]);
@@ -41723,7 +41929,7 @@ async function handleRouting(params) {
41723
41929
  ...current,
41724
41930
  accountPoolRoutingStrategy: value3
41725
41931
  }));
41726
- console.log(`Accounts Pool routing set to ${formatRoutingStrategy(result2.settings.accountPoolRoutingStrategy)}.`);
41932
+ console.log(`Account Pool routing set to ${formatRoutingStrategy(result2.settings.accountPoolRoutingStrategy)}.`);
41727
41933
  }
41728
41934
  async function handleProfiles(params) {
41729
41935
  const action = params[1];
@@ -41783,10 +41989,10 @@ async function handleProfiles(params) {
41783
41989
  };
41784
41990
  });
41785
41991
  if (result2.settings.accountPoolProfilePool.length === 0) {
41786
- console.log("Accounts Pool now uses all saved profiles.");
41992
+ console.log("Account Pool now uses all saved profiles.");
41787
41993
  return;
41788
41994
  }
41789
- printStringList("Accounts Pool selected profiles", result2.settings.accountPoolProfilePool);
41995
+ printStringList("Account Pool selected profiles", result2.settings.accountPoolProfilePool);
41790
41996
  }
41791
41997
  async function handleArraySetting(input) {
41792
41998
  const action = input.params[1];
@@ -41835,7 +42041,7 @@ async function handleKeys(params, flags) {
41835
42041
  if (!action || action === "list") {
41836
42042
  const apiKeys = await listApiKeys(stateDir);
41837
42043
  if (apiKeys.length === 0) {
41838
- console.log("No active Accounts Pool API keys.");
42044
+ console.log("No active Account Pool API keys.");
41839
42045
  return;
41840
42046
  }
41841
42047
  for (const apiKey of apiKeys) {
@@ -41855,7 +42061,7 @@ async function handleKeys(params, flags) {
41855
42061
  if (baseUrl) {
41856
42062
  console.log(`Base URL: ${baseUrl}`);
41857
42063
  } else {
41858
- console.log("Base URL: use the current Accounts Pool URL shown by the running desktop app.");
42064
+ console.log("Base URL: use the current Account Pool URL shown by the running desktop app.");
41859
42065
  }
41860
42066
  console.log("This key only works for the selected runtime state dir.");
41861
42067
  console.log("Store this token now. The plaintext value is only shown once.");
@@ -41868,7 +42074,7 @@ async function handleKeys(params, flags) {
41868
42074
  }
41869
42075
  const removed = await revokeApiKey(stateDir, id2);
41870
42076
  if (!removed) {
41871
- throw new Error(`No Accounts Pool API key found for id ${id2}.`);
42077
+ throw new Error(`No Account Pool API key found for id ${id2}.`);
41872
42078
  }
41873
42079
  console.log(`Revoked key: ${id2}`);
41874
42080
  return;
@@ -41897,7 +42103,7 @@ async function handleQuickstart(flags) {
41897
42103
  const { runtime, stateDir } = resolveStateDir(flags);
41898
42104
  const summary = await readAccountPoolRuntimeSummary({ runtime, stateDir });
41899
42105
  const baseUrl = summary.baseUrl ?? "<shown-in-desktop-app>";
41900
- console.log("Accounts Pool quickstart");
42106
+ console.log("Account Pool quickstart");
41901
42107
  console.log(`Runtime: ${summary.runtime}`);
41902
42108
  console.log(`Enabled: ${summary.enabled ? "yes" : "no"}`);
41903
42109
  console.log(`Access: ${summary.hasAccountPoolAccess ? "yes" : "no"}`);
@@ -41973,7 +42179,7 @@ async function handleAccountPoolCommand(args2, version) {
41973
42179
  }
41974
42180
 
41975
42181
  // src/commands/codex.ts
41976
- var import_node_child_process9 = require("child_process");
42182
+ var import_node_child_process10 = require("child_process");
41977
42183
  var import_node_os6 = __toESM(require("os"));
41978
42184
 
41979
42185
  // ../../packages/runtime-profiles/src/profiles/rate-limit-notifier.ts
@@ -42094,9 +42300,9 @@ async function assertProfileAccessAllowed(profileManager, profileName) {
42094
42300
 
42095
42301
  // ../../packages/runtime-app-state/src/app/workspaceBindings.ts
42096
42302
  var import_node_fs10 = require("fs");
42097
- var import_node_path14 = __toESM(require("path"), 1);
42303
+ var import_node_path15 = __toESM(require("path"), 1);
42098
42304
  async function canonicalizeWorkspacePath(input, options = {}) {
42099
- const resolved = import_node_path14.default.resolve(input || process.cwd());
42305
+ const resolved = import_node_path15.default.resolve(input || process.cwd());
42100
42306
  try {
42101
42307
  const canonical = await import_node_fs10.promises.realpath(resolved);
42102
42308
  if (options.requireDirectory !== false) {
@@ -42105,10 +42311,10 @@ async function canonicalizeWorkspacePath(input, options = {}) {
42105
42311
  throw new Error(`Workspace path is not a directory: ${resolved}`);
42106
42312
  }
42107
42313
  }
42108
- return import_node_path14.default.normalize(canonical);
42314
+ return import_node_path15.default.normalize(canonical);
42109
42315
  } catch (error) {
42110
42316
  if (options.requireDirectory === false) {
42111
- return import_node_path14.default.normalize(resolved);
42317
+ return import_node_path15.default.normalize(resolved);
42112
42318
  }
42113
42319
  const message = error instanceof Error ? error.message : String(error);
42114
42320
  const symptom = new Error(
@@ -42175,7 +42381,7 @@ async function resolveWorkspaceProfileBinding(requestedPath) {
42175
42381
  inherited: candidate !== canonical
42176
42382
  };
42177
42383
  }
42178
- const parent = import_node_path14.default.dirname(candidate);
42384
+ const parent = import_node_path15.default.dirname(candidate);
42179
42385
  if (parent === candidate) {
42180
42386
  return null;
42181
42387
  }
@@ -42184,13 +42390,13 @@ async function resolveWorkspaceProfileBinding(requestedPath) {
42184
42390
  }
42185
42391
 
42186
42392
  // src/platform/codexCli.ts
42187
- var import_node_child_process8 = require("child_process");
42393
+ var import_node_child_process9 = require("child_process");
42188
42394
  var import_node_fs11 = require("fs");
42189
- var import_node_path15 = __toESM(require("path"));
42395
+ var import_node_path16 = __toESM(require("path"));
42190
42396
  var ENV_HINTS2 = ["CODEX_BINARY", "CODEX_CLI_PATH", "CODEX_PATH"];
42191
42397
  function fileExists2(candidate) {
42192
42398
  if (!candidate) return null;
42193
- const resolved = import_node_path15.default.resolve(candidate);
42399
+ const resolved = import_node_path16.default.resolve(candidate);
42194
42400
  try {
42195
42401
  const stat2 = (0, import_node_fs11.statSync)(resolved);
42196
42402
  if (stat2.isFile()) return resolved;
@@ -42210,9 +42416,9 @@ function resolveFromEnv() {
42210
42416
  }
42211
42417
  function resolveFromPath() {
42212
42418
  const pathValue = process.env.PATH ?? "";
42213
- const entries3 = pathValue.split(import_node_path15.default.delimiter).filter(Boolean);
42419
+ const entries3 = pathValue.split(import_node_path16.default.delimiter).filter(Boolean);
42214
42420
  for (const entry of entries3) {
42215
- const candidate = fileExists2(import_node_path15.default.join(entry, "codex"));
42421
+ const candidate = fileExists2(import_node_path16.default.join(entry, "codex"));
42216
42422
  if (candidate) return candidate;
42217
42423
  }
42218
42424
  return null;
@@ -42256,7 +42462,7 @@ async function runCodexLogin(mode, envOverrides = {}) {
42256
42462
  const resolvedMode = resolveLoginMode(mode ?? null);
42257
42463
  const loginArgs = resolvedMode === "device" ? ["login", "--device-auth"] : ["login"];
42258
42464
  const { command, args: args2, shell } = buildCodexCommand2(codexPath, loginArgs);
42259
- const child = (0, import_node_child_process8.spawn)(command, args2, {
42465
+ const child = (0, import_node_child_process9.spawn)(command, args2, {
42260
42466
  stdio: "inherit",
42261
42467
  env: { ...process.env, ...envOverrides },
42262
42468
  shell
@@ -42325,7 +42531,7 @@ function compareCandidates(left, right) {
42325
42531
  async function runCommand3(codexPath, args2, timeoutMs) {
42326
42532
  const command = buildCodexCommand2(codexPath, args2);
42327
42533
  return new Promise((resolve2) => {
42328
- const child = (0, import_node_child_process9.spawn)(command.command, command.args, {
42534
+ const child = (0, import_node_child_process10.spawn)(command.command, command.args, {
42329
42535
  env: process.env,
42330
42536
  shell: command.shell,
42331
42537
  stdio: ["ignore", "pipe", "pipe"]
@@ -42405,7 +42611,7 @@ async function runCodexWithProfile(manager, profileName, codexArgs) {
42405
42611
  });
42406
42612
  const command = buildCodexCommand2(codexPath, codexArgs);
42407
42613
  try {
42408
- const child = (0, import_node_child_process9.spawn)(command.command, command.args, {
42614
+ const child = (0, import_node_child_process10.spawn)(command.command, command.args, {
42409
42615
  env: runtime.env,
42410
42616
  shell: command.shell,
42411
42617
  stdio: "inherit"
@@ -42467,7 +42673,7 @@ async function handleDoctorCommand(args2) {
42467
42673
  console.log(`Usage:
42468
42674
  codexuse doctor
42469
42675
 
42470
- Checks Codex CLI, auth, saved profiles, license, and Accounts Pool readiness.`);
42676
+ Checks Codex CLI, auth, saved profiles, license, and Account Pool readiness.`);
42471
42677
  return;
42472
42678
  }
42473
42679
  const manager = new ProfileManager();
@@ -42495,10 +42701,10 @@ Checks Codex CLI, auth, saved profiles, license, and Accounts Pool readiness.`);
42495
42701
  console.log(`License: ${license ? `${license.tier} (${license.state})` : "unknown"}`);
42496
42702
  if (accountPool) {
42497
42703
  console.log(
42498
- `Accounts Pool: ${accountPool.enabled ? "on" : "off"} | keys ${accountPool.activeApiKeyCount} | sessions ${accountPool.activeSessionCount}`
42704
+ `Account Pool: ${accountPool.enabled ? "on" : "off"} | keys ${accountPool.activeApiKeyCount} | sessions ${accountPool.activeSessionCount}`
42499
42705
  );
42500
42706
  } else {
42501
- console.log("Accounts Pool: unknown");
42707
+ console.log("Account Pool: unknown");
42502
42708
  }
42503
42709
  const fixes = [];
42504
42710
  if (!codexPath) {
@@ -42653,15 +42859,15 @@ async function handleLicense(args2, version) {
42653
42859
  // src/commands/profile.ts
42654
42860
  var import_node_fs13 = require("fs");
42655
42861
  var import_node_os7 = __toESM(require("os"));
42656
- var import_node_path17 = __toESM(require("path"));
42862
+ var import_node_path18 = __toESM(require("path"));
42657
42863
 
42658
42864
  // ../../packages/runtime-app-state/src/app/officialCodexSwitchCoordinator.ts
42659
- var import_node_crypto14 = require("crypto");
42865
+ var import_node_crypto15 = require("crypto");
42660
42866
  var import_node_fs12 = require("fs");
42661
- var import_node_path16 = __toESM(require("path"), 1);
42867
+ var import_node_path17 = __toESM(require("path"), 1);
42662
42868
  var DEFAULT_SWITCH_INTENT_TTL_MS = 10 * 60 * 1e3;
42663
42869
  var SWITCH_INTENT_RENEW_MS = 30 * 1e3;
42664
- var PROCESS_OWNER_ID3 = (0, import_node_crypto14.randomUUID)();
42870
+ var PROCESS_OWNER_ID3 = (0, import_node_crypto15.randomUUID)();
42665
42871
  var PROCESS_STARTED_AT3 = readProcessStartedAt(process.pid);
42666
42872
  var localIntentDepth = /* @__PURE__ */ new Map();
42667
42873
  var pendingLocalIntentAcquisitions = /* @__PURE__ */ new Map();
@@ -42671,7 +42877,7 @@ function nextSwitchIntentGeneration(current) {
42671
42877
  }
42672
42878
  async function acquireOfficialCodexSwitchIntent(input) {
42673
42879
  const now2 = Date.now();
42674
- const operationId = input.operationId?.trim() || (0, import_node_crypto14.randomUUID)();
42880
+ const operationId = input.operationId?.trim() || (0, import_node_crypto15.randomUUID)();
42675
42881
  const targetProfileName = input.targetProfileName.trim();
42676
42882
  if (!targetProfileName) {
42677
42883
  throw new Error("Profile name is required");
@@ -42802,6 +43008,191 @@ async function releaseOfficialCodexSwitchIntent(operationId) {
42802
43008
  }
42803
43009
  }
42804
43010
 
43011
+ // ../../packages/shared/src/core/errors.ts
43012
+ var ANSI_PATTERN = /\u001B\[[0-9;]*m/g;
43013
+ function stripAnsi(value3) {
43014
+ return value3.replace(ANSI_PATTERN, "");
43015
+ }
43016
+ function normalizeWhitespace(value3) {
43017
+ return value3.replace(/\s+/g, " ").trim();
43018
+ }
43019
+ function compactErrorText(value3, maxLength = 220) {
43020
+ if (!value3) {
43021
+ return "";
43022
+ }
43023
+ const cleaned = normalizeWhitespace(stripAnsi(String(value3)));
43024
+ if (!cleaned) {
43025
+ return "";
43026
+ }
43027
+ if (cleaned.length <= maxLength) {
43028
+ return cleaned;
43029
+ }
43030
+ return `${cleaned.slice(0, maxLength).trimEnd()}\u2026`;
43031
+ }
43032
+ function createErrorReferenceId() {
43033
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`.toUpperCase();
43034
+ }
43035
+ function serializeUnknownError(value3) {
43036
+ if (typeof value3 === "string") {
43037
+ return value3;
43038
+ }
43039
+ if (value3 instanceof Error) {
43040
+ return value3.stack ?? value3.message;
43041
+ }
43042
+ try {
43043
+ return JSON.stringify(value3);
43044
+ } catch {
43045
+ return String(value3);
43046
+ }
43047
+ }
43048
+ function extractRawMessage(error) {
43049
+ if (error === null || typeof error === "undefined") {
43050
+ return "";
43051
+ }
43052
+ if (typeof error === "string") {
43053
+ return error;
43054
+ }
43055
+ if (error instanceof Error) {
43056
+ return error.message;
43057
+ }
43058
+ return String(error);
43059
+ }
43060
+ function normalizeRawMessage(rawMessage) {
43061
+ let cleaned = normalizeWhitespace(stripAnsi(rawMessage));
43062
+ if (!cleaned) {
43063
+ return "";
43064
+ }
43065
+ if (cleaned.startsWith("Error invoking remote method")) {
43066
+ cleaned = cleaned.replace(/^Error invoking remote method '[^']+': Error: /, "");
43067
+ }
43068
+ if (cleaned.toLowerCase().includes("openai codex") && cleaned.toLowerCase().includes("workdir:")) {
43069
+ const parts = cleaned.split(/error:/i);
43070
+ if (parts.length > 1) {
43071
+ return parts[parts.length - 1]?.trim() ?? cleaned;
43072
+ }
43073
+ }
43074
+ return cleaned;
43075
+ }
43076
+ function resolveCategory(cleaned, options) {
43077
+ const lower = cleaned.toLowerCase();
43078
+ if (options.notFoundFallback && (lower.includes("enoent") || lower.includes("not found"))) {
43079
+ return {
43080
+ code: "ERR_NOT_FOUND",
43081
+ title: "We couldn't find that item",
43082
+ message: options.notFoundFallback,
43083
+ recovery: "Check the path or selection, then try again.",
43084
+ retryable: true
43085
+ };
43086
+ }
43087
+ if (lower.includes("rate limit") || lower.includes("quota exceeded") || lower.includes("too many requests") || lower.includes("429")) {
43088
+ return {
43089
+ code: "ERR_RATE_LIMIT",
43090
+ title: "Rate limit reached",
43091
+ message: "The provider is rate limited right now.",
43092
+ recovery: "Wait a moment, switch profiles, or try again.",
43093
+ retryable: true
43094
+ };
43095
+ }
43096
+ if (lower.includes("timeout") || lower.includes("timed out")) {
43097
+ return {
43098
+ code: "ERR_TIMEOUT",
43099
+ title: "Request timed out",
43100
+ message: "The operation took too long to finish.",
43101
+ recovery: "Check the connection and try again.",
43102
+ retryable: true
43103
+ };
43104
+ }
43105
+ if (lower.includes("network") || lower.includes("econn") || lower.includes("networkerror") || lower.includes("connection refused") || lower.includes("socket hang up")) {
43106
+ return {
43107
+ code: "ERR_NETWORK",
43108
+ title: "Can't reach the service",
43109
+ message: "CodexUse couldn't connect to the required service.",
43110
+ recovery: "Check your internet or local server connection, then retry.",
43111
+ retryable: true
43112
+ };
43113
+ }
43114
+ if (lower.includes("token_invalidated") || lower.includes("session invalidated") || lower.includes("session expired") || lower.includes("refresh token") || lower.includes("unauthorized") || lower.includes("401")) {
43115
+ return {
43116
+ code: "ERR_AUTH",
43117
+ title: "Sign-in expired",
43118
+ message: "This account needs to sign in again.",
43119
+ recovery: "Reconnect the profile, then retry the action.",
43120
+ retryable: true
43121
+ };
43122
+ }
43123
+ if (lower.includes("permission") || lower.includes("eacces") || lower.includes("operation not permitted")) {
43124
+ return {
43125
+ code: "ERR_PERMISSION",
43126
+ title: "Permission denied",
43127
+ message: "CodexUse doesn't have permission to do that.",
43128
+ recovery: "Check the file permissions or restart the app and try again.",
43129
+ retryable: true
43130
+ };
43131
+ }
43132
+ if (lower.includes("enospc") || lower.includes("disk full") || lower.includes("no space left")) {
43133
+ return {
43134
+ code: "ERR_DISK_FULL",
43135
+ title: "Disk is full",
43136
+ message: "CodexUse couldn't save data because the disk is full.",
43137
+ recovery: "Free up disk space, then try again.",
43138
+ retryable: true
43139
+ };
43140
+ }
43141
+ if (lower.includes("codex cli") || lower.includes("command not found") || lower.includes("spawn codex") || lower.includes("could not find codex") || lower.includes("enoent") && (lower.includes("@openai/codex") || lower.includes("codex-darwin-") || lower.includes("/vendor/") || lower.includes("\\vendor\\")) || lower.includes("missing optional dependency")) {
43142
+ return {
43143
+ code: "ERR_CLI_UNAVAILABLE",
43144
+ title: "Codex CLI unavailable",
43145
+ message: "CodexUse couldn't start the Codex CLI.",
43146
+ recovery: "Run npm install -g @openai/codex@latest --include=optional --force in Terminal, then try again.",
43147
+ retryable: true
43148
+ };
43149
+ }
43150
+ if (lower.includes("provider") || lower.includes("model") || lower.includes("openai") || lower.includes("anthropic")) {
43151
+ return {
43152
+ code: "ERR_PROVIDER",
43153
+ title: "Provider request failed",
43154
+ message: "The AI provider rejected or failed the request.",
43155
+ recovery: "Try again, or switch the active profile or model.",
43156
+ retryable: true
43157
+ };
43158
+ }
43159
+ return {
43160
+ code: "ERR_UNKNOWN",
43161
+ title: "That did not work",
43162
+ message: options.fallback,
43163
+ recovery: "Try again. If it keeps happening, report the error with the reference below.",
43164
+ retryable: true
43165
+ };
43166
+ }
43167
+ function resolveUserFacingError(error, options = {}) {
43168
+ const fallback = options.fallback ?? "That action did not complete.";
43169
+ const rawMessage = extractRawMessage(error);
43170
+ const cleaned = normalizeRawMessage(rawMessage);
43171
+ const category = resolveCategory(cleaned, {
43172
+ fallback,
43173
+ ...options.notFoundFallback ? { notFoundFallback: options.notFoundFallback } : {}
43174
+ });
43175
+ return {
43176
+ ...category,
43177
+ referenceId: createErrorReferenceId(),
43178
+ technicalMessage: compactErrorText(cleaned || rawMessage || fallback, 400),
43179
+ technicalDetails: compactErrorText(serializeUnknownError(error), 4e3)
43180
+ };
43181
+ }
43182
+ function formatUserFacingError(error, options = {}) {
43183
+ const info = resolveUserFacingError(error, options);
43184
+ const maxLength = typeof options.maxLength === "number" ? options.maxLength : 220;
43185
+ const withRecovery = info.recovery && !/try again/i.test(info.message) ? `${info.message} ${info.recovery}` : info.message;
43186
+ if (withRecovery.length <= maxLength) {
43187
+ return withRecovery;
43188
+ }
43189
+ let cleaned = info.message;
43190
+ if (cleaned.length > maxLength) {
43191
+ cleaned = `${cleaned.slice(0, maxLength).trimEnd()}\u2026`;
43192
+ }
43193
+ return cleaned;
43194
+ }
43195
+
42805
43196
  // ../../packages/runtime-profiles/src/profiles/official-codex-profile-switch.ts
42806
43197
  function safeReason(error, fallback) {
42807
43198
  const message = error instanceof Error ? error.message : "";
@@ -43165,7 +43556,7 @@ function formatProfileLabel(name, displayName) {
43165
43556
  }
43166
43557
  var AUTO_ROLL_ACCESS_REQUIRED_MESSAGE = "Auto-roll requires a Pro license or an active trial.";
43167
43558
  async function withIsolatedCodexLogin(mode, action) {
43168
- const home = await import_node_fs13.promises.mkdtemp(import_node_path17.default.join(import_node_os7.default.tmpdir(), "codexuse-cli-login-"));
43559
+ const home = await import_node_fs13.promises.mkdtemp(import_node_path18.default.join(import_node_os7.default.tmpdir(), "codexuse-cli-login-"));
43169
43560
  try {
43170
43561
  await runCodexLogin(mode, {
43171
43562
  HOME: home,
@@ -43173,7 +43564,7 @@ async function withIsolatedCodexLogin(mode, action) {
43173
43564
  CODEX_SQLITE_HOME: home,
43174
43565
  ELECTRON_RUN_AS_NODE: "1"
43175
43566
  });
43176
- return await action(import_node_path17.default.join(home, "auth.json"));
43567
+ return await action(import_node_path18.default.join(home, "auth.json"));
43177
43568
  } finally {
43178
43569
  await import_node_fs13.promises.rm(home, { recursive: true, force: true }).catch(() => void 0);
43179
43570
  }
@@ -44691,9 +45082,53 @@ async function pushRemoteSnapshot(access, snapshot2, options) {
44691
45082
  };
44692
45083
  }
44693
45084
 
45085
+ // ../../packages/runtime-profiles/src/cloud-sync/journal.ts
45086
+ var import_node_fs14 = require("fs");
45087
+ var import_node_crypto16 = require("crypto");
45088
+ var import_node_path19 = __toESM(require("path"), 1);
45089
+ var JOURNAL_FILENAME = "cloud-sync-pull.journal.json";
45090
+ function getCloudSyncJournalPath() {
45091
+ return import_node_path19.default.join(getUserDataDir(), JOURNAL_FILENAME);
45092
+ }
45093
+ async function syncDirectory(dir) {
45094
+ const directory = await import_node_fs14.promises.open(dir, "r");
45095
+ try {
45096
+ await directory.sync();
45097
+ } finally {
45098
+ await directory.close();
45099
+ }
45100
+ }
45101
+ async function writeCloudSyncJournal(journal) {
45102
+ const target = getCloudSyncJournalPath();
45103
+ const dir = import_node_path19.default.dirname(target);
45104
+ await import_node_fs14.promises.mkdir(dir, { recursive: true, mode: 448 });
45105
+ await import_node_fs14.promises.chmod(dir, 448);
45106
+ const staging = `${target}.tmp-${process.pid}-${(0, import_node_crypto16.randomUUID)()}`;
45107
+ await import_node_fs14.promises.writeFile(staging, JSON.stringify(journal), {
45108
+ encoding: "utf8",
45109
+ flag: "wx",
45110
+ mode: 384,
45111
+ flush: true
45112
+ });
45113
+ await import_node_fs14.promises.rename(staging, target);
45114
+ await syncDirectory(dir);
45115
+ }
45116
+ async function clearCloudSyncJournal() {
45117
+ const target = getCloudSyncJournalPath();
45118
+ try {
45119
+ await import_node_fs14.promises.unlink(target);
45120
+ } catch (error) {
45121
+ if (error?.code === "ENOENT") {
45122
+ return;
45123
+ }
45124
+ throw error;
45125
+ }
45126
+ await syncDirectory(import_node_path19.default.dirname(target));
45127
+ }
45128
+
44694
45129
  // ../../packages/runtime-profiles/src/cloud-sync/encryption.ts
44695
- var import_node_child_process10 = require("child_process");
44696
- var import_node_crypto15 = require("crypto");
45130
+ var import_node_child_process11 = require("child_process");
45131
+ var import_node_crypto17 = require("crypto");
44697
45132
  var KEYCHAIN_SERVICE2 = "CODEXUSE_CLOUD_SYNC_PASSPHRASE";
44698
45133
  var KEYCHAIN_ACCOUNT_PREFIX2 = "license-sha256:";
44699
45134
  var ENCRYPTION_AAD = Buffer.from("codexuse-cloud-sync-v2", "utf8");
@@ -44718,7 +45153,7 @@ function requireCloudSyncPassphrase(value3) {
44718
45153
  }
44719
45154
  async function deriveKey(passphrase, salt, params = SCRYPT_PARAMS) {
44720
45155
  return new Promise((resolve2, reject) => {
44721
- (0, import_node_crypto15.scrypt)(passphrase, salt, params.keyLength, {
45156
+ (0, import_node_crypto17.scrypt)(passphrase, salt, params.keyLength, {
44722
45157
  N: params.N,
44723
45158
  r: params.r,
44724
45159
  p: params.p,
@@ -44755,10 +45190,10 @@ function normalizeDecryptedSnapshot(value3) {
44755
45190
  };
44756
45191
  }
44757
45192
  async function encryptCloudSyncSnapshot(snapshot2, passphrase) {
44758
- const salt = (0, import_node_crypto15.randomBytes)(16);
44759
- const iv = (0, import_node_crypto15.randomBytes)(12);
45193
+ const salt = (0, import_node_crypto17.randomBytes)(16);
45194
+ const iv = (0, import_node_crypto17.randomBytes)(12);
44760
45195
  const key = await deriveKey(requireCloudSyncPassphrase(passphrase), salt);
44761
- const cipher = (0, import_node_crypto15.createCipheriv)("aes-256-gcm", key, iv);
45196
+ const cipher = (0, import_node_crypto17.createCipheriv)("aes-256-gcm", key, iv);
44762
45197
  cipher.setAAD(ENCRYPTION_AAD);
44763
45198
  const plaintext = Buffer.from(JSON.stringify(snapshot2), "utf8");
44764
45199
  const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
@@ -44785,7 +45220,7 @@ async function decryptCloudSyncSnapshot(snapshot2, passphrase) {
44785
45220
  const tag2 = fromBase64(snapshot2.encryption.tag);
44786
45221
  const ciphertext = fromBase64(snapshot2.encryption.ciphertext);
44787
45222
  const key = await deriveKey(requireCloudSyncPassphrase(passphrase), salt, snapshot2.encryption.kdfParams);
44788
- const decipher = (0, import_node_crypto15.createDecipheriv)("aes-256-gcm", key, iv);
45223
+ const decipher = (0, import_node_crypto17.createDecipheriv)("aes-256-gcm", key, iv);
44789
45224
  decipher.setAAD(ENCRYPTION_AAD);
44790
45225
  decipher.setAuthTag(tag2);
44791
45226
  const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
@@ -44800,12 +45235,12 @@ async function decryptCloudSyncSnapshot(snapshot2, passphrase) {
44800
45235
  }
44801
45236
  }
44802
45237
  function keychainAccountForLicense(licenseKey) {
44803
- const digest = (0, import_node_crypto15.createHash)("sha256").update(licenseKey).digest("hex");
45238
+ const digest = (0, import_node_crypto17.createHash)("sha256").update(licenseKey).digest("hex");
44804
45239
  return KEYCHAIN_ACCOUNT_PREFIX2 + digest;
44805
45240
  }
44806
45241
  function runSecurityCommand2(args2) {
44807
45242
  return new Promise((resolve2, reject) => {
44808
- const child = (0, import_node_child_process10.spawn)("security", args2, { stdio: ["ignore", "pipe", "ignore"] });
45243
+ const child = (0, import_node_child_process11.spawn)("security", args2, { stdio: ["ignore", "pipe", "ignore"] });
44809
45244
  let stdout = "";
44810
45245
  child.stdout?.on("data", (chunk) => {
44811
45246
  stdout += String(chunk);
@@ -45035,8 +45470,7 @@ function formatMegabytes(bytes) {
45035
45470
  }
45036
45471
  async function buildLocalSnapshot(profileManager, options = {}) {
45037
45472
  const enforcePushGuards = options.enforcePushGuards !== false;
45038
- const profilesFromManager = await profileManager.exportProfilesForCloudSync();
45039
- const profiles = profilesFromManager;
45473
+ const profiles = await profileManager.exportProfilesForCloudSync();
45040
45474
  const runtimeContext = await resolveCodexRuntimeContext();
45041
45475
  const config = await getCodexConfigSnapshot({
45042
45476
  codexHomePath: runtimeContext.codexHomePath
@@ -45055,25 +45489,183 @@ async function buildLocalSnapshot(profileManager, options = {}) {
45055
45489
  configTomlContent: config.exists ? config.content : null,
45056
45490
  settingsJson
45057
45491
  };
45058
- if (!enforcePushGuards) {
45059
- return snapshot2;
45060
- }
45061
45492
  return snapshot2;
45062
45493
  }
45063
- async function applyRemoteSnapshot(profileManager, snapshot2) {
45064
- await profileManager.replaceProfilesFromCloudSync(snapshot2.profiles ?? []);
45065
- if (typeof snapshot2.configTomlContent === "string") {
45066
- const runtimeContext = await resolveCodexRuntimeContext();
45067
- await saveCodexConfigContent(snapshot2.configTomlContent, {
45068
- codexHomePath: runtimeContext.codexHomePath
45069
- });
45494
+ async function applyCloudSyncSnapshot(snapshot2, stores) {
45495
+ const staged = stageCloudSyncSnapshot(snapshot2);
45496
+ const previousSnapshot = await stores.readPrevious();
45497
+ const previous = stageCloudSyncSnapshot(previousSnapshot);
45498
+ const previousHomeIds = await stores.readPreviousHomeIds();
45499
+ await stores.writeJournal({
45500
+ version: 1,
45501
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
45502
+ phase: "restore",
45503
+ previous: previousSnapshot,
45504
+ previousHomeIds: { ...previousHomeIds },
45505
+ pendingHomeIds: []
45506
+ });
45507
+ let pendingHomeIds = [];
45508
+ let staleHomes;
45509
+ try {
45510
+ staleHomes = await writeStaged(
45511
+ staged,
45512
+ stores,
45513
+ void 0,
45514
+ async (homeIds) => {
45515
+ pendingHomeIds = [...new Set(homeIds)];
45516
+ await stores.writeJournal({
45517
+ version: 1,
45518
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
45519
+ phase: "restore",
45520
+ previous: previousSnapshot,
45521
+ previousHomeIds: { ...previousHomeIds },
45522
+ pendingHomeIds
45523
+ });
45524
+ }
45525
+ );
45526
+ } catch (error) {
45527
+ await restoreStaged(
45528
+ previousSnapshot,
45529
+ previous,
45530
+ previousHomeIds,
45531
+ pendingHomeIds,
45532
+ stores,
45533
+ error
45534
+ );
45535
+ throw error;
45070
45536
  }
45071
- if (snapshot2.settingsJson && isRecord7(snapshot2.settingsJson)) {
45072
- await writeCodexSettingsJsonRaw(snapshot2.settingsJson);
45073
- } else {
45074
- await writeCodexSettingsJsonRaw({});
45537
+ await stores.writeJournal({
45538
+ version: 1,
45539
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
45540
+ phase: "committed",
45541
+ previous: previousSnapshot,
45542
+ previousHomeIds: { ...previousHomeIds },
45543
+ pendingHomeIds: []
45544
+ });
45545
+ await stores.clearJournal();
45546
+ if (staleHomes.length > 0) {
45547
+ await stores.removeStaleHomes(staleHomes);
45548
+ }
45549
+ }
45550
+ async function writeStaged(staged, stores, homeIdByProfileName, onPreparedHomeIds) {
45551
+ const staleHomes = await stores.replaceProfiles(
45552
+ staged.profiles,
45553
+ homeIdByProfileName,
45554
+ onPreparedHomeIds
45555
+ );
45556
+ if (staged.configTomlContent !== null || homeIdByProfileName !== void 0) {
45557
+ await stores.writeConfig(staged.configTomlContent);
45558
+ }
45559
+ await stores.writeSettings(staged.settingsJson);
45560
+ return staleHomes;
45561
+ }
45562
+ async function discardAbandonedHomes(previousSnapshot, previousHomeIds, pendingHomeIds, stores) {
45563
+ if (pendingHomeIds.length === 0) {
45564
+ await stores.clearJournal();
45565
+ return;
45566
+ }
45567
+ await stores.writeJournal({
45568
+ version: 1,
45569
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
45570
+ phase: "cleanup",
45571
+ previous: previousSnapshot,
45572
+ previousHomeIds: { ...previousHomeIds },
45573
+ pendingHomeIds
45574
+ });
45575
+ try {
45576
+ const discarded = await stores.discardHomeIds(pendingHomeIds);
45577
+ if (discarded !== pendingHomeIds.length) {
45578
+ throw new Error(
45579
+ `Deleted ${discarded} of ${pendingHomeIds.length} abandoned profile homes.`
45580
+ );
45581
+ }
45582
+ } catch (cleanupError) {
45583
+ logWarn(
45584
+ "[cloud-sync] restored the previous state but could not delete the homes the failed pull created",
45585
+ {
45586
+ error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError)
45587
+ }
45588
+ );
45589
+ return;
45590
+ }
45591
+ await stores.clearJournal();
45592
+ }
45593
+ async function restoreStaged(previousSnapshot, previous, previousHomeIds, pendingHomeIds, stores, cause) {
45594
+ try {
45595
+ const orphanedByFailedPull = await writeStaged(
45596
+ previous,
45597
+ stores,
45598
+ previousHomeIds
45599
+ );
45600
+ const restoredHomeIds = new Set(Object.values(previousHomeIds));
45601
+ const abandonedHomeIds = [
45602
+ .../* @__PURE__ */ new Set([
45603
+ ...pendingHomeIds,
45604
+ ...stores.homeIdsOf(orphanedByFailedPull)
45605
+ ])
45606
+ ].filter((homeId) => !restoredHomeIds.has(homeId));
45607
+ await discardAbandonedHomes(
45608
+ previousSnapshot,
45609
+ previousHomeIds,
45610
+ abandonedHomeIds,
45611
+ stores
45612
+ );
45613
+ logWarn("[cloud-sync] pull failed and the previous local state was restored", {
45614
+ error: cause instanceof Error ? cause.message : String(cause)
45615
+ });
45616
+ } catch (restoreError) {
45617
+ logWarn(
45618
+ "[cloud-sync] pull failed and the previous local state could not be restored",
45619
+ {
45620
+ error: cause instanceof Error ? cause.message : String(cause),
45621
+ restoreError: restoreError instanceof Error ? restoreError.message : String(restoreError)
45622
+ }
45623
+ );
45624
+ throw new Error(
45625
+ "Cloud pull failed and the previous local state could not be fully restored. Your accounts are still on this Mac; check them before syncing again.",
45626
+ { cause: restoreError }
45627
+ );
45075
45628
  }
45076
45629
  }
45630
+ function buildCloudSyncStores(profileManager) {
45631
+ return {
45632
+ readPrevious: () => buildLocalSnapshot(profileManager, { enforcePushGuards: false }),
45633
+ readPreviousHomeIds: () => profileManager.getProfileHomeIdsByName(),
45634
+ replaceProfiles: async (profiles, homeIdByProfileName, onPreparedHomeIds) => (await profileManager.replaceProfilesFromCloudSync(profiles, {
45635
+ deferStaleHomeRemoval: true,
45636
+ homeIdByProfileName,
45637
+ onPreparedHomeIds
45638
+ })).pendingStaleRemovals,
45639
+ writeConfig: async (content) => {
45640
+ const runtimeContext = await resolveCodexRuntimeContext();
45641
+ const options = { codexHomePath: runtimeContext.codexHomePath };
45642
+ if (content === null) {
45643
+ await removeConfigContent(options);
45644
+ } else {
45645
+ await saveCodexConfigContent(content, options);
45646
+ }
45647
+ },
45648
+ writeSettings: (settings) => writeCodexSettingsJsonRaw(settings),
45649
+ removeStaleHomes: (homes) => profileManager.removeStaleProfileHomes(homes),
45650
+ homeIdsOf: (homes) => homes.map((home) => home.homeId),
45651
+ discardHomeIds: (homeIds) => profileManager.deleteAbandonedPullProfileHomes(homeIds),
45652
+ writeJournal: (journal) => writeCloudSyncJournal(journal),
45653
+ clearJournal: () => clearCloudSyncJournal()
45654
+ };
45655
+ }
45656
+ async function applyRemoteSnapshot(profileManager, snapshot2) {
45657
+ await applyCloudSyncSnapshot(
45658
+ snapshot2,
45659
+ buildCloudSyncStores(profileManager)
45660
+ );
45661
+ }
45662
+ function stageCloudSyncSnapshot(snapshot2) {
45663
+ return {
45664
+ profiles: snapshot2.profiles ?? [],
45665
+ configTomlContent: typeof snapshot2.configTomlContent === "string" ? assertValidCodexConfigContent(snapshot2.configTomlContent) : null,
45666
+ settingsJson: snapshot2.settingsJson && isRecord7(snapshot2.settingsJson) ? snapshot2.settingsJson : {}
45667
+ };
45668
+ }
45077
45669
  function getSnapshotKind(snapshot2) {
45078
45670
  if (!snapshot2) {
45079
45671
  return "none";
@@ -45168,7 +45760,11 @@ async function pushCloudSync(options = {}) {
45168
45760
  const profileManager = new ProfileManager();
45169
45761
  try {
45170
45762
  await profileManager.initialize();
45171
- const localSnapshot = await buildLocalSnapshot(profileManager, { enforcePushGuards: true });
45763
+ const localSnapshot = await withCloudSyncTransaction(
45764
+ getUserDataDir(),
45765
+ "write",
45766
+ () => buildLocalSnapshot(profileManager, { enforcePushGuards: true })
45767
+ );
45172
45768
  const passphrase = await resolvePassphrase(eligibility.access.syncKey, options);
45173
45769
  const encryptedSnapshot = await encryptCloudSyncSnapshot(localSnapshot, passphrase.value);
45174
45770
  const serializedSnapshot = JSON.stringify(encryptedSnapshot);
@@ -45260,7 +45856,11 @@ async function pullCloudSync(options = {}) {
45260
45856
  } else {
45261
45857
  plainSnapshot = remote;
45262
45858
  }
45263
- await applyRemoteSnapshot(profileManager, plainSnapshot);
45859
+ await withCloudSyncTransaction(
45860
+ getUserDataDir(),
45861
+ "write",
45862
+ () => applyRemoteSnapshot(profileManager, plainSnapshot)
45863
+ );
45264
45864
  await writeState({
45265
45865
  lastPullAt: (/* @__PURE__ */ new Date()).toISOString(),
45266
45866
  remoteUpdatedAt: remote.updatedAt,
@@ -45366,7 +45966,7 @@ async function handleSync(args2, version) {
45366
45966
  }
45367
45967
 
45368
45968
  // src/commands/workspace.ts
45369
- var import_node_fs14 = require("fs");
45969
+ var import_node_fs15 = require("fs");
45370
45970
  function printWorkspaceHelp() {
45371
45971
  console.log(`Usage:
45372
45972
  codexuse workspace bind <path> <profile>
@@ -45396,7 +45996,7 @@ async function handleWorkspaceCommand(args2) {
45396
45996
  return;
45397
45997
  }
45398
45998
  for (const binding of bindings) {
45399
- const pathState = await import_node_fs14.promises.stat(binding.rootPath).then(() => "").catch(() => " (path missing)");
45999
+ const pathState = await import_node_fs15.promises.stat(binding.rootPath).then(() => "").catch(() => " (path missing)");
45400
46000
  const profileState = profiles.has(binding.profileName) ? "" : " (profile missing)";
45401
46001
  console.log(`${binding.rootPath} -> ${binding.profileName}${pathState}${profileState}`);
45402
46002
  }
@@ -45460,7 +46060,7 @@ async function ensureCliStorageReady() {
45460
46060
  }
45461
46061
 
45462
46062
  // src/app/main.ts
45463
- var VERSION = true ? "6.0.5" : "0.0.0";
46063
+ var VERSION = true ? "6.1.0" : "0.0.0";
45464
46064
  async function runCli() {
45465
46065
  const args2 = process.argv.slice(2);
45466
46066
  if (args2.length === 0) {