dsh-codex-subscription 3.1.6 → 3.1.8

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/lib/index.js CHANGED
@@ -403,6 +403,9 @@ const SEARCH_PROVIDER_FIELD = "searchProvider";
403
403
  const SEARCH_PROVIDER_AUTO = "auto";
404
404
  const SEARCH_PROVIDER_CODEX = "codex";
405
405
  const DEFAULT_SEARCH_PROVIDER = SEARCH_PROVIDER_AUTO;
406
+ const FETCH_PROVIDER_FIELD = "fetchProvider";
407
+ const FETCH_PROVIDER_CODEX = "codex";
408
+ const normalizeFetchProvider = (value) => value === "codex" ? FETCH_PROVIDER_CODEX : "dsh";
406
409
  const SPEED_MODE_FIELD = "speedMode";
407
410
  const SPEED_MODE_STANDARD = "standard";
408
411
  const SPEED_MODE_FAST = "fast";
@@ -458,6 +461,19 @@ const VOICE_LANGUAGES = Object.freeze([
458
461
  const normalizeVoiceCall = (value) => value === "on" ? "on" : "off";
459
462
  const normalizeVoiceVoice = (value) => VOICE_VOICES.includes(value) ? value : "cove";
460
463
  const normalizeVoiceLanguage = (value) => VOICE_LANGUAGES.includes(value) ? value : "auto";
464
+ const DEFAULT_REASONING_EFFORT_FIELD = "defaultReasoningEffort";
465
+ const DEFAULT_REASONING_EFFORTS = Object.freeze([
466
+ "auto",
467
+ "off",
468
+ "minimal",
469
+ "low",
470
+ "medium",
471
+ "high",
472
+ "xhigh",
473
+ "max"
474
+ ]);
475
+ const DEFAULT_REASONING_EFFORT = "auto";
476
+ const normalizeDefaultReasoningEffort = (value) => DEFAULT_REASONING_EFFORTS.includes(value) ? value : DEFAULT_REASONING_EFFORT;
461
477
  const REASONING_SUMMARY_FIELD = "reasoningSummary";
462
478
  const REASONING_SUMMARIES = Object.freeze([
463
479
  "auto",
@@ -601,6 +617,73 @@ const normalizeQuickQuotaMode = (value, legacyVisible = false) => [
601
617
  ].includes(value) ? value : legacyVisible === true ? QUICK_QUOTA_MODE_PERCENT : "off";
602
618
  const supportsCodexFastMode = (modelId) => typeof modelId === "string" && (/^gpt-5\.(?:5|6)(?:$|-)/u.test(modelId) || modelId === "gpt-5.4" || modelId === "gpt-6-astra");
603
619
  //#endregion
620
+ //#region src/default-reasoning-effort.js
621
+ function modelInfo(info, preference, modelDefault) {
622
+ const efforts = info?.reasoning?.efforts;
623
+ if (!Array.isArray(efforts)) return info;
624
+ const supported = (effort) => efforts.some((value) => value.id === effort);
625
+ const fallback = supported(modelDefault) ? modelDefault : info.reasoning.defaultEffort;
626
+ const selected = preference !== "auto" && supported(preference) ? preference : fallback;
627
+ return supported(selected) ? {
628
+ ...info,
629
+ reasoning: {
630
+ ...info.reasoning,
631
+ defaultEffort: selected
632
+ }
633
+ } : info;
634
+ }
635
+ function withDefaultReasoningEffort(adapter, { provider = "openai-codex", preference, modelDefault } = {}) {
636
+ const snapshot = (model) => ({
637
+ choice: normalizeDefaultReasoningEffort(preference?.()),
638
+ fallback: modelDefault?.(model)
639
+ });
640
+ const optionsFor = (options, info) => options.reasoningEffort !== void 0 || options.provider !== provider || options.model !== info.id || info.reasoning?.defaultEffort === void 0 ? options : {
641
+ ...options,
642
+ reasoningEffort: info.reasoning.defaultEffort
643
+ };
644
+ const prepare = async (target, args, captured) => {
645
+ const call = await target.prepareCall(...args);
646
+ const info = modelInfo(call.model, captured.choice, captured.fallback);
647
+ return {
648
+ ...call,
649
+ model: info,
650
+ stream: (options) => call.stream(optionsFor(options, info))
651
+ };
652
+ };
653
+ return new Proxy(adapter, { get(target, property) {
654
+ const value = Reflect.get(target, property, target);
655
+ if (property === "resolveModel" && typeof value === "function") return async (...args) => {
656
+ if (args[0] !== provider) return value.apply(target, args);
657
+ const captured = snapshot(args[1]);
658
+ return modelInfo(await value.apply(target, args), captured.choice, captured.fallback);
659
+ };
660
+ if (property === "prepareCall" && typeof value === "function") return (...args) => args[0] === provider ? prepare(target, args, snapshot(args[1])) : value.apply(target, args);
661
+ if (property === "stream" && typeof value === "function") return (options) => {
662
+ if (options.provider !== provider) return value.call(target, options);
663
+ const captured = snapshot(options.model);
664
+ return (async function* () {
665
+ let call;
666
+ try {
667
+ if (typeof target.prepareCall === "function") call = await prepare(target, [
668
+ options.provider,
669
+ options.model,
670
+ options.signal
671
+ ], captured);
672
+ else {
673
+ const info = modelInfo(await target.resolveModel(options.provider, options.model, options.signal), captured.choice, captured.fallback);
674
+ call = { stream: (input) => value.call(target, optionsFor(input, info)) };
675
+ }
676
+ } catch {
677
+ yield* value.call(target, options);
678
+ return;
679
+ }
680
+ yield* call.stream(options);
681
+ })();
682
+ };
683
+ return typeof value === "function" ? value.bind(target) : value;
684
+ } });
685
+ }
686
+ //#endregion
604
687
  //#region src/preference-fields.js
605
688
  const PREFERENCE_FIELDS = Object.freeze({
606
689
  compactionMode: {
@@ -617,6 +700,11 @@ const PREFERENCE_FIELDS = Object.freeze({
617
700
  default: "on",
618
701
  error: "Invalid reasoning cache preference"
619
702
  },
703
+ [DEFAULT_REASONING_EFFORT_FIELD]: {
704
+ choices: DEFAULT_REASONING_EFFORTS,
705
+ default: DEFAULT_REASONING_EFFORT,
706
+ error: "Invalid default reasoning effort"
707
+ },
620
708
  connectionMode: {
621
709
  choices: ["sse", "websocket"],
622
710
  default: "sse",
@@ -660,6 +748,11 @@ const PREFERENCE_FIELDS = Object.freeze({
660
748
  default: DEFAULT_SEARCH_PROVIDER,
661
749
  error: "Invalid search provider preference"
662
750
  },
751
+ [FETCH_PROVIDER_FIELD]: {
752
+ choices: ["dsh", FETCH_PROVIDER_CODEX],
753
+ default: "dsh",
754
+ error: "Invalid fetch provider preference"
755
+ },
663
756
  [SPEED_MODE_FIELD]: {
664
757
  choices: [
665
758
  SPEED_MODE_STANDARD,
@@ -739,7 +832,8 @@ const areas$1 = /* @__PURE__ */ new Set([
739
832
  "quota",
740
833
  "quota-reset",
741
834
  "search",
742
- "image"
835
+ "image",
836
+ "voice"
743
837
  ]);
744
838
  const codes$1 = /* @__PURE__ */ new Set([
745
839
  "timeout",
@@ -941,7 +1035,9 @@ async function windowsSystemProxy(options = {}) {
941
1035
  "ProxyEnable"
942
1036
  ], {
943
1037
  windowsHide: true,
944
- encoding: "utf8"
1038
+ encoding: "utf8",
1039
+ timeout: 1e4,
1040
+ signal: options.signal
945
1041
  });
946
1042
  if (!/REG_DWORD\s+0x1\b/iu.test(enabled.stdout)) return void 0;
947
1043
  const configured = await run(reg, [
@@ -951,7 +1047,9 @@ async function windowsSystemProxy(options = {}) {
951
1047
  "ProxyServer"
952
1048
  ], {
953
1049
  windowsHide: true,
954
- encoding: "utf8"
1050
+ encoding: "utf8",
1051
+ timeout: 1e4,
1052
+ signal: options.signal
955
1053
  });
956
1054
  return selectWindowsProxy(/^\s*ProxyServer\s+REG_\w+\s+(.+)$/imu.exec(configured.stdout)?.[1]);
957
1055
  } catch {
@@ -961,7 +1059,11 @@ async function windowsSystemProxy(options = {}) {
961
1059
  async function macSystemProxy(options = {}) {
962
1060
  const run = options.execFile ?? execFileAsync;
963
1061
  try {
964
- const result = await run("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8" });
1062
+ const result = await run("/usr/sbin/scutil", ["--proxy"], {
1063
+ encoding: "utf8",
1064
+ timeout: 1e4,
1065
+ signal: options.signal
1066
+ });
965
1067
  if (!/^\s*HTTPSEnable\s*:\s*1\s*$/imu.test(result.stdout)) return void 0;
966
1068
  const host = /^\s*HTTPSProxy\s*:\s*(\S+)\s*$/imu.exec(result.stdout)?.[1];
967
1069
  const port = /^\s*HTTPSPort\s*:\s*(\d+)\s*$/imu.exec(result.stdout)?.[1];
@@ -1024,7 +1126,7 @@ function fetchThroughProxy(input, init, proxyUrl) {
1024
1126
  const request$1 = request(target, {
1025
1127
  method: init?.method ?? "GET",
1026
1128
  headers: Object.fromEntries(headers.entries()),
1027
- agent: new HttpsProxyAgent(proxyUrl),
1129
+ agent: proxyUrl ? new HttpsProxyAgent(proxyUrl) : void 0,
1028
1130
  signal: init?.signal
1029
1131
  }, (response) => {
1030
1132
  const responseHeaders = new Headers();
@@ -1084,7 +1186,7 @@ async function withCodexNetwork(run, options = {}) {
1084
1186
  }
1085
1187
  const route = await proxy;
1086
1188
  scopedOptions.onRoute?.(route.source);
1087
- const response = await (route.url === void 0 ? fetchBeforeScope(input, init) : proxyFetch(input, init, route.url));
1189
+ const response = await (route.url === void 0 && !scopedOptions.standardHttps ? fetchBeforeScope(input, init) : proxyFetch(input, init, route.url));
1088
1190
  return scopedOptions.transformResponse?.(response, target) ?? response;
1089
1191
  };
1090
1192
  globalThis.fetch = scopedFetch;
@@ -1175,7 +1277,7 @@ function createCodexNetworkTransport(options = {}) {
1175
1277
  return Object.freeze({
1176
1278
  run,
1177
1279
  history: evidence.snapshot,
1178
- fetch: (area, input, init) => run(area, () => globalThis.fetch(input, init)),
1280
+ fetch: (area, input, init, connection) => run(area, () => globalThis.fetch(input, init), connection),
1179
1281
  snapshot: () => Object.fromEntries([...attempts].map(([area, value]) => [area, { ...value }]))
1180
1282
  });
1181
1283
  }
@@ -1261,8 +1363,8 @@ const historyHash = (messages) => hash$1(messages.map(({ source, ...message }) =
1261
1363
  model: source.model
1262
1364
  }
1263
1365
  })));
1264
- const MAX_BYTES = 2 * 1024 * 1024;
1265
- const MAX_AGE_MS = 10080 * 60 * 1e3;
1366
+ const MAX_BYTES$1 = 2 * 1024 * 1024;
1367
+ const MAX_AGE_MS$1 = 10080 * 60 * 1e3;
1266
1368
  function createCompactionBridge({ enabled = () => false, threshold, accountScope, diagnostic = () => {}, now = Date.now }) {
1267
1369
  const scope = new AsyncLocalStorage();
1268
1370
  const stats = {
@@ -1288,7 +1390,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1288
1390
  for (let i = messages.length - 1; i >= 0; i--) {
1289
1391
  const candidate = messages[i].source?.replayState?.response?.[key];
1290
1392
  if (!candidate) continue;
1291
- if (Number.isFinite(candidate.createdAt) && candidate.createdAt <= now() && now() - candidate.createdAt <= MAX_AGE_MS && candidate.scope === state.identity && candidate.prefix === historyHash(messages.slice(0, i)) && candidate.content === hash$1(messages[i].content) && Array.isArray(candidate.items) && candidate.items[0]?.type === "compaction" && typeof candidate.items[0].encrypted_content === "string" && candidate.digest === hash$1(candidate.items) && JSON.stringify(candidate.items).length <= MAX_BYTES) {
1393
+ if (Number.isFinite(candidate.createdAt) && candidate.createdAt <= now() && now() - candidate.createdAt <= MAX_AGE_MS$1 && candidate.scope === state.identity && candidate.prefix === historyHash(messages.slice(0, i)) && candidate.content === hash$1(messages[i].content) && Array.isArray(candidate.items) && candidate.items[0]?.type === "compaction" && typeof candidate.items[0].encrypted_content === "string" && candidate.digest === hash$1(candidate.items) && JSON.stringify(candidate.items).length <= MAX_BYTES$1) {
1292
1394
  state.suffix = clone$2(candidate.items);
1293
1395
  messages = [...messages.slice(0, i + 1).filter((m) => m.role === "system"), ...messages.slice(i + 1)];
1294
1396
  }
@@ -1407,7 +1509,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1407
1509
  if (event.type === "response.output_item.done") {
1408
1510
  if (event.item?.type === "compaction") state.captured = [clone$2(event.item)];
1409
1511
  else if (state.captured) state.captured.push(clone$2(event.item));
1410
- if (state.captured && JSON.stringify(state.captured).length > MAX_BYTES) {
1512
+ if (state.captured && JSON.stringify(state.captured).length > MAX_BYTES$1) {
1411
1513
  state.captured = void 0;
1412
1514
  oversized = true;
1413
1515
  }
@@ -1424,7 +1526,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1424
1526
  observe(buffer.slice(0, index).trimEnd());
1425
1527
  buffer = buffer.slice(index + 1);
1426
1528
  }
1427
- if (buffer.length > MAX_BYTES) {
1529
+ if (buffer.length > MAX_BYTES$1) {
1428
1530
  buffer = "";
1429
1531
  oversized = true;
1430
1532
  state.captured = void 0;
@@ -1634,6 +1736,103 @@ function normalizeTransportEvent(event, signal) {
1634
1736
  };
1635
1737
  }
1636
1738
  //#endregion
1739
+ //#region src/model-retry-hint.js
1740
+ /** Keep the provider's wait as a fact; only DSH decides whether and when to retry. */
1741
+ function providerRetryAfterMs(headers, at = Date.now()) {
1742
+ const read = (key) => typeof headers?.get === "function" ? headers.get(key) : headers?.[key];
1743
+ const millis = read("retry-after-ms");
1744
+ if (millis !== void 0 && millis !== null) {
1745
+ const value = Number(millis);
1746
+ if (Number.isFinite(value)) return value > 0 ? Math.min(value, Number.MAX_SAFE_INTEGER) : void 0;
1747
+ }
1748
+ const raw = read("retry-after");
1749
+ if (typeof raw !== "string" || !raw.trim()) return void 0;
1750
+ const seconds = Number(raw), value = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(raw) - at;
1751
+ return Number.isFinite(value) && value > 0 ? Math.min(value, Number.MAX_SAFE_INTEGER) : void 0;
1752
+ }
1753
+ function createModelRetryHint({ now = Date.now, ErrorClass = dshLlm.LlmError } = {}) {
1754
+ let response, outputStarted = false;
1755
+ return {
1756
+ onResponse(info) {
1757
+ response = [429, 503].includes(info?.status) ? {
1758
+ status: info.status,
1759
+ delay: providerRetryAfterMs(info.headers, now())
1760
+ } : void 0;
1761
+ },
1762
+ observe(event) {
1763
+ if (event && ![
1764
+ "start",
1765
+ "done",
1766
+ "error"
1767
+ ].includes(event.type)) outputStarted = true;
1768
+ },
1769
+ failure(original, signal) {
1770
+ if (signal?.aborted || outputStarted || !response || !original || typeof original.message !== "string" || [
1771
+ "ABORTED",
1772
+ "QUOTA",
1773
+ "ACCOUNT_QUOTA",
1774
+ "QUOTA_EXCEEDED"
1775
+ ].includes(original.code) || typeof dshLlm.isQuotaExceededError === "function" && dshLlm.isQuotaExceededError(original.message)) return original;
1776
+ if (/You have hit your ChatGPT usage limit/iu.test(original.message) || response.status === 429 && original.code !== "RATE_LIMIT") return original;
1777
+ let error;
1778
+ try {
1779
+ error = new ErrorClass(original.message, response.status === 429 ? "RATE_LIMIT" : "SERVER", {
1780
+ status: response.status,
1781
+ ...response.delay === void 0 ? {} : { providerRetryAfterMs: response.delay }
1782
+ });
1783
+ } catch {
1784
+ return original;
1785
+ }
1786
+ return error.failure?.status === response.status && (response.delay === void 0 || error.failure.providerRetryAfterMs === response.delay) ? {
1787
+ ...original,
1788
+ ...error.failure
1789
+ } : original;
1790
+ }
1791
+ };
1792
+ }
1793
+ /** One request-local scope spanning the provider and DSH adapter; no timers or replay. */
1794
+ function createModelRetryBridge() {
1795
+ const scope = new AsyncLocalStorage();
1796
+ const wrapStream = (factory, options) => (async function* () {
1797
+ const hint = createModelRetryHint();
1798
+ const iterator = scope.run(hint, () => factory(options)[Symbol.asyncIterator]());
1799
+ try {
1800
+ while (true) {
1801
+ const result = await scope.run(hint, () => iterator.next());
1802
+ if (result.done) return;
1803
+ const event = result.value;
1804
+ if (event.type === "finish" && event.reason?.kind === "error") yield {
1805
+ ...event,
1806
+ reason: {
1807
+ ...event.reason,
1808
+ failure: hint.failure(event.reason.failure, options.signal)
1809
+ }
1810
+ };
1811
+ else yield event;
1812
+ }
1813
+ } finally {
1814
+ await scope.run(hint, () => iterator.return?.());
1815
+ }
1816
+ })();
1817
+ return {
1818
+ current: () => scope.getStore(),
1819
+ wrapAdapter(adapter) {
1820
+ return new Proxy(adapter, { get(target, property) {
1821
+ if (property === "stream") return (options) => wrapStream((o) => target.stream(o), options);
1822
+ if (property === "prepareCall" && typeof target.prepareCall === "function") return async (...args) => {
1823
+ const call = await target.prepareCall(...args);
1824
+ return {
1825
+ ...call,
1826
+ stream: (options) => wrapStream((o) => call.stream(o), options)
1827
+ };
1828
+ };
1829
+ const value = Reflect.get(target, property, target);
1830
+ return typeof value === "function" ? value.bind(target) : value;
1831
+ } });
1832
+ }
1833
+ };
1834
+ }
1835
+ //#endregion
1637
1836
  //#region src/pi-ai-runtime.js
1638
1837
  const FAST_SERVICE_TIER = "priority";
1639
1838
  const ULTRAFAST_SERVICE_TIER = "ultrafast";
@@ -1705,6 +1904,7 @@ function isDshAutoReview(context) {
1705
1904
  */
1706
1905
  function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, resolveOutputVerbosity = () => OUTPUT_VERBOSITY_DEFAULT, resolveInputImageDetail = () => void 0, resolveReasoningSummary = () => void 0, resolveContextMode = () => void 0, resolveCustomContextWindow = () => void 0, resolveReviewModel = () => REVIEW_MODEL_SESSION, catalog, connection, compaction, reasoning, runNetwork = (_area, operation) => operation() } = {}) {
1707
1906
  const provider = createOpenAICodexProvider();
1907
+ const retryBridge = createModelRetryBridge();
1708
1908
  const requestToken = Object.freeze({
1709
1909
  name: "DSH-managed Codex OAuth request token",
1710
1910
  async resolve({ credential }) {
@@ -1869,6 +2069,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1869
2069
  let iterator;
1870
2070
  let prepared;
1871
2071
  let stage = "prepare";
2072
+ const retryHint = direct ? void 0 : retryBridge.current();
1872
2073
  const step = async (method, value) => {
1873
2074
  try {
1874
2075
  const request = await (prepared ??= (direct ? void 0 : connection?.prepare(options)) ?? Promise.resolve({ options }));
@@ -1877,6 +2078,10 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1877
2078
  const next = direct ? request.options : compaction?.requestOptions(request.options) ?? request.options;
1878
2079
  iterator ??= factory({
1879
2080
  ...next,
2081
+ async onResponse(info, requestModel) {
2082
+ retryHint?.onResponse(info);
2083
+ return next.onResponse?.(info, requestModel);
2084
+ },
1880
2085
  async onPayload(payload, requestModel) {
1881
2086
  stage = "payload";
1882
2087
  return next.onPayload?.(payload, requestModel);
@@ -1888,6 +2093,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1888
2093
  }));
1889
2094
  }, direct ? request.network : compaction?.networkOptions(request.network) ?? request.network);
1890
2095
  if (!result.done) {
2096
+ retryHint?.observe(result.value, request.options?.signal);
1891
2097
  if (result.value?.type === "error" && !request.options?.signal?.aborted) noteStreamFailure(stage, void 0, source);
1892
2098
  else if (stage === "payload") stage = "stream";
1893
2099
  }
@@ -1935,7 +2141,8 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1935
2141
  streamSimple: (model, context, options) => routed("streamSimple", model, context, options),
1936
2142
  reviewCounters: () => ({ ...review }),
1937
2143
  streamFailure: () => ({ ...streamFailure }),
1938
- noteAdapterFailure
2144
+ noteAdapterFailure,
2145
+ wrapRetryAdapter: (adapter) => retryBridge.wrapAdapter(adapter)
1939
2146
  });
1940
2147
  }
1941
2148
  Object.freeze([
@@ -2184,7 +2391,7 @@ function createReasoningBridge({ enabled = () => false, cloud = () => false, unl
2184
2391
  };
2185
2392
  };
2186
2393
  const wrapStream = (factory, options) => (async function* () {
2187
- if (isDshAutoReview(options)) {
2394
+ if (isDshAutoReview(options) || options.purpose === "session-title") {
2188
2395
  yield* unscoped(factory, options);
2189
2396
  return;
2190
2397
  }
@@ -2582,7 +2789,8 @@ const SUPPORTED_RUNTIME_VERSIONS = Object.freeze([
2582
2789
  "0.2.1-alpha.5",
2583
2790
  "0.2.1-rc.1",
2584
2791
  "0.2.1-rc.2",
2585
- "0.2.1-rc.3"
2792
+ "0.2.1-rc.3",
2793
+ "0.2.1-rc.4"
2586
2794
  ]);
2587
2795
  const require = createRequire(import.meta.url);
2588
2796
  const execute = promisify(execFile);
@@ -3392,7 +3600,7 @@ function inheritedOriginalImageRef(session, assetId) {
3392
3600
  }
3393
3601
  //#endregion
3394
3602
  //#region src/version.js
3395
- const PACKAGE_VERSION = "3.1.6";
3603
+ const PACKAGE_VERSION = "3.1.8";
3396
3604
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
3397
3605
  //#endregion
3398
3606
  //#region src/codex-images.js
@@ -4577,6 +4785,7 @@ function enrollment(value) {
4577
4785
  * credentials: (signal?: AbortSignal) => Promise<{ access?: string, accountId?: string }>,
4578
4786
  * fetch?: typeof fetch,
4579
4787
  * WebSocket: new (url: string, options: object) => any,
4788
+ * resolveProxy?: (options: { target: URL, signal: AbortSignal }) => Promise<string | undefined>,
4580
4789
  * installationId: string,
4581
4790
  * hostName: string,
4582
4791
  * userAgent: string,
@@ -4943,22 +5152,53 @@ function createRemoteControlRelay(options) {
4943
5152
  };
4944
5153
  const connectOnce = async (signal) => {
4945
5154
  const current = await ensureEnrollment(signal);
5155
+ if (signal.aborted) return;
5156
+ const proxy = endpoints.websocket.protocol === "wss:" ? await new Promise((resolve, reject) => {
5157
+ const lookup = AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
5158
+ const abort = () => reject(signal.aborted ? signal.reason : new RemoteControlError("timeout", "Proxy resolution timed out"));
5159
+ lookup.addEventListener("abort", abort, { once: true });
5160
+ Promise.resolve().then(() => {
5161
+ lookup.throwIfAborted();
5162
+ return (options.resolveProxy ?? resolveCodexOAuthProxy)({
5163
+ target: endpoints.websocket,
5164
+ signal: lookup
5165
+ });
5166
+ }).then(resolve, reject).finally(() => lookup.removeEventListener("abort", abort));
5167
+ if (lookup.aborted) abort();
5168
+ }) : void 0;
5169
+ if (signal.aborted) return;
4946
5170
  await new Promise((resolve, reject) => {
4947
- const ws = new options.WebSocket(endpoints.websocket.toString(), { headers: {
4948
- authorization: `Bearer ${current.token}`,
4949
- "user-agent": options.userAgent,
4950
- "x-codex-installation-id": installation,
4951
- "x-codex-name": Buffer.from(options.hostName).toString("base64"),
4952
- "x-codex-protocol-version": PROTOCOL_VERSION,
4953
- "x-codex-server-id": current.serverId,
4954
- ...subscribeCursor === void 0 ? {} : { "x-codex-subscribe-cursor": subscribeCursor }
4955
- } });
5171
+ const connecting = new AbortController();
5172
+ const agent = proxy ? new HttpsProxyAgent(proxy, { signal: connecting.signal }) : void 0;
5173
+ const ws = new options.WebSocket(endpoints.websocket.toString(), {
5174
+ handshakeTimeout: REQUEST_TIMEOUT_MS,
5175
+ ...agent ? { agent } : {},
5176
+ headers: {
5177
+ authorization: `Bearer ${current.token}`,
5178
+ "user-agent": options.userAgent,
5179
+ "x-codex-installation-id": installation,
5180
+ "x-codex-name": Buffer.from(options.hostName).toString("base64"),
5181
+ "x-codex-protocol-version": PROTOCOL_VERSION,
5182
+ "x-codex-server-id": current.serverId,
5183
+ ...subscribeCursor === void 0 ? {} : { "x-codex-subscribe-cursor": subscribeCursor }
5184
+ }
5185
+ });
4956
5186
  socket = ws;
4957
5187
  let queue = Promise.resolve();
4958
- const onAbort = () => ws.close();
5188
+ const onAbort = () => {
5189
+ stopBeat();
5190
+ ws.close();
5191
+ };
4959
5192
  signal.addEventListener("abort", onAbort, { once: true });
4960
5193
  let ping;
4961
5194
  let silent;
5195
+ const handshake = setTimeout(() => {
5196
+ stopBeat();
5197
+ try {
5198
+ (ws.terminate ?? ws.close).call(ws);
5199
+ } catch {}
5200
+ reject(new RemoteControlError("timeout", "Remote Control connection timed out"));
5201
+ }, REQUEST_TIMEOUT_MS);
4962
5202
  const hearFrom = () => {
4963
5203
  clearTimeout(silent);
4964
5204
  silent = setTimeout(() => {
@@ -4969,10 +5209,14 @@ function createRemoteControlRelay(options) {
4969
5209
  }, options.pongTimeoutMs ?? PONG_TIMEOUT_MS);
4970
5210
  };
4971
5211
  const stopBeat = () => {
5212
+ clearTimeout(handshake);
4972
5213
  clearInterval(ping);
4973
5214
  clearTimeout(silent);
5215
+ connecting.abort();
5216
+ agent?.destroy();
4974
5217
  };
4975
5218
  ws.on("open", () => {
5219
+ clearTimeout(handshake);
4976
5220
  state.status = "connected";
4977
5221
  state.connectedAt = now();
4978
5222
  state.lastError = void 0;
@@ -5017,6 +5261,7 @@ function createRemoteControlRelay(options) {
5017
5261
  signal.removeEventListener("abort", onAbort);
5018
5262
  resolve();
5019
5263
  });
5264
+ if (signal.aborted) onAbort();
5020
5265
  });
5021
5266
  assemblies.clear();
5022
5267
  socket = void 0;
@@ -5033,6 +5278,7 @@ function createRemoteControlRelay(options) {
5033
5278
  await connectOnce(signal);
5034
5279
  if (state.connectedAt !== void 0 && now() - state.connectedAt >= STABLE_MS) delay = INITIAL_RECONNECT_MS;
5035
5280
  } catch (error) {
5281
+ if (signal.aborted) break;
5036
5282
  asked = error?.retryAfterMs;
5037
5283
  state.lastError = error?.code ?? "network";
5038
5284
  if (options.debug) state.detail = String(error?.message ?? error).slice(0, 160);
@@ -6001,8 +6247,9 @@ function parseEvent(payload) {
6001
6247
  * Ask the ChatGPT backend for a voice call: the browser's WebRTC offer goes in with the session settings, the answer
6002
6248
  * comes back as plain SDP and the call id in the Location header. The same request the phone makes for its own call.
6003
6249
  */
6004
- async function createVoiceCall({ fetch, credentials, userAgent, sdp, session, base = "https://chatgpt.com/backend-api", threadId }) {
6005
- const { access, accountId } = await credentials();
6250
+ async function createVoiceCall({ fetch, credentials, userAgent, sdp, session, base = "https://chatgpt.com/backend-api", threadId, signal }) {
6251
+ signal?.throwIfAborted();
6252
+ const { access, accountId } = await credentials(signal);
6006
6253
  const response = await fetch(`${base}/wham/realtime/calls?intent=quicksilver&architecture=avas`, {
6007
6254
  method: "POST",
6008
6255
  headers: {
@@ -6019,7 +6266,7 @@ async function createVoiceCall({ fetch, credentials, userAgent, sdp, session, ba
6019
6266
  sdp,
6020
6267
  session
6021
6268
  }),
6022
- signal: AbortSignal.timeout(2e4)
6269
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(2e4)]) : AbortSignal.timeout(2e4)
6023
6270
  });
6024
6271
  const answer = await response.text();
6025
6272
  if (!response.ok) throw new Error(`the voice backend refused the call (HTTP ${response.status}): ${answer.slice(0, 200)}${response.status === 403 ? " (if your ChatGPT account has no two-step verification, turn it on in ChatGPT security settings and try again)" : ""}`);
@@ -6062,19 +6309,29 @@ function createRealtimeVoice(options) {
6062
6309
  error() {}
6063
6310
  };
6064
6311
  const sessions = /* @__PURE__ */ new Map();
6065
- const connect = (base, callId, headers) => new Promise((resolve, reject) => {
6312
+ const starts = /* @__PURE__ */ new Map();
6313
+ const connect = (base, callId, headers, signal) => new Promise((resolve, reject) => {
6314
+ signal?.throwIfAborted();
6066
6315
  const url = `${base.replace(/\/$/, "")}/${encodeURIComponent(callId)}`;
6067
6316
  const ws = new options.WebSocket(url, { headers });
6068
6317
  let settled = false;
6318
+ const abort = () => {
6319
+ fail(/* @__PURE__ */ new Error("Voice start cancelled"));
6320
+ try {
6321
+ ws.close();
6322
+ } catch {}
6323
+ };
6069
6324
  const fail = (error) => {
6070
6325
  if (!settled) {
6071
6326
  settled = true;
6327
+ signal?.removeEventListener("abort", abort);
6072
6328
  reject(error);
6073
6329
  }
6074
6330
  };
6075
6331
  ws.on("open", () => {
6076
6332
  if (!settled) {
6077
6333
  settled = true;
6334
+ signal?.removeEventListener("abort", abort);
6078
6335
  resolve(ws);
6079
6336
  }
6080
6337
  });
@@ -6088,16 +6345,19 @@ function createRealtimeVoice(options) {
6088
6345
  });
6089
6346
  ws.on("error", (error) => fail(error));
6090
6347
  ws.on("close", () => fail(/* @__PURE__ */ new Error("closed before it opened")));
6348
+ signal?.addEventListener("abort", abort, { once: true });
6091
6349
  });
6092
- async function join(callId, headers) {
6350
+ async function join(callId, headers, signal) {
6093
6351
  let last;
6094
6352
  for (const base of bases) {
6095
6353
  const host = new URL(base).host;
6096
6354
  for (let attempt = 0; attempt <= ACTIVATION_RETRY_MS.length; attempt++) try {
6097
- const ws = await connect(base, callId, headers);
6355
+ signal?.throwIfAborted();
6356
+ const ws = await connect(base, callId, headers, signal);
6098
6357
  log.info("voice", `joined the voice call on ${host}`);
6099
6358
  return ws;
6100
6359
  } catch (error) {
6360
+ signal?.throwIfAborted();
6101
6361
  last = error;
6102
6362
  if (error?.status === 404 && attempt < ACTIVATION_RETRY_MS.length) {
6103
6363
  await new Promise((resolve) => setTimeout(resolve, ACTIVATION_RETRY_MS[attempt]));
@@ -6116,8 +6376,11 @@ function createRealtimeVoice(options) {
6116
6376
  session.chain = session.chain.then(save).catch((error) => log.warn("voice", "could not save the voice transcript to the conversation", String(error?.message ?? error)));
6117
6377
  };
6118
6378
  const stop = (threadId, reason = "requested") => {
6379
+ const pending = starts.get(threadId);
6380
+ starts.delete(threadId);
6381
+ pending?.abort();
6119
6382
  const session = sessions.get(threadId);
6120
- if (!session) return false;
6383
+ if (!session) return pending !== void 0;
6121
6384
  sessions.delete(threadId);
6122
6385
  session.ended = true;
6123
6386
  log.info("voice", "the voice call ended", reason);
@@ -6138,21 +6401,48 @@ function createRealtimeVoice(options) {
6138
6401
  }).catch(() => {});
6139
6402
  return true;
6140
6403
  };
6141
- async function start(params, notify) {
6404
+ async function start(params, notify, { signal } = {}) {
6142
6405
  const threadId = typeof params?.threadId === "string" ? params.threadId : "";
6143
6406
  const callId = params?.transport?.type === "existingCall" ? params.transport.callId : void 0;
6144
6407
  if (threadId === "") throw new Error("The voice start has no thread");
6145
6408
  if (typeof callId !== "string" || callId === "") throw new Error("Live voice needs a call the phone has already set up");
6146
6409
  stop(threadId, "replaced");
6147
- const { access, accountId } = await options.credentials();
6148
- const ws = await join(callId, {
6410
+ const pending = new AbortController();
6411
+ starts.set(threadId, pending);
6412
+ const lifetime = signal ? AbortSignal.any([signal, pending.signal]) : pending.signal;
6413
+ let credential, ws;
6414
+ try {
6415
+ lifetime.throwIfAborted();
6416
+ credential = await options.credentials(lifetime);
6417
+ lifetime.throwIfAborted();
6418
+ } catch (error) {
6419
+ if (starts.get(threadId) === pending) starts.delete(threadId);
6420
+ throw error;
6421
+ }
6422
+ const { access, accountId } = credential;
6423
+ const headers = {
6149
6424
  authorization: `Bearer ${access}`,
6150
6425
  "chatgpt-account-id": accountId,
6151
6426
  "openai-alpha": "quicksilver=v2",
6152
6427
  "user-agent": options.userAgent,
6153
6428
  ...typeof params.realtimeSessionId === "string" ? { "x-session-id": params.realtimeSessionId } : {},
6154
6429
  ...typeof params.voiceSessionId === "string" ? { "voice-session-id": params.voiceSessionId } : {}
6155
- });
6430
+ };
6431
+ try {
6432
+ ws = await join(callId, headers, lifetime);
6433
+ lifetime.throwIfAborted();
6434
+ } catch (error) {
6435
+ if (starts.get(threadId) === pending) starts.delete(threadId);
6436
+ try {
6437
+ ws?.close();
6438
+ } catch {}
6439
+ throw error;
6440
+ }
6441
+ if (starts.get(threadId) !== pending) {
6442
+ ws.close();
6443
+ throw new Error("Voice start replaced");
6444
+ }
6445
+ starts.delete(threadId);
6156
6446
  const session = {
6157
6447
  ws,
6158
6448
  notify,
@@ -6377,7 +6667,7 @@ function createRealtimeVoice(options) {
6377
6667
  };
6378
6668
  },
6379
6669
  closeAll: () => {
6380
- for (const threadId of [...sessions.keys()]) stop(threadId, "shutdown");
6670
+ for (const threadId of /* @__PURE__ */ new Set([...sessions.keys(), ...starts.keys()])) stop(threadId, "shutdown");
6381
6671
  }
6382
6672
  };
6383
6673
  }
@@ -6952,6 +7242,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6952
7242
  const threadSources = /* @__PURE__ */ new Map();
6953
7243
  const active = /* @__PURE__ */ new Map();
6954
7244
  const queues = /* @__PURE__ */ new Map();
7245
+ const starting = /* @__PURE__ */ new Map();
6955
7246
  let catalog;
6956
7247
  const service = () => {
6957
7248
  const value = controller();
@@ -7079,18 +7370,18 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7079
7370
  const values = projections()?.snapshot?.(session, ["tokenUsage", "contextPressure"])?.values;
7080
7371
  const used = values?.tokenUsage;
7081
7372
  if (!used) return void 0;
7082
- const breakdown = (total, input, cached, output) => ({
7373
+ const breakdown = (total, input, cached, output, written = 0) => ({
7083
7374
  totalTokens: total,
7084
7375
  inputTokens: input,
7085
7376
  cachedInputTokens: cached,
7086
- cacheWriteInputTokens: 0,
7377
+ cacheWriteInputTokens: written,
7087
7378
  outputTokens: output,
7088
7379
  reasoningOutputTokens: 0
7089
7380
  });
7090
7381
  const input = (used.uncachedInputTokens ?? 0) + (used.cacheReadTokens ?? 0) + (used.cacheWriteTokens ?? 0);
7091
7382
  const pressure = values.contextPressure?.pressureTokens ?? 0;
7092
7383
  return {
7093
- total: breakdown(input + (used.outputTokens ?? 0), input, used.cacheReadTokens ?? 0, used.outputTokens ?? 0),
7384
+ total: breakdown(input + (used.outputTokens ?? 0), input, used.cacheReadTokens ?? 0, used.outputTokens ?? 0, used.cacheWriteTokens ?? 0),
7094
7385
  last: breakdown(pressure, pressure, 0, 0),
7095
7386
  modelContextWindow: values.contextPressure?.contextWindow ?? null
7096
7387
  };
@@ -7441,7 +7732,35 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7441
7732
  }], ...images]
7442
7733
  };
7443
7734
  };
7444
- async function startTurn(params, notify) {
7735
+ async function startTurn(params, notify, queued) {
7736
+ const id = params?.threadId;
7737
+ if (active.has(id) || starting.has(id)) throw invalidParams("A turn is already running in this conversation");
7738
+ const launch = {
7739
+ queued,
7740
+ submitted: false,
7741
+ abort: new AbortController()
7742
+ };
7743
+ starting.set(id, launch);
7744
+ try {
7745
+ return await acceptTurn(params, notify, launch);
7746
+ } catch (error) {
7747
+ if (launch.abort.signal.aborted && error?.name === "AbortError") throw new RpcError(-32800, "Turn start cancelled");
7748
+ throw error;
7749
+ } finally {
7750
+ if (starting.get(id) === launch) starting.delete(id);
7751
+ }
7752
+ }
7753
+ async function startQueuedTurn(id, notify, queuedId, selection = {}) {
7754
+ const queued = (queues.get(id) ?? []).find((entry) => queuedId == null || entry.id === queuedId);
7755
+ if (!queued) throw invalidParams("Nothing queued");
7756
+ return startTurn({
7757
+ ...selection,
7758
+ threadId: id,
7759
+ input: queued.input,
7760
+ clientUserMessageId: queued.clientUserMessageId
7761
+ }, notify, queued);
7762
+ }
7763
+ async function acceptTurn(params, notify, launch) {
7445
7764
  const { text, pictures, content } = contentOf(params?.input);
7446
7765
  lastPrompt.text = text;
7447
7766
  const id = params?.threadId;
@@ -7452,7 +7771,18 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7452
7771
  applyPermissions(agent, params);
7453
7772
  const speedBefore = speed?.current?.();
7454
7773
  const speedForTurn = typeof params?.serviceTierForTurn === "string" ? params.serviceTierForTurn : void 0;
7455
- await applySpeed(speedForTurn ?? (Object.hasOwn(params ?? {}, "serviceTier") ? params.serviceTier : void 0));
7774
+ const restoreSpeed = async () => {
7775
+ if (speedForTurn !== void 0 && speedBefore !== void 0 && speed?.current?.() !== speedBefore) await Promise.resolve(speed.set?.(speedBefore)).catch(() => {});
7776
+ };
7777
+ try {
7778
+ await applySpeed(speedForTurn ?? (Object.hasOwn(params ?? {}, "serviceTier") ? params.serviceTier : void 0));
7779
+ launch.abort.signal.throwIfAborted();
7780
+ if (active.has(id)) throw invalidParams("A turn is already running in this conversation");
7781
+ if (launch.queued && !(queues.get(id) ?? []).includes(launch.queued)) throw invalidParams("Queued submission was deleted before starting");
7782
+ } catch (error) {
7783
+ await restoreSpeed();
7784
+ throw error;
7785
+ }
7456
7786
  const turn = emptyTurn();
7457
7787
  const userItem = {
7458
7788
  type: "userMessage",
@@ -7473,7 +7803,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7473
7803
  userItem,
7474
7804
  priorMessageIds: new Set(agent.session.deriveMessages().map((message) => message.id)),
7475
7805
  pendingImages: /* @__PURE__ */ new Set(),
7476
- abort: new AbortController()
7806
+ pendingSteers: /* @__PURE__ */ new Set(),
7807
+ abort: launch.abort
7477
7808
  };
7478
7809
  active.set(id, running);
7479
7810
  phoneLog("turn accepted", {
@@ -7508,25 +7839,61 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7508
7839
  completedAtMs: Date.now()
7509
7840
  });
7510
7841
  try {
7511
- await service().prompt({
7512
- requestId: randomUUID(),
7842
+ launch.submitted = true;
7843
+ if ((await service().prompt({
7844
+ requestId: launch.queued?.id ?? randomUUID(),
7513
7845
  sessionId: id,
7514
7846
  mode: "queue",
7515
7847
  content
7516
- }, AbortSignal.timeout(3e4));
7848
+ }, AbortSignal.any([running.abort.signal, AbortSignal.timeout(3e4)])))?.accepted === false) throw new Error("DSH rejected the message");
7517
7849
  } catch (error) {
7518
- active.delete(id);
7850
+ if (active.get(id) === running) active.delete(id);
7851
+ const cancelled = running.abort.signal.aborted;
7852
+ turn.status = cancelled ? "interrupted" : "failed";
7853
+ turn.completedAt = seconds(Date.now());
7854
+ turn.error = cancelled ? null : {
7855
+ message: "DSH did not accept the message",
7856
+ codexErrorInfo: null,
7857
+ additionalDetails: null
7858
+ };
7859
+ running.abort.abort();
7860
+ emit(id, "turn/completed", {
7861
+ threadId: id,
7862
+ turn
7863
+ });
7864
+ emit(id, "thread/status/changed", {
7865
+ threadId: id,
7866
+ status: { type: "idle" }
7867
+ });
7868
+ await restoreSpeed();
7869
+ if (cancelled) throw new RpcError(-32800, "Turn start cancelled");
7519
7870
  throw new RpcError(-32603, error?.message ? `DSH did not accept the message: ${String(error.message).slice(0, 200)}` : "DSH did not accept the message");
7520
7871
  }
7872
+ if (launch.queued) {
7873
+ queues.set(id, (queues.get(id) ?? []).filter((entry) => entry.id !== launch.queued.id));
7874
+ emit(id, "thread/queue/changed", { threadId: id });
7875
+ }
7876
+ if (running.abort.signal.aborted) {
7877
+ running.ended ??= { kind: "aborted" };
7878
+ await Promise.resolve(service().cancel({ sessionId: id })).catch(() => {});
7879
+ }
7880
+ if (starting.get(id) === launch) starting.delete(id);
7521
7881
  Promise.resolve(agent.whenIdle?.()).catch(() => {}).then(async () => {
7882
+ running.finishing = true;
7883
+ const pendingSteers = [...running.pendingSteers];
7884
+ if (pendingSteers.length) {
7885
+ await Promise.allSettled(pendingSteers);
7886
+ await Promise.resolve(agent.whenIdle?.()).catch(() => {});
7887
+ }
7522
7888
  if (running.pendingImages.size) phoneLog("waiting for tool images", {
7523
7889
  threadId: id,
7524
7890
  turnId: turn.id,
7525
7891
  pending: running.pendingImages.size
7526
7892
  });
7527
7893
  await Promise.allSettled([...running.pendingImages]);
7894
+ if (active.get(id) !== running) return;
7528
7895
  turn.items = withRemoteImageOutput(turn).items;
7529
- const reason = active.get(id)?.ended;
7896
+ const reason = running.ended;
7530
7897
  turn.status = reason?.kind === "error" ? "failed" : reason?.kind === "aborted" || reason?.kind === "interrupted" ? "interrupted" : "completed";
7531
7898
  if (reason?.kind === "error") {
7532
7899
  const message = String(reason.error?.message ?? reason.error?.code ?? "The model request failed").slice(0, 500);
@@ -7548,6 +7915,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7548
7915
  for (const message of agent.session.deriveMessages()) reconcileUser(id, running, message);
7549
7916
  } catch {}
7550
7917
  active.delete(id);
7918
+ running.abort.abort();
7551
7919
  compactions.delete(id);
7552
7920
  const usageNow = tokenUsage(agent.session);
7553
7921
  if (usageNow) emit(id, "thread/tokenUsage/updated", {
@@ -7569,16 +7937,10 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7569
7937
  threadId: id,
7570
7938
  status: { type: "idle" }
7571
7939
  });
7572
- const [next, ...rest] = queues.get(id) ?? [];
7573
- if (next) {
7574
- queues.set(id, rest);
7575
- emit(id, "thread/queue/changed", { threadId: id });
7576
- startTurn({
7577
- threadId: id,
7578
- input: next.input,
7579
- clientUserMessageId: next.clientUserMessageId
7580
- }, notify).catch(() => {});
7581
- }
7940
+ if (queues.get(id)?.length) startQueuedTurn(id, notify).catch((error) => phoneLog("queued turn not accepted", {
7941
+ threadId: id,
7942
+ code: error?.code
7943
+ }, "warn"));
7582
7944
  });
7583
7945
  return { turn: {
7584
7946
  ...turn,
@@ -8073,8 +8435,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8073
8435
  },
8074
8436
  "turn/start": (params, { notify }) => titles.has(params?.threadId) ? titleTurn(params, notify) : startTurn(params, notify),
8075
8437
  "turn/interrupt": (params) => {
8076
- service().cancel({ sessionId: params?.threadId });
8077
8438
  active.get(params?.threadId)?.abort?.abort();
8439
+ starting.get(params?.threadId)?.abort.abort();
8440
+ service().cancel({ sessionId: params?.threadId });
8078
8441
  return {};
8079
8442
  },
8080
8443
  "thread/compact/start": async (params, { notify }) => {
@@ -8082,7 +8445,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8082
8445
  const registry = commands();
8083
8446
  const agent = await agentFor(id);
8084
8447
  if (typeof registry?.execute !== "function" || registry.find?.(agent, "compact") === void 0) throw new RpcError(-32601, "This DSH version cannot compact a conversation on request");
8085
- if (active.has(id)) throw new RpcError(-32602, "A turn is already running in this conversation");
8448
+ if (active.has(id) || starting.has(id)) throw new RpcError(-32602, "A turn is already running in this conversation");
8086
8449
  subscribe(id, notify);
8087
8450
  const turn = emptyTurn();
8088
8451
  const abort = new AbortController();
@@ -8162,15 +8525,34 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8162
8525
  })();
8163
8526
  return {};
8164
8527
  },
8165
- "turn/steer": async (params) => {
8528
+ "turn/steer": async (params, { signal } = {}) => {
8529
+ const running = active.get(params?.threadId);
8530
+ const current = () => running && active.get(params?.threadId) === running && running.userItem && !running.finishing && !running.ended && !running.abort.signal.aborted && !starting.has(params?.threadId) && params?.expectedTurnId === running.turn.id;
8531
+ signal?.throwIfAborted();
8532
+ if (!current()) throw invalidParams("The expected turn is not active");
8166
8533
  const { content } = contentOf(params?.input);
8167
- await service().prompt({
8168
- requestId: randomUUID(),
8169
- sessionId: params?.threadId,
8170
- mode: "steer",
8171
- content
8172
- }, AbortSignal.timeout(3e4));
8173
- return { turnId: params?.expectedTurnId ?? active.get(params?.threadId)?.turn.id ?? "" };
8534
+ const operation = (async () => {
8535
+ if ((await service().prompt({
8536
+ requestId: randomUUID(),
8537
+ sessionId: params.threadId,
8538
+ mode: "steer",
8539
+ content
8540
+ }, AbortSignal.any([
8541
+ running.abort.signal,
8542
+ AbortSignal.timeout(3e4),
8543
+ ...signal ? [signal] : []
8544
+ ])))?.accepted === false) throw invalidParams("DSH rejected the steering message");
8545
+ if (!current()) {
8546
+ if (active.get(params.threadId) === running) await Promise.resolve(service().cancel({ sessionId: params.threadId })).catch(() => {});
8547
+ }
8548
+ return { turnId: running.turn.id };
8549
+ })();
8550
+ running.pendingSteers.add(operation);
8551
+ try {
8552
+ return await operation;
8553
+ } finally {
8554
+ running.pendingSteers.delete(operation);
8555
+ }
8174
8556
  },
8175
8557
  "thread/name/set": async (params) => {
8176
8558
  await service().rename({
@@ -8189,6 +8571,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8189
8571
  }),
8190
8572
  "thread/queue/add": async (params, { notify }) => {
8191
8573
  if (!Array.isArray(params?.input)) throw invalidParams("input is required");
8574
+ contentOf(params.input);
8192
8575
  const id = params?.threadId;
8193
8576
  const queued = {
8194
8577
  id: randomUUID(),
@@ -8196,20 +8579,17 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8196
8579
  input: params.input
8197
8580
  };
8198
8581
  subscribe(id, notify);
8199
- if (!active.has(id)) await startTurn({
8200
- threadId: id,
8201
- input: queued.input,
8202
- clientUserMessageId: queued.clientUserMessageId,
8582
+ queues.set(id, [...queues.get(id) ?? [], queued]);
8583
+ emit(id, "thread/queue/changed", { threadId: id });
8584
+ if (!active.has(id) && !starting.has(id)) await startQueuedTurn(id, notify, queued.id, {
8203
8585
  model: params.model,
8204
8586
  effort: params.effort
8205
- }, notify);
8206
- else {
8207
- queues.set(id, [...queues.get(id) ?? [], queued]);
8208
- emit(id, "thread/queue/changed", { threadId: id });
8209
- }
8587
+ });
8210
8588
  return { queuedSubmission: queued };
8211
8589
  },
8212
8590
  "thread/queue/delete": (params) => {
8591
+ const launch = starting.get(params?.threadId);
8592
+ if (launch?.submitted && launch.queued?.id === params?.queuedSubmissionId) throw invalidParams("Queued submission is being accepted");
8213
8593
  const list = queues.get(params?.threadId) ?? [];
8214
8594
  const next = list.filter((entry) => entry.id !== params?.queuedSubmissionId);
8215
8595
  queues.set(params?.threadId, next);
@@ -8217,24 +8597,13 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8217
8597
  return { deleted: next.length !== list.length };
8218
8598
  },
8219
8599
  "thread/queue/reorder": (params) => {
8220
- const order = Array.isArray(params?.queuedSubmissionIds) ? params.queuedSubmissionIds : [];
8600
+ const order = Array.isArray(params?.queuedSubmissionIds) ? [...new Set(params.queuedSubmissionIds)] : [];
8221
8601
  const list = queues.get(params?.threadId) ?? [];
8222
8602
  queues.set(params?.threadId, [...order.map((id) => list.find((entry) => entry.id === id)).filter(Boolean), ...list.filter((entry) => !order.includes(entry.id))]);
8223
8603
  emit(params?.threadId, "thread/queue/changed", { threadId: params?.threadId });
8224
8604
  return {};
8225
8605
  },
8226
- "thread/queue/start": async (params, { notify }) => {
8227
- const list = queues.get(params?.threadId) ?? [];
8228
- const queued = list.find((entry) => params?.queuedSubmissionId == null || entry.id === params.queuedSubmissionId);
8229
- if (!queued) throw invalidParams("Nothing queued");
8230
- queues.set(params.threadId, list.filter((entry) => entry !== queued));
8231
- emit(params.threadId, "thread/queue/changed", { threadId: params.threadId });
8232
- return startTurn({
8233
- threadId: params.threadId,
8234
- input: queued.input,
8235
- clientUserMessageId: queued.clientUserMessageId
8236
- }, notify);
8237
- }
8606
+ "thread/queue/start": (params, { notify }) => startQueuedTurn(params?.threadId, notify, params?.queuedSubmissionId)
8238
8607
  };
8239
8608
  const callOf = (session, callId) => {
8240
8609
  for (const message of session.deriveMessages().toReversed()) {
@@ -8632,40 +9001,43 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8632
9001
  if (!set.has(notify)) subscribe(threadId, notify);
8633
9002
  }
8634
9003
  };
9004
+ const startDesktopVoice = async ({ sessionId, sdp, voice: voiceName, language, signal }) => {
9005
+ if (typeof sdp !== "string" || !sdp.startsWith("v=0") || sdp.length > 64 * 1024) throw new RpcError(-32602, "Invalid voice offer");
9006
+ const agent = await agentFor(sessionId);
9007
+ diagnosticLog.info("voice", "the conversation can take a context note", String(typeof agent.inject === "function"));
9008
+ const session = {
9009
+ audio: { output: { voice: typeof voiceName === "string" && /^[a-z]{2,16}$/u.test(voiceName) ? voiceName : "cove" } },
9010
+ delegation: { type: "client" },
9011
+ instructions: desktopInstructions(language),
9012
+ model: "gpt-live-1.1-codex"
9013
+ };
9014
+ const { callId, answer } = await createVoiceCall({
9015
+ fetch: voice.fetch,
9016
+ credentials: voice.credentials,
9017
+ userAgent,
9018
+ sdp,
9019
+ session,
9020
+ threadId: sessionId,
9021
+ signal
9022
+ });
9023
+ signal?.throwIfAborted();
9024
+ await realtimeVoice.start({
9025
+ threadId: sessionId,
9026
+ transport: {
9027
+ type: "existingCall",
9028
+ callId
9029
+ },
9030
+ flushTranscriptTailOnSessionEnd: true,
9031
+ silentTailRecord: true,
9032
+ hangUpOnGoodbye: true,
9033
+ version: "v3"
9034
+ }, async () => {}, { signal });
9035
+ return { answer };
9036
+ };
8635
9037
  return {
8636
9038
  methods,
8637
9039
  desktopVoice: realtimeVoice === void 0 ? void 0 : Object.freeze({
8638
- async start({ sessionId, sdp, voice: voiceName, language }) {
8639
- if (typeof sdp !== "string" || !sdp.startsWith("v=0") || sdp.length > 64 * 1024) throw new RpcError(-32602, "Invalid voice offer");
8640
- const agent = await agentFor(sessionId);
8641
- diagnosticLog.info("voice", "the conversation can take a context note", String(typeof agent.inject === "function"));
8642
- const session = {
8643
- audio: { output: { voice: typeof voiceName === "string" && /^[a-z]{2,16}$/u.test(voiceName) ? voiceName : "cove" } },
8644
- delegation: { type: "client" },
8645
- instructions: desktopInstructions(language),
8646
- model: "gpt-live-1.1-codex"
8647
- };
8648
- const { callId, answer } = await createVoiceCall({
8649
- fetch: voice.fetch,
8650
- credentials: voice.credentials,
8651
- userAgent,
8652
- sdp,
8653
- session,
8654
- threadId: sessionId
8655
- });
8656
- await realtimeVoice.start({
8657
- threadId: sessionId,
8658
- transport: {
8659
- type: "existingCall",
8660
- callId
8661
- },
8662
- flushTranscriptTailOnSessionEnd: true,
8663
- silentTailRecord: true,
8664
- hangUpOnGoodbye: true,
8665
- version: "v3"
8666
- }, async () => {});
8667
- return { answer };
8668
- },
9040
+ start: startDesktopVoice,
8669
9041
  stop: (sessionId) => realtimeVoice.stop(sessionId),
8670
9042
  interrupt: (sessionId) => realtimeVoice.interrupt(sessionId),
8671
9043
  end: (sessionId) => realtimeVoice.requestClose(sessionId),
@@ -8676,6 +9048,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8676
9048
  onApproval,
8677
9049
  onQuestion,
8678
9050
  adopt,
9051
+ close() {
9052
+ realtimeVoice?.closeAll();
9053
+ },
8679
9054
  forget: (notify) => {
8680
9055
  for (const set of subscribers.values()) set.delete(notify);
8681
9056
  }
@@ -9855,6 +10230,110 @@ function createCodexRpcHandler(coordinator, options = {}) {
9855
10230
  };
9856
10231
  }
9857
10232
  //#endregion
10233
+ //#region src/model-catalog-cache.js
10234
+ const SCHEMA_VERSION = 1;
10235
+ const MAX_AGE_MS = 1440 * 60 * 1e3;
10236
+ const MAX_BYTES = 4 * 1024 * 1024;
10237
+ /**
10238
+ * 按账号身份读取并校验本地模型目录缓存。
10239
+ * @param {string} accountId - 当前 OAuth 账号标识
10240
+ * @param {{ directory?: string, now?: number, parseCatalog: Function }} options - 缓存目录与目录校验方法
10241
+ * @returns {Promise<{ rawCatalog: object, etag?: string } | undefined>} 有效目录缓存;缺失或无效时返回 undefined
10242
+ */
10243
+ async function loadModelCatalogCache(accountId, options) {
10244
+ const { accountKey, filename } = cacheLocation(accountId, options.directory);
10245
+ let entry;
10246
+ try {
10247
+ options.signal?.throwIfAborted();
10248
+ if ((await stat(filename)).size > MAX_BYTES) return void 0;
10249
+ entry = JSON.parse(await readFile(filename, {
10250
+ encoding: "utf8",
10251
+ signal: options.signal
10252
+ }));
10253
+ } catch (error) {
10254
+ if (error?.code === "ENOENT" || error instanceof SyntaxError) return void 0;
10255
+ throw error;
10256
+ }
10257
+ const now = options.now ?? Date.now();
10258
+ if (!Number.isSafeInteger(now) || now <= 0 || !isRecord(entry) || entry.schemaVersion !== SCHEMA_VERSION || entry.accountKey !== accountKey || !Number.isSafeInteger(entry.savedAt) || entry.savedAt <= 0 || entry.savedAt > now || now - entry.savedAt > MAX_AGE_MS || entry.etag !== void 0 && typeof entry.etag !== "string") return void 0;
10259
+ try {
10260
+ const parsed = options.parseCatalog(entry.rawCatalog, now);
10261
+ if (!Array.isArray(parsed) || parsed.length === 0) return void 0;
10262
+ } catch {
10263
+ return;
10264
+ }
10265
+ return {
10266
+ rawCatalog: entry.rawCatalog,
10267
+ ...entry.etag === void 0 ? {} : { etag: entry.etag }
10268
+ };
10269
+ }
10270
+ /**
10271
+ * 将经过目录校验的原始账号目录以原子替换方式保存。
10272
+ * @param {string} accountId - 当前 OAuth 账号标识
10273
+ * @param {{ rawCatalog: object, etag?: string }} catalog - 远端返回的完整目录和 ETag
10274
+ * @param {{ directory?: string, now?: number, parseCatalog: Function, isCurrent?: () => boolean }} options - 缓存目录、目录校验方法和写入状态检查
10275
+ * @returns {Promise<void>} 缓存写入完成
10276
+ */
10277
+ async function saveModelCatalogCache(accountId, catalog, options) {
10278
+ options.signal?.throwIfAborted();
10279
+ const { accountKey, filename } = cacheLocation(accountId, options.directory);
10280
+ const now = options.now ?? Date.now();
10281
+ if (!isRecord(catalog) || !isRecord(catalog.rawCatalog) || !Number.isSafeInteger(now) || now <= 0 || catalog.etag !== void 0 && typeof catalog.etag !== "string") throw new Error("Refusing to persist malformed model catalog cache");
10282
+ const parsed = options.parseCatalog(catalog.rawCatalog, now);
10283
+ if (!Array.isArray(parsed) || parsed.length === 0) throw new Error("Refusing to persist an empty model catalog cache");
10284
+ const data = `${JSON.stringify({
10285
+ schemaVersion: SCHEMA_VERSION,
10286
+ accountKey,
10287
+ savedAt: now,
10288
+ ...catalog.etag === void 0 ? {} : { etag: catalog.etag },
10289
+ rawCatalog: catalog.rawCatalog
10290
+ })}\n`;
10291
+ if (Buffer.byteLength(data) > MAX_BYTES) throw new Error("Model catalog cache exceeds its size limit");
10292
+ if (options.isCurrent?.() === false) return;
10293
+ await mkdir(dirname(filename), {
10294
+ recursive: true,
10295
+ mode: 448
10296
+ });
10297
+ const temporary = `${filename}.${process.pid}.${randomUUID()}.tmp`;
10298
+ let handle;
10299
+ try {
10300
+ handle = await open(temporary, "wx", 384);
10301
+ options.signal?.throwIfAborted();
10302
+ await handle.writeFile(data, { signal: options.signal });
10303
+ await handle.sync();
10304
+ await handle.close();
10305
+ handle = void 0;
10306
+ options.signal?.throwIfAborted();
10307
+ if (options.isCurrent !== void 0 && !options.isCurrent()) return;
10308
+ await rename(temporary, filename);
10309
+ } finally {
10310
+ await handle?.close().catch(() => void 0);
10311
+ await rm(temporary, { force: true }).catch(() => void 0);
10312
+ }
10313
+ }
10314
+ /**
10315
+ * 根据账号标识生成只含摘要的缓存路径。
10316
+ * @param {string} accountId - OAuth 账号标识
10317
+ * @param {string | undefined} directory - 可选缓存目录
10318
+ * @returns {{ accountKey: string, filename: string }} 账号摘要和缓存文件路径
10319
+ */
10320
+ function cacheLocation(accountId, directory) {
10321
+ if (typeof accountId !== "string" || accountId.length === 0) throw new Error("A current account is required for the model catalog cache");
10322
+ const accountKey = createHash("sha256").update(accountId).digest("hex");
10323
+ return {
10324
+ accountKey,
10325
+ filename: join(directory ?? dshHomePath("state", "codex-subscription", "model-catalog"), `${accountKey}.json`)
10326
+ };
10327
+ }
10328
+ /**
10329
+ * 判断值是否为普通记录。
10330
+ * @param {unknown} value - 待检查的值
10331
+ * @returns {boolean} 值是否为普通记录
10332
+ */
10333
+ function isRecord(value) {
10334
+ return value !== null && typeof value === "object" && !Array.isArray(value);
10335
+ }
10336
+ //#endregion
9858
10337
  //#region src/model-catalog.js
9859
10338
  const CODEX_MODELS_URL = `https://chatgpt.com/backend-api/codex/models?client_version=${encodeURIComponent(PACKAGE_VERSION)}`;
9860
10339
  const LEVELS = [
@@ -9957,6 +10436,9 @@ function visibleModel(value, displayNames, now) {
9957
10436
  const reserve = id === "gpt-reserve" && ["list", "hide"].includes(value.visibility);
9958
10437
  if (id === void 0 || value.visibility !== "list" && !reserve) return void 0;
9959
10438
  const supported = Array.isArray(value.supported_reasoning_levels) ? value.supported_reasoning_levels : [];
10439
+ const thinkingLevelMap = reasoningMap(supported);
10440
+ const defaultEffort = value.default_reasoning_level === "none" ? "off" : value.default_reasoning_level;
10441
+ const defaultReasoningEffort = LEVELS.includes(defaultEffort) && thinkingLevelMap[defaultEffort] != null ? defaultEffort : void 0;
9960
10442
  const input = Array.isArray(value.input_modalities) ? value.input_modalities.filter((item) => ["text", "image"].includes(item)) : ["text", "image"];
9961
10443
  const unsupported = unsupportedCapabilities({
9962
10444
  ...value,
@@ -9981,7 +10463,8 @@ function visibleModel(value, displayNames, now) {
9981
10463
  ...positiveInteger(value.max_context_window) === void 0 ? {} : { maxContextWindow: value.max_context_window },
9982
10464
  reasoning: supported.length > 0,
9983
10465
  supportsReasoningEffortUpdates: value.supports_reasoning_effort_updates === true,
9984
- thinkingLevelMap: reasoningMap(supported),
10466
+ thinkingLevelMap,
10467
+ ...defaultReasoningEffort === void 0 ? {} : { defaultReasoningEffort },
9985
10468
  supportVerbosity: value.support_verbosity === true,
9986
10469
  defaultVerbosity: [
9987
10470
  "low",
@@ -10034,6 +10517,7 @@ function mergeModel(baseModels, remote) {
10034
10517
  reasoning: remote.reasoning,
10035
10518
  supportsReasoningEffortUpdates: remote.supportsReasoningEffortUpdates,
10036
10519
  thinkingLevelMap: remote.thinkingLevelMap,
10520
+ ...remote.defaultReasoningEffort === void 0 ? {} : { defaultReasoningEffort: remote.defaultReasoningEffort },
10037
10521
  ...remote.contextWindow === void 0 ? {} : { contextWindow: remote.contextWindow },
10038
10522
  ...remote.maxContextWindow === void 0 ? {} : { maxContextWindow: remote.maxContextWindow },
10039
10523
  ...base.id === remote.id ? {} : { cost: {
@@ -10044,161 +10528,292 @@ function mergeModel(baseModels, remote) {
10044
10528
  } }
10045
10529
  };
10046
10530
  }
10531
+ /**
10532
+ * 创建带账号缓存、远端刷新和模型能力元数据的官方目录。
10533
+ * @param {object} options - 凭据、模型来源、网络和目录更新配置
10534
+ * @returns {object} 可初始化、刷新、查询和清除的模型目录
10535
+ */
10047
10536
  function createOfficialModelCatalog(options = {}) {
10048
10537
  const fetchCatalog = options.fetch ?? fetch;
10049
10538
  const getNow = options.now ?? Date.now;
10050
- const scheduleTimeout = options.setTimeout ?? setTimeout;
10051
- const cancelTimeout = options.clearTimeout ?? clearTimeout;
10539
+ const schedule = options.setTimeout ?? setTimeout;
10540
+ const cancelTimer = options.clearTimeout ?? clearTimeout;
10052
10541
  const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : DEFAULT_REFRESH_TIMEOUT_MS;
10053
- let models;
10054
- let metadata = /* @__PURE__ */ new Map();
10055
- let etag;
10056
- let rawCatalog;
10057
- let revision = 0;
10058
- let refreshing;
10059
- let generation = 0;
10060
- let refreshStatus = "idle";
10061
- const retryDelays = Array.isArray(options.retryDelaysMs) ? options.retryDelaysMs.filter((delay) => Number.isFinite(delay) && delay > 0) : [];
10062
- let retries = 0;
10063
- let retryTimer;
10542
+ const loadCache = options.loadCache ?? loadModelCatalogCache;
10543
+ const saveCache = options.saveCache ?? saveModelCatalogCache;
10544
+ const retryDelays = (options.retryDelaysMs ?? []).filter((delay) => Number.isFinite(delay) && delay > 0);
10545
+ let models, rawCatalog, etag, accountId, initializing, refreshing, retryTimer;
10546
+ let metadata = /* @__PURE__ */ new Map(), generation = 0, revision = 0, retries = 0, initialized = false;
10547
+ let source = "unavailable", refreshStatus = "idle", writeSequence = 0;
10548
+ const writes = /* @__PURE__ */ new Set();
10549
+ const notify = () => {
10550
+ try {
10551
+ options.onUpdated?.();
10552
+ } catch {}
10553
+ };
10554
+ const cacheError = (error) => {
10555
+ try {
10556
+ options.onCacheError?.(error);
10557
+ } catch {}
10558
+ };
10064
10559
  const stopRetry = () => {
10065
- if (retryTimer !== void 0) cancelTimeout(retryTimer);
10560
+ if (retryTimer !== void 0) cancelTimer(retryTimer);
10066
10561
  retryTimer = void 0;
10067
10562
  };
10068
- const scheduleRetry = (currentGeneration) => {
10069
- if (models !== void 0 || currentGeneration !== generation || retryTimer !== void 0 || retries >= retryDelays.length) return;
10070
- retryTimer = scheduleTimeout(() => {
10563
+ const cancelled = () => Object.assign(/* @__PURE__ */ new Error("Codex model catalog operation cancelled"), { name: "AbortError" });
10564
+ const current = (flight) => flight.generation === generation && !flight.controller.signal.aborted;
10565
+ const wait = (promise, signal) => {
10566
+ if (!signal) return promise;
10567
+ if (signal.aborted) return Promise.reject(signal.reason ?? cancelled());
10568
+ let abort;
10569
+ const interrupted = new Promise((_, reject) => {
10570
+ abort = () => reject(signal.reason ?? cancelled());
10571
+ signal.addEventListener("abort", abort, { once: true });
10572
+ });
10573
+ return Promise.race([promise, interrupted]).finally(() => signal.removeEventListener("abort", abort));
10574
+ };
10575
+ const bounded = (label, work, signal) => {
10576
+ const controller = new AbortController();
10577
+ const abort = () => controller.abort(signal?.reason ?? cancelled());
10578
+ signal?.addEventListener("abort", abort, { once: true });
10579
+ if (signal?.aborted) abort();
10580
+ const flight = {
10581
+ generation,
10582
+ controller
10583
+ };
10584
+ const timer = schedule(() => controller.abort(/* @__PURE__ */ new Error(`Codex model catalog ${label} timed out`)), timeoutMs);
10585
+ timer.unref?.();
10586
+ const task = Promise.resolve().then(() => {
10587
+ controller.signal.throwIfAborted();
10588
+ return work(flight, controller.signal);
10589
+ });
10590
+ flight.promise = wait(task, controller.signal).finally(() => {
10591
+ cancelTimer(timer);
10592
+ signal?.removeEventListener("abort", abort);
10593
+ });
10594
+ return flight;
10595
+ };
10596
+ const scheduleRetry = (expected) => {
10597
+ if (expected !== generation || retryTimer !== void 0 || retries >= retryDelays.length) return;
10598
+ retryTimer = schedule(() => {
10071
10599
  retryTimer = void 0;
10072
- if (models !== void 0 || currentGeneration !== generation) return;
10073
- refresh().catch(() => {});
10600
+ if (expected === generation) refresh().catch(() => {});
10074
10601
  }, retryDelays[retries++]);
10075
10602
  retryTimer.unref?.();
10076
10603
  };
10604
+ const restore = async (nextAccountId, flight, signal) => {
10605
+ if (!current(flight)) return false;
10606
+ if (accountId !== nextAccountId) {
10607
+ const hadModels = models !== void 0;
10608
+ accountId = nextAccountId;
10609
+ models = rawCatalog = etag = void 0;
10610
+ metadata = /* @__PURE__ */ new Map();
10611
+ source = "unavailable";
10612
+ if (hadModels) {
10613
+ revision += 1;
10614
+ notify();
10615
+ }
10616
+ }
10617
+ let cached;
10618
+ if (nextAccountId && options.cacheDirectory !== void 0) try {
10619
+ cached = await loadCache(nextAccountId, {
10620
+ directory: options.cacheDirectory,
10621
+ now: getNow(),
10622
+ parseCatalog: parseOfficialModelCatalog,
10623
+ signal
10624
+ });
10625
+ } catch (error) {
10626
+ if (!current(flight)) throw error;
10627
+ cacheError(error);
10628
+ }
10629
+ if (!current(flight) || accountId !== nextAccountId) return false;
10630
+ if (cached !== void 0) {
10631
+ const remote = parseOfficialModelCatalog(cached.rawCatalog, getNow());
10632
+ const next = remote.map((model) => mergeModel(options.baseModels(), model)).filter(Boolean);
10633
+ if (next.length) {
10634
+ models = next;
10635
+ rawCatalog = cached.rawCatalog;
10636
+ etag = cached.etag;
10637
+ metadata = new Map(remote.map((model) => [model.id, model]));
10638
+ source = "cached";
10639
+ revision += 1;
10640
+ notify();
10641
+ }
10642
+ }
10643
+ return true;
10644
+ };
10645
+ const initialize = ({ signal } = {}) => {
10646
+ if (signal?.aborted) return Promise.reject(signal.reason ?? cancelled());
10647
+ if (initializing) return wait(initializing.promise, signal);
10648
+ if (initialized) return Promise.resolve(accountId !== void 0);
10649
+ const flight = bounded("initialization", async (flight, requestSignal) => {
10650
+ const credential = await options.readCredential?.({ signal: requestSignal });
10651
+ if (!current(flight)) return false;
10652
+ const id = credential?.type === "oauth" ? nonEmpty$1(credential.accountId) : void 0;
10653
+ await restore(id, flight, requestSignal);
10654
+ if (!current(flight)) return false;
10655
+ initialized = true;
10656
+ return id !== void 0;
10657
+ }, signal);
10658
+ initializing = flight;
10659
+ flight.promise = flight.promise.finally(() => {
10660
+ if (initializing === flight) initializing = void 0;
10661
+ });
10662
+ return flight.promise;
10663
+ };
10664
+ const persist = (id, raw, nextEtag) => {
10665
+ if (options.cacheDirectory === void 0) return;
10666
+ const expected = generation, sequence = ++writeSequence;
10667
+ const flight = bounded("cache write", async (flight, signal) => {
10668
+ await saveCache(id, {
10669
+ rawCatalog: raw,
10670
+ etag: nextEtag
10671
+ }, {
10672
+ directory: options.cacheDirectory,
10673
+ now: getNow(),
10674
+ parseCatalog: parseOfficialModelCatalog,
10675
+ signal,
10676
+ isCurrent: () => current(flight) && accountId === id && writeSequence === sequence
10677
+ });
10678
+ });
10679
+ writes.add(flight);
10680
+ flight.promise.catch((error) => {
10681
+ if (expected === generation) cacheError(error);
10682
+ }).finally(() => writes.delete(flight));
10683
+ };
10077
10684
  const refresh = ({ signal } = {}) => {
10078
- if (signal?.aborted) return Promise.reject(signal.reason ?? /* @__PURE__ */ new Error("Codex model catalog refresh aborted"));
10079
- if (refreshing?.generation === generation) return refreshing.promise;
10080
- const currentGeneration = generation;
10685
+ if (signal?.aborted) return Promise.reject(signal.reason ?? cancelled());
10686
+ if (refreshing) return wait(refreshing.promise, signal);
10081
10687
  refreshStatus = "refreshing";
10082
- let outcome = "idle";
10083
- const controller = new AbortController();
10084
- const abort = () => {
10085
- if (!controller.signal.aborted) controller.abort(signal?.reason ?? /* @__PURE__ */ new Error("Codex model catalog refresh aborted"));
10086
- };
10087
- signal?.addEventListener("abort", abort, { once: true });
10088
- const requestSignal = controller.signal;
10089
- let timer;
10090
- const timeoutError = /* @__PURE__ */ new Error("Codex model catalog refresh timed out");
10091
- const work = (async () => {
10092
- const { access, accountId } = await readSubscriptionCredentials(options.getAuth, options.readCredential, requestSignal);
10093
- if (currentGeneration !== generation || requestSignal.aborted) return false;
10094
- if (typeof access !== "string" || access.length === 0 || typeof accountId !== "string" || accountId.length === 0) return false;
10095
- const headers = {
10096
- authorization: `Bearer ${access}`,
10097
- "chatgpt-account-id": accountId,
10098
- accept: "application/json",
10099
- originator: "pi",
10100
- "user-agent": USER_AGENT,
10101
- ...etag === void 0 ? {} : { "if-none-match": etag }
10102
- };
10688
+ const flight = bounded("refresh", async (flight, requestSignal) => {
10689
+ await initialize({ signal: requestSignal });
10690
+ if (!current(flight)) return false;
10691
+ const credentials = await readSubscriptionCredentials(options.getAuth, options.readCredential, requestSignal);
10692
+ if (!current(flight)) return false;
10693
+ if (!nonEmpty$1(credentials.access) || !nonEmpty$1(credentials.accountId)) {
10694
+ if (accountId !== void 0 || models !== void 0) throw new Error("Codex model catalog credentials are unavailable");
10695
+ refreshStatus = "idle";
10696
+ return false;
10697
+ }
10698
+ if (credentials.accountId !== accountId) {
10699
+ await restore(credentials.accountId, flight, requestSignal);
10700
+ if (!current(flight)) return false;
10701
+ initialized = true;
10702
+ }
10703
+ const id = credentials.accountId;
10103
10704
  const response = await fetchCatalog(CODEX_MODELS_URL, {
10104
10705
  method: "GET",
10105
10706
  redirect: "error",
10106
- headers,
10107
- signal: requestSignal
10707
+ signal: requestSignal,
10708
+ headers: {
10709
+ authorization: `Bearer ${credentials.access}`,
10710
+ "chatgpt-account-id": id,
10711
+ accept: "application/json",
10712
+ originator: "pi",
10713
+ "user-agent": USER_AGENT,
10714
+ ...etag === void 0 ? {} : { "if-none-match": etag }
10715
+ }
10108
10716
  });
10109
- if (currentGeneration !== generation || requestSignal.aborted) return false;
10110
- if (response.status === 304) {
10111
- outcome = "ok";
10112
- if (rawCatalog === void 0) return false;
10113
- const remote = parseOfficialModelCatalog(rawCatalog, getNow());
10114
- const next = remote.map((model) => mergeModel(options.baseModels(), model)).filter(Boolean);
10115
- if (next.length === 0 || JSON.stringify(next) === JSON.stringify(models)) return false;
10116
- models = next;
10117
- metadata = new Map(remote.map((model) => [model.id, model]));
10118
- revision += 1;
10119
- options.onUpdated?.();
10120
- return true;
10121
- }
10122
- if (!response.ok) throw new Error(`Codex model catalog failed (HTTP ${response.status})`);
10123
- const raw = await response.json();
10717
+ if (!current(flight) || accountId !== id) return false;
10718
+ if (response.status !== 304 && !response.ok) throw new Error(`Codex model catalog failed (HTTP ${response.status})`);
10719
+ const raw = response.status === 304 ? rawCatalog : await response.json();
10720
+ if (!current(flight) || accountId !== id) return false;
10721
+ if (raw === void 0) throw new Error("Codex returned HTTP 304 without a cached model catalog");
10124
10722
  const remote = parseOfficialModelCatalog(raw, getNow());
10125
- if (currentGeneration !== generation || requestSignal.aborted) return false;
10126
- if (remote.length === 0) throw new Error("Codex returned an empty model catalog");
10127
- const baseModels = options.baseModels();
10128
- const next = remote.map((model) => mergeModel(baseModels, model)).filter(Boolean);
10129
- if (next.length === 0) throw new Error("Codex model catalog has no compatible models");
10130
- if (currentGeneration !== generation || requestSignal.aborted) return false;
10723
+ const next = remote.map((model) => mergeModel(options.baseModels(), model)).filter(Boolean);
10724
+ if (!next.length) throw new Error("Codex returned an empty or incompatible model catalog");
10725
+ const changed = response.status !== 304 || JSON.stringify(next) !== JSON.stringify(models);
10726
+ const previousSource = source;
10131
10727
  models = next;
10132
10728
  rawCatalog = raw;
10133
10729
  metadata = new Map(remote.map((model) => [model.id, model]));
10134
10730
  etag = nonEmpty$1(response.headers.get("etag")) ?? etag;
10135
- revision += 1;
10136
- outcome = "ok";
10137
- options.onUpdated?.();
10138
- return true;
10139
- })();
10140
- let rejectAborted;
10141
- const abortPromise = new Promise((_, reject) => {
10142
- rejectAborted = () => reject(requestSignal.reason ?? /* @__PURE__ */ new Error("Codex model catalog refresh aborted"));
10143
- if (requestSignal.aborted) rejectAborted();
10144
- else requestSignal.addEventListener("abort", rejectAborted, { once: true });
10145
- });
10146
- timer = scheduleTimeout(() => controller.abort(timeoutError), timeoutMs);
10147
- timer.unref?.();
10148
- const promise = Promise.race([work, abortPromise]).catch((error) => {
10149
- outcome = "failed";
10150
- throw error;
10151
- }).finally(() => {
10152
- cancelTimeout(timer);
10153
- signal?.removeEventListener("abort", abort);
10154
- requestSignal.removeEventListener("abort", rejectAborted);
10155
- if (refreshing?.promise === promise) {
10156
- refreshing = void 0;
10157
- refreshStatus = outcome;
10158
- }
10159
- if (outcome === "ok") {
10731
+ source = "online";
10732
+ refreshStatus = "ok";
10733
+ if (changed) revision += 1;
10734
+ if (changed || previousSource !== "online") notify();
10735
+ if (current(flight) && accountId === id) persist(id, raw, etag);
10736
+ return changed;
10737
+ }, signal);
10738
+ refreshing = flight;
10739
+ flight.promise = flight.promise.then((value) => {
10740
+ if (current(flight)) {
10160
10741
  retries = 0;
10161
10742
  stopRetry();
10162
- } else if (outcome === "failed") scheduleRetry(currentGeneration);
10743
+ }
10744
+ return value;
10745
+ }, (error) => {
10746
+ if (flight.generation === generation) {
10747
+ refreshStatus = signal?.aborted ? "idle" : "failed";
10748
+ if (!signal?.aborted) scheduleRetry(flight.generation);
10749
+ }
10750
+ throw error;
10751
+ }).finally(() => {
10752
+ if (refreshing === flight) refreshing = void 0;
10163
10753
  });
10164
- refreshing = {
10165
- generation: currentGeneration,
10166
- promise,
10167
- cancel: () => controller.abort()
10168
- };
10169
- return promise;
10754
+ return flight.promise;
10170
10755
  };
10171
10756
  return Object.freeze({
10757
+ initialize,
10172
10758
  refresh,
10173
10759
  getModels: () => models ?? [],
10174
- metadata: (modelId) => metadata.get(modelId),
10175
- reviewModel: (parentId) => officialReviewModel(rawCatalog, parentId),
10760
+ metadata: (id) => metadata.get(id),
10761
+ reviewModel: (id) => officialReviewModel(rawCatalog, id),
10176
10762
  revision: () => revision,
10177
10763
  capabilityGaps: () => [...metadata.values()].filter((model) => model.unsupported && /^[a-z][a-z0-9._-]{0,79}$/u.test(model.id)).slice(0, 20).map((model) => ({
10178
10764
  model: model.id,
10179
10765
  ...structuredClone(model.unsupported)
10180
10766
  })),
10181
10767
  status: () => ({
10182
- source: models === void 0 ? "unavailable" : "online",
10768
+ source,
10183
10769
  refresh: refreshStatus
10184
10770
  }),
10771
+ flushCache: () => Promise.all([...writes].map((flight) => flight.promise.catch(() => {}))),
10185
10772
  clear() {
10186
10773
  generation += 1;
10187
- const flight = refreshing;
10188
- refreshing = void 0;
10189
- flight?.cancel();
10774
+ writeSequence += 1;
10775
+ initializing?.controller.abort(cancelled());
10776
+ refreshing?.controller.abort(cancelled());
10777
+ for (const flight of writes) flight.controller.abort(cancelled());
10778
+ initializing = refreshing = void 0;
10190
10779
  stopRetry();
10191
10780
  retries = 0;
10192
- models = void 0;
10193
- rawCatalog = void 0;
10781
+ initialized = false;
10782
+ models = rawCatalog = etag = accountId = void 0;
10194
10783
  metadata = /* @__PURE__ */ new Map();
10195
- etag = void 0;
10784
+ source = "unavailable";
10196
10785
  refreshStatus = "idle";
10197
10786
  revision += 1;
10198
- options.onUpdated?.();
10787
+ notify();
10199
10788
  }
10200
10789
  });
10201
10790
  }
10791
+ /** Gate actual asynchronous adapter entry points, while keeping the provider registered. */
10792
+ function withModelCatalogReady(adapter, catalog, { signal: lifetime } = {}) {
10793
+ const ready = async (signal) => {
10794
+ const active = lifetime && signal ? AbortSignal.any([lifetime, signal]) : lifetime ?? signal;
10795
+ active?.throwIfAborted();
10796
+ await catalog.initialize({ signal: active });
10797
+ if (catalog.getModels().length === 0) await catalog.refresh({ signal: active });
10798
+ active?.throwIfAborted();
10799
+ };
10800
+ return new Proxy(adapter, { get(target, property) {
10801
+ const value = Reflect.get(target, property, target);
10802
+ if (typeof value === "function" && [
10803
+ "resolveModel",
10804
+ "prepareCall",
10805
+ "listModels"
10806
+ ].includes(property)) return async (...args) => {
10807
+ await ready(args[2]);
10808
+ return value.apply(target, args);
10809
+ };
10810
+ if (property === "stream" && typeof value === "function") return async function* (options) {
10811
+ await ready(options?.signal);
10812
+ yield* value.call(target, options);
10813
+ };
10814
+ return typeof value === "function" ? value.bind(target) : value;
10815
+ } });
10816
+ }
10202
10817
  //#endregion
10203
10818
  //#region src/dsh-search.js
10204
10819
  const DSH_SEARCH_PROVIDER_ID = "codex-subscription-dsh";
@@ -10223,6 +10838,12 @@ const CODEX_SEARCH_URL = "https://chatgpt.com/backend-api/codex/alpha/search";
10223
10838
  const DEFAULT_MODEL = "gpt-5.6-luna";
10224
10839
  const MAX_OUTPUT_TOKENS = 4096;
10225
10840
  const MAX_SOURCE_DATE = 64;
10841
+ const RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
10842
+ 500,
10843
+ 502,
10844
+ 503,
10845
+ 504
10846
+ ]);
10226
10847
  const record$5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
10227
10848
  const nonEmpty = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
10228
10849
  const displayText = (value) => {
@@ -10287,7 +10908,7 @@ function createCodexSearchProvider(options) {
10287
10908
  const id = nonEmpty(options.resolveSessionId?.()) ?? randomUUID();
10288
10909
  let response;
10289
10910
  try {
10290
- response = await fetchSearch(CODEX_SEARCH_URL, {
10911
+ const init = {
10291
10912
  method: "POST",
10292
10913
  redirect: "error",
10293
10914
  headers: {
@@ -10313,19 +10934,35 @@ function createCodexSearchProvider(options) {
10313
10934
  max_output_tokens: MAX_OUTPUT_TOKENS
10314
10935
  }),
10315
10936
  signal
10316
- });
10937
+ };
10938
+ for (let attempt = 0; attempt < 2; attempt++) {
10939
+ response = await fetchSearch(CODEX_SEARCH_URL, init);
10940
+ signal?.throwIfAborted();
10941
+ const requestId = response.headers?.get?.("x-request-id") ?? response.headers?.get?.("cf-ray");
10942
+ const detail = `model=${model}, mode=${preferences.searchMode}, attempt=${attempt + 1}${typeof requestId === "string" && /^[a-zA-Z0-9._:-]{1,128}$/u.test(requestId) ? `, requestId=${requestId}` : ""}`;
10943
+ const retry = attempt === 0 && RETRYABLE_STATUSES.has(response.status);
10944
+ diagnosticLog.log(response.ok ? "info" : "warn", "search", `Codex search HTTP ${response.status}${retry ? "; retrying once on the same source" : ""}`, detail);
10945
+ if (!retry) break;
10946
+ try {
10947
+ response.body?.cancel().catch(() => {});
10948
+ } catch {}
10949
+ await setTimeout$1(300, void 0, { signal });
10950
+ }
10317
10951
  } catch (error) {
10318
10952
  if (signal?.aborted || error?.name === "AbortError") throw new WebError("Codex search aborted", "WEB_ABORTED", { cause: error });
10319
10953
  throw new WebError("Codex search request failed", "WEB_PROVIDER_ERROR", { cause: error });
10320
10954
  }
10321
10955
  if (!response.ok) {
10322
10956
  const authFailure = await authFailureMessage(response);
10957
+ if (signal?.aborted) throw new WebError("Codex search aborted", "WEB_ABORTED", { cause: signal.reason });
10323
10958
  throw authFailure === "ChatGPT sign-in needs to be renewed" ? new WebError(authFailure, "WEB_PROVIDER_CREDENTIAL_MISSING") : authFailure !== void 0 ? new WebError(authFailure, "WEB_PROVIDER_ERROR") : new WebError(`Codex search request failed (HTTP ${response.status})`, "WEB_PROVIDER_ERROR");
10324
10959
  }
10325
10960
  let value;
10326
10961
  try {
10327
10962
  value = await response.json();
10963
+ signal?.throwIfAborted();
10328
10964
  } catch (error) {
10965
+ if (signal?.aborted || error?.name === "AbortError") throw new WebError("Codex search aborted", "WEB_ABORTED", { cause: error });
10329
10966
  throw new WebError("Codex returned an unreadable search response", "WEB_PROVIDER_ERROR", { cause: error });
10330
10967
  }
10331
10968
  try {
@@ -10448,6 +11085,135 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
10448
11085
  } });
10449
11086
  }
10450
11087
  //#endregion
11088
+ //#region src/codex-fetch.js
11089
+ const CODEX_FETCH_PROVIDER_ID = "codex-subscription-fetch";
11090
+ const MAX_CONTENT = 64e3;
11091
+ const httpUrl = (value) => {
11092
+ try {
11093
+ const url = new URL(value);
11094
+ return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password ? url.href : void 0;
11095
+ } catch {
11096
+ return;
11097
+ }
11098
+ };
11099
+ /** Read public page text through Codex commands.open; never call another provider. */
11100
+ function createCodexFetchProvider(options) {
11101
+ const fetchPage = options.fetch ?? fetch;
11102
+ return Object.freeze({
11103
+ id: CODEX_FETCH_PROVIDER_ID,
11104
+ available: () => true,
11105
+ async fetch(request, signal) {
11106
+ signal?.throwIfAborted();
11107
+ if (options.allowed?.() === false) throw new WebError("Codex webpage reading is disabled for this model", "WEB_PROVIDER_UNAVAILABLE");
11108
+ const url = typeof request?.url === "string" && request.url.length <= 8192 ? httpUrl(request.url) : void 0;
11109
+ if (url === void 0) throw new WebError("Codex webpage reading requires an HTTP or HTTPS URL without credentials", "WEB_INVALID_URL");
11110
+ let credentials;
11111
+ try {
11112
+ credentials = await readSubscriptionCredentials(options.getAuth, options.readCredential, signal);
11113
+ } catch {
11114
+ if (signal?.aborted) throw new WebError("Codex webpage request aborted", "WEB_ABORTED");
11115
+ throw new WebError("Could not read ChatGPT subscription sign-in", "WEB_PROVIDER_CREDENTIAL_MISSING");
11116
+ }
11117
+ const { access, accountId } = credentials;
11118
+ if (typeof access !== "string" || !access || typeof accountId !== "string" || !accountId) throw new WebError("ChatGPT subscription is not signed in", "WEB_PROVIDER_CREDENTIAL_MISSING");
11119
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 3e4);
11120
+ const activeSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
11121
+ try {
11122
+ const response = await fetchPage(CODEX_SEARCH_URL, {
11123
+ method: "POST",
11124
+ redirect: "error",
11125
+ headers: {
11126
+ authorization: `Bearer ${access}`,
11127
+ "chatgpt-account-id": accountId,
11128
+ accept: "application/json",
11129
+ "content-type": "application/json",
11130
+ originator: "pi",
11131
+ "user-agent": USER_AGENT
11132
+ },
11133
+ body: JSON.stringify({
11134
+ id: options.resolveSessionId?.() || randomUUID(),
11135
+ model: options.resolveModel?.() || "gpt-5.6-luna",
11136
+ input: url,
11137
+ commands: {
11138
+ open: [{ ref_id: url }],
11139
+ response_length: "long"
11140
+ },
11141
+ settings: {
11142
+ allowed_callers: ["direct"],
11143
+ external_web_access: true
11144
+ },
11145
+ max_output_tokens: 4096
11146
+ }),
11147
+ signal: activeSignal
11148
+ });
11149
+ activeSignal.throwIfAborted();
11150
+ if (!response.ok) {
11151
+ const authFailure = await authFailureMessage(response);
11152
+ throw new WebError(authFailure ?? `Codex webpage request failed (HTTP ${response.status})`, authFailure === "ChatGPT sign-in needs to be renewed" ? "WEB_PROVIDER_CREDENTIAL_MISSING" : "WEB_PROVIDER_ERROR");
11153
+ }
11154
+ const value = await response.json();
11155
+ activeSignal.throwIfAborted();
11156
+ const source = Array.isArray(value?.results) ? value.results.find((item) => httpUrl(item?.url) !== void 0 && item?.type !== "error" && item?.title !== "Internal Error") : void 0;
11157
+ const output = typeof value?.output === "string" ? value.output : "";
11158
+ const heading = output.split(/\r?\n/u, 1)[0].trim();
11159
+ const headingUrl = heading.endsWith(")") ? httpUrl(heading.slice(heading.lastIndexOf(" (") + 2, -1)) : void 0;
11160
+ const metadata = output.slice(0, 1024);
11161
+ const pageUrl = source ? httpUrl(source.url) : headingUrl && /Content type:/u.test(metadata) && /Source: open\(/u.test(metadata) ? headingUrl : void 0;
11162
+ if (!pageUrl || output.trim() === "" || /^Internal Error(?:\s|\()/iu.test(heading)) throw new WebError("Codex could not read this webpage", "WEB_PROVIDER_ERROR");
11163
+ const lineCount = Number(metadata.match(/Total lines: (\d+)/u)?.[1]);
11164
+ const shownLines = new Set([...output.matchAll(/^L(\d+):/gmu)].map((match) => Number(match[1]))).size;
11165
+ const partialPage = Number.isSafeInteger(lineCount) && lineCount > 0 && shownLines > 0 && shownLines < lineCount;
11166
+ return {
11167
+ url: pageUrl,
11168
+ statusCode: 200,
11169
+ body: {
11170
+ kind: "text",
11171
+ content: output.slice(0, MAX_CONTENT)
11172
+ },
11173
+ truncated: output.length > MAX_CONTENT || partialPage
11174
+ };
11175
+ } catch (error) {
11176
+ if (signal?.aborted || error?.name === "AbortError") throw new WebError("Codex webpage request aborted", "WEB_ABORTED");
11177
+ if (activeSignal.aborted) throw new WebError("Codex webpage request timed out", "WEB_FETCH_TIMEOUT");
11178
+ if (error instanceof WebError) throw error;
11179
+ throw new WebError("Codex webpage request failed", "WEB_PROVIDER_ERROR");
11180
+ }
11181
+ }
11182
+ });
11183
+ }
11184
+ /** Preserve DSH's configured fetch provider; only an explicit plugin choice changes dispatch. */
11185
+ function createCodexFetchRouter({ registry, configuredId, mode, codex }) {
11186
+ if (!(registry instanceof Map)) return void 0;
11187
+ const wrappers = /* @__PURE__ */ new Map();
11188
+ const wrapper = (id) => {
11189
+ if (!wrappers.has(id)) wrappers.set(id, Object.freeze({
11190
+ id,
11191
+ available: () => mode() === "codex",
11192
+ fetch(request, signal) {
11193
+ if (mode() !== "codex") throw new WebError("Codex webpage reading is no longer selected", "WEB_PROVIDER_UNAVAILABLE");
11194
+ return codex.fetch(request, signal);
11195
+ }
11196
+ }));
11197
+ return wrappers.get(id);
11198
+ };
11199
+ return new Proxy(registry, { get(target, property) {
11200
+ if (property === "get") return (id) => mode() === "codex" && id === configuredId() ? wrapper(id) : target.get(id);
11201
+ if (property === "values" && mode() === "codex" && configuredId() === void 0) return () => [wrapper(CODEX_FETCH_PROVIDER_ID)].values();
11202
+ const value = Reflect.get(target, property, target);
11203
+ return typeof value === "function" ? value.bind(target) : value;
11204
+ } });
11205
+ }
11206
+ /** Match the runtime's live volatile selection and constructor-time env snapshot. */
11207
+ function configuredFetchProviderId(web, entries = [], ambient = process.env.DSH_WEB_FETCH_PROVIDER) {
11208
+ if ("fetchProviderId" in web) return web.fetchProviderId;
11209
+ const environment = "fetchProviderEnv" in web ? web.fetchProviderEnv : ambient;
11210
+ if (typeof web.config?.fetchProvider?.get === "function") return web.config.fetchProvider.get() ?? environment;
11211
+ const entry = [...entries].find((item) => item.options?.id === "web");
11212
+ const value = entry?.fiber?.config?.fetchProvider;
11213
+ if (typeof value?.get === "function") return value.get() ?? environment;
11214
+ return value ?? entry?.options?.config?.fetchProvider ?? environment;
11215
+ }
11216
+ //#endregion
10451
11217
  //#region src/image-tool-registration.js
10452
11218
  /** Removing the tool also removes its schema from subsequent model requests. */
10453
11219
  function watchImageTool(settings, register) {
@@ -10688,6 +11454,7 @@ const areas = {
10688
11454
  search: "search",
10689
11455
  image: "images",
10690
11456
  model: "transport",
11457
+ voice: "transport",
10691
11458
  login: "account",
10692
11459
  "quota-reset": "quota"
10693
11460
  };
@@ -10754,8 +11521,8 @@ function capabilityCoverage({ account, preference, runtime, catalog, tools, stor
10754
11521
  readiness = runtime.installed && !runtime.restartRequired ? "pass" : "warn";
10755
11522
  reason = runtime.restartRequired ? "restart-required" : runtime.installed ? "runtime-present" : "runtime-missing";
10756
11523
  } else if (id === "models" && catalog) {
10757
- readiness = catalog.source === "online" ? "pass" : "warn";
10758
- reason = catalog.source === "online" ? "catalog-online" : "catalog-unavailable";
11524
+ readiness = catalog.source === "online" || catalog.source === "cached" ? "pass" : "warn";
11525
+ reason = catalog.source === "online" ? "catalog-online" : catalog.source === "cached" ? "catalog-cached" : "catalog-unavailable";
10759
11526
  } else if (id === "storage" && storage?.readable) {
10760
11527
  readiness = "pass";
10761
11528
  reason = "storage-readable";
@@ -10900,7 +11667,8 @@ const requestAreas = /* @__PURE__ */ new Set([
10900
11667
  "quota",
10901
11668
  "quota-reset",
10902
11669
  "search",
10903
- "image"
11670
+ "image",
11671
+ "voice"
10904
11672
  ]);
10905
11673
  const statuses = /* @__PURE__ */ new Set(["ok", "failed"]);
10906
11674
  const stages = /* @__PURE__ */ new Set(["transport", "http"]);
@@ -11161,7 +11929,11 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
11161
11929
  ...collected.compaction ? { compaction: collected.compaction } : {},
11162
11930
  ...collected.review ? { review: collected.review } : {},
11163
11931
  ...collected.streamFailure ? { streamFailure: collected.streamFailure } : {},
11164
- ...catalog && ["unavailable", "online"].includes(catalog.source) && [
11932
+ ...catalog && [
11933
+ "unavailable",
11934
+ "cached",
11935
+ "online"
11936
+ ].includes(catalog.source) && [
11165
11937
  "idle",
11166
11938
  "refreshing",
11167
11939
  "ok",
@@ -11597,7 +12369,7 @@ const timestamp = (value) => {
11597
12369
  const parsed = typeof value === "string" ? Date.parse(value) : NaN;
11598
12370
  return Number.isFinite(parsed) ? parsed : void 0;
11599
12371
  };
11600
- const percent = (basisPoints) => Number.isFinite(basisPoints) && basisPoints >= 0 ? Math.round(basisPoints) / 100 : void 0;
12372
+ const percent = (basisPoints) => Number.isFinite(basisPoints) && basisPoints >= 0 ? basisPoints / 100 : void 0;
11601
12373
  /** Reduce the provider payload to a browser-safe projection; anything malformed is dropped, never an error. */
11602
12374
  function parsePlanHistory(value) {
11603
12375
  if (!record$3(value) || !Array.isArray(value.periods)) throw new Error("Codex returned a malformed usage history");
@@ -12323,12 +13095,19 @@ function refineQuotaRate(samples, conservative) {
12323
13095
  }
12324
13096
  if (crossings < 3) return conservative;
12325
13097
  const candidate = quotaSharedOffsetInterval(samples);
12326
- if (!candidate.feasible || candidate.min <= 0) return conservative;
12327
- if (candidate.max - candidate.min >= conservative.max - conservative.min) return conservative;
13098
+ if (!candidate.feasible) return {
13099
+ ...conservative,
13100
+ steadyHypothesisFailed: true
13101
+ };
13102
+ if (candidate.min <= 0 || candidate.max - candidate.min >= conservative.max - conservative.min) return {
13103
+ ...conservative,
13104
+ steadyHypothesisFailed: false
13105
+ };
12328
13106
  return {
12329
13107
  ...candidate,
12330
13108
  method: "shared-offset",
12331
- maxLagMs: 12e4
13109
+ maxLagMs: 12e4,
13110
+ steadyHypothesisFailed: false
12332
13111
  };
12333
13112
  }
12334
13113
  //#endregion
@@ -12395,14 +13174,15 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
12395
13174
  status: "calibrating",
12396
13175
  reason: "stale"
12397
13176
  };
12398
- let bounds = quotaRateInterval(samples);
13177
+ const rateBounds = (readings) => refineQuotaRate(readings, quotaRateInterval(readings));
13178
+ const contradicted = (range) => !range.feasible || range.steadyHypothesisFailed === true || range.min > 1e-9 && range.max - range.min <= 1e-9;
13179
+ let bounds = rateBounds(samples);
12399
13180
  let changedIntensity = false;
12400
- while (!bounds.feasible && samples.length > 3) {
13181
+ while (contradicted(bounds) && samples.length > 3) {
12401
13182
  samples = samples.slice(1);
12402
- bounds = quotaRateInterval(samples);
13183
+ bounds = rateBounds(samples);
12403
13184
  changedIntensity = true;
12404
13185
  }
12405
- bounds = refineQuotaRate(samples, bounds);
12406
13186
  const spanMs = samples.at(-1).at - samples[0].at;
12407
13187
  const common = {
12408
13188
  sampleCount: samples.length,
@@ -12413,7 +13193,8 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
12413
13193
  changedIntensity,
12414
13194
  rateMethod: bounds.method ?? "conservative"
12415
13195
  };
12416
- if (!bounds.feasible) return {
13196
+ const integerReports = samples.every((sample) => Number.isInteger(sample.remainingPercent));
13197
+ if (contradicted(bounds) || changedIntensity && (samples.length < 4 || spanMs < 20 * 6e4 || integerReports && bounds.steadyHypothesisFailed !== false)) return {
12417
13198
  ...common,
12418
13199
  status: "calibrating",
12419
13200
  reason: "changing-pace"
@@ -12423,17 +13204,16 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
12423
13204
  status: "calibrating",
12424
13205
  reason: "stale"
12425
13206
  };
12426
- if (spanMs >= 5 * 6e4 && samples.length >= 3 && bounds.min <= 1e-9 && common.consumedPercent >= 1) {
13207
+ if (spanMs >= 5 * 6e4 && samples.length >= 3 && (changedIntensity || bounds.min <= 1e-9) && common.consumedPercent >= 1) {
12427
13208
  const pacePerHour = common.consumedPercent / (spanMs / HOUR_MS);
12428
13209
  const runwaySeconds = clampPercent(window.remainingPercent) / pacePerHour * 3600;
12429
- const untilReset = resetsAt === null ? null : resetsAt - now / 1e3;
12430
13210
  return {
12431
13211
  ...common,
12432
13212
  status: "ready",
12433
13213
  provisional: true,
12434
13214
  pacePerHour,
12435
13215
  runwaySeconds,
12436
- survivesReset: untilReset !== null && runwaySeconds >= untilReset
13216
+ survivesReset: false
12437
13217
  };
12438
13218
  }
12439
13219
  if (spanMs < 6e4 || bounds.min <= 1e-9) return {
@@ -13026,7 +13806,8 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13026
13806
  sessionId: payload.sessionId,
13027
13807
  sdp: payload.sdp,
13028
13808
  voice: current.voiceVoice,
13029
- language: current.voiceLanguage
13809
+ language: current.voiceLanguage,
13810
+ signal
13030
13811
  })
13031
13812
  };
13032
13813
  } catch (error) {
@@ -13038,16 +13819,20 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13038
13819
  if (!voicePreview) return publicError("unavailable", "Voice preview is unavailable");
13039
13820
  if (endpoint === "voice/catalog") return {
13040
13821
  ok: true,
13041
- value: { voices: await voicePreview.available(payload?.language) }
13822
+ value: { voices: await voicePreview.available(payload?.language, signal) }
13042
13823
  };
13043
- const value = await voicePreview.preview(payload?.voice, payload?.language);
13824
+ const value = await voicePreview.preview(payload?.voice, payload?.language, signal);
13044
13825
  return value === void 0 ? publicError("not-found", "No sample for this voice") : {
13045
13826
  ok: true,
13046
13827
  value
13047
13828
  };
13048
13829
  } catch (error) {
13049
13830
  if (signal.aborted) throw error;
13050
- return publicError("operation-error", "Could not load the voice sample");
13831
+ return publicError([
13832
+ "voice-auth",
13833
+ "voice-catalog",
13834
+ "voice-download"
13835
+ ].includes(error?.code) ? error.code : "operation-error", "Could not load the voice sample");
13051
13836
  }
13052
13837
  if ([
13053
13838
  "remote/status",
@@ -13305,7 +14090,9 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13305
14090
  ];
13306
14091
  if (endpoint === "logout") tasks.push(() => usageReader.clear(), () => accountUsageReader?.clear());
13307
14092
  if (endpoint === "account/remove" && typeof payload?.id === "string") tasks.push(() => usageReader.clearScope(payload.id));
13308
- if ((await Promise.allSettled(tasks.map((task) => Promise.resolve().then(task)))).some((value) => value.status === "rejected")) try {
14093
+ const outcomes = await Promise.allSettled(tasks.map((task) => Promise.resolve().then(task)));
14094
+ const catalogOutcomes = endpoint === "logout" ? [] : await Promise.allSettled([Promise.resolve().then(() => modelCatalog?.initialize())]);
14095
+ if ([...outcomes, ...catalogOutcomes].some((value) => value.status === "rejected")) try {
13309
14096
  onCleanupFailure?.();
13310
14097
  } catch {}
13311
14098
  if (endpoint !== "logout") Promise.resolve().then(() => modelCatalog?.refresh({ signal: void 0 })).catch(() => {});
@@ -13319,6 +14106,7 @@ const BASE = "https://chatgpt.com/backend-api";
13319
14106
  const CATALOG_TTL_MS = 10 * 6e4;
13320
14107
  const MAX_CLIP_BYTES = 2 * 1024 * 1024;
13321
14108
  const PREVIEW_HOSTS = /^https:\/\/[a-z0-9.-]*oaistatic\.com\//u;
14109
+ const failure = (code, message) => Object.assign(new Error(message), { code });
13322
14110
  function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, base = BASE }) {
13323
14111
  const catalogs = /* @__PURE__ */ new Map();
13324
14112
  const clips = /* @__PURE__ */ new Map();
@@ -13326,21 +14114,33 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
13326
14114
  const language = normalizeVoiceLanguage(value);
13327
14115
  return language === "auto" ? "en" : language;
13328
14116
  };
13329
- const readCatalog = async (language) => {
14117
+ const readCatalog = async (language, signal) => {
14118
+ signal?.throwIfAborted();
13330
14119
  const catalog = catalogs.get(language);
13331
14120
  if (catalog && now() - catalog.at < CATALOG_TTL_MS) return catalog.voices;
13332
- const { access, accountId } = await credentials();
13333
- const response = await fetch(`${base}/settings/voices?spoken_language=${language}`, {
13334
- headers: {
13335
- authorization: `Bearer ${access}`,
13336
- "chatgpt-account-id": accountId,
13337
- accept: "application/json",
13338
- "user-agent": userAgent
13339
- },
13340
- signal: AbortSignal.timeout(15e3)
13341
- });
13342
- if (!response.ok) throw new Error(`voice catalog HTTP ${response.status}`);
13343
- const value = await response.json();
14121
+ let value;
14122
+ try {
14123
+ const { access, accountId } = await credentials(signal);
14124
+ if (!access || !accountId) throw failure("voice-auth", "ChatGPT sign-in is required");
14125
+ const response = await fetch(`${base}/settings/voices?spoken_language=${language}`, {
14126
+ headers: {
14127
+ authorization: `Bearer ${access}`,
14128
+ "chatgpt-account-id": accountId,
14129
+ accept: "application/json",
14130
+ "user-agent": userAgent
14131
+ },
14132
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3)
14133
+ });
14134
+ if (response.status === 401) throw failure("voice-auth", "ChatGPT sign-in needs renewal");
14135
+ if (!response.ok) throw failure("voice-catalog", `voice catalog HTTP ${response.status}`);
14136
+ value = await response.json();
14137
+ if (!Array.isArray(value?.voices)) throw failure("voice-catalog", "Invalid voice catalog");
14138
+ signal?.throwIfAborted();
14139
+ } catch (error) {
14140
+ signal?.throwIfAborted();
14141
+ if (error?.code === "voice-auth" || error?.code === "voice-catalog") throw error;
14142
+ throw failure("voice-catalog", "Could not load the voice catalog");
14143
+ }
13344
14144
  const voices = (Array.isArray(value?.voices) ? value.voices : []).filter((entry) => typeof entry?.name === "string" && typeof entry?.preview_url === "string" && PREVIEW_HOSTS.test(entry.preview_url));
13345
14145
  catalogs.set(language, {
13346
14146
  at: now(),
@@ -13350,21 +14150,29 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
13350
14150
  };
13351
14151
  return {
13352
14152
  /** Which voices ChatGPT's own catalog offers right now (lower-case names), so the settings can mark the others unavailable. */
13353
- async available(language) {
13354
- return (await readCatalog(languageOf(language))).map((entry) => entry.name.toLowerCase());
14153
+ async available(language, signal) {
14154
+ return (await readCatalog(languageOf(language), signal)).map((entry) => entry.name.toLowerCase());
13355
14155
  },
13356
14156
  /** The clip of one voice (by its Codex name, e.g. "spruce") as a data URL, with the catalog's description. */
13357
- async preview(voice, selectedLanguage) {
14157
+ async preview(voice, selectedLanguage, signal) {
14158
+ signal?.throwIfAborted();
13358
14159
  if (typeof voice !== "string" || !/^[a-z]{2,16}$/u.test(voice)) return void 0;
13359
14160
  const language = languageOf(selectedLanguage);
13360
14161
  const key = `${language}:${voice}`;
13361
14162
  if (clips.has(key)) return clips.get(key);
13362
- const entry = (await readCatalog(language)).find((item) => item.name.toLowerCase() === voice || item.voice === voice);
14163
+ const entry = (await readCatalog(language, signal)).find((item) => item.name.toLowerCase() === voice || item.voice === voice);
13363
14164
  if (!entry) return void 0;
13364
- const response = await fetch(entry.preview_url, { signal: AbortSignal.timeout(15e3) });
13365
- if (!response.ok) throw new Error(`voice sample HTTP ${response.status}`);
13366
- const bytes = Buffer.from(await response.arrayBuffer());
13367
- if (bytes.byteLength === 0 || bytes.byteLength > MAX_CLIP_BYTES) throw new Error("voice sample has an unexpected size");
14165
+ let bytes;
14166
+ try {
14167
+ const response = await fetch(entry.preview_url, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3) });
14168
+ if (!response.ok) throw failure("voice-download", `voice sample HTTP ${response.status}`);
14169
+ bytes = Buffer.from(await response.arrayBuffer());
14170
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_CLIP_BYTES) throw failure("voice-download", "voice sample has an unexpected size");
14171
+ signal?.throwIfAborted();
14172
+ } catch {
14173
+ signal?.throwIfAborted();
14174
+ throw failure("voice-download", "Could not download the voice sample");
14175
+ }
13368
14176
  const type = /\.mp3(?:$|\?)/u.test(entry.preview_url) ? "audio/mpeg" : "audio/mp4";
13369
14177
  const result = {
13370
14178
  name: entry.name,
@@ -13558,6 +14366,8 @@ function apply(ctx, config = {}) {
13558
14366
  ctx.effect(() => ctx.on?.("plugin-manager/install-state", (value) => runtimeManagement.progress(value)));
13559
14367
  const modelCatalog = createOfficialModelCatalog({
13560
14368
  onUpdated: () => ctx.llm.emitAdaptersUpdated?.(),
14369
+ onCacheError: (error) => ctx.logger?.debug?.("could not access the Codex model catalog cache (%s)", error?.code ?? error?.name ?? "unknown error"),
14370
+ cacheDirectory: dshHomePath("state", "codex-subscription", "model-catalog"),
13561
14371
  getAuth: (options) => resolveAuth(options),
13562
14372
  readCredential: (options) => store.read(PROVIDER, options),
13563
14373
  baseModels: () => baseProvider.getModels(),
@@ -13618,6 +14428,7 @@ function apply(ctx, config = {}) {
13618
14428
  catalog: modelCatalog,
13619
14429
  runNetwork: network.run
13620
14430
  });
14431
+ let fetchRouted = false;
13621
14432
  const preferences = {
13622
14433
  status: () => {
13623
14434
  const models = modelCatalog.getModels();
@@ -13626,6 +14437,7 @@ function apply(ctx, config = {}) {
13626
14437
  [AUTO_QUOTA_RETRY_FIELD]: normalizeAutoQuotaRetry(settings.get()[AUTO_QUOTA_RETRY_FIELD]),
13627
14438
  compactionMode: settings.get().compactionMode ?? "dsh",
13628
14439
  reasoningCache: normalizeReasoningCache(settings.get().reasoningCache),
14440
+ [DEFAULT_REASONING_EFFORT_FIELD]: normalizeDefaultReasoningEffort(settings.get()[DEFAULT_REASONING_EFFORT_FIELD]),
13629
14441
  connectionMode: settings.get().connectionMode ?? "sse",
13630
14442
  reviewModel: settings.get().reviewModel ?? "session",
13631
14443
  remoteControl: settings.get().remoteControl ?? "off",
@@ -13636,6 +14448,8 @@ function apply(ctx, config = {}) {
13636
14448
  ...readCapabilitySettings(settings.get()),
13637
14449
  [QUICK_QUOTA_MODE_FIELD]: normalizeQuickQuotaMode(settings.get()[QUICK_QUOTA_MODE_FIELD], settings.get()[LEGACY_QUICK_QUOTA_FIELD]),
13638
14450
  [SEARCH_PROVIDER_FIELD]: settings.get()[SEARCH_PROVIDER_FIELD],
14451
+ [FETCH_PROVIDER_FIELD]: normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]),
14452
+ fetchRoutingAvailable: fetchRouted,
13639
14453
  [SPEED_MODE_FIELD]: settings.get()[SPEED_MODE_FIELD],
13640
14454
  [OUTPUT_VERBOSITY_FIELD]: normalizeOutputVerbosity(settings.get()[OUTPUT_VERBOSITY_FIELD]),
13641
14455
  [INPUT_IMAGE_DETAIL_FIELD]: normalizeInputImageDetail(settings.get()[INPUT_IMAGE_DETAIL_FIELD]),
@@ -13662,6 +14476,7 @@ function apply(ctx, config = {}) {
13662
14476
  };
13663
14477
  },
13664
14478
  update: async (patch) => {
14479
+ if (patch["fetchProvider"] === "codex" && !fetchRouted) throw new Error("This DSH version does not support Codex webpage reading");
13665
14480
  if (Object.hasOwn(patch, "subagentBackend")) {
13666
14481
  if (!subagentBackend) throw new Error("DSH subagent services are unavailable");
13667
14482
  await subagentBackend.select(patch.subagentBackend);
@@ -13852,8 +14667,72 @@ function apply(ctx, config = {}) {
13852
14667
  ctx.effect(() => ctx.on?.("session/event", (_session, event) => {
13853
14668
  if (event?.type === "request/context") hiddenDirectory.dependenciesChanged();
13854
14669
  }), "codex-subscription: hidden model dependencies");
13855
- ctx.llm.registerAdapter([PROVIDER], hiddenDirectory.wrap(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(adapter)), provider)));
14670
+ ctx.effect(() => settings.watch((value, previous) => {
14671
+ if (normalizeDefaultReasoningEffort(value["defaultReasoningEffort"]) !== normalizeDefaultReasoningEffort(previous["defaultReasoningEffort"])) ctx.llm.emitAdaptersUpdated?.();
14672
+ }), "codex-subscription: default reasoning effort");
14673
+ ctx.effect(() => {
14674
+ const lifetime = new AbortController();
14675
+ const defaults = withDefaultReasoningEffort(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(provider.wrapRetryAdapter(adapter))), provider), {
14676
+ preference: () => settings.get()[DEFAULT_REASONING_EFFORT_FIELD],
14677
+ modelDefault: (id) => modelCatalog.metadata(id)?.defaultReasoningEffort
14678
+ });
14679
+ const readyAdapter = withModelCatalogReady(hiddenDirectory.wrap(defaults), modelCatalog, { signal: lifetime.signal });
14680
+ const disposeAdapter = ctx.llm.registerAdapter([PROVIDER], readyAdapter);
14681
+ Promise.resolve().then(() => modelCatalog.refresh({ signal: lifetime.signal })).catch((error) => {
14682
+ if (!lifetime.signal.aborted) ctx.logger?.debug?.("could not refresh Codex model catalog (%s)", error?.code ?? error?.name ?? "unknown error");
14683
+ });
14684
+ return () => {
14685
+ lifetime.abort();
14686
+ disposeAdapter?.();
14687
+ modelCatalog.clear();
14688
+ };
14689
+ }, "codex-subscription: official model catalog");
13856
14690
  const currentAgent = () => ctx.get?.("agents")?.currentInitiator?.();
14691
+ const codexFetch = createCodexFetchProvider({
14692
+ allowed: () => fetchRouted && (settings.get().otherModels !== "off" || currentAgent()?.session.requestContext?.()?.provider === PROVIDER),
14693
+ getAuth: resolveAuth,
14694
+ readCredential: (options) => store.read(PROVIDER, options),
14695
+ resolveModel: () => {
14696
+ const request = currentAgent()?.session.requestContext?.();
14697
+ return request?.provider === PROVIDER ? request.model : void 0;
14698
+ },
14699
+ resolveSessionId: () => currentAgent()?.session.id,
14700
+ fetch: (input, init) => network.fetch("search", input, init)
14701
+ });
14702
+ const realFetchProviders = ctx.web.fetchProviders;
14703
+ ctx.web.registerFetchProvider?.({
14704
+ ...codexFetch,
14705
+ available: () => fetchRouted && normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex"
14706
+ });
14707
+ ctx.effect(() => {
14708
+ const web = ctx.web;
14709
+ const configuredId = () => configuredFetchProviderId(web, ctx.loader.entries());
14710
+ const router = createCodexFetchRouter({
14711
+ registry: realFetchProviders,
14712
+ configuredId,
14713
+ mode: () => fetchRouted ? normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]) : "dsh",
14714
+ codex: codexFetch
14715
+ });
14716
+ if (router !== void 0) {
14717
+ try {
14718
+ web.fetchProviders = router;
14719
+ } catch {}
14720
+ fetchRouted = web.fetchProviders === router;
14721
+ }
14722
+ if (!fetchRouted) {
14723
+ diagnosticLog.warn("fetch", "Codex webpage reading is unavailable: DSH does not support fetch routing");
14724
+ if (normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex") {
14725
+ diagnosticLog.error("fetch", "Configured Codex webpage reading could not be activated; select DSH or update the host");
14726
+ throw new Error("Configured Codex webpage reading could not be activated; select DSH or update the host");
14727
+ }
14728
+ return;
14729
+ }
14730
+ diagnosticLog.info("fetch", "webpage reading is routed without replacing the configured DSH provider");
14731
+ return () => {
14732
+ fetchRouted = false;
14733
+ if (web.fetchProviders === router) web.fetchProviders = realFetchProviders;
14734
+ };
14735
+ }, "codex-subscription: fetch router");
13857
14736
  const servesCurrentModel = () => {
13858
14737
  if (settings.get().otherModels !== "off") return true;
13859
14738
  const provider = currentAgent()?.session.requestContext?.()?.provider;
@@ -13993,6 +14872,7 @@ function apply(ctx, config = {}) {
13993
14872
  }), signal)
13994
14873
  }
13995
14874
  });
14875
+ ctx.effect(() => () => remoteBridge.close());
13996
14876
  const remoteControl = createRemoteControl({
13997
14877
  credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
13998
14878
  ...options,
@@ -14162,7 +15042,7 @@ function apply(ctx, config = {}) {
14162
15042
  remoteControl,
14163
15043
  desktopVoice: withEndCallTool(remoteBridge.desktopVoice, (tool) => ctx.tools.register(tool)),
14164
15044
  voicePreview: createVoicePreview({
14165
- fetch: (input, init) => network.fetch("remote", input, init),
15045
+ fetch: (input, init) => network.fetch("voice", input, init, { standardHttps: true }),
14166
15046
  credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
14167
15047
  ...options,
14168
15048
  signal
@@ -14195,9 +15075,6 @@ function apply(ctx, config = {}) {
14195
15075
  resolveInheritedOriginal: (sessionId, assetId) => inheritedOriginalImageRef(ctx.get?.("sessions")?.get?.(sessionId), assetId)
14196
15076
  });
14197
15077
  const handler = diagnosticOperations.wrap((endpoint, payload, signal) => endpoint.startsWith("sketch/") ? sketchBridge.rpc(endpoint, payload) : subscriptionHandler(endpoint, payload, signal));
14198
- ctx.effect(() => {
14199
- modelCatalog.refresh().catch((error) => ctx.logger?.debug?.("could not refresh Codex model catalog: %s", error.message));
14200
- }, "codex-subscription: official model catalog");
14201
15078
  ctx.inject(["connection"], (connectionContext) => connectionContext.effect(() => registerSubscriptionTransport(connectionContext.connection, handler), "codex-subscription: DSH-trusted account RPC"));
14202
15079
  }
14203
15080
  //#endregion