codexuse-cli 6.1.0 → 6.2.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
@@ -2082,6 +2082,57 @@ var import_node_crypto2 = require("crypto");
2082
2082
  var import_node_path4 = __toESM(require("path"), 1);
2083
2083
  var import_node_os = __toESM(require("os"), 1);
2084
2084
 
2085
+ // ../../packages/contracts/src/license/offer-config.ts
2086
+ function getActiveOffer() {
2087
+ const basePriceUsd = 39;
2088
+ const discountPercent = 50;
2089
+ const salePriceUsd = basePriceUsd * (100 - discountPercent) / 100;
2090
+ return {
2091
+ basePriceUsd,
2092
+ basePriceDisplay: `$${basePriceUsd}`,
2093
+ couponCode: "SUMMER50",
2094
+ discountPercent,
2095
+ salePriceUsd,
2096
+ salePriceDisplay: `$${salePriceUsd.toFixed(2)}`,
2097
+ isActive: true,
2098
+ campaign: "summer-2026",
2099
+ productPermalink: "codex-use",
2100
+ checkoutBaseUrl: "https://hweihwang.gumroad.com/l/codex-use",
2101
+ trialEnabled: true,
2102
+ trialDays: 7
2103
+ };
2104
+ }
2105
+ function buildCheckoutUrl(offer2, options) {
2106
+ const base2 = offer2.checkoutBaseUrl;
2107
+ const withCoupon = offer2.isActive && offer2.couponCode ? `${base2}/${offer2.couponCode}` : base2;
2108
+ const url = new URL(withCoupon);
2109
+ if (options?.directCheckout) {
2110
+ url.searchParams.set("wanted", "true");
2111
+ }
2112
+ if (!options?.source || !options?.medium) {
2113
+ return url.toString();
2114
+ }
2115
+ url.searchParams.set("utm_source", options.source);
2116
+ url.searchParams.set("utm_medium", options.medium);
2117
+ if (options.campaign) {
2118
+ url.searchParams.set("utm_campaign", options.campaign);
2119
+ } else if (offer2.campaign) {
2120
+ url.searchParams.set("utm_campaign", offer2.campaign);
2121
+ }
2122
+ return url.toString();
2123
+ }
2124
+
2125
+ // ../../packages/contracts/src/license/activation-session.ts
2126
+ var ACTIVATION_RETENTION_MS = 24 * 60 * 60 * 1e3;
2127
+ var ACTIVATION_WATCH_MS = 20 * 60 * 1e3;
2128
+ var ACTIVATION_SESSION_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
2129
+ function normalizePendingCheckout(value3) {
2130
+ if (!value3 || typeof value3 !== "object" || Array.isArray(value3)) return null;
2131
+ const { sessionId, startedAt } = value3;
2132
+ if (typeof sessionId !== "string" || !ACTIVATION_SESSION_PATTERN.test(sessionId) || typeof startedAt !== "number" || !Number.isSafeInteger(startedAt) || startedAt <= 0) return null;
2133
+ return { sessionId, startedAt };
2134
+ }
2135
+
2085
2136
  // ../../packages/contracts/src/desktop/llm-compatibility.ts
2086
2137
  var DESKTOP_LLM_CAPABILITY_NAMES = [
2087
2138
  "streamingText",
@@ -3408,6 +3459,7 @@ function resolveStorageDbPath() {
3408
3459
  function createDefaultAppState() {
3409
3460
  return {
3410
3461
  schemaVersion: 1,
3462
+ trialExperience: { knownLicenseHolder: false, pendingInteractiveAt: null, trial: null },
3411
3463
  autoRoll: {
3412
3464
  enabled: false,
3413
3465
  rearmRemainingThreshold: 15,
@@ -3498,7 +3550,8 @@ function createDefaultAppState() {
3498
3550
  proUnlockedCelebrated: false
3499
3551
  },
3500
3552
  duplicateWarningDismissedKey: null,
3501
- pendingLicenseActivation: false
3553
+ pendingLicenseActivation: false,
3554
+ pendingCheckout: null
3502
3555
  },
3503
3556
  profileDashboard: {
3504
3557
  customGroupsByAccountKey: {}
@@ -4110,6 +4163,35 @@ function normalizeOfficialCodexPowerStatus(value3) {
4110
4163
  appliedAt: asString(value3.appliedAt)
4111
4164
  };
4112
4165
  }
4166
+ function normalizeTrialExperience(raw) {
4167
+ const value3 = isRecord2(raw) ? raw : {};
4168
+ const trial = isRecord2(value3.trial) ? value3.trial : {};
4169
+ const startedAt = asString(trial.startedAt);
4170
+ const expiresAt = asString(trial.expiresAt);
4171
+ const start = startedAt ? Date.parse(startedAt) : NaN;
4172
+ const end = expiresAt ? Date.parse(expiresAt) : NaN;
4173
+ const observedAt = asNumberOrNull(trial.observedAt);
4174
+ const valid = startedAt && expiresAt && Number.isFinite(start) && end > start && observedAt !== null && observedAt >= start;
4175
+ const first = isRecord2(trial.firstOutcome) ? trial.firstOutcome : {};
4176
+ const completedAt = asNumberOrNull(first.completedAt);
4177
+ const kind = first.kind;
4178
+ const validKind = kind === "shared_history_switch" || kind === "shared_history_window" || kind === "matched_window" || kind === "provider_window" || kind === "pool_request";
4179
+ const interactiveAt = asNumberOrNull(trial.interactiveAt);
4180
+ const pendingInteractiveAt = asNumberOrNull(value3.pendingInteractiveAt);
4181
+ return {
4182
+ knownLicenseHolder: value3.knownLicenseHolder === true,
4183
+ pendingInteractiveAt: pendingInteractiveAt !== null && pendingInteractiveAt > 0 ? pendingInteractiveAt : null,
4184
+ trial: valid ? {
4185
+ startedAt,
4186
+ expiresAt,
4187
+ observedAt,
4188
+ priorPayment: trial.priorPayment === "known_prior_license" ? "known_prior_license" : "unknown",
4189
+ interactiveAt: interactiveAt !== null && interactiveAt > 0 && interactiveAt < end ? interactiveAt : null,
4190
+ firstOutcome: validKind && completedAt !== null && completedAt >= start && completedAt < end ? { kind, completedAt } : null,
4191
+ entitlementObservedAt: asNumberOrNull(trial.entitlementObservedAt)
4192
+ } : null
4193
+ };
4194
+ }
4113
4195
  function normalizeAppState(raw) {
4114
4196
  const defaults = createDefaultAppState();
4115
4197
  if (!isRecord2(raw)) {
@@ -4120,6 +4202,7 @@ function normalizeAppState(raw) {
4120
4202
  const next = deepMerge(defaults, raw);
4121
4203
  const merged = next;
4122
4204
  merged.schemaVersion = 1;
4205
+ merged.trialExperience = normalizeTrialExperience(raw.trialExperience);
4123
4206
  merged.autoRoll = normalizeAutoRollSettings(rawAutoRoll);
4124
4207
  if (!isRecord2(merged.officialCodex)) {
4125
4208
  merged.officialCodex = clone2(defaults.officialCodex);
@@ -4562,6 +4645,7 @@ function normalizeAppState(raw) {
4562
4645
  if (typeof merged.ui.pendingLicenseActivation !== "boolean") {
4563
4646
  merged.ui.pendingLicenseActivation = false;
4564
4647
  }
4648
+ merged.ui.pendingCheckout = normalizePendingCheckout(merged.ui.pendingCheckout);
4565
4649
  {
4566
4650
  const allowedUiKeys = new Set(Object.keys(defaults.ui));
4567
4651
  for (const key of Object.keys(merged.ui)) {
@@ -5139,27 +5223,35 @@ async function getStoredLicense() {
5139
5223
  const state = await getAppState();
5140
5224
  return parseStoredLicense(state.license);
5141
5225
  }
5142
- async function persistLicense(license) {
5226
+ async function persistLicense(license, expected) {
5143
5227
  const parsed = parseStoredLicense(license);
5144
- await patchAppState({
5145
- license: parsed ? {
5146
- licenseKey: parsed.licenseKey ?? null,
5147
- purchaseEmail: parsed.purchaseEmail ?? null,
5148
- lastVerifiedAt: parsed.lastVerifiedAt ?? null,
5149
- nextCheckAt: parsed.nextCheckAt ?? null,
5150
- lastVerificationError: parsed.lastVerificationError ?? null,
5151
- status: parsed.status ?? "inactive",
5152
- signature: parsed.signature ?? null
5153
- } : {
5154
- licenseKey: null,
5155
- purchaseEmail: null,
5156
- lastVerifiedAt: null,
5157
- nextCheckAt: null,
5158
- lastVerificationError: null,
5159
- status: "inactive",
5160
- signature: null
5228
+ let persisted = false;
5229
+ await updateAppState((current) => {
5230
+ if (expected !== void 0 && JSON.stringify(parseStoredLicense(current.license)) !== JSON.stringify(parseStoredLicense(expected))) {
5231
+ return {};
5161
5232
  }
5233
+ persisted = true;
5234
+ return {
5235
+ license: parsed ? {
5236
+ licenseKey: parsed.licenseKey ?? null,
5237
+ purchaseEmail: parsed.purchaseEmail ?? null,
5238
+ lastVerifiedAt: parsed.lastVerifiedAt ?? null,
5239
+ nextCheckAt: parsed.nextCheckAt ?? null,
5240
+ lastVerificationError: parsed.lastVerificationError ?? null,
5241
+ status: parsed.status ?? "inactive",
5242
+ signature: parsed.signature ?? null
5243
+ } : {
5244
+ licenseKey: null,
5245
+ purchaseEmail: null,
5246
+ lastVerifiedAt: null,
5247
+ nextCheckAt: null,
5248
+ lastVerificationError: null,
5249
+ status: "inactive",
5250
+ signature: null
5251
+ }
5252
+ };
5162
5253
  });
5254
+ return persisted;
5163
5255
  }
5164
5256
  async function getStoredAutoRollSettings() {
5165
5257
  const state = await getAppState();
@@ -5254,46 +5346,6 @@ async function getLicenseSecret() {
5254
5346
  return persistLicenseSecret(dbPath, secret);
5255
5347
  }
5256
5348
 
5257
- // ../../packages/contracts/src/license/offer-config.ts
5258
- function getActiveOffer() {
5259
- const basePriceUsd = 39;
5260
- const discountPercent = 50;
5261
- const salePriceUsd = basePriceUsd * (100 - discountPercent) / 100;
5262
- return {
5263
- basePriceUsd,
5264
- basePriceDisplay: `$${basePriceUsd}`,
5265
- couponCode: "SUMMER50",
5266
- discountPercent,
5267
- salePriceUsd,
5268
- salePriceDisplay: `$${salePriceUsd.toFixed(2)}`,
5269
- isActive: true,
5270
- campaign: "summer-2026",
5271
- productPermalink: "codex-use",
5272
- checkoutBaseUrl: "https://hweihwang.gumroad.com/l/codex-use",
5273
- trialEnabled: true,
5274
- trialDays: 7
5275
- };
5276
- }
5277
- function buildCheckoutUrl(offer2, options) {
5278
- const base2 = offer2.checkoutBaseUrl;
5279
- const withCoupon = offer2.isActive && offer2.couponCode ? `${base2}/${offer2.couponCode}` : base2;
5280
- const url = new URL(withCoupon);
5281
- if (options?.directCheckout) {
5282
- url.searchParams.set("wanted", "true");
5283
- }
5284
- if (!options?.source || !options?.medium) {
5285
- return url.toString();
5286
- }
5287
- url.searchParams.set("utm_source", options.source);
5288
- url.searchParams.set("utm_medium", options.medium);
5289
- if (options.campaign) {
5290
- url.searchParams.set("utm_campaign", options.campaign);
5291
- } else if (offer2.campaign) {
5292
- url.searchParams.set("utm_campaign", offer2.campaign);
5293
- }
5294
- return url.toString();
5295
- }
5296
-
5297
5349
  // ../../packages/runtime-profiles/src/license/trial.ts
5298
5350
  var import_node_crypto6 = __toESM(require("crypto"), 1);
5299
5351
 
@@ -5562,6 +5614,7 @@ function buildTrialInfo(stored, now2) {
5562
5614
  const expired = stored?.serverExpired === true || expiresAtMs === null || expiresAtMs <= now2;
5563
5615
  const daysLeft = expired || expiresAtMs === null ? 0 : Math.max(0, Math.ceil((expiresAtMs - now2) / DAY_MS));
5564
5616
  return {
5617
+ startedAt: stored?.startedAt ?? null,
5565
5618
  active: !expired,
5566
5619
  expired,
5567
5620
  expiresAt: stored?.expiresAt ?? null,
@@ -5573,6 +5626,7 @@ function lockReasonFor(info) {
5573
5626
  }
5574
5627
  function buildLockedTrialInfo(stored) {
5575
5628
  return {
5629
+ startedAt: null,
5576
5630
  active: false,
5577
5631
  expired: true,
5578
5632
  expiresAt: stored?.expiresAt ?? null,
@@ -6078,6 +6132,7 @@ var LicenseService = class {
6078
6132
  constructor() {
6079
6133
  this.refreshPromise = null;
6080
6134
  this.verificationPromise = null;
6135
+ this.activationTail = Promise.resolve();
6081
6136
  }
6082
6137
  async getCachedStatus() {
6083
6138
  try {
@@ -6129,8 +6184,10 @@ var LicenseService = class {
6129
6184
  nextCheckAt: new Date(cappedNextCheckTs).toISOString()
6130
6185
  };
6131
6186
  const signed = withSignature(updated, secret);
6187
+ if (!await persistLicense(signed, workingStored)) {
6188
+ return this.getStatus({ allowStale: true });
6189
+ }
6132
6190
  workingStored = signed;
6133
- await persistLicense(signed);
6134
6191
  }
6135
6192
  const tampered = Boolean(workingStored.licenseKey) && !signatureValid;
6136
6193
  const cached2 = tampered ? toLicenseStatus(null, {
@@ -6161,7 +6218,9 @@ var LicenseService = class {
6161
6218
  lastVerificationError: null
6162
6219
  };
6163
6220
  const signed = withSignature(updated, secret);
6164
- await persistLicense(signed);
6221
+ if (!await persistLicense(signed, workingStored)) {
6222
+ return this.getStatus({ allowStale: true });
6223
+ }
6165
6224
  return finalize2(toLicenseStatus(signed));
6166
6225
  } catch (error) {
6167
6226
  const message = error instanceof Error ? error.message : "License verification failed.";
@@ -6175,7 +6234,9 @@ var LicenseService = class {
6175
6234
  },
6176
6235
  secret
6177
6236
  );
6178
- await persistLicense(fallbackStored2);
6237
+ if (!await persistLicense(fallbackStored2, workingStored)) {
6238
+ return this.getStatus({ allowStale: true });
6239
+ }
6179
6240
  const fallback = toLicenseStatus(fallbackStored2, {
6180
6241
  state: fallbackStored2.status ?? "grace",
6181
6242
  error: message
@@ -6190,7 +6251,9 @@ var LicenseService = class {
6190
6251
  status: "inactive",
6191
6252
  lastVerificationError: message
6192
6253
  }, secret);
6193
- await persistLicense(fallbackStored);
6254
+ if (!await persistLicense(fallbackStored, workingStored)) {
6255
+ return this.getStatus({ allowStale: true });
6256
+ }
6194
6257
  return finalize2(toLicenseStatus(fallbackStored, { error: message }));
6195
6258
  }
6196
6259
  };
@@ -6202,6 +6265,23 @@ var LicenseService = class {
6202
6265
  }
6203
6266
  }
6204
6267
  async activate(licenseKey) {
6268
+ return (await this.queueActivation(licenseKey, false)).license;
6269
+ }
6270
+ activateFromCheckout(licenseKey) {
6271
+ return this.queueActivation(licenseKey, true);
6272
+ }
6273
+ queueActivation(licenseKey, onlyIfUnlicensed) {
6274
+ const result2 = this.activationTail.then(async () => {
6275
+ if (onlyIfUnlicensed) {
6276
+ const current = await this.getCachedStatus();
6277
+ if (current.isPro) return { license: current, activated: false };
6278
+ }
6279
+ return { license: await this.performActivation(licenseKey), activated: true };
6280
+ });
6281
+ this.activationTail = result2.then(() => void 0, () => void 0);
6282
+ return result2;
6283
+ }
6284
+ async performActivation(licenseKey) {
6205
6285
  const trimmed = licenseKey.trim();
6206
6286
  if (!trimmed) {
6207
6287
  throw new Error("License key is required.");
@@ -7560,7 +7640,7 @@ function logInfo(...args2) {
7560
7640
  console.info(...args2);
7561
7641
  }
7562
7642
 
7563
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Pipeable.js
7643
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Pipeable.js
7564
7644
  var pipeArguments = (self, args2) => {
7565
7645
  switch (args2.length) {
7566
7646
  case 0:
@@ -7604,7 +7684,7 @@ var Class = /* @__PURE__ */ (function() {
7604
7684
  return PipeableBase;
7605
7685
  })();
7606
7686
 
7607
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Function.js
7687
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Function.js
7608
7688
  var dual = function(arity, body) {
7609
7689
  if (typeof arity === "function") {
7610
7690
  return function() {
@@ -7675,7 +7755,7 @@ function memoizeIdempotent(f) {
7675
7755
  };
7676
7756
  }
7677
7757
 
7678
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/equal.js
7758
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/equal.js
7679
7759
  var getAllObjectKeys = (obj) => {
7680
7760
  const keys4 = new Set(Reflect.ownKeys(obj));
7681
7761
  if (obj.constructor === Object) return keys4;
@@ -7698,7 +7778,7 @@ var getAllObjectKeys = (obj) => {
7698
7778
  };
7699
7779
  var byReferenceInstances = /* @__PURE__ */ new WeakSet();
7700
7780
 
7701
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Predicate.js
7781
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Predicate.js
7702
7782
  function isString(input) {
7703
7783
  return typeof input === "string";
7704
7784
  }
@@ -7746,7 +7826,7 @@ function isError(input) {
7746
7826
  return input instanceof Error;
7747
7827
  }
7748
7828
 
7749
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Hash.js
7829
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Hash.js
7750
7830
  var symbol = "~effect/interfaces/Hash";
7751
7831
  var hash = (self) => {
7752
7832
  switch (typeof self) {
@@ -7870,7 +7950,7 @@ function withVisitedTracking(obj, fn2) {
7870
7950
  return result2;
7871
7951
  }
7872
7952
 
7873
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Equal.js
7953
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Equal.js
7874
7954
  var symbol2 = "~effect/interfaces/Equal";
7875
7955
  function equals() {
7876
7956
  if (arguments.length === 1) {
@@ -8062,7 +8142,7 @@ function makeCompareSet(equivalence) {
8062
8142
  var compareSets = /* @__PURE__ */ makeCompareSet(compareBoth);
8063
8143
  var isEqual = (u) => hasProperty(u, symbol2);
8064
8144
 
8065
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Reducer.js
8145
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Reducer.js
8066
8146
  function make(combine2, initialValue, combineAll) {
8067
8147
  return {
8068
8148
  combine: combine2,
@@ -8077,7 +8157,7 @@ function make(combine2, initialValue, combineAll) {
8077
8157
  };
8078
8158
  }
8079
8159
 
8080
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Equivalence.js
8160
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Equivalence.js
8081
8161
  var make2 = (isEquivalent) => (self, that) => self === that || isEquivalent(self, that);
8082
8162
  var isStrictEquivalent = (x, y) => x === y;
8083
8163
  var strictEqual = () => isStrictEquivalent;
@@ -8100,10 +8180,10 @@ function Struct(fields) {
8100
8180
  });
8101
8181
  }
8102
8182
 
8103
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/array.js
8183
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/array.js
8104
8184
  var isArrayNonEmpty = (self) => self.length > 0;
8105
8185
 
8106
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/record.js
8186
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/record.js
8107
8187
  function assignProperty(self, key, value3) {
8108
8188
  if (key === "__proto__") {
8109
8189
  Object.defineProperty(self, key, {
@@ -8125,14 +8205,14 @@ function assignProperties(self, source) {
8125
8205
  }
8126
8206
  }
8127
8207
 
8128
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Combiner.js
8208
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Combiner.js
8129
8209
  function make3(combine2) {
8130
8210
  return {
8131
8211
  combine: combine2
8132
8212
  };
8133
8213
  }
8134
8214
 
8135
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Redactable.js
8215
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Redactable.js
8136
8216
  var symbolRedactable = /* @__PURE__ */ Symbol.for("~effect/Redactable");
8137
8217
  var isRedactable = (u) => hasProperty(u, symbolRedactable);
8138
8218
  function redact(u) {
@@ -8154,7 +8234,7 @@ var emptyContext = {
8154
8234
  }
8155
8235
  };
8156
8236
 
8157
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Formatter.js
8237
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Formatter.js
8158
8238
  function format(input, options) {
8159
8239
  const space = options?.space ?? 0;
8160
8240
  const ancestors = /* @__PURE__ */ new WeakSet();
@@ -8255,7 +8335,7 @@ function formatJson(input, options) {
8255
8335
  }, options?.space) ?? "null";
8256
8336
  }
8257
8337
 
8258
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Inspectable.js
8338
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Inspectable.js
8259
8339
  var NodeInspectSymbol = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
8260
8340
  var toJson = (input) => {
8261
8341
  try {
@@ -8308,7 +8388,7 @@ var Class2 = class {
8308
8388
  }
8309
8389
  };
8310
8390
 
8311
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Utils.js
8391
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Utils.js
8312
8392
  var SingleShotGen = class _SingleShotGen {
8313
8393
  called = false;
8314
8394
  self;
@@ -8368,7 +8448,7 @@ var pickInternalCall = () => {
8368
8448
  };
8369
8449
  var internalCall = /* @__PURE__ */ pickInternalCall();
8370
8450
 
8371
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/core.js
8451
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/core.js
8372
8452
  var EffectTypeId = `~effect/Effect`;
8373
8453
  var ExitTypeId = `~effect/Exit`;
8374
8454
  var effectVariance = {
@@ -8713,7 +8793,7 @@ var DoneVoid = {
8713
8793
  value: void 0
8714
8794
  };
8715
8795
 
8716
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/option.js
8796
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/option.js
8717
8797
  var TypeId = "~effect/data/Option";
8718
8798
  var CommonProto = {
8719
8799
  [TypeId]: {
@@ -8779,7 +8859,7 @@ var some = (value3) => {
8779
8859
  return a;
8780
8860
  };
8781
8861
 
8782
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/result.js
8862
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/result.js
8783
8863
  var TypeId2 = "~effect/data/Result";
8784
8864
  var CommonProto2 = {
8785
8865
  [TypeId2]: {
@@ -8846,7 +8926,7 @@ var succeed = (success) => {
8846
8926
  return a;
8847
8927
  };
8848
8928
 
8849
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Order.js
8929
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Order.js
8850
8930
  function make4(compare) {
8851
8931
  return (self, that) => self === that ? 0 : compare(self, that);
8852
8932
  }
@@ -8876,7 +8956,7 @@ var isGreaterThan = (O) => dual(2, (self, that) => O(self, that) === 1);
8876
8956
  var isLessThanOrEqualTo = (O) => dual(2, (self, that) => O(self, that) !== 1);
8877
8957
  var isGreaterThanOrEqualTo = (O) => dual(2, (self, that) => O(self, that) !== -1);
8878
8958
 
8879
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Option.js
8959
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Option.js
8880
8960
  var none2 = () => none;
8881
8961
  var some2 = some;
8882
8962
  var isOption2 = isOption;
@@ -8905,7 +8985,7 @@ var flatten = /* @__PURE__ */ flatMap(identity);
8905
8985
  var filter = /* @__PURE__ */ dual(2, (self, predicate) => isNone2(self) ? none2() : predicate(self.value) ? some2(self.value) : none2());
8906
8986
  var makeEquivalence = (isEquivalent) => make2((x, y) => isNone2(x) ? isNone2(y) : isNone2(y) ? false : isEquivalent(x.value, y.value));
8907
8987
 
8908
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Result.js
8988
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Result.js
8909
8989
  var succeed2 = succeed;
8910
8990
  var fail2 = fail;
8911
8991
  var try_ = (evaluate2) => {
@@ -8936,7 +9016,7 @@ var match2 = /* @__PURE__ */ dual(2, (self, {
8936
9016
  var getOrElse2 = /* @__PURE__ */ dual(2, (self, onFailure) => isFailure2(self) ? onFailure(self.failure) : self.success);
8937
9017
  var flatMap2 = /* @__PURE__ */ dual(2, (self, f) => isFailure2(self) ? fail2(self.failure) : f(self.success));
8938
9018
 
8939
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Record.js
9019
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Record.js
8940
9020
  var map3 = /* @__PURE__ */ dual(2, (self, f) => {
8941
9021
  const out = {
8942
9022
  ...self
@@ -8948,7 +9028,7 @@ var map3 = /* @__PURE__ */ dual(2, (self, f) => {
8948
9028
  });
8949
9029
  var keys = (self) => Object.keys(self);
8950
9030
 
8951
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Array.js
9031
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Array.js
8952
9032
  var Array2 = globalThis.Array;
8953
9033
  var fromIterable = (collection) => Array2.isArray(collection) ? collection : Array2.from(collection);
8954
9034
  var ensure = (self) => Array2.isArray(self) ? self : [self];
@@ -9022,7 +9102,7 @@ function makeReducerConcat() {
9022
9102
  return reducer;
9023
9103
  }
9024
9104
 
9025
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/BigDecimal.js
9105
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/BigDecimal.js
9026
9106
  var FINITE_INT_REGEXP = /^[+-]?\d+$/;
9027
9107
  var TypeId3 = "~effect/BigDecimal";
9028
9108
  var BigDecimalProto = {
@@ -9251,17 +9331,17 @@ var floor = /* @__PURE__ */ dual(isBigDecimalArgs, (self, scale2 = 0) => {
9251
9331
  return truncated;
9252
9332
  });
9253
9333
 
9254
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Boolean.js
9334
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Boolean.js
9255
9335
  var Boolean2 = globalThis.Boolean;
9256
9336
  var ReducerOr = /* @__PURE__ */ make((a, b) => a || b, false);
9257
9337
 
9258
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Effectable.js
9338
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Effectable.js
9259
9339
  var Prototype2 = (options) => makePrimitiveProto({
9260
9340
  op: options.label,
9261
9341
  [evaluate]: options.evaluate
9262
9342
  });
9263
9343
 
9264
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Context.js
9344
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Context.js
9265
9345
  var ServiceTypeId = "~effect/Context/Service";
9266
9346
  var Service = function() {
9267
9347
  function KeyClass() {
@@ -9438,7 +9518,7 @@ var serviceNotFoundError = (service2) => {
9438
9518
  };
9439
9519
  var Reference = Service;
9440
9520
 
9441
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Duration.js
9521
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Duration.js
9442
9522
  var TypeId5 = "~effect/time/Duration";
9443
9523
  var bigint02 = /* @__PURE__ */ BigInt(0);
9444
9524
  var bigint12 = /* @__PURE__ */ BigInt(1);
@@ -9696,7 +9776,7 @@ var Equivalence2 = (self, that) => matchPair(self, that, {
9696
9776
  });
9697
9777
  var equals3 = /* @__PURE__ */ dual(2, (self, that) => Equivalence2(self, that));
9698
9778
 
9699
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Scheduler.js
9779
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Scheduler.js
9700
9780
  var Scheduler = /* @__PURE__ */ Reference("effect/Scheduler", {
9701
9781
  fiberCached: true,
9702
9782
  defaultValue: () => new MixedScheduler()
@@ -9833,7 +9913,7 @@ var PreventSchedulerYield = /* @__PURE__ */ Reference("effect/Scheduler/PreventS
9833
9913
  defaultValue: () => false
9834
9914
  });
9835
9915
 
9836
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Data.js
9916
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Data.js
9837
9917
  var Class3 = class extends Class {
9838
9918
  constructor(props) {
9839
9919
  super();
@@ -9844,7 +9924,7 @@ var Class3 = class extends Class {
9844
9924
  };
9845
9925
  var TaggedError2 = TaggedError;
9846
9926
 
9847
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Encoding.js
9927
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Encoding.js
9848
9928
  var EncodingErrorTypeId = "~effect/encoding/EncodingError";
9849
9929
  var EncodingError = class extends (/* @__PURE__ */ TaggedError2("EncodingError")) {
9850
9930
  /**
@@ -10017,14 +10097,14 @@ var fromHexChar = (byte) => {
10017
10097
  throw new TypeError("Invalid input");
10018
10098
  };
10019
10099
 
10020
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Tracer.js
10100
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Tracer.js
10021
10101
  var ParentSpanKey = "effect/Tracer/ParentSpan";
10022
10102
  var TracerKey = "effect/Tracer";
10023
10103
 
10024
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/metric.js
10104
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/metric.js
10025
10105
  var FiberRuntimeMetricsKey = "effect/observability/Metric/FiberRuntimeMetricsKey";
10026
10106
 
10027
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/references.js
10107
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/references.js
10028
10108
  var CurrentStackFrame = /* @__PURE__ */ Reference("effect/References/CurrentStackFrame", {
10029
10109
  fiberCached: true,
10030
10110
  defaultValue: constUndefined
@@ -10038,7 +10118,7 @@ var MinimumLogLevel = /* @__PURE__ */ Reference("effect/References/MinimumLogLev
10038
10118
  defaultValue: () => "Info"
10039
10119
  });
10040
10120
 
10041
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/stackTraceLimit.js
10121
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/stackTraceLimit.js
10042
10122
  var isStackTraceLimitWritable = () => {
10043
10123
  const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
10044
10124
  if (desc === void 0) {
@@ -10055,7 +10135,7 @@ var setStackTraceLimit = (value3) => {
10055
10135
  }
10056
10136
  };
10057
10137
 
10058
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/effect.js
10138
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/effect.js
10059
10139
  var Interrupt = class extends ReasonBase {
10060
10140
  fiberId;
10061
10141
  constructor(fiberId2, annotations = constEmptyAnnotations) {
@@ -10886,7 +10966,7 @@ var iterateEagerImpl = (options) => {
10886
10966
  if (concurrency === 1) {
10887
10967
  return runSequential(state, items, 0, end);
10888
10968
  }
10889
- const orderedStep = opts?.orderedStep === true && concurrency > 1;
10969
+ const orderedStep = opts?.orderedStep === true;
10890
10970
  let done2 = false;
10891
10971
  let parentFiber;
10892
10972
  let fibers;
@@ -11153,7 +11233,7 @@ var logLevelColors = {
11153
11233
  Fatal: [colors.bgBrightRed, colors.black]
11154
11234
  };
11155
11235
 
11156
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Cause.js
11236
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Cause.js
11157
11237
  var isCause2 = isCause;
11158
11238
  var isReason = isCauseReason;
11159
11239
  var isFailReason2 = isFailReason;
@@ -11166,7 +11246,7 @@ var map6 = causeMap;
11166
11246
  var pretty = causePretty;
11167
11247
  var IllegalArgumentError2 = IllegalArgumentError;
11168
11248
 
11169
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Exit.js
11249
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Exit.js
11170
11250
  var isExit2 = isExit;
11171
11251
  var succeed4 = exitSucceed;
11172
11252
  var failCause2 = exitFailCause;
@@ -11175,7 +11255,7 @@ var void_2 = exitVoid;
11175
11255
  var isSuccess3 = exitIsSuccess;
11176
11256
  var isFailure3 = exitIsFailure;
11177
11257
 
11178
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/dateTime.js
11258
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/dateTime.js
11179
11259
  var TypeId6 = "~effect/time/DateTime";
11180
11260
  var TimeZoneTypeId = "~effect/time/DateTime/TimeZone";
11181
11261
  var Proto2 = {
@@ -11569,7 +11649,7 @@ var formatIsoOffset = (self) => {
11569
11649
  };
11570
11650
  var formatIsoZoned = (self) => self.zone._tag === "Offset" ? formatIsoOffset(self) : `${formatIsoOffset(self)}[${self.zone.id}]`;
11571
11651
 
11572
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Number.js
11652
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Number.js
11573
11653
  var Number3 = globalThis.Number;
11574
11654
  var remainder = /* @__PURE__ */ dual(2, (self, divisor) => {
11575
11655
  const selfString = self.toString();
@@ -11610,17 +11690,18 @@ function toScientificInteger(n) {
11610
11690
  var ReducerMax = /* @__PURE__ */ make((a, b) => Math.max(a, b), -Infinity);
11611
11691
  var ReducerMin = /* @__PURE__ */ make((a, b) => Math.min(a, b), Infinity);
11612
11692
 
11613
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/String.js
11693
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/String.js
11614
11694
  var String2 = globalThis.String;
11615
11695
  var trim = (self) => self.trim();
11616
11696
 
11617
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Effect.js
11697
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Effect.js
11618
11698
  var tryPromise2 = tryPromise;
11619
11699
  var succeed5 = succeed3;
11620
11700
  var succeedNone2 = succeedNone;
11621
11701
  var void_3 = void_;
11622
11702
  var fail5 = fail3;
11623
11703
  var failCauseSync2 = failCauseSync;
11704
+ var die2 = die;
11624
11705
  var try_3 = try_2;
11625
11706
  var fromResult2 = fromResult;
11626
11707
  var flatMap4 = flatMap3;
@@ -11638,7 +11719,7 @@ var flatMapEager2 = flatMapEager;
11638
11719
  var catchEager2 = catchEager;
11639
11720
  var fnUntracedEager2 = fnUntracedEager;
11640
11721
 
11641
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/schema/annotations.js
11722
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/schema/annotations.js
11642
11723
  function resolve(ast) {
11643
11724
  return ast.checks ? ast.checks[ast.checks.length - 1].annotations : ast.annotations;
11644
11725
  }
@@ -11661,7 +11742,7 @@ var getExpected = /* @__PURE__ */ memoize((ast) => {
11661
11742
  });
11662
11743
  var annotationExcludedKeys = /* @__PURE__ */ new Set([SENTINELS_ANNOTATION_KEY, STRUCTURAL_ANNOTATION_KEY, "representation", "arbitrary", "brands", "toJsonSchema", "toCode", "toArbitrary", "toEquivalence", "toFormatter", "toCodec", "toCodecJson", "toCodecStringTree", "toCodecIso"]);
11663
11744
 
11664
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/schema/parser.js
11745
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/schema/parser.js
11665
11746
  var missing = /* @__PURE__ */ Symbol();
11666
11747
  var succeed6 = succeed4;
11667
11748
  var missingExit = /* @__PURE__ */ succeed6(missing);
@@ -11669,7 +11750,7 @@ var sameExit = /* @__PURE__ */ succeed6(missing);
11669
11750
  var toOption = (value3) => value3 === missing ? none2() : some2(value3);
11670
11751
  var fromOptionExit = (option2) => option2._tag === "None" ? missingExit : succeed6(option2.value);
11671
11752
 
11672
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/SchemaIssue.js
11753
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/SchemaIssue.js
11673
11754
  var TypeId7 = "~effect/SchemaIssue/Issue";
11674
11755
  function isIssue(u) {
11675
11756
  return hasProperty(u, TypeId7) && u[TypeId7] === TypeId7;
@@ -12012,7 +12093,7 @@ function findMessage(issue) {
12012
12093
  if (typeof message === "string") return message;
12013
12094
  }
12014
12095
 
12015
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/schema/cause.js
12096
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/schema/cause.js
12016
12097
  function getSchemaIssue(cause) {
12017
12098
  let issue;
12018
12099
  for (const reason of cause.reasons) {
@@ -12033,7 +12114,7 @@ function getSchemaIssueOrThrow(cause, message) {
12033
12114
  return issue;
12034
12115
  }
12035
12116
 
12036
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/DateTime.js
12117
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/DateTime.js
12037
12118
  var isDateTime2 = isDateTime;
12038
12119
  var isTimeZone2 = isTimeZone;
12039
12120
  var isTimeZoneOffset2 = isTimeZoneOffset;
@@ -12057,7 +12138,7 @@ var toEpochMillis2 = toEpochMillis;
12057
12138
  var formatIso2 = formatIso;
12058
12139
  var formatIsoZoned2 = formatIsoZoned;
12059
12140
 
12060
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/SchemaGetter.js
12141
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/SchemaGetter.js
12061
12142
  var Getter = class _Getter extends Class {
12062
12143
  run;
12063
12144
  constructor(run2) {
@@ -12344,7 +12425,7 @@ function collectBracketPathEntries(isLeaf) {
12344
12425
  };
12345
12426
  }
12346
12427
 
12347
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/SchemaTransformation.js
12428
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/SchemaTransformation.js
12348
12429
  var Middleware = class _Middleware {
12349
12430
  _tag = "Middleware";
12350
12431
  decode;
@@ -12585,7 +12666,7 @@ var dateTimeZonedFromString = /* @__PURE__ */ transformOrFail2({
12585
12666
  encode: (zoned) => succeed5(formatIsoZoned2(zoned))
12586
12667
  });
12587
12668
 
12588
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/SchemaAST.js
12669
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/SchemaAST.js
12589
12670
  function makeGuard(tag2) {
12590
12671
  return (ast) => ast._tag === tag2;
12591
12672
  }
@@ -12641,11 +12722,17 @@ var Declaration = class _Declaration extends Base2 {
12641
12722
  typeParameters;
12642
12723
  run;
12643
12724
  encodingChecks;
12644
- constructor(typeParameters, run2, annotations, checks, encoding, context2, encodingChecks) {
12725
+ /**
12726
+ * Parser factory {@link flip} swaps in, so a declaration can behave
12727
+ * differently when encoding. `undefined` reuses {@link run}.
12728
+ */
12729
+ encodingRun;
12730
+ constructor(typeParameters, run2, annotations, checks, encoding, context2, encodingChecks, encodingRun) {
12645
12731
  super(annotations, checks, encoding, context2);
12646
12732
  this.typeParameters = typeParameters;
12647
12733
  this.run = run2;
12648
12734
  this.encodingChecks = encodingChecks;
12735
+ this.encodingRun = encodingRun;
12649
12736
  }
12650
12737
  /** @internal */
12651
12738
  getParser() {
@@ -12655,17 +12742,17 @@ var Declaration = class _Declaration extends Base2 {
12655
12742
  return (run2 ??= this.run(this.typeParameters))(input, this, options);
12656
12743
  };
12657
12744
  }
12658
- _rebuild(recur3, checks, encodingChecks) {
12745
+ _rebuild(recur3, checks, encodingChecks, run2, encodingRun) {
12659
12746
  const tps = mapOrSame(this.typeParameters, recur3);
12660
- return tps === this.typeParameters && checks === this.checks && encodingChecks === this.encodingChecks ? this : new _Declaration(tps, this.run, this.annotations, checks, void 0, this.context, encodingChecks);
12747
+ return tps === this.typeParameters && checks === this.checks && encodingChecks === this.encodingChecks && run2 === this.run && encodingRun === this.encodingRun ? this : new _Declaration(tps, run2, this.annotations, checks, void 0, this.context, encodingChecks, encodingRun);
12661
12748
  }
12662
12749
  /** @internal */
12663
12750
  recur(recur3) {
12664
- return this._rebuild(recur3, this.checks, this.encodingChecks);
12751
+ return this._rebuild(recur3, this.checks, this.encodingChecks, this.run, this.encodingRun);
12665
12752
  }
12666
12753
  /** @internal */
12667
12754
  flip(recur3) {
12668
- return this._rebuild(recur3, this.encodingChecks, this.checks);
12755
+ return this._rebuild(recur3, this.encodingChecks, this.checks, this.encodingRun ?? this.run, this.run);
12669
12756
  }
12670
12757
  /** @internal */
12671
12758
  getExpected() {
@@ -13332,13 +13419,7 @@ var Objects = class _Objects extends Base2 {
13332
13419
  onItem: (s, [key, index2]) => parseIndex(s, key, index2),
13333
13420
  step: (_s, _, exit3) => exit3._tag === "Failure" ? exit3 : void 0
13334
13421
  }) : void 0;
13335
- return fnUntracedEager2(function* (input, options) {
13336
- if (input === missing) {
13337
- return missing;
13338
- }
13339
- if (!(typeof input === "object" && input !== null && !Array.isArray(input))) {
13340
- return yield* fail5(new InvalidType(ast, input, options));
13341
- }
13422
+ const compileMembers = () => {
13342
13423
  if (!properties) {
13343
13424
  properties = ast.propertySignatures.map((ps) => ({
13344
13425
  parser: compileConstructorDefault2(ps.type),
@@ -13351,6 +13432,16 @@ var Objects = class _Objects extends Base2 {
13351
13432
  parserValue: compileConstructorDefault2(is3.type)
13352
13433
  })) : void 0;
13353
13434
  }
13435
+ return properties;
13436
+ };
13437
+ const fallback = fnUntracedEager2(function* (input, options) {
13438
+ if (input === missing) {
13439
+ return missing;
13440
+ }
13441
+ if (!(typeof input === "object" && input !== null && !Array.isArray(input))) {
13442
+ return yield* fail5(new InvalidType(ast, input, options));
13443
+ }
13444
+ compileMembers();
13354
13445
  const record2 = input;
13355
13446
  const out = {};
13356
13447
  const state = {
@@ -13432,6 +13523,57 @@ var Objects = class _Objects extends Base2 {
13432
13523
  }
13433
13524
  return out;
13434
13525
  });
13526
+ if (indexCount) return fallback;
13527
+ const resume = (state, index2, pending) => {
13528
+ const property = properties[index2];
13529
+ return flatMap4(exit2(pending), (exit3) => {
13530
+ const terminal = stepProperty(state, property, exit3);
13531
+ if (terminal) return terminal;
13532
+ const done2 = () => succeed6(state.out);
13533
+ const eff = parseProperties(state, properties.slice(index2 + 1));
13534
+ return eff ? flatMapEager2(eff, done2) : done2();
13535
+ });
13536
+ };
13537
+ return (input, options) => {
13538
+ if (input === missing) return missingExit;
13539
+ if (options.errors === "all" || options.onExcessProperty !== void 0 || options.propertyOrder === "original" || options.concurrency !== void 0) {
13540
+ return fallback(input, options);
13541
+ }
13542
+ if (!(typeof input === "object" && input !== null && !Array.isArray(input))) {
13543
+ return fail5(new InvalidType(ast, input, options));
13544
+ }
13545
+ const props = compileMembers();
13546
+ const record2 = input;
13547
+ const out = {};
13548
+ const state = {
13549
+ ast,
13550
+ input: record2,
13551
+ out,
13552
+ issues: void 0,
13553
+ options
13554
+ };
13555
+ try {
13556
+ for (let index2 = 0; index2 < props.length; index2++) {
13557
+ const property = props[index2];
13558
+ const name = property.name;
13559
+ const hasKey2 = Object.hasOwn(record2, name);
13560
+ const value3 = hasKey2 ? record2[name] : missing;
13561
+ const exit3 = property.parser(value3, options);
13562
+ if (!effectIsExit(exit3)) {
13563
+ return resume(state, index2, exit3);
13564
+ }
13565
+ if (exit3 === sameExit) {
13566
+ if (hasKey2) assignProperty(out, name, value3);
13567
+ continue;
13568
+ }
13569
+ const terminal = stepProperty(state, property, exit3);
13570
+ if (terminal) return terminal;
13571
+ }
13572
+ } catch (error) {
13573
+ return die2(error);
13574
+ }
13575
+ return succeed6(out);
13576
+ };
13435
13577
  }
13436
13578
  _rebuild(recur3, recurParameter, checks, encodingChecks) {
13437
13579
  const props = mapOrSame(this.propertySignatures, (ps) => {
@@ -13459,6 +13601,28 @@ var Objects = class _Objects extends Base2 {
13459
13601
  return "object";
13460
13602
  }
13461
13603
  };
13604
+ function stepProperty(s, p, exit3) {
13605
+ if (exit3._tag === "Failure") {
13606
+ return wrapPropertyKeyIssue(s, s.ast, p.name, exit3);
13607
+ }
13608
+ if (exit3 === sameExit) return;
13609
+ const value3 = exit3[args];
13610
+ if (value3 !== missing) {
13611
+ assignProperty(s.out, p.name, value3);
13612
+ return;
13613
+ }
13614
+ delete s.out[p.name];
13615
+ if (!isOptional(p.type)) {
13616
+ const issue = new Pointer([p.name], new MissingKey(p.type.context?.annotations));
13617
+ if (s.options.errors === "all") {
13618
+ if (s.issues) s.issues.push(issue);
13619
+ else s.issues = [issue];
13620
+ return;
13621
+ } else {
13622
+ return fail4(new Composite(s.ast, [issue], s.input, s.options));
13623
+ }
13624
+ }
13625
+ }
13462
13626
  var parseProperties = /* @__PURE__ */ iterateEager()({
13463
13627
  onItem(s, p) {
13464
13628
  if (!Object.hasOwn(s.input, p.name)) {
@@ -13468,28 +13632,7 @@ var parseProperties = /* @__PURE__ */ iterateEager()({
13468
13632
  assignProperty(s.out, p.name, value3);
13469
13633
  return p.parser(value3, s.options);
13470
13634
  },
13471
- step(s, p, exit3) {
13472
- if (exit3._tag === "Failure") {
13473
- return wrapPropertyKeyIssue(s, s.ast, p.name, exit3);
13474
- }
13475
- if (exit3 === sameExit) return;
13476
- const value3 = exit3[args];
13477
- if (value3 !== missing) {
13478
- assignProperty(s.out, p.name, value3);
13479
- return;
13480
- }
13481
- delete s.out[p.name];
13482
- if (!isOptional(p.type)) {
13483
- const issue = new Pointer([p.name], new MissingKey(p.type.context?.annotations));
13484
- if (s.options.errors === "all") {
13485
- if (s.issues) s.issues.push(issue);
13486
- else s.issues = [issue];
13487
- return;
13488
- } else {
13489
- return fail4(new Composite(s.ast, [issue], s.input, s.options));
13490
- }
13491
- }
13492
- }
13635
+ step: stepProperty
13493
13636
  });
13494
13637
  function combineChecks(a, b) {
13495
13638
  if (!a) return b;
@@ -14572,7 +14715,7 @@ var StringTree = /* @__PURE__ */ new Declaration([], () => (input, ast, options)
14572
14715
  });
14573
14716
  var unknownToStringTree = /* @__PURE__ */ new Link(StringTree, /* @__PURE__ */ passthrough2());
14574
14717
 
14575
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Chunk.js
14718
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Chunk.js
14576
14719
  var TypeId10 = "~effect/collections/Chunk";
14577
14720
  function copy(src, srcPos, dest, destPos, len) {
14578
14721
  for (let i = srcPos; i < Math.min(src.length, srcPos + len); i++) {
@@ -14756,7 +14899,7 @@ var getUnsafe2 = /* @__PURE__ */ dual(2, (self, index2) => {
14756
14899
  });
14757
14900
  var size = (self) => self.length;
14758
14901
 
14759
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Schema.js
14902
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Schema.js
14760
14903
  var Schema_exports = {};
14761
14904
  __export(Schema_exports, {
14762
14905
  Any: () => Any2,
@@ -15109,7 +15252,7 @@ __export(Schema_exports, {
15109
15252
  withDecodingDefaultTypeKey: () => withDecodingDefaultTypeKey
15110
15253
  });
15111
15254
 
15112
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/graph.js
15255
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/graph.js
15113
15256
  var TypeId11 = "~effect/collections/Graph";
15114
15257
  var toImpl = (graph) => graph;
15115
15258
  var edgeEquals = (type, self, that) => (type === "directed" ? self.source === that.source && self.target === that.target : self.source === that.source && self.target === that.target || self.source === that.target && self.target === that.source) && equals(self.data, that.data);
@@ -15230,7 +15373,7 @@ var hydrate = (snapshot2) => {
15230
15373
  return graph;
15231
15374
  };
15232
15375
 
15233
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Graph.js
15376
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Graph.js
15234
15377
  var TypeId12 = TypeId11;
15235
15378
  var isGraph = (u) => hasProperty(u, TypeId12);
15236
15379
  var EdgeIdentity = class _EdgeIdentity {
@@ -15259,7 +15402,7 @@ var EdgeIdentity = class _EdgeIdentity {
15259
15402
  }
15260
15403
  };
15261
15404
 
15262
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/hashMap.js
15405
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/hashMap.js
15263
15406
  var HashMapTypeId = "~effect/collections/HashMap";
15264
15407
  var SHIFT = 5;
15265
15408
  var BUCKET_SIZE = 1 << SHIFT;
@@ -15901,14 +16044,14 @@ var entries = (self) => {
15901
16044
  };
15902
16045
  var size2 = (self) => self.size;
15903
16046
 
15904
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/HashMap.js
16047
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/HashMap.js
15905
16048
  var isHashMap2 = isHashMap;
15906
16049
  var fromIterable4 = fromIterable3;
15907
16050
  var entries2 = entries;
15908
16051
  var toEntries = (self) => Array.from(entries2(self));
15909
16052
  var size3 = size2;
15910
16053
 
15911
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/hashSet.js
16054
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/hashSet.js
15912
16055
  var HashSetTypeId = "~effect/collections/HashSet";
15913
16056
  var HashSetProto = {
15914
16057
  [symbol]() {
@@ -15962,12 +16105,12 @@ var every2 = (self, predicate) => {
15962
16105
  return true;
15963
16106
  };
15964
16107
 
15965
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/HashSet.js
16108
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/HashSet.js
15966
16109
  var fromIterable6 = fromIterable5;
15967
16110
  var isHashSet2 = isHashSet;
15968
16111
  var size5 = size4;
15969
16112
 
15970
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/SchemaParser.js
16113
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/SchemaParser.js
15971
16114
  function makeEffect(schema) {
15972
16115
  const parser = runWithCompiler(constructorCompiler, toType(schema.ast));
15973
16116
  return (input, options) => {
@@ -16265,7 +16408,7 @@ function makeParser(ast, compile, compileConstructorDefault2, constructorDefault
16265
16408
  };
16266
16409
  }
16267
16410
 
16268
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/schema/schema.js
16411
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/schema/schema.js
16269
16412
  var TypeId13 = "~effect/Schema/Schema";
16270
16413
  function makeDeclarationReviver(id2, payloadSchema, revive) {
16271
16414
  return {
@@ -16310,7 +16453,7 @@ function make15(ast, options) {
16310
16453
  return self;
16311
16454
  }
16312
16455
 
16313
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Struct.js
16456
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Struct.js
16314
16457
  var Struct_exports = {};
16315
16458
  __export(Struct_exports, {
16316
16459
  Record: () => Record,
@@ -16413,7 +16556,7 @@ function Record(keys4, value3) {
16413
16556
  return out;
16414
16557
  }
16415
16558
 
16416
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/UndefinedOr.js
16559
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/UndefinedOr.js
16417
16560
  function makeReducer2(combiner2) {
16418
16561
  return make((self, that) => {
16419
16562
  if (self === void 0) return that;
@@ -16422,7 +16565,7 @@ function makeReducer2(combiner2) {
16422
16565
  }, void 0);
16423
16566
  }
16424
16567
 
16425
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/errors.js
16568
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/errors.js
16426
16569
  function errorWithPath(message, path21) {
16427
16570
  if (path21.length > 0) {
16428
16571
  message += `
@@ -16431,7 +16574,7 @@ function errorWithPath(message, path21) {
16431
16574
  return new Error(message);
16432
16575
  }
16433
16576
 
16434
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/schema/toArbitrary.js
16577
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/schema/toArbitrary.js
16435
16578
  var arbitraryMemoMap = /* @__PURE__ */ new WeakMap();
16436
16579
  var suspendDepthIdentifierMap = /* @__PURE__ */ new WeakMap();
16437
16580
  var emptyRecursionStack = [];
@@ -17093,7 +17236,7 @@ function base(ast, path21) {
17093
17236
  }
17094
17237
  }
17095
17238
 
17096
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/schema/toEquivalence.js
17239
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/schema/toEquivalence.js
17097
17240
  var toEquivalence = /* @__PURE__ */ memoize((ast) => {
17098
17241
  return recur2(ast, []);
17099
17242
  });
@@ -17216,7 +17359,7 @@ function recur2(ast, path21) {
17216
17359
  }
17217
17360
  }
17218
17361
 
17219
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/JsonPointer.js
17362
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/JsonPointer.js
17220
17363
  function escapeToken(token) {
17221
17364
  return token.replace(/~/g, "~0").replace(/\//g, "~1");
17222
17365
  }
@@ -17224,73 +17367,23 @@ function unescapeToken(token) {
17224
17367
  return token.replace(/~1/g, "/").replace(/~0/g, "~");
17225
17368
  }
17226
17369
 
17227
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/JsonSchema.js
17228
- var RE_DEFS = /^#\/\$defs(?=\/|$)/;
17229
- var DRAFT_04_COPY_KEYWORDS = /* @__PURE__ */ new Set(["$ref", "type", "required", "enum", "title", "description", "default", "format", "pattern", "minLength", "maxLength", "minItems", "maxItems", "minProperties", "maxProperties", "multipleOf", "uniqueItems"]);
17230
- var DRAFT_07_COPY_KEYWORDS = /* @__PURE__ */ new Set([...DRAFT_04_COPY_KEYWORDS, "const", "examples", "readOnly", "writeOnly", "minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum"]);
17231
- var DRAFT_07_SINGLE_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set(["not", "additionalProperties", "propertyNames"]);
17232
- var MAP_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set(["properties", "patternProperties"]);
17233
- var ARRAY_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set(["allOf", "anyOf", "oneOf"]);
17370
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/JsonSchema.js
17371
+ var META_SCHEMA_URI_DRAFT_07 = "http://json-schema.org/draft-07/schema#";
17372
+ var META_SCHEMA_URI_DRAFT_2020_12 = "https://json-schema.org/draft/2020-12/schema";
17373
+ function isMetaSchemaUri(value3, uri) {
17374
+ return value3 === uri || value3 === (uri.endsWith("#") ? uri.slice(0, -1) : `${uri}#`);
17375
+ }
17234
17376
  function toDocumentDraft07(document) {
17235
17377
  return {
17236
17378
  dialect: "draft-07",
17237
- schema: toSchemaDraft07(document.schema),
17238
- definitions: map3(document.definitions, toSchemaDraft07)
17379
+ ...convertDocument(document, draft07Adapter)
17239
17380
  };
17240
17381
  }
17241
- function toSchemaDraft07(schema) {
17242
- return transformSchema(schema, (src) => {
17243
- rewriteSchemaRef(src, (ref) => ref.replace(RE_DEFS, "#/definitions"));
17244
- const out = {};
17245
- let prefixItems = void 0;
17246
- let items = void 0;
17247
- for (const k of Object.keys(src)) {
17248
- const v = src[k];
17249
- if (k === "required" && Array.isArray(v) && v.length === 0) continue;
17250
- if (DRAFT_07_COPY_KEYWORDS.has(k)) {
17251
- out[k] = v;
17252
- continue;
17253
- }
17254
- if (MAP_SUBSCHEMA_KEYWORDS.has(k) || ARRAY_SUBSCHEMA_KEYWORDS.has(k) || DRAFT_07_SINGLE_SUBSCHEMA_KEYWORDS.has(k)) {
17255
- out[k] = v;
17256
- continue;
17257
- }
17258
- switch (k) {
17259
- // Tuple handling (2020-12 form)
17260
- case "prefixItems":
17261
- prefixItems = v;
17262
- break;
17263
- case "items":
17264
- items = v;
17265
- break;
17266
- default:
17267
- break;
17268
- }
17269
- }
17270
- if (prefixItems !== void 0) {
17271
- if (Array.isArray(prefixItems)) {
17272
- out.items = prefixItems;
17273
- if (items !== void 0) out.additionalItems = items;
17274
- } else {
17275
- out.items = prefixItems;
17276
- }
17277
- } else if (items !== void 0) {
17278
- out.items = items;
17279
- }
17280
- const $ref = out.$ref;
17281
- if (typeof $ref === "string" && Object.keys(out).length > 1) {
17282
- delete out.$ref;
17283
- out.allOf = [{
17284
- $ref
17285
- }, ...Array.isArray(out.allOf) ? out.allOf : []];
17286
- }
17287
- return out;
17288
- });
17289
- }
17290
17382
  function transformSchema(node, transform3) {
17291
- return walk(node);
17292
- function walk(node2) {
17383
+ return walk(node, false, true);
17384
+ function walk(node2, inheritedResource, isRoot = false) {
17293
17385
  if (!isObject(node2)) return node2;
17386
+ const inEmbeddedResource = inheritedResource || !isRoot && createsResource(node2.$id);
17294
17387
  const out = {};
17295
17388
  for (const key of Object.keys(node2)) {
17296
17389
  const value3 = node2[key];
@@ -17300,13 +17393,13 @@ function transformSchema(node, transform3) {
17300
17393
  case "properties":
17301
17394
  case "patternProperties":
17302
17395
  case "dependentSchemas":
17303
- transformed = mapObject(value3, walk) ?? value3;
17396
+ transformed = mapObject(value3, (value4) => walk(value4, inEmbeddedResource)) ?? value3;
17304
17397
  break;
17305
17398
  case "allOf":
17306
17399
  case "anyOf":
17307
17400
  case "oneOf":
17308
17401
  case "prefixItems":
17309
- transformed = Array.isArray(value3) ? value3.map(walk) : value3;
17402
+ transformed = Array.isArray(value3) ? value3.map((value4) => walk(value4, inEmbeddedResource)) : value3;
17310
17403
  break;
17311
17404
  case "not":
17312
17405
  case "additionalProperties":
@@ -17319,31 +17412,340 @@ function transformSchema(node, transform3) {
17319
17412
  case "then":
17320
17413
  case "else":
17321
17414
  case "contentSchema":
17322
- transformed = walk(value3);
17415
+ transformed = walk(value3, inEmbeddedResource);
17323
17416
  }
17324
17417
  assignProperty(out, key, transformed);
17325
17418
  }
17326
- return transform3(out);
17419
+ transform3(out, inEmbeddedResource);
17420
+ return out;
17327
17421
  }
17328
17422
  }
17329
17423
  function rewriteRefs(schema, rewrite) {
17330
- return transformSchema(schema, (schema2) => rewriteSchemaRef(schema2, rewrite));
17424
+ return transformSchema(schema, (schema2) => {
17425
+ rewriteSchemaRef(schema2, rewrite);
17426
+ });
17331
17427
  }
17332
17428
  function rewriteSchemaRef(schema, rewrite) {
17333
17429
  if (typeof schema.$ref === "string") {
17334
- assignProperty(schema, "$ref", rewrite(schema.$ref));
17430
+ assignProperty(schema, "$ref", rewrite(schema.$ref, "$ref"));
17431
+ }
17432
+ if (typeof schema.$dynamicRef === "string") {
17433
+ assignProperty(schema, "$dynamicRef", rewrite(schema.$dynamicRef, "$dynamicRef"));
17335
17434
  }
17336
- return schema;
17337
17435
  }
17338
17436
  function mapObject(value3, f) {
17339
- return isObject(value3) ? map3(value3, f) : void 0;
17437
+ if (!isObject(value3)) return void 0;
17438
+ const out = {};
17439
+ for (const key of Object.keys(value3)) {
17440
+ assignProperty(out, key, f(value3[key], key));
17441
+ }
17442
+ return out;
17443
+ }
17444
+ function runConverter(adapter, options, use) {
17445
+ const locations = /* @__PURE__ */ new Map();
17446
+ const references = [];
17447
+ let rootUri = ROOT_URI;
17448
+ function convert(root, sourcePath = [], targetPath = []) {
17449
+ if (sourcePath.length === 0 && options?.trackIds) {
17450
+ const id2 = isObject(root) ? getResourceId(root) : void 0;
17451
+ rootUri = resolveResourceUri(id2, ROOT_URI) ?? ROOT_URI;
17452
+ }
17453
+ return loop(root, sourcePath, targetPath, {
17454
+ sourceRoot: [],
17455
+ targetRoot: [],
17456
+ uri: rootUri
17457
+ });
17458
+ }
17459
+ function finish() {
17460
+ for (const [out2, value3, sourceResource] of references) {
17461
+ let reference = value3;
17462
+ const resolved = resolveUrl(value3, sourceResource);
17463
+ if (resolved !== void 0) {
17464
+ const sourcePointer = parsePointerFragment(resolved.hash);
17465
+ resolved.hash = "";
17466
+ if (sourcePointer !== void 0) {
17467
+ const targetPath = locations.get(locationKey(resolved.href, sourcePointer));
17468
+ if (targetPath !== void 0) reference = relocateReference(value3, targetPath);
17469
+ }
17470
+ }
17471
+ assignProperty(out2, "$ref", reference);
17472
+ }
17473
+ }
17474
+ const out = use(convert);
17475
+ finish();
17476
+ return out;
17477
+ function loop(node, sourcePath, targetPath, resourceScope) {
17478
+ if (typeof node === "boolean") {
17479
+ recordLocations(sourcePath, targetPath, resourceScope);
17480
+ return options?.booleanAdapter?.(node) ?? node;
17481
+ }
17482
+ if (!isObject(node)) return node;
17483
+ let currentResourceScope = resourceScope;
17484
+ const id2 = getResourceId(node);
17485
+ if (sourcePath.length > 0 && options?.trackIds && createsResource(id2)) {
17486
+ const uri = resolveResourceUri(id2, resourceScope.uri);
17487
+ if (uri !== void 0) {
17488
+ currentResourceScope = {
17489
+ parent: resourceScope,
17490
+ sourceRoot: sourcePath,
17491
+ targetRoot: targetPath,
17492
+ uri
17493
+ };
17494
+ }
17495
+ }
17496
+ recordLocations(sourcePath, targetPath, currentResourceScope);
17497
+ const currentResource = currentResourceScope.uri;
17498
+ const context2 = {
17499
+ isDocumentRoot: sourcePath.length === 0,
17500
+ schema(value3, sourceKey, targetKey = sourceKey) {
17501
+ return loop(value3, [...sourcePath, sourceKey], [...targetPath, targetKey], currentResourceScope);
17502
+ },
17503
+ schemaAt(value3, sourceSuffix, targetSuffix) {
17504
+ return loop(value3, [...sourcePath, ...sourceSuffix], [...targetPath, ...targetSuffix], currentResourceScope);
17505
+ },
17506
+ schemaArray(value3, sourceKey, targetKey = sourceKey) {
17507
+ return Array.isArray(value3) ? value3.map((item, index2) => loop(item, [...sourcePath, sourceKey, String(index2)], [...targetPath, targetKey, String(index2)], currentResourceScope)) : value3;
17508
+ },
17509
+ schemaMap(value3, sourceKey, targetKey = sourceKey) {
17510
+ if (!isObject(value3)) return value3;
17511
+ return mapObject(value3, (item, key) => loop(item, [...sourcePath, sourceKey, key], [...targetPath, targetKey, key], currentResourceScope));
17512
+ },
17513
+ reference(out2, value3) {
17514
+ if (typeof value3 === "string") {
17515
+ references.push([out2, value3, currentResource]);
17516
+ } else {
17517
+ assignProperty(out2, "$ref", value3);
17518
+ }
17519
+ }
17520
+ };
17521
+ return adapter(node, context2);
17522
+ }
17523
+ function getResourceId(schema) {
17524
+ return options?.ignoreRefSiblings === true && typeof schema.$ref === "string" ? void 0 : schema.$id;
17525
+ }
17526
+ function recordLocations(sourcePath, targetPath, scope2) {
17527
+ if (scope2.parent !== void 0) recordLocations(sourcePath, targetPath, scope2.parent);
17528
+ locations.set(locationKey(scope2.uri, sourcePath.slice(scope2.sourceRoot.length)), targetPath.slice(scope2.targetRoot.length));
17529
+ }
17530
+ }
17531
+ var ROOT_URI = "https://effect.invalid/.json-schema/";
17532
+ function resolveUrl(value3, base2) {
17533
+ return URL.canParse(value3, base2) ? new URL(value3, base2) : void 0;
17534
+ }
17535
+ function resolveResourceUri(value3, base2) {
17536
+ if (typeof value3 !== "string") return void 0;
17537
+ const url = resolveUrl(value3, base2);
17538
+ if (url === void 0) return void 0;
17539
+ url.hash = "";
17540
+ return url.href;
17541
+ }
17542
+ function parsePointerFragment(hash2) {
17543
+ if (hash2.length === 0) return [];
17544
+ let pointer;
17545
+ try {
17546
+ pointer = decodeURIComponent(hash2.slice(1));
17547
+ } catch {
17548
+ return void 0;
17549
+ }
17550
+ if (!pointer.startsWith("/")) return void 0;
17551
+ return /~(?:[^01]|$)/.test(pointer) ? void 0 : pointer.slice(1).split("/").map(unescapeToken);
17552
+ }
17553
+ function relocateReference(reference, targetPath) {
17554
+ const index2 = reference.indexOf("#");
17555
+ if (index2 === -1 && targetPath.length === 0) return reference;
17556
+ const uri = index2 === -1 ? reference : reference.slice(0, index2);
17557
+ return `${uri}${formatPointerFragment(targetPath)}`;
17558
+ }
17559
+ function formatPointerFragment(path21) {
17560
+ return path21.length === 0 ? "#" : `#/${path21.map((token) => encodeURI(escapeToken(token)).replace(/#/g, "%23")).join("/")}`;
17561
+ }
17562
+ function locationKey(resource, pointer) {
17563
+ return `${resource}\0${JSON.stringify(pointer)}`;
17564
+ }
17565
+ function createsResource(id2) {
17566
+ return typeof id2 === "string" && id2.length > 0 && id2[0] !== "#";
17567
+ }
17568
+ function convertDocument(document, adapter, options) {
17569
+ return runConverter(adapter, {
17570
+ ...options,
17571
+ trackIds: true
17572
+ }, (convert) => ({
17573
+ schema: convert(document.schema),
17574
+ definitions: mapObject(document.definitions, (definition, key) => convert(definition, ["$defs", key], ["definitions", key]))
17575
+ }));
17576
+ }
17577
+ var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set(["properties", "patternProperties"]);
17578
+ var SCHEMA_ARRAY_KEYWORDS = /* @__PURE__ */ new Set(["allOf", "anyOf", "oneOf"]);
17579
+ var JSON_SCHEMA_SINGLE_KEYWORDS = /* @__PURE__ */ new Set(["not", "additionalProperties", "propertyNames", "contains", "if", "then", "else", "contentSchema"]);
17580
+ function convertSubschemaKeyword(out, key, value3, context2, singleKeywords, mapKeywords = SCHEMA_MAP_KEYWORDS) {
17581
+ let converted;
17582
+ if (mapKeywords.has(key)) converted = context2.schemaMap(value3, key);
17583
+ else if (SCHEMA_ARRAY_KEYWORDS.has(key)) converted = context2.schemaArray(value3, key);
17584
+ else if (singleKeywords.has(key)) converted = context2.schema(value3, key);
17585
+ else return false;
17586
+ assignProperty(out, key, converted);
17587
+ return true;
17588
+ }
17589
+ var PRE_2020_TO_2020_COLLISIONS = ["$anchor", "$defs", "$dynamicAnchor", "$dynamicRef", "$vocabulary", "contentSchema", "dependentRequired", "dependentSchemas", "maxContains", "minContains", "prefixItems", "unevaluatedItems", "unevaluatedProperties"];
17590
+ var DRAFT_07_TO_2020_COLLISIONS = [...PRE_2020_TO_2020_COLLISIONS, "deprecated"];
17591
+ var OPEN_API_30_TO_2020_COLLISIONS = [...PRE_2020_TO_2020_COLLISIONS, "$comment", "$id", "$schema", "const", "contains", "contentEncoding", "contentMediaType", "else", "examples", "if", "patternProperties", "propertyNames", "then"];
17592
+ var ANCHOR_REGEXP = /^[A-Za-z_][-A-Za-z0-9._]*$/;
17593
+ var LEGACY_ID_FRAGMENT_REGEXP = /^[A-Za-z][-A-Za-z0-9._:]*$/;
17594
+ function unsupported(keyword, dialect, details) {
17595
+ throw new Error(`Cannot convert JSON Schema keyword "${keyword}" to ${dialect}: ${details}`);
17596
+ }
17597
+ function rejectKeywordCollisions(source, keywords, targetDialect, sourceDialect) {
17598
+ for (const keyword of keywords) {
17599
+ if (Object.hasOwn(source, keyword)) {
17600
+ unsupported(keyword, targetDialect, `it is not active in ${sourceDialect} but would become active in the target`);
17601
+ }
17602
+ }
17603
+ }
17604
+ var DRAFT_07_TARGET_COLLISIONS = ["additionalItems", "definitions", "dependencies"];
17605
+ function convertMetaSchemaKeyword(out, value3, context2, targetUri, targetDialect) {
17606
+ if (context2.isDocumentRoot) {
17607
+ assignProperty(out, "$schema", isMetaSchemaUri(value3, META_SCHEMA_URI_DRAFT_2020_12) ? targetUri : value3);
17608
+ } else if (!isMetaSchemaUri(value3, META_SCHEMA_URI_DRAFT_2020_12)) {
17609
+ unsupported("$schema", targetDialect, "an embedded resource cannot declare a different dialect");
17610
+ }
17611
+ }
17612
+ function draft07Adapter(source, context2) {
17613
+ rejectKeywordCollisions(source, DRAFT_07_TARGET_COLLISIONS, "Draft-07", "Draft 2020-12");
17614
+ const out = {};
17615
+ let reference = void 0;
17616
+ let prefixItems = void 0;
17617
+ let items = void 0;
17618
+ for (const key of Object.keys(source)) {
17619
+ const value3 = source[key];
17620
+ if (convertSubschemaKeyword(out, key, value3, context2, JSON_SCHEMA_SINGLE_KEYWORDS)) continue;
17621
+ switch (key) {
17622
+ case "$ref":
17623
+ reference = value3;
17624
+ break;
17625
+ case "$schema":
17626
+ convertMetaSchemaKeyword(out, value3, context2, META_SCHEMA_URI_DRAFT_07, "Draft-07");
17627
+ break;
17628
+ case "$id":
17629
+ case "$anchor":
17630
+ break;
17631
+ case "$defs":
17632
+ assignProperty(out, "definitions", context2.schemaMap(value3, key, "definitions"));
17633
+ break;
17634
+ case "prefixItems":
17635
+ prefixItems = value3;
17636
+ break;
17637
+ case "items":
17638
+ items = value3;
17639
+ break;
17640
+ case "dependentRequired":
17641
+ case "dependentSchemas":
17642
+ case "minContains":
17643
+ case "maxContains":
17644
+ break;
17645
+ case "$dynamicRef":
17646
+ case "$dynamicAnchor":
17647
+ case "$vocabulary":
17648
+ case "unevaluatedProperties":
17649
+ case "unevaluatedItems":
17650
+ unsupported(key, "Draft-07", "the target dialect has no equivalent");
17651
+ case "required":
17652
+ if (Array.isArray(value3) && value3.length === 0) break;
17653
+ assignProperty(out, key, value3);
17654
+ break;
17655
+ default:
17656
+ assignProperty(out, key, value3);
17657
+ }
17658
+ }
17659
+ convertTuple(out, prefixItems, items, context2);
17660
+ if (Object.hasOwn(source, "contains")) {
17661
+ const minContains = source.minContains;
17662
+ const maxContains = source.maxContains;
17663
+ if (minContains !== void 0 && minContains !== 1 || maxContains !== void 0) {
17664
+ unsupported("minContains/maxContains", "Draft-07", "contains cardinality cannot be represented");
17665
+ }
17666
+ if (Object.hasOwn(source, "minContains")) assignProperty(out, "minContains", minContains);
17667
+ } else {
17668
+ if (Object.hasOwn(source, "minContains")) assignProperty(out, "minContains", source.minContains);
17669
+ if (Object.hasOwn(source, "maxContains")) assignProperty(out, "maxContains", source.maxContains);
17670
+ }
17671
+ convertDependencies(source, out, context2, "draft-07");
17672
+ convertLegacyId(source, out, "$id", "Draft-07");
17673
+ convertReference(out, reference, context2);
17674
+ return out;
17675
+ }
17676
+ function convertTuple(out, prefixItems, items, context2) {
17677
+ if (prefixItems === void 0) {
17678
+ if (items !== void 0) assignProperty(out, "items", context2.schema(items, "items"));
17679
+ return;
17680
+ }
17681
+ assignProperty(out, "items", context2.schemaArray(prefixItems, "prefixItems", "items"));
17682
+ if (items !== void 0) {
17683
+ assignProperty(out, "additionalItems", context2.schema(items, "items", "additionalItems"));
17684
+ }
17685
+ }
17686
+ function convertReference(out, reference, context2) {
17687
+ if (reference === void 0) return;
17688
+ if (typeof reference === "string" && Object.keys(out).length > 0) {
17689
+ const referenceSchema = {};
17690
+ context2.reference(referenceSchema, reference);
17691
+ appendAllOf(out, referenceSchema);
17692
+ } else {
17693
+ context2.reference(out, reference);
17694
+ }
17695
+ }
17696
+ function convertDependencies(source, out, context2, targetDialect) {
17697
+ const dependentRequired = isObject(source.dependentRequired) ? source.dependentRequired : void 0;
17698
+ const dependentSchemas = isObject(source.dependentSchemas) ? source.dependentSchemas : void 0;
17699
+ if (dependentRequired === void 0 && dependentSchemas === void 0) return;
17700
+ const dependencies = {};
17701
+ const keys4 = /* @__PURE__ */ new Set([...Object.keys(dependentRequired ?? {}), ...Object.keys(dependentSchemas ?? {})]);
17702
+ for (const key of keys4) {
17703
+ const required2 = dependentRequired?.[key];
17704
+ const dependency = dependentSchemas?.[key];
17705
+ const omitRequired = targetDialect === "draft-04" && Array.isArray(required2) && required2.length === 0;
17706
+ if (dependency === void 0) {
17707
+ if (!omitRequired) assignProperty(dependencies, key, required2);
17708
+ } else if (required2 === void 0 || omitRequired) {
17709
+ assignProperty(dependencies, key, context2.schemaAt(dependency, ["dependentSchemas", key], ["dependencies", key]));
17710
+ } else {
17711
+ assignProperty(dependencies, key, {
17712
+ allOf: [context2.schemaAt(dependency, ["dependentSchemas", key], ["dependencies", key, "allOf", "0"]), {
17713
+ required: required2
17714
+ }]
17715
+ });
17716
+ }
17717
+ }
17718
+ if (Object.keys(dependencies).length > 0) assignProperty(out, "dependencies", dependencies);
17719
+ }
17720
+ function appendAllOf(out, schema) {
17721
+ if (Array.isArray(out.allOf)) out.allOf.push(schema);
17722
+ else assignProperty(out, "allOf", [schema]);
17723
+ }
17724
+ function convertLegacyId(source, out, targetKey, dialect) {
17725
+ const id2 = source.$id;
17726
+ const anchor = source.$anchor;
17727
+ if (anchor === void 0) {
17728
+ if (id2 !== void 0) assignProperty(out, targetKey, id2);
17729
+ return;
17730
+ }
17731
+ if (typeof anchor !== "string" || !ANCHOR_REGEXP.test(anchor)) {
17732
+ unsupported("$anchor", dialect, "the anchor is not valid");
17733
+ }
17734
+ if (!LEGACY_ID_FRAGMENT_REGEXP.test(anchor)) {
17735
+ unsupported("$anchor", dialect, "the anchor cannot be represented as a plain-name fragment identifier");
17736
+ }
17737
+ if (id2 === void 0) {
17738
+ assignProperty(out, targetKey, `#${anchor}`);
17739
+ } else {
17740
+ unsupported("$anchor", dialect, "it cannot be combined with the schema $id");
17741
+ }
17340
17742
  }
17341
17743
 
17342
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/RegExp.js
17744
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/RegExp.js
17343
17745
  var RegExp2 = globalThis.RegExp;
17344
17746
  var escape = (string3) => string3.replace(/[/\\^$*+?.()|[\]{}]/g, "\\$&");
17345
17747
 
17346
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/schema/toJsonSchemaDocument.js
17748
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/schema/toJsonSchemaDocument.js
17347
17749
  var jsonSchemaAnnotationExcludedKeys = /* @__PURE__ */ new Set([...annotationExcludedKeys, IDENTIFIER_FALLBACK_KEY, ...jsonSchemaAnnotationKeys]);
17348
17750
  function collectJsonSchemaAnnotations(annotations, options) {
17349
17751
  if (annotations === void 0) return void 0;
@@ -17786,7 +18188,7 @@ function compileJsonSchema(representations, rootPaths, references, options) {
17786
18188
  if (types.length === 0) return {
17787
18189
  not: {}
17788
18190
  };
17789
- if (types.length > 1) {
18191
+ if (representation.mode === "anyOf" && types.length > 1) {
17790
18192
  const compacted = compactEnums(types);
17791
18193
  if (compacted !== void 0) return compacted;
17792
18194
  }
@@ -17880,7 +18282,7 @@ function toJsonSchemaDocument(document, options) {
17880
18282
  };
17881
18283
  }
17882
18284
 
17883
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/schema/toRepresentation.js
18285
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/schema/toRepresentation.js
17884
18286
  var defaultReferencePolicy = ({
17885
18287
  identifier: identifier2
17886
18288
  }) => identifier2;
@@ -18195,7 +18597,7 @@ function toRepresentations(asts, options) {
18195
18597
  }
18196
18598
  }
18197
18599
 
18198
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/JsonPatch.js
18600
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/JsonPatch.js
18199
18601
  function get4(oldValue, newValue) {
18200
18602
  const patches = [];
18201
18603
  getLoop(oldValue, newValue, "", patches);
@@ -18376,7 +18778,7 @@ function rebuildFromStack(stack, newParent) {
18376
18778
  return acc;
18377
18779
  }
18378
18780
 
18379
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Optic.js
18781
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Optic.js
18380
18782
  function makeIso(get5, set2) {
18381
18783
  return make16(primitiveNode("Iso", get5, set2));
18382
18784
  }
@@ -18722,7 +19124,7 @@ function id() {
18722
19124
  return identityIso;
18723
19125
  }
18724
19126
 
18725
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/internal/redacted.js
19127
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/internal/redacted.js
18726
19128
  var redactedRegistry = /* @__PURE__ */ new WeakMap();
18727
19129
  var value = (self) => {
18728
19130
  if (redactedRegistry.has(self)) {
@@ -18732,7 +19134,7 @@ var value = (self) => {
18732
19134
  }
18733
19135
  };
18734
19136
 
18735
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Redacted.js
19137
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Redacted.js
18736
19138
  var TypeId14 = "~effect/data/Redacted";
18737
19139
  var isRedacted = (u) => hasProperty(u, TypeId14);
18738
19140
  var make17 = (value3, options) => {
@@ -18765,7 +19167,7 @@ var Proto3 = {
18765
19167
  var value2 = value;
18766
19168
  var makeEquivalence5 = (isEquivalent) => make2((x, y) => isEquivalent(value2(x), value2(y)));
18767
19169
 
18768
- // ../../node_modules/.bun/effect@4.0.0-rc.111/node_modules/effect/dist/Schema.js
19170
+ // ../../node_modules/.bun/effect@4.0.0-rc.112/node_modules/effect/dist/Schema.js
18769
19171
  var TypeId15 = TypeId13;
18770
19172
  function declareConstructor() {
18771
19173
  return (typeParameters, run2, annotations) => {
@@ -18796,9 +19198,15 @@ var SchemaErrorTypeId = "~effect/SchemaError/SchemaError";
18796
19198
  var SchemaError = class extends (/* @__PURE__ */ TaggedError2("SchemaError")) {
18797
19199
  [SchemaErrorTypeId] = SchemaErrorTypeId;
18798
19200
  constructor(issue) {
18799
- super({
18800
- issue
18801
- });
19201
+ const stackTraceLimit = getStackTraceLimit();
19202
+ setStackTraceLimit(0);
19203
+ try {
19204
+ super({
19205
+ issue
19206
+ });
19207
+ } finally {
19208
+ setStackTraceLimit(stackTraceLimit);
19209
+ }
18802
19210
  }
18803
19211
  get message() {
18804
19212
  return defaultFormatter(this.issue);
@@ -18915,6 +19323,9 @@ function decodeUnknownEffect2(schema, options) {
18915
19323
  };
18916
19324
  }
18917
19325
  function fromIssueEffect(self) {
19326
+ if (effectIsExit(self)) {
19327
+ return fromIssueExit(self);
19328
+ }
18918
19329
  return catchCause2(self, (cause) => failCauseSync2(() => map6(cause, (issue) => new SchemaError(issue))));
18919
19330
  }
18920
19331
  var decodeEffect2 = decodeUnknownEffect2;
@@ -19390,7 +19801,8 @@ function toTaggedUnion(tag2) {
19390
19801
  discriminants,
19391
19802
  isAnyOf,
19392
19803
  guards,
19393
- match: match7
19804
+ match: match7,
19805
+ matchOrElse
19394
19806
  });
19395
19807
  function walk(schema) {
19396
19808
  const ast = schema.ast;
@@ -19429,6 +19841,23 @@ function toTaggedUnion(tag2) {
19429
19841
  const handler = Object.hasOwn(cases2, key) ? cases2[key] : void 0;
19430
19842
  return handler(value3);
19431
19843
  }
19844
+ function matchOrElse() {
19845
+ if (arguments.length === 2) {
19846
+ const cases3 = arguments[0];
19847
+ const orElse2 = arguments[1];
19848
+ return function(value4) {
19849
+ const key2 = value4[tag2];
19850
+ const handler2 = Object.hasOwn(cases3, key2) ? cases3[key2] ?? orElse2 : orElse2;
19851
+ return handler2(value4);
19852
+ };
19853
+ }
19854
+ const value3 = arguments[0];
19855
+ const cases2 = arguments[1];
19856
+ const orElse = arguments[2];
19857
+ const key = value3[tag2];
19858
+ const handler = Object.hasOwn(cases2, key) ? cases2[key] ?? orElse : orElse;
19859
+ return handler(value3);
19860
+ }
19432
19861
  };
19433
19862
  }
19434
19863
  function TaggedUnion(casesByTag) {
@@ -19443,13 +19872,15 @@ function TaggedUnion(casesByTag) {
19443
19872
  const {
19444
19873
  guards,
19445
19874
  isAnyOf,
19446
- match: match7
19875
+ match: match7,
19876
+ matchOrElse
19447
19877
  } = toTaggedUnion("_tag")(union5);
19448
19878
  return make18(union5.ast, {
19449
19879
  cases,
19450
19880
  isAnyOf,
19451
19881
  guards,
19452
- match: match7
19882
+ match: match7,
19883
+ matchOrElse
19453
19884
  });
19454
19885
  }
19455
19886
  function Opaque() {
@@ -23285,6 +23716,7 @@ var RPC_METHODS = {
23285
23716
  runtimeRefreshProviders: "runtime.refreshProviders",
23286
23717
  appStateGet: "appState.get",
23287
23718
  appStatePatch: "appState.patch",
23719
+ trialExperienceStart: "trialExperience.start",
23288
23720
  appSettingsGet: "appSettings.get",
23289
23721
  appSettingsUpdate: "appSettings.update",
23290
23722
  officialCodexSetAutoControl: "officialCodex.setAutoControl",
@@ -23468,6 +23900,7 @@ var DesktopRpcRequestBody = Schema_exports.Union([
23468
23900
  // Desktop dashboard/runtime methods
23469
23901
  tagRequestBody(RPC_METHODS.appStateGet, Schema_exports.Struct({})),
23470
23902
  tagRequestBody(RPC_METHODS.appStatePatch, Schema_exports.Struct({ patch: Schema_exports.Unknown })),
23903
+ tagRequestBody(RPC_METHODS.trialExperienceStart, Schema_exports.Struct({ interactiveAt: Schema_exports.Number })),
23471
23904
  tagRequestBody(RPC_METHODS.appSettingsGet, Schema_exports.Struct({})),
23472
23905
  tagRequestBody(
23473
23906
  RPC_METHODS.appSettingsUpdate,
@@ -25532,7 +25965,6 @@ var CODEX_BRIDGE_PROBE_TTL_MS = 5e3;
25532
25965
  var CODEX_BRIDGE_LAUNCH_WAIT_MS = 3e4;
25533
25966
  var CODEX_LAUNCH_RUNAWAY_STARTUP_MS = 18e4;
25534
25967
  var CODEX_LAUNCH_RUNAWAY_STARTUP_SAMPLE_MS = 2e3;
25535
- var CODEX_LAUNCH_RUNAWAY_LIFETIME_SAMPLE_MS = 5e3;
25536
25968
  var CODEX_LAUNCH_RUNAWAY_THREAD_LIMIT = 180;
25537
25969
  var CODEX_LAUNCH_RUNAWAY_DESCENDANT_LIMIT = 96;
25538
25970
  var CODEX_LAUNCH_RUNAWAY_CONSECUTIVE_SAMPLES = 3;
@@ -25568,6 +26000,28 @@ function logOfficialCodexTakeoverPhase(trace, candidate, phase, context2 = {}) {
25568
26000
  ...context2
25569
26001
  });
25570
26002
  }
26003
+ function normalizeOfficialCodexBridgeActionResult(value3) {
26004
+ if (!value3 || typeof value3 !== "object") {
26005
+ return {
26006
+ status: "failed",
26007
+ message: "The action did not return a verified result."
26008
+ };
26009
+ }
26010
+ const record2 = value3;
26011
+ const status = record2.status === "completed" || record2.status === "pending" || record2.status === "failed" ? record2.status : null;
26012
+ const message = typeof record2.message === "string" ? record2.message.trim().slice(0, 240) : "";
26013
+ if (!status || !message) {
26014
+ return {
26015
+ status: "failed",
26016
+ message: "The action returned an invalid result."
26017
+ };
26018
+ }
26019
+ return {
26020
+ status,
26021
+ message,
26022
+ ...record2.mode === "shared-switch" || record2.mode === "isolated-open" ? { mode: record2.mode } : {}
26023
+ };
26024
+ }
25571
26025
  var officialCodexBridgeActionHandler = null;
25572
26026
  var bridgeActionListeners = /* @__PURE__ */ new Map();
25573
26027
  var bridgeActionListenerReady = /* @__PURE__ */ new Map();
@@ -25701,7 +26155,7 @@ async function officialCodexLiveLoginExpiryGuardMatches(guard) {
25701
26155
  if (account.status !== "observed") {
25702
26156
  return "unknown";
25703
26157
  }
25704
- return expectedAccountMatches(
26158
+ return officialCodexExpectedAccountMatches(
25705
26159
  {
25706
26160
  email: null,
25707
26161
  accountId: guard.accountId,
@@ -26740,6 +27194,9 @@ function createBridgeApplyQolExpression(settings) {
26740
27194
  const conversationTimelineEnabled = ${JSON.stringify(settings.conversationTimelineEnabled === true)};
26741
27195
  const inCodexStatusEnabled = ${JSON.stringify(settings.inCodexStatusEnabled === true)};
26742
27196
  const handoffEnabled = ${JSON.stringify(settings.handoffChipEnabled !== false)};
27197
+ const accountActionMode = ${JSON.stringify(
27198
+ settings.overlayAccountActionMode === "shared-switch" ? "shared-switch" : "isolated-open"
27199
+ )};
26743
27200
  let currentAutoRollDecision = ${JSON.stringify(settings.autoRollDecision ?? null)};
26744
27201
  let currentOverlayAutoRollEnabled = ${JSON.stringify(
26745
27202
  typeof settings.overlayAutoRollEnabled === "boolean" ? settings.overlayAutoRollEnabled : null
@@ -27282,7 +27739,7 @@ function createBridgeApplyQolExpression(settings) {
27282
27739
  const title = document.createElement("span");
27283
27740
  // Names the job, not the brand. The list holds OpenAI accounts and
27284
27741
  // custom-model profiles, so "accounts" was also the wrong word.
27285
- title.textContent = "Switch profile";
27742
+ title.textContent = accountActionMode === "shared-switch" ? "Switch profile" : "Open profile";
27286
27743
  const actionStatus = document.createElement("span");
27287
27744
  actionStatus.className = "codexuse-action-status";
27288
27745
  actionStatus.setAttribute("data-codexuse-action-status", "true");
@@ -27429,7 +27886,12 @@ function createBridgeApplyQolExpression(settings) {
27429
27886
  row.appendChild(meter);
27430
27887
  }
27431
27888
  if (canSwitch) {
27432
- row.setAttribute("aria-label", "Switch to " + label.textContent);
27889
+ row.setAttribute(
27890
+ "aria-label",
27891
+ accountActionMode === "shared-switch"
27892
+ ? "Switch to " + label.textContent
27893
+ : "Open " + label.textContent + " in isolated window"
27894
+ );
27433
27895
  row.addEventListener("click", (event) => {
27434
27896
  event.preventDefault();
27435
27897
  event.stopPropagation();
@@ -28967,7 +29429,8 @@ function normalizeOfficialCodexQolSettings2(value3) {
28967
29429
  canonicalSyncLine: typeof value3.canonicalSyncLine === "string" && value3.canonicalSyncLine.trim() ? value3.canonicalSyncLine.trim().slice(0, 40) : null,
28968
29430
  autoRollDecision: normalizeOverlayAutoRollDecision(value3.autoRollDecision),
28969
29431
  overlayAutoRollEnabled: typeof value3.overlayAutoRollEnabled === "boolean" ? value3.overlayAutoRollEnabled : null,
28970
- overlayRunningThreadHandoffEnabled: typeof value3.overlayRunningThreadHandoffEnabled === "boolean" ? value3.overlayRunningThreadHandoffEnabled : null
29432
+ overlayRunningThreadHandoffEnabled: typeof value3.overlayRunningThreadHandoffEnabled === "boolean" ? value3.overlayRunningThreadHandoffEnabled : null,
29433
+ overlayAccountActionMode: value3.overlayAccountActionMode === "shared-switch" || value3.overlayAccountActionMode === "isolated-open" ? value3.overlayAccountActionMode : null
28971
29434
  };
28972
29435
  }
28973
29436
  function hasActiveQolSettings(settings) {
@@ -29157,7 +29620,7 @@ function createBridgeInstallExpression() {
29157
29620
  const action = request.action;
29158
29621
  state.lastActionRequest = null;
29159
29622
  if (result && typeof result === "object" && result.status === "failed") {
29160
- const message = typeof result.reason === "string" && result.reason ? result.reason : "Did not switch";
29623
+ const message = typeof result.message === "string" && result.message ? result.message : "The action failed";
29161
29624
  state.lastActionMessage = message;
29162
29625
  if (action === "setting" && typeof request.settingKey === "string" && typeof request.settingValue === "boolean") {
29163
29626
  const host = document.getElementById("codexuse-profile-menu-section");
@@ -29172,14 +29635,9 @@ function createBridgeInstallExpression() {
29172
29635
  settleActionMessage(message);
29173
29636
  return true;
29174
29637
  }
29175
- const message =
29176
- action === "switch" ? "Switched"
29177
- : action === "continue" ? "Thread moved"
29178
- : action === "auto-roll-accept" ? "Switched"
29179
- : action === "auto-roll-cancel" ? "Staying here"
29180
- : action === "restart" ? "Restarted"
29181
- : action === "setting" ? "Saved"
29182
- : "Done";
29638
+ const message = result && typeof result.message === "string" && result.message
29639
+ ? result.message
29640
+ : "The action returned an invalid result.";
29183
29641
  state.lastActionMessage = message;
29184
29642
  settleActionMessage(message);
29185
29643
  return true;
@@ -30175,6 +30633,7 @@ async function startOfficialCodexBridgeActionListenerOnce(args2) {
30175
30633
  autoRollDecisionId,
30176
30634
  settingKey,
30177
30635
  settingValue,
30636
+ sourceProcessEpoch: args2.processEpoch,
30178
30637
  cdpPort: args2.cdpPort,
30179
30638
  route: typeof payload.route === "string" ? sanitizeBridgeActionRoute(payload.route) : null,
30180
30639
  activeThreadId: normalizeOfficialCodexThreadId(payload.activeThreadId),
@@ -30184,26 +30643,30 @@ async function startOfficialCodexBridgeActionListenerOnce(args2) {
30184
30643
  void (async () => {
30185
30644
  let result2;
30186
30645
  if (!handler) {
30187
- result2 = { status: "failed", reason: "Action handler is reconnecting" };
30646
+ result2 = { status: "failed", message: "The action handler is reconnecting." };
30188
30647
  } else {
30189
30648
  try {
30190
- result2 = await handler(request);
30649
+ result2 = normalizeOfficialCodexBridgeActionResult(
30650
+ await handler(request)
30651
+ );
30191
30652
  } catch (error) {
30192
- const reason = sanitizeUserFacingError(error) ?? "Action failed";
30653
+ const reason = sanitizeUserFacingError(error) ?? "The action failed.";
30193
30654
  console.warn("[official-codex-bridge-action] Handler failed.", {
30194
30655
  action: request.action,
30195
30656
  error: reason
30196
30657
  });
30197
- result2 = { status: "failed", reason };
30658
+ result2 = { status: "failed", message: reason };
30198
30659
  }
30199
30660
  }
30200
30661
  let serialized;
30201
30662
  try {
30202
- serialized = JSON.stringify(result2 ?? { status: "ok" }) ?? "null";
30663
+ serialized = JSON.stringify(
30664
+ normalizeOfficialCodexBridgeActionResult(result2)
30665
+ );
30203
30666
  } catch {
30204
30667
  serialized = JSON.stringify({
30205
30668
  status: "failed",
30206
- reason: "Action result was invalid"
30669
+ message: "The action result was invalid."
30207
30670
  });
30208
30671
  }
30209
30672
  send("Runtime.evaluate", {
@@ -30345,7 +30808,10 @@ async function reapplyDesiredBridgeSettings(instance, bridge, allowAnyPageTarget
30345
30808
  const qolSettings = normalizeOfficialCodexQolSettings2(
30346
30809
  instance.desiredQolSettings
30347
30810
  );
30348
- const qolExpression = createBridgeApplyQolExpression(qolSettings);
30811
+ const qolExpression = createBridgeApplyQolExpression({
30812
+ ...qolSettings,
30813
+ overlayAccountActionMode: instance.profileHome === null ? "shared-switch" : "isolated-open"
30814
+ });
30349
30815
  const qolValue = await evaluateOfficialCodexBridgeCommand(
30350
30816
  target.webSocketDebuggerUrl,
30351
30817
  "applyQol",
@@ -30976,82 +31442,64 @@ async function readProcessThreadCount(pid) {
30976
31442
  }).length;
30977
31443
  return threadCount > 0 ? threadCount : null;
30978
31444
  }
30979
- function startOfficialCodexLaunchRunawayWatchdog(args2) {
31445
+ function startBoundedOfficialCodexLaunchRunawayWatchdog(args2) {
31446
+ const now2 = args2.now ?? Date.now;
31447
+ const wait = args2.wait ?? sleep3;
31448
+ const deadline = now2() + (args2.startupDeadlineMs ?? CODEX_LAUNCH_RUNAWAY_STARTUP_MS);
31449
+ const sampleMs = args2.sampleMs ?? CODEX_LAUNCH_RUNAWAY_STARTUP_SAMPLE_MS;
31450
+ const consecutiveSampleLimit = args2.consecutiveSampleLimit ?? CODEX_LAUNCH_RUNAWAY_CONSECUTIVE_SAMPLES;
31451
+ const threadLimit = args2.threadLimit ?? CODEX_LAUNCH_RUNAWAY_THREAD_LIMIT;
31452
+ const descendantLimit = args2.descendantLimit ?? CODEX_LAUNCH_RUNAWAY_DESCENDANT_LIMIT;
31453
+ const inspectionFailureLimit = args2.inspectionFailureLimit ?? CODEX_LAUNCH_RUNAWAY_INSPECTION_FAILURE_LIMIT;
31454
+ const evidenceTtlMs = args2.evidenceTtlMs ?? CODEX_LAUNCH_RUNAWAY_EVIDENCE_TTL_MS;
30980
31455
  let cancelled = false;
30981
31456
  const result2 = (async () => {
30982
31457
  let consecutiveRunawaySamples = 0;
30983
31458
  let lastRunawaySampleAt = null;
30984
31459
  let consecutiveInspectionFailures = 0;
30985
- const startedWatchingAt = Date.now();
30986
- while (!cancelled) {
30987
- await sleep3(
30988
- Date.now() - startedWatchingAt < CODEX_LAUNCH_RUNAWAY_STARTUP_MS ? CODEX_LAUNCH_RUNAWAY_STARTUP_SAMPLE_MS : CODEX_LAUNCH_RUNAWAY_LIFETIME_SAMPLE_MS
30989
- );
30990
- if (cancelled) return null;
30991
- let rows;
31460
+ while (!cancelled && now2() < deadline) {
31461
+ await wait(Math.min(sampleMs, Math.max(0, deadline - now2())));
31462
+ if (cancelled || now2() >= deadline) return null;
31463
+ let sample;
30992
31464
  try {
30993
- rows = await readProcessRows();
31465
+ sample = await args2.inspect();
30994
31466
  } catch {
30995
31467
  consecutiveInspectionFailures += 1;
30996
- if (consecutiveInspectionFailures >= CODEX_LAUNCH_RUNAWAY_INSPECTION_FAILURE_LIMIT) {
30997
- console.warn(
30998
- "[official-codex-launch] Runaway watchdog stopped after persistent process-inspection failures.",
30999
- {
31000
- pid: args2.pid,
31001
- startedAt: args2.startedAt,
31002
- cdpPort: args2.cdpPort,
31003
- consecutiveInspectionFailures
31004
- }
31005
- );
31468
+ if (consecutiveInspectionFailures >= inspectionFailureLimit) {
31469
+ args2.onInspectionFailureLimit?.(consecutiveInspectionFailures);
31006
31470
  return null;
31007
31471
  }
31008
31472
  continue;
31009
31473
  }
31010
31474
  consecutiveInspectionFailures = 0;
31011
- const mainRow = rows.find((row) => row.pid === args2.pid) ?? null;
31012
- if (!mainRow || !isMainProcessRow(mainRow, args2.candidate) || mainRow.startedAt !== args2.startedAt || !remoteDebuggingPortMatches(mainRow.args, args2.cdpPort)) {
31475
+ if (!sample.epochMatches) {
31013
31476
  return null;
31014
31477
  }
31015
- const descendantProcessCount = getDescendantPids(args2.pid, rows).length;
31016
- const threadCount = await readProcessThreadCount(args2.pid);
31017
- const runawaySample = threadCount !== null && threadCount >= CODEX_LAUNCH_RUNAWAY_THREAD_LIMIT || descendantProcessCount >= CODEX_LAUNCH_RUNAWAY_DESCENDANT_LIMIT;
31478
+ const runawaySample = sample.threadCount !== null && sample.threadCount >= threadLimit || sample.descendantProcessCount >= descendantLimit;
31018
31479
  if (runawaySample) {
31019
31480
  consecutiveRunawaySamples += 1;
31020
- lastRunawaySampleAt = Date.now();
31021
- } else if (threadCount !== null) {
31481
+ lastRunawaySampleAt = now2();
31482
+ } else if (sample.threadCount !== null) {
31022
31483
  consecutiveRunawaySamples = 0;
31023
31484
  lastRunawaySampleAt = null;
31024
- } else if (lastRunawaySampleAt !== null && Date.now() - lastRunawaySampleAt > CODEX_LAUNCH_RUNAWAY_EVIDENCE_TTL_MS) {
31485
+ } else if (lastRunawaySampleAt !== null && now2() - lastRunawaySampleAt > evidenceTtlMs) {
31025
31486
  consecutiveRunawaySamples = 0;
31026
31487
  lastRunawaySampleAt = null;
31027
31488
  }
31028
- if (consecutiveRunawaySamples < CODEX_LAUNCH_RUNAWAY_CONSECUTIVE_SAMPLES) {
31489
+ if (consecutiveRunawaySamples < consecutiveSampleLimit) {
31029
31490
  continue;
31030
31491
  }
31031
- const remainingPids = await stopOfficialCodexProcessEpoch({
31032
- candidate: args2.candidate,
31033
- pid: args2.pid,
31034
- startedAt: args2.startedAt,
31035
- cdpPort: args2.cdpPort
31036
- }).catch(() => [args2.pid]);
31037
- console.warn("[official-codex-launch] Stopped runaway managed launch.", {
31038
- pid: args2.pid,
31039
- startedAt: args2.startedAt,
31040
- cdpPort: args2.cdpPort,
31041
- threadCount,
31042
- descendantProcessCount,
31043
- remainingPids
31044
- });
31045
- return { threadCount, descendantProcessCount, remainingPids };
31492
+ const runaway = {
31493
+ threadCount: sample.threadCount,
31494
+ descendantProcessCount: sample.descendantProcessCount,
31495
+ remainingPids: await args2.stop()
31496
+ };
31497
+ args2.onRunaway?.(runaway);
31498
+ return runaway;
31046
31499
  }
31047
31500
  return null;
31048
31501
  })().catch((error) => {
31049
- console.warn("[official-codex-launch] Runaway watchdog failed.", {
31050
- pid: args2.pid,
31051
- startedAt: args2.startedAt,
31052
- cdpPort: args2.cdpPort,
31053
- error: sanitizeUserFacingError(error) ?? "process-inspection-failed"
31054
- });
31502
+ args2.onError?.(error);
31055
31503
  return null;
31056
31504
  });
31057
31505
  return {
@@ -31061,6 +31509,59 @@ function startOfficialCodexLaunchRunawayWatchdog(args2) {
31061
31509
  }
31062
31510
  };
31063
31511
  }
31512
+ function startOfficialCodexLaunchRunawayWatchdog(args2) {
31513
+ return startBoundedOfficialCodexLaunchRunawayWatchdog({
31514
+ inspect: async () => {
31515
+ const rows = await readProcessRows();
31516
+ const mainRow = rows.find((row) => row.pid === args2.pid) ?? null;
31517
+ if (!mainRow || !isMainProcessRow(mainRow, args2.candidate) || mainRow.startedAt !== args2.startedAt || !remoteDebuggingPortMatches(mainRow.args, args2.cdpPort)) {
31518
+ return {
31519
+ epochMatches: false,
31520
+ threadCount: null,
31521
+ descendantProcessCount: 0
31522
+ };
31523
+ }
31524
+ const descendantProcessCount = getDescendantPids(args2.pid, rows).length;
31525
+ const threadCount = await readProcessThreadCount(args2.pid);
31526
+ return { epochMatches: true, threadCount, descendantProcessCount };
31527
+ },
31528
+ stop: () => stopOfficialCodexProcessEpoch({
31529
+ candidate: args2.candidate,
31530
+ pid: args2.pid,
31531
+ startedAt: args2.startedAt,
31532
+ cdpPort: args2.cdpPort
31533
+ }).catch(() => [args2.pid]),
31534
+ onRunaway: ({ threadCount, descendantProcessCount, remainingPids }) => {
31535
+ console.warn("[official-codex-launch] Stopped runaway managed launch.", {
31536
+ pid: args2.pid,
31537
+ startedAt: args2.startedAt,
31538
+ cdpPort: args2.cdpPort,
31539
+ threadCount,
31540
+ descendantProcessCount,
31541
+ remainingPids
31542
+ });
31543
+ },
31544
+ onInspectionFailureLimit: (consecutiveInspectionFailures) => {
31545
+ console.warn(
31546
+ "[official-codex-launch] Runaway watchdog stopped after persistent process-inspection failures.",
31547
+ {
31548
+ pid: args2.pid,
31549
+ startedAt: args2.startedAt,
31550
+ cdpPort: args2.cdpPort,
31551
+ consecutiveInspectionFailures
31552
+ }
31553
+ );
31554
+ },
31555
+ onError: (error) => {
31556
+ console.warn("[official-codex-launch] Runaway watchdog failed.", {
31557
+ pid: args2.pid,
31558
+ startedAt: args2.startedAt,
31559
+ cdpPort: args2.cdpPort,
31560
+ error: sanitizeUserFacingError(error) ?? "process-inspection-failed"
31561
+ });
31562
+ }
31563
+ });
31564
+ }
31064
31565
  async function waitForLaunchStepOrRunaway(step, watchdog) {
31065
31566
  const runaway = watchdog.result.then(
31066
31567
  (value3) => value3 ? { kind: "runaway", value: value3 } : new Promise(() => void 0)
@@ -31253,34 +31754,6 @@ async function readManagedInstance(profileName) {
31253
31754
  const state = await getAppState();
31254
31755
  return state.officialCodex.instancesByProfileName[profileName] ?? null;
31255
31756
  }
31256
- function recordManagedLaunchRunaway(args2) {
31257
- void args2.watchdog.result.then(async (runaway) => {
31258
- if (!runaway) return;
31259
- const current = await readManagedInstance(args2.profileName);
31260
- if (!current || current.pid !== args2.pid || current.launchedAt !== args2.startedAt || current.cdpPort !== args2.cdpPort) {
31261
- return;
31262
- }
31263
- const rows = await readProcessRows().catch(() => []);
31264
- const mainStillRunning = rows.some(
31265
- (row) => row.pid === args2.pid && row.startedAt === args2.startedAt && isMainProcessRow(row, args2.candidate) && remoteDebuggingPortMatches(row.args, args2.cdpPort)
31266
- );
31267
- await patchManagedInstance({
31268
- ...current,
31269
- pid: mainStillRunning ? args2.pid : null,
31270
- appServerPid: mainStillRunning ? current.appServerPid : null,
31271
- ...mainStillRunning ? bridgeStateForStoredInstance(current, true, Date.now()) : bridgeStateUnavailable(),
31272
- lastVerifiedAt: Date.now(),
31273
- lastStatus: "failed",
31274
- lastError: mainStillRunning ? "launch-runaway-stop-timeout" : "launch-runaway-detected"
31275
- });
31276
- }).catch((error) => {
31277
- console.warn("[official-codex-launch] Failed to record runaway launch.", {
31278
- profileName: args2.profileName,
31279
- pid: args2.pid,
31280
- error: sanitizeUserFacingError(error) ?? "state-update-failed"
31281
- });
31282
- });
31283
- }
31284
31757
  async function resolveInstanceRuntimeState(args2) {
31285
31758
  const pid = args2.instance.pid;
31286
31759
  if (!pid) {
@@ -31573,9 +32046,15 @@ async function openCodexWithProfileHome(candidate, profileHome, profileName, pre
31573
32046
  };
31574
32047
  }
31575
32048
  const telemetryLabel = `codexuse-profile-${encodeURIComponent(profileName)}`;
31576
- const launchHome = resolveCodexLaunchHome(profileHome);
31577
- const appUserDataDir = options.useDefaultUserData === true ? null : options.userDataDir ?? import_node_path12.default.join(profileHome, "codex-app-user-data");
31578
- const sqliteHome = options.sqliteHome ?? profileHome;
32049
+ const launchConfiguration = resolveOfficialCodexLaunchConfiguration(
32050
+ profileHome,
32051
+ options
32052
+ );
32053
+ const {
32054
+ codexHome: launchHome,
32055
+ sqliteHome,
32056
+ userDataDir: appUserDataDir
32057
+ } = launchConfiguration;
31579
32058
  const activePortPaths = devToolsActivePortPaths(appUserDataDir);
31580
32059
  let child;
31581
32060
  try {
@@ -31870,6 +32349,15 @@ async function signalPids(pids, signal) {
31870
32349
  return signaled;
31871
32350
  }
31872
32351
  var SHARED_CODEX_HOME = resolveDefaultCodexHomeDir();
32352
+ function resolveOfficialCodexLaunchConfiguration(profileHome, options = {}) {
32353
+ return {
32354
+ codexHome: resolveCodexLaunchHome(profileHome),
32355
+ sqliteHome: options.sqliteHome ?? profileHome,
32356
+ // Managed profile windows keep Electron state separate as well as CODEX_HOME.
32357
+ // Callers can supply another isolated directory or explicitly use stock state.
32358
+ userDataDir: options.useDefaultUserData === true ? null : options.userDataDir ?? import_node_path12.default.join(profileHome, "codex-app-user-data")
32359
+ };
32360
+ }
31873
32361
  function resolveOfficialCodexThreadSqliteHome(profileHome) {
31874
32362
  return profileHome === SHARED_CODEX_HOME ? resolveCodexSqliteHomeDir(profileHome) : profileHome;
31875
32363
  }
@@ -31889,7 +32377,7 @@ var sharedHomeCdpWindow = null;
31889
32377
  function normalizedAccountWorkspaceId(value3) {
31890
32378
  return value3?.trim() || "__default__";
31891
32379
  }
31892
- function expectedAccountMatches(expected, observed) {
32380
+ function officialCodexExpectedAccountMatches(expected, observed) {
31893
32381
  const identityMatches = expected.accountId ? observed.accountId === expected.accountId : Boolean(
31894
32382
  expected.email && observed.email && observed.email.toLowerCase() === expected.email.toLowerCase()
31895
32383
  );
@@ -33934,7 +34422,7 @@ async function waitForExpectedOfficialCodexAccount(debuggerUrl, expectedAccount)
33934
34422
  false
33935
34423
  )
33936
34424
  );
33937
- if (observed && expectedAccountMatches(expectedAccount, observed)) {
34425
+ if (observed && officialCodexExpectedAccountMatches(expectedAccount, observed)) {
33938
34426
  return observed;
33939
34427
  }
33940
34428
  } catch {
@@ -34039,7 +34527,7 @@ async function applySharedLaunchFollowUp(args2) {
34039
34527
  readSharedBridgeSnapshot(debuggerUrl)
34040
34528
  ]);
34041
34529
  const expectedDraft = args2.carryDraft && args2.carriedDraft.trim() ? args2.carriedDraft : "";
34042
- if (!finalAccount || !expectedAccountMatches(args2.expectedAccount, finalAccount) || !snapshot2 || snapshot2.activeThreadId !== null || (snapshot2.composerText ?? "") !== expectedDraft) {
34530
+ if (!finalAccount || !officialCodexExpectedAccountMatches(args2.expectedAccount, finalAccount) || !snapshot2 || snapshot2.activeThreadId !== null || (snapshot2.composerText ?? "") !== expectedDraft) {
34043
34531
  return { verified: false, reason: "renderer-postcondition-unverified" };
34044
34532
  }
34045
34533
  return { verified: true, reason: null };
@@ -34161,7 +34649,7 @@ async function attemptOfficialCodexManagedLiveLogin(args2) {
34161
34649
  const notified = await notification.promise;
34162
34650
  notification = null;
34163
34651
  const account = await readSharedOfficialCodexAppAccount();
34164
- if (account.status !== "observed" || !expectedAccountMatches(expectedAccount, account)) {
34652
+ if (account.status !== "observed" || !officialCodexExpectedAccountMatches(expectedAccount, account)) {
34165
34653
  return null;
34166
34654
  }
34167
34655
  await adoptSharedManagedWindow({
@@ -34215,7 +34703,7 @@ async function attemptOfficialCodexManagedLiveLogin(args2) {
34215
34703
  return null;
34216
34704
  }
34217
34705
  const refreshedAccount = await readSharedOfficialCodexAppAccount();
34218
- if (refreshedAccount.status !== "observed" || !expectedAccountMatches(expectedAccount, refreshedAccount)) {
34706
+ if (refreshedAccount.status !== "observed" || !officialCodexExpectedAccountMatches(expectedAccount, refreshedAccount)) {
34219
34707
  return null;
34220
34708
  }
34221
34709
  reconciled = await reconcile(args2.debuggerUrl);
@@ -34357,11 +34845,11 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
34357
34845
  if (driveTarget) {
34358
34846
  const managedTarget = driveTarget;
34359
34847
  const mainRow = rows.find((row) => row.pid === managedTarget.pid) ?? null;
34360
- const appServerPid2 = findAppServerPid(rows, managedTarget.pid);
34361
- if (!mainRow?.startedAt || !appServerPid2 || !await attestOfficialCodexProcessEpoch({
34848
+ const appServerPid = findAppServerPid(rows, managedTarget.pid);
34849
+ if (!mainRow?.startedAt || !appServerPid || !await attestOfficialCodexProcessEpoch({
34362
34850
  candidate,
34363
34851
  pid: managedTarget.pid,
34364
- appServerPid: appServerPid2,
34852
+ appServerPid,
34365
34853
  startedAt: mainRow.startedAt,
34366
34854
  cdpPort: managedTarget.cdpPort
34367
34855
  })) {
@@ -34382,12 +34870,12 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
34382
34870
  await ensureOfficialCodexBridgeInstalled(debuggerUrl, false);
34383
34871
  } catch {
34384
34872
  }
34385
- let bridge2 = null;
34873
+ let bridge = null;
34386
34874
  if (options.profileName) {
34387
34875
  await adoptSharedManagedWindow({
34388
34876
  candidate,
34389
34877
  pid: managedTarget.pid,
34390
- appServerPid: appServerPid2,
34878
+ appServerPid,
34391
34879
  cdpPort: managedTarget.cdpPort,
34392
34880
  startedAt: mainRow.startedAt,
34393
34881
  profileName: options.profileName,
@@ -34395,19 +34883,19 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
34395
34883
  desiredQolSettings: options.desiredQolSettings,
34396
34884
  desiredPowerSettings: options.desiredPowerSettings
34397
34885
  });
34398
- bridge2 = await refreshAdoptedSharedWindow(options.profileName);
34399
- if (bridge2?.bridgeStatus !== "healthy") {
34886
+ bridge = await refreshAdoptedSharedWindow(options.profileName);
34887
+ if (bridge?.bridgeStatus !== "healthy") {
34400
34888
  return {
34401
34889
  status: "failed",
34402
34890
  mechanism: "none",
34403
- reason: bridge2?.bridgeError ?? "bridge-not-healthy",
34891
+ reason: bridge?.bridgeError ?? "bridge-not-healthy",
34404
34892
  pid: managedTarget.pid,
34405
- appServerPid: appServerPid2,
34893
+ appServerPid,
34406
34894
  cdpPort: managedTarget.cdpPort,
34407
- bridgeStatus: bridge2?.bridgeStatus ?? null,
34408
- bridgeError: bridge2?.bridgeError ?? null,
34409
- bridgeActiveThreadId: bridge2?.bridgeActiveThreadId ?? null,
34410
- bridgeWorkspacePath: bridge2?.bridgeWorkspacePath ?? null
34895
+ bridgeStatus: bridge?.bridgeStatus ?? null,
34896
+ bridgeError: bridge?.bridgeError ?? null,
34897
+ bridgeActiveThreadId: bridge?.bridgeActiveThreadId ?? null,
34898
+ bridgeWorkspacePath: bridge?.bridgeWorkspacePath ?? null
34411
34899
  };
34412
34900
  }
34413
34901
  }
@@ -34416,12 +34904,12 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
34416
34904
  mechanism: "none",
34417
34905
  reason: null,
34418
34906
  pid: managedTarget.pid,
34419
- appServerPid: appServerPid2,
34907
+ appServerPid,
34420
34908
  cdpPort: managedTarget.cdpPort,
34421
- bridgeStatus: bridge2?.bridgeStatus ?? null,
34422
- bridgeError: bridge2?.bridgeError ?? null,
34423
- bridgeActiveThreadId: bridge2?.bridgeActiveThreadId ?? null,
34424
- bridgeWorkspacePath: bridge2?.bridgeWorkspacePath ?? null
34909
+ bridgeStatus: bridge?.bridgeStatus ?? null,
34910
+ bridgeError: bridge?.bridgeError ?? null,
34911
+ bridgeActiveThreadId: bridge?.bridgeActiveThreadId ?? null,
34912
+ bridgeWorkspacePath: bridge?.bridgeWorkspacePath ?? null
34425
34913
  };
34426
34914
  }
34427
34915
  sharedHomeCdpWindow = null;
@@ -34479,7 +34967,7 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
34479
34967
  const live = await attemptOfficialCodexManagedLiveLogin({
34480
34968
  candidate,
34481
34969
  driveTarget: managedTarget,
34482
- appServerPid: appServerPid2,
34970
+ appServerPid,
34483
34971
  startedAt: mainRow.startedAt,
34484
34972
  debuggerUrl: target.webSocketDebuggerUrl,
34485
34973
  sourceSnapshot: snapshot2,
@@ -34593,6 +35081,7 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
34593
35081
  reason: launch2.reason ?? null
34594
35082
  });
34595
35083
  if (!launch2.opened || launch2.pid === null || launch2.startedAt === null || launch2.cdpPort === null || !launch2.watchdog) {
35084
+ launch2.watchdog?.cancel();
34596
35085
  return {
34597
35086
  status: "failed",
34598
35087
  reason: launch2.reason ?? "shared-home-launch-failed",
@@ -34600,376 +35089,442 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
34600
35089
  closedPreviousWindow: false
34601
35090
  };
34602
35091
  }
34603
- const cdpPort2 = launch2.cdpPort;
34604
- const appServerStep2 = await waitForLaunchStepOrRunaway(
34605
- waitForAppServerPid(launch2.pid, SHARED_CODEX_HOME),
34606
- launch2.watchdog
34607
- );
34608
- if (appServerStep2.kind === "runaway") {
34609
- return {
34610
- status: "failed",
34611
- reason: launchRunawayFailureReason(appServerStep2.value, launch2.pid),
34612
- pid: launch2.pid,
34613
- appServerPid: null,
34614
- cdpPort: cdpPort2,
34615
- closedPreviousWindow: false
34616
- };
34617
- }
34618
- const appServerPid2 = appServerStep2.value;
34619
- logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "verifier-app-server", {
34620
- verified: appServerPid2 !== null
34621
- });
34622
- if (appServerPid2 === null) {
34623
- const remaining = await stopUnverifiedLaunch({
34624
- candidate,
34625
- pid: launch2.pid,
34626
- startedAt: launch2.startedAt,
34627
- cdpPort: cdpPort2
34628
- });
34629
- return {
34630
- status: "failed",
34631
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "app-server-not-verified",
34632
- pid: launch2.pid,
34633
- appServerPid: null,
34634
- cdpPort: cdpPort2,
34635
- closedPreviousWindow: false
34636
- };
34637
- }
34638
- const replacementTarget = await waitForCdpTargetAfterLaunch(cdpPort2);
34639
- if (!replacementTarget?.webSocketDebuggerUrl) {
34640
- const remaining = await stopUnverifiedLaunch({
34641
- candidate,
34642
- pid: launch2.pid,
34643
- startedAt: launch2.startedAt,
34644
- cdpPort: cdpPort2
35092
+ let finalLaunchWatchdog = null;
35093
+ try {
35094
+ const cdpPort = launch2.cdpPort;
35095
+ const appServerStep = await waitForLaunchStepOrRunaway(
35096
+ waitForAppServerPid(launch2.pid, SHARED_CODEX_HOME),
35097
+ launch2.watchdog
35098
+ );
35099
+ if (appServerStep.kind === "runaway") {
35100
+ return {
35101
+ status: "failed",
35102
+ reason: launchRunawayFailureReason(appServerStep.value, launch2.pid),
35103
+ pid: launch2.pid,
35104
+ appServerPid: null,
35105
+ cdpPort,
35106
+ closedPreviousWindow: false
35107
+ };
35108
+ }
35109
+ const appServerPid = appServerStep.value;
35110
+ logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "verifier-app-server", {
35111
+ verified: appServerPid !== null
34645
35112
  });
34646
- return {
34647
- status: "failed",
34648
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "bridge-not-healthy-after-launch",
34649
- pid: launch2.pid,
34650
- appServerPid: appServerPid2,
34651
- cdpPort: cdpPort2,
34652
- bridgeError: "cdp-target-not-found",
34653
- closedPreviousWindow: false
34654
- };
34655
- }
34656
- const attestedStep2 = await waitForLaunchStepOrRunaway(
34657
- waitForAttestedProcessEpoch({
34658
- candidate,
34659
- pid: launch2.pid,
34660
- appServerPid: appServerPid2,
34661
- startedAt: launch2.startedAt,
34662
- cdpPort: cdpPort2
34663
- }),
34664
- launch2.watchdog
34665
- );
34666
- if (attestedStep2.kind === "runaway") {
34667
- return {
34668
- status: "failed",
34669
- reason: launchRunawayFailureReason(attestedStep2.value, launch2.pid),
34670
- pid: launch2.pid,
34671
- appServerPid: appServerPid2,
34672
- cdpPort: cdpPort2,
34673
- closedPreviousWindow: false
34674
- };
34675
- }
34676
- if (!attestedStep2.value) {
34677
- const remaining = await stopUnverifiedLaunch({
34678
- candidate,
34679
- pid: launch2.pid,
34680
- startedAt: launch2.startedAt,
34681
- cdpPort: cdpPort2
35113
+ if (appServerPid === null) {
35114
+ const remaining = await stopUnverifiedLaunch({
35115
+ candidate,
35116
+ pid: launch2.pid,
35117
+ startedAt: launch2.startedAt,
35118
+ cdpPort
35119
+ });
35120
+ return {
35121
+ status: "failed",
35122
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "app-server-not-verified",
35123
+ pid: launch2.pid,
35124
+ appServerPid: null,
35125
+ cdpPort,
35126
+ closedPreviousWindow: false
35127
+ };
35128
+ }
35129
+ const replacementTarget = await waitForCdpTargetAfterLaunch(cdpPort);
35130
+ if (!replacementTarget?.webSocketDebuggerUrl) {
35131
+ const remaining = await stopUnverifiedLaunch({
35132
+ candidate,
35133
+ pid: launch2.pid,
35134
+ startedAt: launch2.startedAt,
35135
+ cdpPort
35136
+ });
35137
+ return {
35138
+ status: "failed",
35139
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "bridge-not-healthy-after-launch",
35140
+ pid: launch2.pid,
35141
+ appServerPid,
35142
+ cdpPort,
35143
+ bridgeError: "cdp-target-not-found",
35144
+ closedPreviousWindow: false
35145
+ };
35146
+ }
35147
+ const attestedStep = await waitForLaunchStepOrRunaway(
35148
+ waitForAttestedProcessEpoch({
35149
+ candidate,
35150
+ pid: launch2.pid,
35151
+ appServerPid,
35152
+ startedAt: launch2.startedAt,
35153
+ cdpPort
35154
+ }),
35155
+ launch2.watchdog
35156
+ );
35157
+ if (attestedStep.kind === "runaway") {
35158
+ return {
35159
+ status: "failed",
35160
+ reason: launchRunawayFailureReason(attestedStep.value, launch2.pid),
35161
+ pid: launch2.pid,
35162
+ appServerPid,
35163
+ cdpPort,
35164
+ closedPreviousWindow: false
35165
+ };
35166
+ }
35167
+ if (!attestedStep.value) {
35168
+ const remaining = await stopUnverifiedLaunch({
35169
+ candidate,
35170
+ pid: launch2.pid,
35171
+ startedAt: launch2.startedAt,
35172
+ cdpPort
35173
+ });
35174
+ return {
35175
+ status: "failed",
35176
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "process-identity-not-verified",
35177
+ pid: launch2.pid,
35178
+ appServerPid,
35179
+ cdpPort,
35180
+ closedPreviousWindow: false
35181
+ };
35182
+ }
35183
+ try {
35184
+ await ensureOfficialCodexBridgeInstalled(
35185
+ replacementTarget.webSocketDebuggerUrl,
35186
+ false
35187
+ );
35188
+ } catch (error) {
35189
+ const remaining = await stopUnverifiedLaunch({
35190
+ candidate,
35191
+ pid: launch2.pid,
35192
+ startedAt: launch2.startedAt,
35193
+ cdpPort
35194
+ });
35195
+ return {
35196
+ status: "failed",
35197
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "bridge-not-healthy-after-launch",
35198
+ pid: launch2.pid,
35199
+ appServerPid,
35200
+ cdpPort,
35201
+ bridgeError: sanitizeUserFacingError(error) ?? "bridge-install-failed",
35202
+ closedPreviousWindow: false
35203
+ };
35204
+ }
35205
+ logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "verifier-bridge", {
35206
+ healthy: true
34682
35207
  });
34683
- return {
34684
- status: "failed",
34685
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "process-identity-not-verified",
34686
- pid: launch2.pid,
34687
- appServerPid: appServerPid2,
34688
- cdpPort: cdpPort2,
34689
- closedPreviousWindow: false
34690
- };
34691
- }
34692
- try {
34693
- await ensureOfficialCodexBridgeInstalled(
35208
+ const verifierAccount = options.expectedAccount ? await waitForExpectedOfficialCodexAccount(
34694
35209
  replacementTarget.webSocketDebuggerUrl,
34695
- false
35210
+ options.expectedAccount
35211
+ ) : null;
35212
+ if (!options.expectedAccount || !verifierAccount || !officialCodexExpectedAccountMatches(options.expectedAccount, verifierAccount)) {
35213
+ const remaining = await stopUnverifiedLaunch({
35214
+ candidate,
35215
+ pid: launch2.pid,
35216
+ startedAt: launch2.startedAt,
35217
+ cdpPort
35218
+ });
35219
+ return {
35220
+ status: "failed",
35221
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "official-codex-target-account-unverified",
35222
+ pid: launch2.pid,
35223
+ appServerPid,
35224
+ cdpPort,
35225
+ closedPreviousWindow: false
35226
+ };
35227
+ }
35228
+ const verifierSurface = await prepareOfficialCodexRendererSurface(
35229
+ replacementTarget.webSocketDebuggerUrl,
35230
+ true
34696
35231
  );
34697
- } catch (error) {
34698
- const remaining = await stopUnverifiedLaunch({
34699
- candidate,
34700
- pid: launch2.pid,
34701
- startedAt: launch2.startedAt,
34702
- cdpPort: cdpPort2
35232
+ logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "verifier-surface", {
35233
+ status: verifierSurface
34703
35234
  });
34704
- return {
34705
- status: "failed",
34706
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "bridge-not-healthy-after-launch",
34707
- pid: launch2.pid,
34708
- appServerPid: appServerPid2,
34709
- cdpPort: cdpPort2,
34710
- bridgeError: sanitizeUserFacingError(error) ?? "bridge-install-failed",
34711
- closedPreviousWindow: false
34712
- };
34713
- }
34714
- logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "verifier-bridge", {
34715
- healthy: true
34716
- });
34717
- const verifierAccount = options.expectedAccount ? await waitForExpectedOfficialCodexAccount(
34718
- replacementTarget.webSocketDebuggerUrl,
34719
- options.expectedAccount
34720
- ) : null;
34721
- if (!options.expectedAccount || !verifierAccount || !expectedAccountMatches(options.expectedAccount, verifierAccount)) {
34722
- const remaining = await stopUnverifiedLaunch({
34723
- candidate,
34724
- pid: launch2.pid,
34725
- startedAt: launch2.startedAt,
34726
- cdpPort: cdpPort2
35235
+ if (verifierSurface !== "ready") {
35236
+ const remaining = await stopUnverifiedLaunch({
35237
+ candidate,
35238
+ pid: launch2.pid,
35239
+ startedAt: launch2.startedAt,
35240
+ cdpPort
35241
+ });
35242
+ return {
35243
+ status: "failed",
35244
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "renderer-surface-unavailable",
35245
+ pid: launch2.pid,
35246
+ appServerPid,
35247
+ cdpPort,
35248
+ closedPreviousWindow: false
35249
+ };
35250
+ }
35251
+ if (!await expectedSharedWindowTopologyStillMatches(
35252
+ expectedWindowPreflight,
35253
+ /* @__PURE__ */ new Set([launch2.pid])
35254
+ )) {
35255
+ await stopUnverifiedLaunch({
35256
+ candidate,
35257
+ pid: launch2.pid,
35258
+ startedAt: launch2.startedAt,
35259
+ cdpPort
35260
+ });
35261
+ return {
35262
+ status: "failed",
35263
+ reason: "official-codex-process-state-changed-before-switch",
35264
+ pid: null,
35265
+ closedPreviousWindow: false
35266
+ };
35267
+ }
35268
+ const takeoverVetoReason2 = await resolveStandingTakeoverActivityVeto(options);
35269
+ if (takeoverVetoReason2) {
35270
+ const remaining = await stopUnverifiedLaunch({
35271
+ candidate,
35272
+ pid: launch2.pid,
35273
+ startedAt: launch2.startedAt,
35274
+ cdpPort
35275
+ });
35276
+ return {
35277
+ status: remaining.length > 0 ? "failed" : "skipped",
35278
+ mechanism: "none",
35279
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : takeoverVetoReason2,
35280
+ pid: launch2.pid,
35281
+ appServerPid,
35282
+ cdpPort,
35283
+ closedPreviousWindow: false
35284
+ };
35285
+ }
35286
+ const remainingPlainPids = /* @__PURE__ */ new Set();
35287
+ for (const row of plainSharedRows) {
35288
+ for (const pid of await stopOfficialCodexProcessEpoch({
35289
+ candidate,
35290
+ pid: row.pid,
35291
+ startedAt: row.startedAt,
35292
+ cdpPort: null
35293
+ })) {
35294
+ remainingPlainPids.add(pid);
35295
+ }
35296
+ }
35297
+ logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "previous-window-exit", {
35298
+ remainingCount: remainingPlainPids.size
34727
35299
  });
34728
- return {
34729
- status: "failed",
34730
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "official-codex-target-account-unverified",
34731
- pid: launch2.pid,
34732
- appServerPid: appServerPid2,
34733
- cdpPort: cdpPort2,
34734
- closedPreviousWindow: false
34735
- };
34736
- }
34737
- const verifierSurface = await prepareOfficialCodexRendererSurface(
34738
- replacementTarget.webSocketDebuggerUrl,
34739
- true
34740
- );
34741
- logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "verifier-surface", {
34742
- status: verifierSurface
34743
- });
34744
- if (verifierSurface !== "ready") {
34745
- const remaining = await stopUnverifiedLaunch({
35300
+ if (remainingPlainPids.size > 0) {
35301
+ await stopUnverifiedLaunch({
35302
+ candidate,
35303
+ pid: launch2.pid,
35304
+ startedAt: launch2.startedAt,
35305
+ cdpPort
35306
+ });
35307
+ return {
35308
+ status: "failed",
35309
+ reason: "previous-instance-still-running",
35310
+ pid: null,
35311
+ closedPreviousWindow: false
35312
+ };
35313
+ }
35314
+ closedPreviousWindow = true;
35315
+ await sleep3(POST_EXIT_SETTLE_MS);
35316
+ const remainingVerifierPids = await stopUnverifiedLaunch({
34746
35317
  candidate,
34747
35318
  pid: launch2.pid,
34748
35319
  startedAt: launch2.startedAt,
34749
- cdpPort: cdpPort2
35320
+ cdpPort
34750
35321
  });
34751
- return {
34752
- status: "failed",
34753
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "renderer-surface-unavailable",
34754
- pid: launch2.pid,
34755
- appServerPid: appServerPid2,
34756
- cdpPort: cdpPort2,
34757
- closedPreviousWindow: false
34758
- };
34759
- }
34760
- if (!await expectedSharedWindowTopologyStillMatches(
34761
- expectedWindowPreflight,
34762
- /* @__PURE__ */ new Set([launch2.pid])
34763
- )) {
34764
- await stopUnverifiedLaunch({
34765
- candidate,
34766
- pid: launch2.pid,
34767
- startedAt: launch2.startedAt,
34768
- cdpPort: cdpPort2
35322
+ logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "verifier-exit", {
35323
+ remainingCount: remainingVerifierPids.length
34769
35324
  });
34770
- return {
34771
- status: "failed",
34772
- reason: "official-codex-process-state-changed-before-switch",
34773
- pid: null,
34774
- closedPreviousWindow: false
34775
- };
34776
- }
34777
- const takeoverVetoReason2 = await resolveStandingTakeoverActivityVeto(options);
34778
- if (takeoverVetoReason2) {
34779
- const remaining = await stopUnverifiedLaunch({
35325
+ if (remainingVerifierPids.length > 0) {
35326
+ return {
35327
+ status: "failed",
35328
+ reason: "temporary-instance-still-running",
35329
+ pid: launch2.pid,
35330
+ closedPreviousWindow
35331
+ };
35332
+ }
35333
+ sharedHomeCdpWindow = null;
35334
+ rows = await readProcessRows();
35335
+ if (findSharedHomeDebugWindows(rows, candidate).length > 0 || findPlainSharedHomeRows(rows, candidate).length > 0) {
35336
+ return {
35337
+ status: "failed",
35338
+ reason: "official-codex-process-state-changed-before-switch",
35339
+ pid: null,
35340
+ closedPreviousWindow,
35341
+ suppressPlainReopen: true
35342
+ };
35343
+ }
35344
+ const finalLaunch = await openCodexWithProfileHome(
34780
35345
  candidate,
34781
- pid: launch2.pid,
34782
- startedAt: launch2.startedAt,
34783
- cdpPort: cdpPort2
35346
+ SHARED_CODEX_HOME,
35347
+ options.profileName ?? "shared",
35348
+ new Set(rows.map((row) => row.pid)),
35349
+ sharedCodexLaunchOptions(
35350
+ false,
35351
+ options.profileKey ?? options.profileName
35352
+ )
35353
+ );
35354
+ finalLaunchWatchdog = finalLaunch.watchdog;
35355
+ logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "final-launched", {
35356
+ opened: finalLaunch.opened,
35357
+ hasPid: finalLaunch.pid !== null,
35358
+ reason: finalLaunch.reason ?? null
34784
35359
  });
34785
- return {
34786
- status: remaining.length > 0 ? "failed" : "skipped",
34787
- mechanism: "none",
34788
- reason: remaining.length > 0 ? "temporary-instance-still-running" : takeoverVetoReason2,
34789
- pid: launch2.pid,
34790
- appServerPid: appServerPid2,
34791
- cdpPort: cdpPort2,
34792
- closedPreviousWindow: false
34793
- };
34794
- }
34795
- const remainingPlainPids = /* @__PURE__ */ new Set();
34796
- for (const row of plainSharedRows) {
34797
- for (const pid of await stopOfficialCodexProcessEpoch({
34798
- candidate,
34799
- pid: row.pid,
34800
- startedAt: row.startedAt,
34801
- cdpPort: null
34802
- })) {
34803
- remainingPlainPids.add(pid);
35360
+ if (!finalLaunch.opened || finalLaunch.pid === null || finalLaunch.startedAt === null || finalLaunch.cdpPort === null || !finalLaunch.watchdog) {
35361
+ return {
35362
+ status: "failed",
35363
+ reason: finalLaunch.reason ?? "shared-home-launch-failed",
35364
+ pid: null,
35365
+ closedPreviousWindow
35366
+ };
34804
35367
  }
34805
- }
34806
- logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "previous-window-exit", {
34807
- remainingCount: remainingPlainPids.size
34808
- });
34809
- if (remainingPlainPids.size > 0) {
34810
- await stopUnverifiedLaunch({
34811
- candidate,
34812
- pid: launch2.pid,
34813
- startedAt: launch2.startedAt,
34814
- cdpPort: cdpPort2
35368
+ const finalCdpPort = finalLaunch.cdpPort;
35369
+ const finalAppServerStep = await waitForLaunchStepOrRunaway(
35370
+ waitForAppServerPid(finalLaunch.pid, SHARED_CODEX_HOME),
35371
+ finalLaunch.watchdog
35372
+ );
35373
+ if (finalAppServerStep.kind === "runaway") {
35374
+ return {
35375
+ status: "failed",
35376
+ reason: launchRunawayFailureReason(
35377
+ finalAppServerStep.value,
35378
+ finalLaunch.pid
35379
+ ),
35380
+ pid: finalLaunch.pid,
35381
+ appServerPid: null,
35382
+ cdpPort: finalCdpPort,
35383
+ closedPreviousWindow
35384
+ };
35385
+ }
35386
+ let finalAppServerPid = finalAppServerStep.value;
35387
+ logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "final-app-server", {
35388
+ verified: finalAppServerPid !== null
34815
35389
  });
34816
- return {
34817
- status: "failed",
34818
- reason: "previous-instance-still-running",
34819
- pid: null,
34820
- closedPreviousWindow: false
34821
- };
34822
- }
34823
- closedPreviousWindow = true;
34824
- await sleep3(POST_EXIT_SETTLE_MS);
34825
- const remainingVerifierPids = await stopUnverifiedLaunch({
34826
- candidate,
34827
- pid: launch2.pid,
34828
- startedAt: launch2.startedAt,
34829
- cdpPort: cdpPort2
34830
- });
34831
- logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "verifier-exit", {
34832
- remainingCount: remainingVerifierPids.length
34833
- });
34834
- if (remainingVerifierPids.length > 0) {
34835
- return {
34836
- status: "failed",
34837
- reason: "temporary-instance-still-running",
34838
- pid: launch2.pid,
34839
- closedPreviousWindow
34840
- };
34841
- }
34842
- sharedHomeCdpWindow = null;
34843
- rows = await readProcessRows();
34844
- if (findSharedHomeDebugWindows(rows, candidate).length > 0 || findPlainSharedHomeRows(rows, candidate).length > 0) {
34845
- return {
34846
- status: "failed",
34847
- reason: "official-codex-process-state-changed-before-switch",
34848
- pid: null,
34849
- closedPreviousWindow,
34850
- suppressPlainReopen: true
34851
- };
34852
- }
34853
- const finalLaunch = await openCodexWithProfileHome(
34854
- candidate,
34855
- SHARED_CODEX_HOME,
34856
- options.profileName ?? "shared",
34857
- new Set(rows.map((row) => row.pid)),
34858
- sharedCodexLaunchOptions(
34859
- false,
34860
- options.profileKey ?? options.profileName
34861
- )
34862
- );
34863
- logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "final-launched", {
34864
- opened: finalLaunch.opened,
34865
- hasPid: finalLaunch.pid !== null,
34866
- reason: finalLaunch.reason ?? null
34867
- });
34868
- if (!finalLaunch.opened || finalLaunch.pid === null || finalLaunch.startedAt === null || finalLaunch.cdpPort === null || !finalLaunch.watchdog) {
34869
- return {
34870
- status: "failed",
34871
- reason: finalLaunch.reason ?? "shared-home-launch-failed",
34872
- pid: null,
34873
- closedPreviousWindow
34874
- };
34875
- }
34876
- const finalCdpPort = finalLaunch.cdpPort;
34877
- const finalAppServerStep = await waitForLaunchStepOrRunaway(
34878
- waitForAppServerPid(finalLaunch.pid, SHARED_CODEX_HOME),
34879
- finalLaunch.watchdog
34880
- );
34881
- if (finalAppServerStep.kind === "runaway") {
34882
- return {
34883
- status: "failed",
34884
- reason: launchRunawayFailureReason(
34885
- finalAppServerStep.value,
34886
- finalLaunch.pid
34887
- ),
34888
- pid: finalLaunch.pid,
34889
- appServerPid: null,
35390
+ if (finalAppServerPid === null) {
35391
+ const remaining = await stopUnverifiedLaunch({
35392
+ candidate,
35393
+ pid: finalLaunch.pid,
35394
+ startedAt: finalLaunch.startedAt,
35395
+ cdpPort: finalCdpPort
35396
+ });
35397
+ return {
35398
+ status: "failed",
35399
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "app-server-not-verified",
35400
+ pid: finalLaunch.pid,
35401
+ appServerPid: null,
35402
+ cdpPort: finalCdpPort,
35403
+ closedPreviousWindow
35404
+ };
35405
+ }
35406
+ const finalAttestedStep = await waitForLaunchStepOrRunaway(
35407
+ waitForAttestedProcessEpoch({
35408
+ candidate,
35409
+ pid: finalLaunch.pid,
35410
+ appServerPid: finalAppServerPid,
35411
+ startedAt: finalLaunch.startedAt,
35412
+ cdpPort: finalCdpPort
35413
+ }),
35414
+ finalLaunch.watchdog
35415
+ );
35416
+ if (finalAttestedStep.kind === "runaway") {
35417
+ return {
35418
+ status: "failed",
35419
+ reason: launchRunawayFailureReason(
35420
+ finalAttestedStep.value,
35421
+ finalLaunch.pid
35422
+ ),
35423
+ pid: finalLaunch.pid,
35424
+ appServerPid: finalAppServerPid,
35425
+ cdpPort: finalCdpPort,
35426
+ closedPreviousWindow
35427
+ };
35428
+ }
35429
+ if (!finalAttestedStep.value) {
35430
+ const remaining = await stopUnverifiedLaunch({
35431
+ candidate,
35432
+ pid: finalLaunch.pid,
35433
+ startedAt: finalLaunch.startedAt,
35434
+ cdpPort: finalCdpPort
35435
+ });
35436
+ return {
35437
+ status: "failed",
35438
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "process-identity-not-verified",
35439
+ pid: finalLaunch.pid,
35440
+ appServerPid: finalAppServerPid,
35441
+ cdpPort: finalCdpPort,
35442
+ closedPreviousWindow
35443
+ };
35444
+ }
35445
+ sharedHomeCdpWindow = { pid: finalLaunch.pid, cdpPort: finalCdpPort };
35446
+ let bridge = null;
35447
+ if (options.profileName) {
35448
+ await adoptSharedManagedWindow({
35449
+ candidate,
35450
+ pid: finalLaunch.pid,
35451
+ appServerPid: finalAppServerPid,
35452
+ cdpPort: finalCdpPort,
35453
+ startedAt: finalLaunch.startedAt,
35454
+ profileName: options.profileName,
35455
+ profileKey: options.profileKey,
35456
+ desiredQolSettings: options.desiredQolSettings,
35457
+ desiredPowerSettings: options.desiredPowerSettings
35458
+ });
35459
+ bridge = await refreshAdoptedSharedWindow(options.profileName);
35460
+ logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "final-bridge", {
35461
+ healthy: bridge?.bridgeStatus === "healthy",
35462
+ bridgeStatus: bridge?.bridgeStatus ?? null
35463
+ });
35464
+ if (bridge?.bridgeStatus !== "healthy") {
35465
+ const remaining = await stopUnverifiedLaunch({
35466
+ candidate,
35467
+ pid: finalLaunch.pid,
35468
+ startedAt: finalLaunch.startedAt,
35469
+ cdpPort: finalCdpPort
35470
+ });
35471
+ sharedHomeCdpWindow = null;
35472
+ return {
35473
+ status: "failed",
35474
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "bridge-not-healthy-after-launch",
35475
+ pid: finalLaunch.pid,
35476
+ appServerPid: finalAppServerPid,
35477
+ cdpPort: finalCdpPort,
35478
+ bridgeStatus: bridge?.bridgeStatus ?? null,
35479
+ bridgeError: bridge?.bridgeError ?? null,
35480
+ bridgeActiveThreadId: bridge?.bridgeActiveThreadId ?? null,
35481
+ bridgeWorkspacePath: bridge?.bridgeWorkspacePath ?? null,
35482
+ closedPreviousWindow
35483
+ };
35484
+ }
35485
+ }
35486
+ const followUp = await applySharedLaunchFollowUp({
34890
35487
  cdpPort: finalCdpPort,
34891
- closedPreviousWindow
34892
- };
34893
- }
34894
- let finalAppServerPid = finalAppServerStep.value;
34895
- logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "final-app-server", {
34896
- verified: finalAppServerPid !== null
34897
- });
34898
- if (finalAppServerPid === null) {
34899
- const remaining = await stopUnverifiedLaunch({
34900
- candidate,
34901
- pid: finalLaunch.pid,
34902
- startedAt: finalLaunch.startedAt,
34903
- cdpPort: finalCdpPort
35488
+ carriedDraft,
35489
+ carryDraft: options.carryDraft === true,
35490
+ expectedAccount: options.expectedAccount ?? null,
35491
+ allowOnboardingOverride: true
34904
35492
  });
34905
- return {
34906
- status: "failed",
34907
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "app-server-not-verified",
34908
- pid: finalLaunch.pid,
34909
- appServerPid: null,
34910
- cdpPort: finalCdpPort,
34911
- closedPreviousWindow
34912
- };
34913
- }
34914
- const finalAttestedStep = await waitForLaunchStepOrRunaway(
34915
- waitForAttestedProcessEpoch({
35493
+ const reconciliation = await reconcileSharedManagedWindowAfterLaunch({
34916
35494
  candidate,
34917
35495
  pid: finalLaunch.pid,
34918
35496
  appServerPid: finalAppServerPid,
34919
- startedAt: finalLaunch.startedAt,
34920
- cdpPort: finalCdpPort
34921
- }),
34922
- finalLaunch.watchdog
34923
- );
34924
- if (finalAttestedStep.kind === "runaway") {
34925
- return {
34926
- status: "failed",
34927
- reason: launchRunawayFailureReason(
34928
- finalAttestedStep.value,
34929
- finalLaunch.pid
34930
- ),
34931
- pid: finalLaunch.pid,
34932
- appServerPid: finalAppServerPid,
34933
35497
  cdpPort: finalCdpPort,
34934
- closedPreviousWindow
34935
- };
34936
- }
34937
- if (!finalAttestedStep.value) {
34938
- const remaining = await stopUnverifiedLaunch({
34939
- candidate,
34940
- pid: finalLaunch.pid,
34941
35498
  startedAt: finalLaunch.startedAt,
34942
- cdpPort: finalCdpPort
35499
+ profileName: options.profileName,
35500
+ profileKey: options.profileKey,
35501
+ desiredQolSettings: options.desiredQolSettings,
35502
+ desiredPowerSettings: options.desiredPowerSettings,
35503
+ bridge
34943
35504
  });
34944
- return {
34945
- status: "failed",
34946
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "process-identity-not-verified",
34947
- pid: finalLaunch.pid,
34948
- appServerPid: finalAppServerPid,
34949
- cdpPort: finalCdpPort,
34950
- closedPreviousWindow
34951
- };
34952
- }
34953
- sharedHomeCdpWindow = { pid: finalLaunch.pid, cdpPort: finalCdpPort };
34954
- let bridge2 = null;
34955
- if (options.profileName) {
34956
- await adoptSharedManagedWindow({
35505
+ if (reconciliation) {
35506
+ finalAppServerPid = reconciliation.appServerPid;
35507
+ bridge = reconciliation.bridge;
35508
+ }
35509
+ const finalEpoch = reconciliation?.processEpoch ?? null;
35510
+ const finalBridgeVerified = !options.profileName || bridge?.bridgeStatus === "healthy";
35511
+ const finalTopologyVerified = Boolean(
35512
+ finalEpoch && isExclusiveSharedManagedWindow(
35513
+ finalEpoch.rows,
35514
+ candidate,
35515
+ finalLaunch.pid,
35516
+ finalCdpPort
35517
+ )
35518
+ );
35519
+ const accountObservation = finalTopologyVerified && options.expectedAccount ? await readVerifiedTransitionAccountObservation({
34957
35520
  candidate,
34958
35521
  pid: finalLaunch.pid,
34959
35522
  appServerPid: finalAppServerPid,
34960
- cdpPort: finalCdpPort,
34961
35523
  startedAt: finalLaunch.startedAt,
34962
- profileName: options.profileName,
34963
- profileKey: options.profileKey,
34964
- desiredQolSettings: options.desiredQolSettings,
34965
- desiredPowerSettings: options.desiredPowerSettings
34966
- });
34967
- bridge2 = await refreshAdoptedSharedWindow(options.profileName);
34968
- logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "final-bridge", {
34969
- healthy: bridge2?.bridgeStatus === "healthy",
34970
- bridgeStatus: bridge2?.bridgeStatus ?? null
34971
- });
34972
- if (bridge2?.bridgeStatus !== "healthy") {
35524
+ cdpPort: finalCdpPort,
35525
+ expectedAccount: options.expectedAccount
35526
+ }) : null;
35527
+ if (!followUp.verified || !finalTopologyVerified || !finalBridgeVerified || !accountObservation) {
34973
35528
  const remaining = await stopUnverifiedLaunch({
34974
35529
  candidate,
34975
35530
  pid: finalLaunch.pid,
@@ -34979,114 +35534,47 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
34979
35534
  sharedHomeCdpWindow = null;
34980
35535
  return {
34981
35536
  status: "failed",
34982
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "bridge-not-healthy-after-launch",
35537
+ mechanism: "relaunch",
35538
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : !finalEpoch ? "observed-process-identity-changed" : !finalTopologyVerified ? "official-codex-process-state-changed-before-switch" : !finalBridgeVerified ? "bridge-not-healthy-after-launch" : !accountObservation ? "official-codex-target-account-unverified" : followUp.reason,
34983
35539
  pid: finalLaunch.pid,
34984
35540
  appServerPid: finalAppServerPid,
34985
35541
  cdpPort: finalCdpPort,
34986
- bridgeStatus: bridge2?.bridgeStatus ?? null,
34987
- bridgeError: bridge2?.bridgeError ?? null,
34988
- bridgeActiveThreadId: bridge2?.bridgeActiveThreadId ?? null,
34989
- bridgeWorkspacePath: bridge2?.bridgeWorkspacePath ?? null,
34990
- closedPreviousWindow
35542
+ closedPreviousWindow,
35543
+ rendererVerified: false,
35544
+ suppressPlainReopen: true
34991
35545
  };
34992
35546
  }
34993
- }
34994
- const followUp2 = await applySharedLaunchFollowUp({
34995
- cdpPort: finalCdpPort,
34996
- carriedDraft,
34997
- carryDraft: options.carryDraft === true,
34998
- expectedAccount: options.expectedAccount ?? null,
34999
- allowOnboardingOverride: true
35000
- });
35001
- const reconciliation2 = await reconcileSharedManagedWindowAfterLaunch({
35002
- candidate,
35003
- pid: finalLaunch.pid,
35004
- appServerPid: finalAppServerPid,
35005
- cdpPort: finalCdpPort,
35006
- startedAt: finalLaunch.startedAt,
35007
- profileName: options.profileName,
35008
- profileKey: options.profileKey,
35009
- desiredQolSettings: options.desiredQolSettings,
35010
- desiredPowerSettings: options.desiredPowerSettings,
35011
- bridge: bridge2
35012
- });
35013
- if (reconciliation2) {
35014
- finalAppServerPid = reconciliation2.appServerPid;
35015
- bridge2 = reconciliation2.bridge;
35016
- }
35017
- const finalEpoch2 = reconciliation2?.processEpoch ?? null;
35018
- const finalBridgeVerified2 = !options.profileName || bridge2?.bridgeStatus === "healthy";
35019
- const finalTopologyVerified2 = Boolean(
35020
- finalEpoch2 && isExclusiveSharedManagedWindow(
35021
- finalEpoch2.rows,
35022
- candidate,
35023
- finalLaunch.pid,
35024
- finalCdpPort
35025
- )
35026
- );
35027
- const accountObservation2 = finalTopologyVerified2 && options.expectedAccount ? await readVerifiedTransitionAccountObservation({
35028
- candidate,
35029
- pid: finalLaunch.pid,
35030
- appServerPid: finalAppServerPid,
35031
- startedAt: finalLaunch.startedAt,
35032
- cdpPort: finalCdpPort,
35033
- expectedAccount: options.expectedAccount
35034
- }) : null;
35035
- if (!followUp2.verified || !finalTopologyVerified2 || !finalBridgeVerified2 || !accountObservation2) {
35036
- const remaining = await stopUnverifiedLaunch({
35037
- candidate,
35038
- pid: finalLaunch.pid,
35039
- startedAt: finalLaunch.startedAt,
35040
- cdpPort: finalCdpPort
35547
+ if (options.profileName) {
35548
+ await recordOfficialCodexManagedAccountObservation(
35549
+ options.profileName,
35550
+ finalLaunch.pid,
35551
+ finalAppServerPid,
35552
+ finalLaunch.startedAt,
35553
+ finalCdpPort
35554
+ );
35555
+ }
35556
+ logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "completed", {
35557
+ status: "launched"
35041
35558
  });
35042
- sharedHomeCdpWindow = null;
35043
35559
  return {
35044
- status: "failed",
35560
+ status: "launched",
35045
35561
  mechanism: "relaunch",
35046
- reason: remaining.length > 0 ? "temporary-instance-still-running" : !finalEpoch2 ? "observed-process-identity-changed" : !finalTopologyVerified2 ? "official-codex-process-state-changed-before-switch" : !finalBridgeVerified2 ? "bridge-not-healthy-after-launch" : !accountObservation2 ? "official-codex-target-account-unverified" : followUp2.reason,
35562
+ reason: null,
35047
35563
  pid: finalLaunch.pid,
35048
35564
  appServerPid: finalAppServerPid,
35049
35565
  cdpPort: finalCdpPort,
35566
+ bridgeStatus: bridge?.bridgeStatus ?? null,
35567
+ bridgeError: bridge?.bridgeError ?? null,
35568
+ bridgeActiveThreadId: bridge?.bridgeActiveThreadId ?? null,
35569
+ bridgeWorkspacePath: bridge?.bridgeWorkspacePath ?? null,
35050
35570
  closedPreviousWindow,
35051
- rendererVerified: false,
35052
- suppressPlainReopen: true
35571
+ rendererVerified: true,
35572
+ accountObservation
35053
35573
  };
35574
+ } finally {
35575
+ launch2.watchdog.cancel();
35576
+ finalLaunchWatchdog?.cancel();
35054
35577
  }
35055
- if (options.profileName) {
35056
- await recordOfficialCodexManagedAccountObservation(
35057
- options.profileName,
35058
- finalLaunch.pid,
35059
- finalAppServerPid,
35060
- finalLaunch.startedAt,
35061
- finalCdpPort
35062
- );
35063
- recordManagedLaunchRunaway({
35064
- watchdog: finalLaunch.watchdog,
35065
- candidate,
35066
- profileName: options.profileName,
35067
- pid: finalLaunch.pid,
35068
- startedAt: finalLaunch.startedAt,
35069
- cdpPort: finalCdpPort
35070
- });
35071
- }
35072
- logOfficialCodexTakeoverPhase(takeoverTrace, candidate, "completed", {
35073
- status: "launched"
35074
- });
35075
- return {
35076
- status: "launched",
35077
- mechanism: "relaunch",
35078
- reason: null,
35079
- pid: finalLaunch.pid,
35080
- appServerPid: finalAppServerPid,
35081
- cdpPort: finalCdpPort,
35082
- bridgeStatus: bridge2?.bridgeStatus ?? null,
35083
- bridgeError: bridge2?.bridgeError ?? null,
35084
- bridgeActiveThreadId: bridge2?.bridgeActiveThreadId ?? null,
35085
- bridgeWorkspacePath: bridge2?.bridgeWorkspacePath ?? null,
35086
- closedPreviousWindow,
35087
- rendererVerified: true,
35088
- accountObservation: accountObservation2
35089
- };
35090
35578
  }
35091
35579
  if (plainSharedRows.length > 0 && !await expectedSharedWindowTopologyStillMatches(
35092
35580
  expectedWindowPreflight
@@ -35148,6 +35636,7 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
35148
35636
  sharedCodexLaunchOptions(true)
35149
35637
  );
35150
35638
  if (!launch.opened || launch.pid === null || launch.startedAt === null || launch.cdpPort === null || !launch.watchdog) {
35639
+ launch.watchdog?.cancel();
35151
35640
  return {
35152
35641
  status: "failed",
35153
35642
  reason: launch.reason ?? "shared-home-launch-failed",
@@ -35155,90 +35644,154 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
35155
35644
  closedPreviousWindow
35156
35645
  };
35157
35646
  }
35158
- const cdpPort = launch.cdpPort;
35159
- const appServerStep = await waitForLaunchStepOrRunaway(
35160
- waitForAppServerPid(launch.pid, SHARED_CODEX_HOME),
35161
- launch.watchdog
35162
- );
35163
- if (appServerStep.kind === "runaway") {
35164
- return {
35165
- status: "failed",
35166
- reason: launchRunawayFailureReason(appServerStep.value, launch.pid),
35167
- pid: launch.pid,
35168
- appServerPid: null,
35647
+ try {
35648
+ const cdpPort = launch.cdpPort;
35649
+ const appServerStep = await waitForLaunchStepOrRunaway(
35650
+ waitForAppServerPid(launch.pid, SHARED_CODEX_HOME),
35651
+ launch.watchdog
35652
+ );
35653
+ if (appServerStep.kind === "runaway") {
35654
+ return {
35655
+ status: "failed",
35656
+ reason: launchRunawayFailureReason(appServerStep.value, launch.pid),
35657
+ pid: launch.pid,
35658
+ appServerPid: null,
35659
+ cdpPort,
35660
+ closedPreviousWindow
35661
+ };
35662
+ }
35663
+ let appServerPid = appServerStep.value;
35664
+ if (appServerPid === null) {
35665
+ const remaining = await stopUnverifiedLaunch({
35666
+ candidate,
35667
+ pid: launch.pid,
35668
+ startedAt: launch.startedAt,
35669
+ cdpPort
35670
+ });
35671
+ return {
35672
+ status: "failed",
35673
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "app-server-not-verified",
35674
+ pid: launch.pid,
35675
+ appServerPid: null,
35676
+ cdpPort,
35677
+ closedPreviousWindow
35678
+ };
35679
+ }
35680
+ const attestedStep = await waitForLaunchStepOrRunaway(
35681
+ waitForAttestedProcessEpoch({
35682
+ candidate,
35683
+ pid: launch.pid,
35684
+ appServerPid,
35685
+ startedAt: launch.startedAt,
35686
+ cdpPort
35687
+ }),
35688
+ launch.watchdog
35689
+ );
35690
+ if (attestedStep.kind === "runaway") {
35691
+ return {
35692
+ status: "failed",
35693
+ reason: launchRunawayFailureReason(attestedStep.value, launch.pid),
35694
+ pid: launch.pid,
35695
+ appServerPid,
35696
+ cdpPort,
35697
+ closedPreviousWindow
35698
+ };
35699
+ }
35700
+ if (!attestedStep.value) {
35701
+ const remaining = await stopUnverifiedLaunch({
35702
+ candidate,
35703
+ pid: launch.pid,
35704
+ startedAt: launch.startedAt,
35705
+ cdpPort
35706
+ });
35707
+ return {
35708
+ status: "failed",
35709
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "process-identity-not-verified",
35710
+ pid: launch.pid,
35711
+ appServerPid,
35712
+ cdpPort,
35713
+ closedPreviousWindow
35714
+ };
35715
+ }
35716
+ sharedHomeCdpWindow = { pid: launch.pid, cdpPort };
35717
+ let bridge = null;
35718
+ if (options.profileName) {
35719
+ await adoptSharedManagedWindow({
35720
+ candidate,
35721
+ pid: launch.pid,
35722
+ appServerPid,
35723
+ cdpPort,
35724
+ startedAt: launch.startedAt,
35725
+ profileName: options.profileName,
35726
+ profileKey: options.profileKey,
35727
+ desiredQolSettings: options.desiredQolSettings,
35728
+ desiredPowerSettings: options.desiredPowerSettings
35729
+ });
35730
+ bridge = await refreshAdoptedSharedWindow(options.profileName);
35731
+ if (bridge?.bridgeStatus !== "healthy") {
35732
+ const remaining = await stopUnverifiedLaunch({
35733
+ candidate,
35734
+ pid: launch.pid,
35735
+ startedAt: launch.startedAt,
35736
+ cdpPort
35737
+ });
35738
+ sharedHomeCdpWindow = null;
35739
+ return {
35740
+ status: "failed",
35741
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : "bridge-not-healthy-after-launch",
35742
+ pid: launch.pid,
35743
+ appServerPid,
35744
+ cdpPort,
35745
+ bridgeStatus: bridge?.bridgeStatus ?? null,
35746
+ bridgeError: bridge?.bridgeError ?? null,
35747
+ bridgeActiveThreadId: bridge?.bridgeActiveThreadId ?? null,
35748
+ bridgeWorkspacePath: bridge?.bridgeWorkspacePath ?? null,
35749
+ closedPreviousWindow
35750
+ };
35751
+ }
35752
+ }
35753
+ const followUp = await applySharedLaunchFollowUp({
35169
35754
  cdpPort,
35170
- closedPreviousWindow
35171
- };
35172
- }
35173
- let appServerPid = appServerStep.value;
35174
- if (appServerPid === null) {
35175
- const remaining = await stopUnverifiedLaunch({
35176
- candidate,
35177
- pid: launch.pid,
35178
- startedAt: launch.startedAt,
35179
- cdpPort
35755
+ carriedDraft,
35756
+ carryDraft: options.carryDraft === true,
35757
+ expectedAccount: options.expectedAccount ?? null,
35758
+ allowOnboardingOverride: false
35180
35759
  });
35181
- return {
35182
- status: "failed",
35183
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "app-server-not-verified",
35184
- pid: launch.pid,
35185
- appServerPid: null,
35186
- cdpPort,
35187
- closedPreviousWindow
35188
- };
35189
- }
35190
- const attestedStep = await waitForLaunchStepOrRunaway(
35191
- waitForAttestedProcessEpoch({
35760
+ const reconciliation = await reconcileSharedManagedWindowAfterLaunch({
35192
35761
  candidate,
35193
35762
  pid: launch.pid,
35194
35763
  appServerPid,
35195
- startedAt: launch.startedAt,
35196
- cdpPort
35197
- }),
35198
- launch.watchdog
35199
- );
35200
- if (attestedStep.kind === "runaway") {
35201
- return {
35202
- status: "failed",
35203
- reason: launchRunawayFailureReason(attestedStep.value, launch.pid),
35204
- pid: launch.pid,
35205
- appServerPid,
35206
35764
  cdpPort,
35207
- closedPreviousWindow
35208
- };
35209
- }
35210
- if (!attestedStep.value) {
35211
- const remaining = await stopUnverifiedLaunch({
35212
- candidate,
35213
- pid: launch.pid,
35214
35765
  startedAt: launch.startedAt,
35215
- cdpPort
35766
+ profileName: options.profileName,
35767
+ profileKey: options.profileKey,
35768
+ desiredQolSettings: options.desiredQolSettings,
35769
+ desiredPowerSettings: options.desiredPowerSettings,
35770
+ bridge
35216
35771
  });
35217
- return {
35218
- status: "failed",
35219
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "process-identity-not-verified",
35220
- pid: launch.pid,
35221
- appServerPid,
35222
- cdpPort,
35223
- closedPreviousWindow
35224
- };
35225
- }
35226
- sharedHomeCdpWindow = { pid: launch.pid, cdpPort };
35227
- let bridge = null;
35228
- if (options.profileName) {
35229
- await adoptSharedManagedWindow({
35772
+ if (reconciliation) {
35773
+ appServerPid = reconciliation.appServerPid;
35774
+ bridge = reconciliation.bridge;
35775
+ }
35776
+ const finalEpoch = reconciliation?.processEpoch ?? null;
35777
+ const finalBridgeVerified = !options.profileName || bridge?.bridgeStatus === "healthy";
35778
+ const finalTopologyVerified = Boolean(
35779
+ finalEpoch && isExclusiveSharedManagedWindow(
35780
+ finalEpoch.rows,
35781
+ candidate,
35782
+ launch.pid,
35783
+ cdpPort
35784
+ )
35785
+ );
35786
+ const accountObservation = finalTopologyVerified && options.expectedAccount ? await readVerifiedTransitionAccountObservation({
35230
35787
  candidate,
35231
35788
  pid: launch.pid,
35232
35789
  appServerPid,
35233
- cdpPort,
35234
35790
  startedAt: launch.startedAt,
35235
- profileName: options.profileName,
35236
- profileKey: options.profileKey,
35237
- desiredQolSettings: options.desiredQolSettings,
35238
- desiredPowerSettings: options.desiredPowerSettings
35239
- });
35240
- bridge = await refreshAdoptedSharedWindow(options.profileName);
35241
- if (bridge?.bridgeStatus !== "healthy") {
35791
+ cdpPort,
35792
+ expectedAccount: options.expectedAccount
35793
+ }) : null;
35794
+ if (!followUp.verified || !finalTopologyVerified || !finalBridgeVerified || !accountObservation) {
35242
35795
  const remaining = await stopUnverifiedLaunch({
35243
35796
  candidate,
35244
35797
  pid: launch.pid,
@@ -35248,111 +35801,43 @@ async function applyOfficialCodexLiveAccountSwitchOnce(options = {}, takeoverTra
35248
35801
  sharedHomeCdpWindow = null;
35249
35802
  return {
35250
35803
  status: "failed",
35251
- reason: remaining.length > 0 ? "temporary-instance-still-running" : "bridge-not-healthy-after-launch",
35804
+ mechanism: "relaunch",
35805
+ reason: remaining.length > 0 ? "temporary-instance-still-running" : !finalEpoch ? "observed-process-identity-changed" : !finalTopologyVerified ? "official-codex-process-state-changed-before-switch" : !finalBridgeVerified ? "bridge-not-healthy-after-launch" : !accountObservation ? "official-codex-target-account-unverified" : followUp.reason,
35252
35806
  pid: launch.pid,
35253
35807
  appServerPid,
35254
35808
  cdpPort,
35255
- bridgeStatus: bridge?.bridgeStatus ?? null,
35256
- bridgeError: bridge?.bridgeError ?? null,
35257
- bridgeActiveThreadId: bridge?.bridgeActiveThreadId ?? null,
35258
- bridgeWorkspacePath: bridge?.bridgeWorkspacePath ?? null,
35259
- closedPreviousWindow
35809
+ closedPreviousWindow,
35810
+ rendererVerified: false,
35811
+ suppressPlainReopen: true
35260
35812
  };
35261
35813
  }
35262
- }
35263
- const followUp = await applySharedLaunchFollowUp({
35264
- cdpPort,
35265
- carriedDraft,
35266
- carryDraft: options.carryDraft === true,
35267
- expectedAccount: options.expectedAccount ?? null,
35268
- allowOnboardingOverride: false
35269
- });
35270
- const reconciliation = await reconcileSharedManagedWindowAfterLaunch({
35271
- candidate,
35272
- pid: launch.pid,
35273
- appServerPid,
35274
- cdpPort,
35275
- startedAt: launch.startedAt,
35276
- profileName: options.profileName,
35277
- profileKey: options.profileKey,
35278
- desiredQolSettings: options.desiredQolSettings,
35279
- desiredPowerSettings: options.desiredPowerSettings,
35280
- bridge
35281
- });
35282
- if (reconciliation) {
35283
- appServerPid = reconciliation.appServerPid;
35284
- bridge = reconciliation.bridge;
35285
- }
35286
- const finalEpoch = reconciliation?.processEpoch ?? null;
35287
- const finalBridgeVerified = !options.profileName || bridge?.bridgeStatus === "healthy";
35288
- const finalTopologyVerified = Boolean(
35289
- finalEpoch && isExclusiveSharedManagedWindow(
35290
- finalEpoch.rows,
35291
- candidate,
35292
- launch.pid,
35293
- cdpPort
35294
- )
35295
- );
35296
- const accountObservation = finalTopologyVerified && options.expectedAccount ? await readVerifiedTransitionAccountObservation({
35297
- candidate,
35298
- pid: launch.pid,
35299
- appServerPid,
35300
- startedAt: launch.startedAt,
35301
- cdpPort,
35302
- expectedAccount: options.expectedAccount
35303
- }) : null;
35304
- if (!followUp.verified || !finalTopologyVerified || !finalBridgeVerified || !accountObservation) {
35305
- const remaining = await stopUnverifiedLaunch({
35306
- candidate,
35307
- pid: launch.pid,
35308
- startedAt: launch.startedAt,
35309
- cdpPort
35310
- });
35311
- sharedHomeCdpWindow = null;
35814
+ if (options.profileName) {
35815
+ await recordOfficialCodexManagedAccountObservation(
35816
+ options.profileName,
35817
+ launch.pid,
35818
+ appServerPid,
35819
+ launch.startedAt,
35820
+ cdpPort
35821
+ );
35822
+ }
35312
35823
  return {
35313
- status: "failed",
35824
+ status: "launched",
35314
35825
  mechanism: "relaunch",
35315
- reason: remaining.length > 0 ? "temporary-instance-still-running" : !finalEpoch ? "observed-process-identity-changed" : !finalTopologyVerified ? "official-codex-process-state-changed-before-switch" : !finalBridgeVerified ? "bridge-not-healthy-after-launch" : !accountObservation ? "official-codex-target-account-unverified" : followUp.reason,
35826
+ reason: null,
35316
35827
  pid: launch.pid,
35317
35828
  appServerPid,
35318
35829
  cdpPort,
35830
+ bridgeStatus: bridge?.bridgeStatus ?? null,
35831
+ bridgeError: bridge?.bridgeError ?? null,
35832
+ bridgeActiveThreadId: bridge?.bridgeActiveThreadId ?? null,
35833
+ bridgeWorkspacePath: bridge?.bridgeWorkspacePath ?? null,
35319
35834
  closedPreviousWindow,
35320
- rendererVerified: false,
35321
- suppressPlainReopen: true
35835
+ rendererVerified: true,
35836
+ accountObservation
35322
35837
  };
35838
+ } finally {
35839
+ launch.watchdog.cancel();
35323
35840
  }
35324
- if (options.profileName) {
35325
- await recordOfficialCodexManagedAccountObservation(
35326
- options.profileName,
35327
- launch.pid,
35328
- appServerPid,
35329
- launch.startedAt,
35330
- cdpPort
35331
- );
35332
- recordManagedLaunchRunaway({
35333
- watchdog: launch.watchdog,
35334
- candidate,
35335
- profileName: options.profileName,
35336
- pid: launch.pid,
35337
- startedAt: launch.startedAt,
35338
- cdpPort
35339
- });
35340
- }
35341
- return {
35342
- status: "launched",
35343
- mechanism: "relaunch",
35344
- reason: null,
35345
- pid: launch.pid,
35346
- appServerPid,
35347
- cdpPort,
35348
- bridgeStatus: bridge?.bridgeStatus ?? null,
35349
- bridgeError: bridge?.bridgeError ?? null,
35350
- bridgeActiveThreadId: bridge?.bridgeActiveThreadId ?? null,
35351
- bridgeWorkspacePath: bridge?.bridgeWorkspacePath ?? null,
35352
- closedPreviousWindow,
35353
- rendererVerified: true,
35354
- accountObservation
35355
- };
35356
35841
  }
35357
35842
  function applyOfficialCodexLiveAccountSwitch(options = {}) {
35358
35843
  return enqueueProfileAction("shared-window", async () => {
@@ -35868,6 +36353,8 @@ async function launchOfficialCodexProfileInstanceOnce(options) {
35868
36353
  };
35869
36354
  }
35870
36355
  if (!launch.opened) {
36356
+ launch.watchdog?.cancel();
36357
+ launchedProcess = null;
35871
36358
  const reason = launch.reason ?? "open-failed";
35872
36359
  const failed = failedLaunchState({
35873
36360
  reason,
@@ -36031,14 +36518,7 @@ async function launchOfficialCodexProfileInstanceOnce(options) {
36031
36518
  lastError: null
36032
36519
  };
36033
36520
  await patchManagedInstance(instance);
36034
- recordManagedLaunchRunaway({
36035
- watchdog: launchWatchdog,
36036
- candidate,
36037
- profileName: options.profileName,
36038
- pid: launchedPid,
36039
- startedAt: launch.startedAt,
36040
- cdpPort
36041
- });
36521
+ launchWatchdog.cancel();
36042
36522
  launchedProcess = null;
36043
36523
  return {
36044
36524
  status: "started",
@@ -42744,9 +43224,9 @@ Runs the profile bound to the current workspace. --profile warns when it overrid
42744
43224
  }
42745
43225
  const profileName = readOption(flags, "--profile", "-p");
42746
43226
  const allowedFlags = profileName ? /* @__PURE__ */ new Set(["--profile", "-p", "--strict", profileName, `--profile=${profileName}`]) : /* @__PURE__ */ new Set(["--strict"]);
42747
- const unsupported = flags.filter((entry) => !allowedFlags.has(entry));
42748
- if (unsupported.length > 0) {
42749
- throw new Error(`Unsupported run option: ${unsupported[0]}`);
43227
+ const unsupported2 = flags.filter((entry) => !allowedFlags.has(entry));
43228
+ if (unsupported2.length > 0) {
43229
+ throw new Error(`Unsupported run option: ${unsupported2[0]}`);
42750
43230
  }
42751
43231
  if (codexArgs.some(
42752
43232
  (entry) => entry === "-C" || entry.startsWith("-C") && entry.length > 2 || entry === "--cd" || entry.startsWith("--cd=") || entry === "--cwd" || entry.startsWith("--cwd=")
@@ -46060,7 +46540,7 @@ async function ensureCliStorageReady() {
46060
46540
  }
46061
46541
 
46062
46542
  // src/app/main.ts
46063
- var VERSION = true ? "6.1.0" : "0.0.0";
46543
+ var VERSION = true ? "6.2.0" : "0.0.0";
46064
46544
  async function runCli() {
46065
46545
  const args2 = process.argv.slice(2);
46066
46546
  if (args2.length === 0) {