dsh-codex-subscription 3.1.6 → 3.1.7

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";
@@ -660,6 +663,11 @@ const PREFERENCE_FIELDS = Object.freeze({
660
663
  default: DEFAULT_SEARCH_PROVIDER,
661
664
  error: "Invalid search provider preference"
662
665
  },
666
+ [FETCH_PROVIDER_FIELD]: {
667
+ choices: ["dsh", FETCH_PROVIDER_CODEX],
668
+ default: "dsh",
669
+ error: "Invalid fetch provider preference"
670
+ },
663
671
  [SPEED_MODE_FIELD]: {
664
672
  choices: [
665
673
  SPEED_MODE_STANDARD,
@@ -739,7 +747,8 @@ const areas$1 = /* @__PURE__ */ new Set([
739
747
  "quota",
740
748
  "quota-reset",
741
749
  "search",
742
- "image"
750
+ "image",
751
+ "voice"
743
752
  ]);
744
753
  const codes$1 = /* @__PURE__ */ new Set([
745
754
  "timeout",
@@ -1024,7 +1033,7 @@ function fetchThroughProxy(input, init, proxyUrl) {
1024
1033
  const request$1 = request(target, {
1025
1034
  method: init?.method ?? "GET",
1026
1035
  headers: Object.fromEntries(headers.entries()),
1027
- agent: new HttpsProxyAgent(proxyUrl),
1036
+ agent: proxyUrl ? new HttpsProxyAgent(proxyUrl) : void 0,
1028
1037
  signal: init?.signal
1029
1038
  }, (response) => {
1030
1039
  const responseHeaders = new Headers();
@@ -1084,7 +1093,7 @@ async function withCodexNetwork(run, options = {}) {
1084
1093
  }
1085
1094
  const route = await proxy;
1086
1095
  scopedOptions.onRoute?.(route.source);
1087
- const response = await (route.url === void 0 ? fetchBeforeScope(input, init) : proxyFetch(input, init, route.url));
1096
+ const response = await (route.url === void 0 && !scopedOptions.standardHttps ? fetchBeforeScope(input, init) : proxyFetch(input, init, route.url));
1088
1097
  return scopedOptions.transformResponse?.(response, target) ?? response;
1089
1098
  };
1090
1099
  globalThis.fetch = scopedFetch;
@@ -1175,7 +1184,7 @@ function createCodexNetworkTransport(options = {}) {
1175
1184
  return Object.freeze({
1176
1185
  run,
1177
1186
  history: evidence.snapshot,
1178
- fetch: (area, input, init) => run(area, () => globalThis.fetch(input, init)),
1187
+ fetch: (area, input, init, connection) => run(area, () => globalThis.fetch(input, init), connection),
1179
1188
  snapshot: () => Object.fromEntries([...attempts].map(([area, value]) => [area, { ...value }]))
1180
1189
  });
1181
1190
  }
@@ -1261,8 +1270,8 @@ const historyHash = (messages) => hash$1(messages.map(({ source, ...message }) =
1261
1270
  model: source.model
1262
1271
  }
1263
1272
  })));
1264
- const MAX_BYTES = 2 * 1024 * 1024;
1265
- const MAX_AGE_MS = 10080 * 60 * 1e3;
1273
+ const MAX_BYTES$1 = 2 * 1024 * 1024;
1274
+ const MAX_AGE_MS$1 = 10080 * 60 * 1e3;
1266
1275
  function createCompactionBridge({ enabled = () => false, threshold, accountScope, diagnostic = () => {}, now = Date.now }) {
1267
1276
  const scope = new AsyncLocalStorage();
1268
1277
  const stats = {
@@ -1288,7 +1297,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1288
1297
  for (let i = messages.length - 1; i >= 0; i--) {
1289
1298
  const candidate = messages[i].source?.replayState?.response?.[key];
1290
1299
  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) {
1300
+ 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
1301
  state.suffix = clone$2(candidate.items);
1293
1302
  messages = [...messages.slice(0, i + 1).filter((m) => m.role === "system"), ...messages.slice(i + 1)];
1294
1303
  }
@@ -1407,7 +1416,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1407
1416
  if (event.type === "response.output_item.done") {
1408
1417
  if (event.item?.type === "compaction") state.captured = [clone$2(event.item)];
1409
1418
  else if (state.captured) state.captured.push(clone$2(event.item));
1410
- if (state.captured && JSON.stringify(state.captured).length > MAX_BYTES) {
1419
+ if (state.captured && JSON.stringify(state.captured).length > MAX_BYTES$1) {
1411
1420
  state.captured = void 0;
1412
1421
  oversized = true;
1413
1422
  }
@@ -1424,7 +1433,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1424
1433
  observe(buffer.slice(0, index).trimEnd());
1425
1434
  buffer = buffer.slice(index + 1);
1426
1435
  }
1427
- if (buffer.length > MAX_BYTES) {
1436
+ if (buffer.length > MAX_BYTES$1) {
1428
1437
  buffer = "";
1429
1438
  oversized = true;
1430
1439
  state.captured = void 0;
@@ -1634,6 +1643,103 @@ function normalizeTransportEvent(event, signal) {
1634
1643
  };
1635
1644
  }
1636
1645
  //#endregion
1646
+ //#region src/model-retry-hint.js
1647
+ /** Keep the provider's wait as a fact; only DSH decides whether and when to retry. */
1648
+ function providerRetryAfterMs(headers, at = Date.now()) {
1649
+ const read = (key) => typeof headers?.get === "function" ? headers.get(key) : headers?.[key];
1650
+ const millis = read("retry-after-ms");
1651
+ if (millis !== void 0 && millis !== null) {
1652
+ const value = Number(millis);
1653
+ if (Number.isFinite(value)) return value > 0 ? Math.min(value, Number.MAX_SAFE_INTEGER) : void 0;
1654
+ }
1655
+ const raw = read("retry-after");
1656
+ if (typeof raw !== "string" || !raw.trim()) return void 0;
1657
+ const seconds = Number(raw), value = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(raw) - at;
1658
+ return Number.isFinite(value) && value > 0 ? Math.min(value, Number.MAX_SAFE_INTEGER) : void 0;
1659
+ }
1660
+ function createModelRetryHint({ now = Date.now, ErrorClass = dshLlm.LlmError } = {}) {
1661
+ let response, outputStarted = false;
1662
+ return {
1663
+ onResponse(info) {
1664
+ response = [429, 503].includes(info?.status) ? {
1665
+ status: info.status,
1666
+ delay: providerRetryAfterMs(info.headers, now())
1667
+ } : void 0;
1668
+ },
1669
+ observe(event) {
1670
+ if (event && ![
1671
+ "start",
1672
+ "done",
1673
+ "error"
1674
+ ].includes(event.type)) outputStarted = true;
1675
+ },
1676
+ failure(original, signal) {
1677
+ if (signal?.aborted || outputStarted || !response || !original || typeof original.message !== "string" || [
1678
+ "ABORTED",
1679
+ "QUOTA",
1680
+ "ACCOUNT_QUOTA",
1681
+ "QUOTA_EXCEEDED"
1682
+ ].includes(original.code) || typeof dshLlm.isQuotaExceededError === "function" && dshLlm.isQuotaExceededError(original.message)) return original;
1683
+ if (/You have hit your ChatGPT usage limit/iu.test(original.message) || response.status === 429 && original.code !== "RATE_LIMIT") return original;
1684
+ let error;
1685
+ try {
1686
+ error = new ErrorClass(original.message, response.status === 429 ? "RATE_LIMIT" : "SERVER", {
1687
+ status: response.status,
1688
+ ...response.delay === void 0 ? {} : { providerRetryAfterMs: response.delay }
1689
+ });
1690
+ } catch {
1691
+ return original;
1692
+ }
1693
+ return error.failure?.status === response.status && (response.delay === void 0 || error.failure.providerRetryAfterMs === response.delay) ? {
1694
+ ...original,
1695
+ ...error.failure
1696
+ } : original;
1697
+ }
1698
+ };
1699
+ }
1700
+ /** One request-local scope spanning the provider and DSH adapter; no timers or replay. */
1701
+ function createModelRetryBridge() {
1702
+ const scope = new AsyncLocalStorage();
1703
+ const wrapStream = (factory, options) => (async function* () {
1704
+ const hint = createModelRetryHint();
1705
+ const iterator = scope.run(hint, () => factory(options)[Symbol.asyncIterator]());
1706
+ try {
1707
+ while (true) {
1708
+ const result = await scope.run(hint, () => iterator.next());
1709
+ if (result.done) return;
1710
+ const event = result.value;
1711
+ if (event.type === "finish" && event.reason?.kind === "error") yield {
1712
+ ...event,
1713
+ reason: {
1714
+ ...event.reason,
1715
+ failure: hint.failure(event.reason.failure, options.signal)
1716
+ }
1717
+ };
1718
+ else yield event;
1719
+ }
1720
+ } finally {
1721
+ await scope.run(hint, () => iterator.return?.());
1722
+ }
1723
+ })();
1724
+ return {
1725
+ current: () => scope.getStore(),
1726
+ wrapAdapter(adapter) {
1727
+ return new Proxy(adapter, { get(target, property) {
1728
+ if (property === "stream") return (options) => wrapStream((o) => target.stream(o), options);
1729
+ if (property === "prepareCall" && typeof target.prepareCall === "function") return async (...args) => {
1730
+ const call = await target.prepareCall(...args);
1731
+ return {
1732
+ ...call,
1733
+ stream: (options) => wrapStream((o) => call.stream(o), options)
1734
+ };
1735
+ };
1736
+ const value = Reflect.get(target, property, target);
1737
+ return typeof value === "function" ? value.bind(target) : value;
1738
+ } });
1739
+ }
1740
+ };
1741
+ }
1742
+ //#endregion
1637
1743
  //#region src/pi-ai-runtime.js
1638
1744
  const FAST_SERVICE_TIER = "priority";
1639
1745
  const ULTRAFAST_SERVICE_TIER = "ultrafast";
@@ -1705,6 +1811,7 @@ function isDshAutoReview(context) {
1705
1811
  */
1706
1812
  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
1813
  const provider = createOpenAICodexProvider();
1814
+ const retryBridge = createModelRetryBridge();
1708
1815
  const requestToken = Object.freeze({
1709
1816
  name: "DSH-managed Codex OAuth request token",
1710
1817
  async resolve({ credential }) {
@@ -1869,6 +1976,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1869
1976
  let iterator;
1870
1977
  let prepared;
1871
1978
  let stage = "prepare";
1979
+ const retryHint = direct ? void 0 : retryBridge.current();
1872
1980
  const step = async (method, value) => {
1873
1981
  try {
1874
1982
  const request = await (prepared ??= (direct ? void 0 : connection?.prepare(options)) ?? Promise.resolve({ options }));
@@ -1877,6 +1985,10 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1877
1985
  const next = direct ? request.options : compaction?.requestOptions(request.options) ?? request.options;
1878
1986
  iterator ??= factory({
1879
1987
  ...next,
1988
+ async onResponse(info, requestModel) {
1989
+ retryHint?.onResponse(info);
1990
+ return next.onResponse?.(info, requestModel);
1991
+ },
1880
1992
  async onPayload(payload, requestModel) {
1881
1993
  stage = "payload";
1882
1994
  return next.onPayload?.(payload, requestModel);
@@ -1888,6 +2000,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1888
2000
  }));
1889
2001
  }, direct ? request.network : compaction?.networkOptions(request.network) ?? request.network);
1890
2002
  if (!result.done) {
2003
+ retryHint?.observe(result.value, request.options?.signal);
1891
2004
  if (result.value?.type === "error" && !request.options?.signal?.aborted) noteStreamFailure(stage, void 0, source);
1892
2005
  else if (stage === "payload") stage = "stream";
1893
2006
  }
@@ -1935,7 +2048,8 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1935
2048
  streamSimple: (model, context, options) => routed("streamSimple", model, context, options),
1936
2049
  reviewCounters: () => ({ ...review }),
1937
2050
  streamFailure: () => ({ ...streamFailure }),
1938
- noteAdapterFailure
2051
+ noteAdapterFailure,
2052
+ wrapRetryAdapter: (adapter) => retryBridge.wrapAdapter(adapter)
1939
2053
  });
1940
2054
  }
1941
2055
  Object.freeze([
@@ -2184,7 +2298,7 @@ function createReasoningBridge({ enabled = () => false, cloud = () => false, unl
2184
2298
  };
2185
2299
  };
2186
2300
  const wrapStream = (factory, options) => (async function* () {
2187
- if (isDshAutoReview(options)) {
2301
+ if (isDshAutoReview(options) || options.purpose === "session-title") {
2188
2302
  yield* unscoped(factory, options);
2189
2303
  return;
2190
2304
  }
@@ -3392,7 +3506,7 @@ function inheritedOriginalImageRef(session, assetId) {
3392
3506
  }
3393
3507
  //#endregion
3394
3508
  //#region src/version.js
3395
- const PACKAGE_VERSION = "3.1.6";
3509
+ const PACKAGE_VERSION = "3.1.7";
3396
3510
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
3397
3511
  //#endregion
3398
3512
  //#region src/codex-images.js
@@ -6001,8 +6115,9 @@ function parseEvent(payload) {
6001
6115
  * Ask the ChatGPT backend for a voice call: the browser's WebRTC offer goes in with the session settings, the answer
6002
6116
  * comes back as plain SDP and the call id in the Location header. The same request the phone makes for its own call.
6003
6117
  */
6004
- async function createVoiceCall({ fetch, credentials, userAgent, sdp, session, base = "https://chatgpt.com/backend-api", threadId }) {
6005
- const { access, accountId } = await credentials();
6118
+ async function createVoiceCall({ fetch, credentials, userAgent, sdp, session, base = "https://chatgpt.com/backend-api", threadId, signal }) {
6119
+ signal?.throwIfAborted();
6120
+ const { access, accountId } = await credentials(signal);
6006
6121
  const response = await fetch(`${base}/wham/realtime/calls?intent=quicksilver&architecture=avas`, {
6007
6122
  method: "POST",
6008
6123
  headers: {
@@ -6019,7 +6134,7 @@ async function createVoiceCall({ fetch, credentials, userAgent, sdp, session, ba
6019
6134
  sdp,
6020
6135
  session
6021
6136
  }),
6022
- signal: AbortSignal.timeout(2e4)
6137
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(2e4)]) : AbortSignal.timeout(2e4)
6023
6138
  });
6024
6139
  const answer = await response.text();
6025
6140
  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 +6177,29 @@ function createRealtimeVoice(options) {
6062
6177
  error() {}
6063
6178
  };
6064
6179
  const sessions = /* @__PURE__ */ new Map();
6065
- const connect = (base, callId, headers) => new Promise((resolve, reject) => {
6180
+ const starts = /* @__PURE__ */ new Map();
6181
+ const connect = (base, callId, headers, signal) => new Promise((resolve, reject) => {
6182
+ signal?.throwIfAborted();
6066
6183
  const url = `${base.replace(/\/$/, "")}/${encodeURIComponent(callId)}`;
6067
6184
  const ws = new options.WebSocket(url, { headers });
6068
6185
  let settled = false;
6186
+ const abort = () => {
6187
+ fail(/* @__PURE__ */ new Error("Voice start cancelled"));
6188
+ try {
6189
+ ws.close();
6190
+ } catch {}
6191
+ };
6069
6192
  const fail = (error) => {
6070
6193
  if (!settled) {
6071
6194
  settled = true;
6195
+ signal?.removeEventListener("abort", abort);
6072
6196
  reject(error);
6073
6197
  }
6074
6198
  };
6075
6199
  ws.on("open", () => {
6076
6200
  if (!settled) {
6077
6201
  settled = true;
6202
+ signal?.removeEventListener("abort", abort);
6078
6203
  resolve(ws);
6079
6204
  }
6080
6205
  });
@@ -6088,16 +6213,19 @@ function createRealtimeVoice(options) {
6088
6213
  });
6089
6214
  ws.on("error", (error) => fail(error));
6090
6215
  ws.on("close", () => fail(/* @__PURE__ */ new Error("closed before it opened")));
6216
+ signal?.addEventListener("abort", abort, { once: true });
6091
6217
  });
6092
- async function join(callId, headers) {
6218
+ async function join(callId, headers, signal) {
6093
6219
  let last;
6094
6220
  for (const base of bases) {
6095
6221
  const host = new URL(base).host;
6096
6222
  for (let attempt = 0; attempt <= ACTIVATION_RETRY_MS.length; attempt++) try {
6097
- const ws = await connect(base, callId, headers);
6223
+ signal?.throwIfAborted();
6224
+ const ws = await connect(base, callId, headers, signal);
6098
6225
  log.info("voice", `joined the voice call on ${host}`);
6099
6226
  return ws;
6100
6227
  } catch (error) {
6228
+ signal?.throwIfAborted();
6101
6229
  last = error;
6102
6230
  if (error?.status === 404 && attempt < ACTIVATION_RETRY_MS.length) {
6103
6231
  await new Promise((resolve) => setTimeout(resolve, ACTIVATION_RETRY_MS[attempt]));
@@ -6116,8 +6244,11 @@ function createRealtimeVoice(options) {
6116
6244
  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
6245
  };
6118
6246
  const stop = (threadId, reason = "requested") => {
6247
+ const pending = starts.get(threadId);
6248
+ starts.delete(threadId);
6249
+ pending?.abort();
6119
6250
  const session = sessions.get(threadId);
6120
- if (!session) return false;
6251
+ if (!session) return pending !== void 0;
6121
6252
  sessions.delete(threadId);
6122
6253
  session.ended = true;
6123
6254
  log.info("voice", "the voice call ended", reason);
@@ -6138,21 +6269,48 @@ function createRealtimeVoice(options) {
6138
6269
  }).catch(() => {});
6139
6270
  return true;
6140
6271
  };
6141
- async function start(params, notify) {
6272
+ async function start(params, notify, { signal } = {}) {
6142
6273
  const threadId = typeof params?.threadId === "string" ? params.threadId : "";
6143
6274
  const callId = params?.transport?.type === "existingCall" ? params.transport.callId : void 0;
6144
6275
  if (threadId === "") throw new Error("The voice start has no thread");
6145
6276
  if (typeof callId !== "string" || callId === "") throw new Error("Live voice needs a call the phone has already set up");
6146
6277
  stop(threadId, "replaced");
6147
- const { access, accountId } = await options.credentials();
6148
- const ws = await join(callId, {
6278
+ const pending = new AbortController();
6279
+ starts.set(threadId, pending);
6280
+ const lifetime = signal ? AbortSignal.any([signal, pending.signal]) : pending.signal;
6281
+ let credential, ws;
6282
+ try {
6283
+ lifetime.throwIfAborted();
6284
+ credential = await options.credentials(lifetime);
6285
+ lifetime.throwIfAborted();
6286
+ } catch (error) {
6287
+ if (starts.get(threadId) === pending) starts.delete(threadId);
6288
+ throw error;
6289
+ }
6290
+ const { access, accountId } = credential;
6291
+ const headers = {
6149
6292
  authorization: `Bearer ${access}`,
6150
6293
  "chatgpt-account-id": accountId,
6151
6294
  "openai-alpha": "quicksilver=v2",
6152
6295
  "user-agent": options.userAgent,
6153
6296
  ...typeof params.realtimeSessionId === "string" ? { "x-session-id": params.realtimeSessionId } : {},
6154
6297
  ...typeof params.voiceSessionId === "string" ? { "voice-session-id": params.voiceSessionId } : {}
6155
- });
6298
+ };
6299
+ try {
6300
+ ws = await join(callId, headers, lifetime);
6301
+ lifetime.throwIfAborted();
6302
+ } catch (error) {
6303
+ if (starts.get(threadId) === pending) starts.delete(threadId);
6304
+ try {
6305
+ ws?.close();
6306
+ } catch {}
6307
+ throw error;
6308
+ }
6309
+ if (starts.get(threadId) !== pending) {
6310
+ ws.close();
6311
+ throw new Error("Voice start replaced");
6312
+ }
6313
+ starts.delete(threadId);
6156
6314
  const session = {
6157
6315
  ws,
6158
6316
  notify,
@@ -6377,7 +6535,7 @@ function createRealtimeVoice(options) {
6377
6535
  };
6378
6536
  },
6379
6537
  closeAll: () => {
6380
- for (const threadId of [...sessions.keys()]) stop(threadId, "shutdown");
6538
+ for (const threadId of /* @__PURE__ */ new Set([...sessions.keys(), ...starts.keys()])) stop(threadId, "shutdown");
6381
6539
  }
6382
6540
  };
6383
6541
  }
@@ -6952,6 +7110,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6952
7110
  const threadSources = /* @__PURE__ */ new Map();
6953
7111
  const active = /* @__PURE__ */ new Map();
6954
7112
  const queues = /* @__PURE__ */ new Map();
7113
+ const starting = /* @__PURE__ */ new Map();
6955
7114
  let catalog;
6956
7115
  const service = () => {
6957
7116
  const value = controller();
@@ -7079,18 +7238,18 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7079
7238
  const values = projections()?.snapshot?.(session, ["tokenUsage", "contextPressure"])?.values;
7080
7239
  const used = values?.tokenUsage;
7081
7240
  if (!used) return void 0;
7082
- const breakdown = (total, input, cached, output) => ({
7241
+ const breakdown = (total, input, cached, output, written = 0) => ({
7083
7242
  totalTokens: total,
7084
7243
  inputTokens: input,
7085
7244
  cachedInputTokens: cached,
7086
- cacheWriteInputTokens: 0,
7245
+ cacheWriteInputTokens: written,
7087
7246
  outputTokens: output,
7088
7247
  reasoningOutputTokens: 0
7089
7248
  });
7090
7249
  const input = (used.uncachedInputTokens ?? 0) + (used.cacheReadTokens ?? 0) + (used.cacheWriteTokens ?? 0);
7091
7250
  const pressure = values.contextPressure?.pressureTokens ?? 0;
7092
7251
  return {
7093
- total: breakdown(input + (used.outputTokens ?? 0), input, used.cacheReadTokens ?? 0, used.outputTokens ?? 0),
7252
+ total: breakdown(input + (used.outputTokens ?? 0), input, used.cacheReadTokens ?? 0, used.outputTokens ?? 0, used.cacheWriteTokens ?? 0),
7094
7253
  last: breakdown(pressure, pressure, 0, 0),
7095
7254
  modelContextWindow: values.contextPressure?.contextWindow ?? null
7096
7255
  };
@@ -7441,7 +7600,35 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7441
7600
  }], ...images]
7442
7601
  };
7443
7602
  };
7444
- async function startTurn(params, notify) {
7603
+ async function startTurn(params, notify, queued) {
7604
+ const id = params?.threadId;
7605
+ if (active.has(id) || starting.has(id)) throw invalidParams("A turn is already running in this conversation");
7606
+ const launch = {
7607
+ queued,
7608
+ submitted: false,
7609
+ abort: new AbortController()
7610
+ };
7611
+ starting.set(id, launch);
7612
+ try {
7613
+ return await acceptTurn(params, notify, launch);
7614
+ } catch (error) {
7615
+ if (launch.abort.signal.aborted && error?.name === "AbortError") throw new RpcError(-32800, "Turn start cancelled");
7616
+ throw error;
7617
+ } finally {
7618
+ if (starting.get(id) === launch) starting.delete(id);
7619
+ }
7620
+ }
7621
+ async function startQueuedTurn(id, notify, queuedId, selection = {}) {
7622
+ const queued = (queues.get(id) ?? []).find((entry) => queuedId == null || entry.id === queuedId);
7623
+ if (!queued) throw invalidParams("Nothing queued");
7624
+ return startTurn({
7625
+ ...selection,
7626
+ threadId: id,
7627
+ input: queued.input,
7628
+ clientUserMessageId: queued.clientUserMessageId
7629
+ }, notify, queued);
7630
+ }
7631
+ async function acceptTurn(params, notify, launch) {
7445
7632
  const { text, pictures, content } = contentOf(params?.input);
7446
7633
  lastPrompt.text = text;
7447
7634
  const id = params?.threadId;
@@ -7452,7 +7639,18 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7452
7639
  applyPermissions(agent, params);
7453
7640
  const speedBefore = speed?.current?.();
7454
7641
  const speedForTurn = typeof params?.serviceTierForTurn === "string" ? params.serviceTierForTurn : void 0;
7455
- await applySpeed(speedForTurn ?? (Object.hasOwn(params ?? {}, "serviceTier") ? params.serviceTier : void 0));
7642
+ const restoreSpeed = async () => {
7643
+ if (speedForTurn !== void 0 && speedBefore !== void 0 && speed?.current?.() !== speedBefore) await Promise.resolve(speed.set?.(speedBefore)).catch(() => {});
7644
+ };
7645
+ try {
7646
+ await applySpeed(speedForTurn ?? (Object.hasOwn(params ?? {}, "serviceTier") ? params.serviceTier : void 0));
7647
+ launch.abort.signal.throwIfAborted();
7648
+ if (active.has(id)) throw invalidParams("A turn is already running in this conversation");
7649
+ if (launch.queued && !(queues.get(id) ?? []).includes(launch.queued)) throw invalidParams("Queued submission was deleted before starting");
7650
+ } catch (error) {
7651
+ await restoreSpeed();
7652
+ throw error;
7653
+ }
7456
7654
  const turn = emptyTurn();
7457
7655
  const userItem = {
7458
7656
  type: "userMessage",
@@ -7473,7 +7671,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7473
7671
  userItem,
7474
7672
  priorMessageIds: new Set(agent.session.deriveMessages().map((message) => message.id)),
7475
7673
  pendingImages: /* @__PURE__ */ new Set(),
7476
- abort: new AbortController()
7674
+ pendingSteers: /* @__PURE__ */ new Set(),
7675
+ abort: launch.abort
7477
7676
  };
7478
7677
  active.set(id, running);
7479
7678
  phoneLog("turn accepted", {
@@ -7508,25 +7707,61 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7508
7707
  completedAtMs: Date.now()
7509
7708
  });
7510
7709
  try {
7511
- await service().prompt({
7512
- requestId: randomUUID(),
7710
+ launch.submitted = true;
7711
+ if ((await service().prompt({
7712
+ requestId: launch.queued?.id ?? randomUUID(),
7513
7713
  sessionId: id,
7514
7714
  mode: "queue",
7515
7715
  content
7516
- }, AbortSignal.timeout(3e4));
7716
+ }, AbortSignal.any([running.abort.signal, AbortSignal.timeout(3e4)])))?.accepted === false) throw new Error("DSH rejected the message");
7517
7717
  } catch (error) {
7518
- active.delete(id);
7718
+ if (active.get(id) === running) active.delete(id);
7719
+ const cancelled = running.abort.signal.aborted;
7720
+ turn.status = cancelled ? "interrupted" : "failed";
7721
+ turn.completedAt = seconds(Date.now());
7722
+ turn.error = cancelled ? null : {
7723
+ message: "DSH did not accept the message",
7724
+ codexErrorInfo: null,
7725
+ additionalDetails: null
7726
+ };
7727
+ running.abort.abort();
7728
+ emit(id, "turn/completed", {
7729
+ threadId: id,
7730
+ turn
7731
+ });
7732
+ emit(id, "thread/status/changed", {
7733
+ threadId: id,
7734
+ status: { type: "idle" }
7735
+ });
7736
+ await restoreSpeed();
7737
+ if (cancelled) throw new RpcError(-32800, "Turn start cancelled");
7519
7738
  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
7739
  }
7740
+ if (launch.queued) {
7741
+ queues.set(id, (queues.get(id) ?? []).filter((entry) => entry.id !== launch.queued.id));
7742
+ emit(id, "thread/queue/changed", { threadId: id });
7743
+ }
7744
+ if (running.abort.signal.aborted) {
7745
+ running.ended ??= { kind: "aborted" };
7746
+ await Promise.resolve(service().cancel({ sessionId: id })).catch(() => {});
7747
+ }
7748
+ if (starting.get(id) === launch) starting.delete(id);
7521
7749
  Promise.resolve(agent.whenIdle?.()).catch(() => {}).then(async () => {
7750
+ running.finishing = true;
7751
+ const pendingSteers = [...running.pendingSteers];
7752
+ if (pendingSteers.length) {
7753
+ await Promise.allSettled(pendingSteers);
7754
+ await Promise.resolve(agent.whenIdle?.()).catch(() => {});
7755
+ }
7522
7756
  if (running.pendingImages.size) phoneLog("waiting for tool images", {
7523
7757
  threadId: id,
7524
7758
  turnId: turn.id,
7525
7759
  pending: running.pendingImages.size
7526
7760
  });
7527
7761
  await Promise.allSettled([...running.pendingImages]);
7762
+ if (active.get(id) !== running) return;
7528
7763
  turn.items = withRemoteImageOutput(turn).items;
7529
- const reason = active.get(id)?.ended;
7764
+ const reason = running.ended;
7530
7765
  turn.status = reason?.kind === "error" ? "failed" : reason?.kind === "aborted" || reason?.kind === "interrupted" ? "interrupted" : "completed";
7531
7766
  if (reason?.kind === "error") {
7532
7767
  const message = String(reason.error?.message ?? reason.error?.code ?? "The model request failed").slice(0, 500);
@@ -7548,6 +7783,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7548
7783
  for (const message of agent.session.deriveMessages()) reconcileUser(id, running, message);
7549
7784
  } catch {}
7550
7785
  active.delete(id);
7786
+ running.abort.abort();
7551
7787
  compactions.delete(id);
7552
7788
  const usageNow = tokenUsage(agent.session);
7553
7789
  if (usageNow) emit(id, "thread/tokenUsage/updated", {
@@ -7569,16 +7805,10 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7569
7805
  threadId: id,
7570
7806
  status: { type: "idle" }
7571
7807
  });
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
- }
7808
+ if (queues.get(id)?.length) startQueuedTurn(id, notify).catch((error) => phoneLog("queued turn not accepted", {
7809
+ threadId: id,
7810
+ code: error?.code
7811
+ }, "warn"));
7582
7812
  });
7583
7813
  return { turn: {
7584
7814
  ...turn,
@@ -8073,8 +8303,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8073
8303
  },
8074
8304
  "turn/start": (params, { notify }) => titles.has(params?.threadId) ? titleTurn(params, notify) : startTurn(params, notify),
8075
8305
  "turn/interrupt": (params) => {
8076
- service().cancel({ sessionId: params?.threadId });
8077
8306
  active.get(params?.threadId)?.abort?.abort();
8307
+ starting.get(params?.threadId)?.abort.abort();
8308
+ service().cancel({ sessionId: params?.threadId });
8078
8309
  return {};
8079
8310
  },
8080
8311
  "thread/compact/start": async (params, { notify }) => {
@@ -8082,7 +8313,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8082
8313
  const registry = commands();
8083
8314
  const agent = await agentFor(id);
8084
8315
  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");
8316
+ if (active.has(id) || starting.has(id)) throw new RpcError(-32602, "A turn is already running in this conversation");
8086
8317
  subscribe(id, notify);
8087
8318
  const turn = emptyTurn();
8088
8319
  const abort = new AbortController();
@@ -8162,15 +8393,34 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8162
8393
  })();
8163
8394
  return {};
8164
8395
  },
8165
- "turn/steer": async (params) => {
8396
+ "turn/steer": async (params, { signal } = {}) => {
8397
+ const running = active.get(params?.threadId);
8398
+ 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;
8399
+ signal?.throwIfAborted();
8400
+ if (!current()) throw invalidParams("The expected turn is not active");
8166
8401
  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 ?? "" };
8402
+ const operation = (async () => {
8403
+ if ((await service().prompt({
8404
+ requestId: randomUUID(),
8405
+ sessionId: params.threadId,
8406
+ mode: "steer",
8407
+ content
8408
+ }, AbortSignal.any([
8409
+ running.abort.signal,
8410
+ AbortSignal.timeout(3e4),
8411
+ ...signal ? [signal] : []
8412
+ ])))?.accepted === false) throw invalidParams("DSH rejected the steering message");
8413
+ if (!current()) {
8414
+ if (active.get(params.threadId) === running) await Promise.resolve(service().cancel({ sessionId: params.threadId })).catch(() => {});
8415
+ }
8416
+ return { turnId: running.turn.id };
8417
+ })();
8418
+ running.pendingSteers.add(operation);
8419
+ try {
8420
+ return await operation;
8421
+ } finally {
8422
+ running.pendingSteers.delete(operation);
8423
+ }
8174
8424
  },
8175
8425
  "thread/name/set": async (params) => {
8176
8426
  await service().rename({
@@ -8189,6 +8439,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8189
8439
  }),
8190
8440
  "thread/queue/add": async (params, { notify }) => {
8191
8441
  if (!Array.isArray(params?.input)) throw invalidParams("input is required");
8442
+ contentOf(params.input);
8192
8443
  const id = params?.threadId;
8193
8444
  const queued = {
8194
8445
  id: randomUUID(),
@@ -8196,20 +8447,17 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8196
8447
  input: params.input
8197
8448
  };
8198
8449
  subscribe(id, notify);
8199
- if (!active.has(id)) await startTurn({
8200
- threadId: id,
8201
- input: queued.input,
8202
- clientUserMessageId: queued.clientUserMessageId,
8450
+ queues.set(id, [...queues.get(id) ?? [], queued]);
8451
+ emit(id, "thread/queue/changed", { threadId: id });
8452
+ if (!active.has(id) && !starting.has(id)) await startQueuedTurn(id, notify, queued.id, {
8203
8453
  model: params.model,
8204
8454
  effort: params.effort
8205
- }, notify);
8206
- else {
8207
- queues.set(id, [...queues.get(id) ?? [], queued]);
8208
- emit(id, "thread/queue/changed", { threadId: id });
8209
- }
8455
+ });
8210
8456
  return { queuedSubmission: queued };
8211
8457
  },
8212
8458
  "thread/queue/delete": (params) => {
8459
+ const launch = starting.get(params?.threadId);
8460
+ if (launch?.submitted && launch.queued?.id === params?.queuedSubmissionId) throw invalidParams("Queued submission is being accepted");
8213
8461
  const list = queues.get(params?.threadId) ?? [];
8214
8462
  const next = list.filter((entry) => entry.id !== params?.queuedSubmissionId);
8215
8463
  queues.set(params?.threadId, next);
@@ -8217,24 +8465,13 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8217
8465
  return { deleted: next.length !== list.length };
8218
8466
  },
8219
8467
  "thread/queue/reorder": (params) => {
8220
- const order = Array.isArray(params?.queuedSubmissionIds) ? params.queuedSubmissionIds : [];
8468
+ const order = Array.isArray(params?.queuedSubmissionIds) ? [...new Set(params.queuedSubmissionIds)] : [];
8221
8469
  const list = queues.get(params?.threadId) ?? [];
8222
8470
  queues.set(params?.threadId, [...order.map((id) => list.find((entry) => entry.id === id)).filter(Boolean), ...list.filter((entry) => !order.includes(entry.id))]);
8223
8471
  emit(params?.threadId, "thread/queue/changed", { threadId: params?.threadId });
8224
8472
  return {};
8225
8473
  },
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
- }
8474
+ "thread/queue/start": (params, { notify }) => startQueuedTurn(params?.threadId, notify, params?.queuedSubmissionId)
8238
8475
  };
8239
8476
  const callOf = (session, callId) => {
8240
8477
  for (const message of session.deriveMessages().toReversed()) {
@@ -8632,40 +8869,43 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8632
8869
  if (!set.has(notify)) subscribe(threadId, notify);
8633
8870
  }
8634
8871
  };
8872
+ const startDesktopVoice = async ({ sessionId, sdp, voice: voiceName, language, signal }) => {
8873
+ if (typeof sdp !== "string" || !sdp.startsWith("v=0") || sdp.length > 64 * 1024) throw new RpcError(-32602, "Invalid voice offer");
8874
+ const agent = await agentFor(sessionId);
8875
+ diagnosticLog.info("voice", "the conversation can take a context note", String(typeof agent.inject === "function"));
8876
+ const session = {
8877
+ audio: { output: { voice: typeof voiceName === "string" && /^[a-z]{2,16}$/u.test(voiceName) ? voiceName : "cove" } },
8878
+ delegation: { type: "client" },
8879
+ instructions: desktopInstructions(language),
8880
+ model: "gpt-live-1.1-codex"
8881
+ };
8882
+ const { callId, answer } = await createVoiceCall({
8883
+ fetch: voice.fetch,
8884
+ credentials: voice.credentials,
8885
+ userAgent,
8886
+ sdp,
8887
+ session,
8888
+ threadId: sessionId,
8889
+ signal
8890
+ });
8891
+ signal?.throwIfAborted();
8892
+ await realtimeVoice.start({
8893
+ threadId: sessionId,
8894
+ transport: {
8895
+ type: "existingCall",
8896
+ callId
8897
+ },
8898
+ flushTranscriptTailOnSessionEnd: true,
8899
+ silentTailRecord: true,
8900
+ hangUpOnGoodbye: true,
8901
+ version: "v3"
8902
+ }, async () => {}, { signal });
8903
+ return { answer };
8904
+ };
8635
8905
  return {
8636
8906
  methods,
8637
8907
  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
- },
8908
+ start: startDesktopVoice,
8669
8909
  stop: (sessionId) => realtimeVoice.stop(sessionId),
8670
8910
  interrupt: (sessionId) => realtimeVoice.interrupt(sessionId),
8671
8911
  end: (sessionId) => realtimeVoice.requestClose(sessionId),
@@ -8676,6 +8916,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8676
8916
  onApproval,
8677
8917
  onQuestion,
8678
8918
  adopt,
8919
+ close() {
8920
+ realtimeVoice?.closeAll();
8921
+ },
8679
8922
  forget: (notify) => {
8680
8923
  for (const set of subscribers.values()) set.delete(notify);
8681
8924
  }
@@ -9855,6 +10098,110 @@ function createCodexRpcHandler(coordinator, options = {}) {
9855
10098
  };
9856
10099
  }
9857
10100
  //#endregion
10101
+ //#region src/model-catalog-cache.js
10102
+ const SCHEMA_VERSION = 1;
10103
+ const MAX_AGE_MS = 1440 * 60 * 1e3;
10104
+ const MAX_BYTES = 4 * 1024 * 1024;
10105
+ /**
10106
+ * 按账号身份读取并校验本地模型目录缓存。
10107
+ * @param {string} accountId - 当前 OAuth 账号标识
10108
+ * @param {{ directory?: string, now?: number, parseCatalog: Function }} options - 缓存目录与目录校验方法
10109
+ * @returns {Promise<{ rawCatalog: object, etag?: string } | undefined>} 有效目录缓存;缺失或无效时返回 undefined
10110
+ */
10111
+ async function loadModelCatalogCache(accountId, options) {
10112
+ const { accountKey, filename } = cacheLocation(accountId, options.directory);
10113
+ let entry;
10114
+ try {
10115
+ options.signal?.throwIfAborted();
10116
+ if ((await stat(filename)).size > MAX_BYTES) return void 0;
10117
+ entry = JSON.parse(await readFile(filename, {
10118
+ encoding: "utf8",
10119
+ signal: options.signal
10120
+ }));
10121
+ } catch (error) {
10122
+ if (error?.code === "ENOENT" || error instanceof SyntaxError) return void 0;
10123
+ throw error;
10124
+ }
10125
+ const now = options.now ?? Date.now();
10126
+ 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;
10127
+ try {
10128
+ const parsed = options.parseCatalog(entry.rawCatalog, now);
10129
+ if (!Array.isArray(parsed) || parsed.length === 0) return void 0;
10130
+ } catch {
10131
+ return;
10132
+ }
10133
+ return {
10134
+ rawCatalog: entry.rawCatalog,
10135
+ ...entry.etag === void 0 ? {} : { etag: entry.etag }
10136
+ };
10137
+ }
10138
+ /**
10139
+ * 将经过目录校验的原始账号目录以原子替换方式保存。
10140
+ * @param {string} accountId - 当前 OAuth 账号标识
10141
+ * @param {{ rawCatalog: object, etag?: string }} catalog - 远端返回的完整目录和 ETag
10142
+ * @param {{ directory?: string, now?: number, parseCatalog: Function, isCurrent?: () => boolean }} options - 缓存目录、目录校验方法和写入状态检查
10143
+ * @returns {Promise<void>} 缓存写入完成
10144
+ */
10145
+ async function saveModelCatalogCache(accountId, catalog, options) {
10146
+ options.signal?.throwIfAborted();
10147
+ const { accountKey, filename } = cacheLocation(accountId, options.directory);
10148
+ const now = options.now ?? Date.now();
10149
+ 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");
10150
+ const parsed = options.parseCatalog(catalog.rawCatalog, now);
10151
+ if (!Array.isArray(parsed) || parsed.length === 0) throw new Error("Refusing to persist an empty model catalog cache");
10152
+ const data = `${JSON.stringify({
10153
+ schemaVersion: SCHEMA_VERSION,
10154
+ accountKey,
10155
+ savedAt: now,
10156
+ ...catalog.etag === void 0 ? {} : { etag: catalog.etag },
10157
+ rawCatalog: catalog.rawCatalog
10158
+ })}\n`;
10159
+ if (Buffer.byteLength(data) > MAX_BYTES) throw new Error("Model catalog cache exceeds its size limit");
10160
+ if (options.isCurrent?.() === false) return;
10161
+ await mkdir(dirname(filename), {
10162
+ recursive: true,
10163
+ mode: 448
10164
+ });
10165
+ const temporary = `${filename}.${process.pid}.${randomUUID()}.tmp`;
10166
+ let handle;
10167
+ try {
10168
+ handle = await open(temporary, "wx", 384);
10169
+ options.signal?.throwIfAborted();
10170
+ await handle.writeFile(data, { signal: options.signal });
10171
+ await handle.sync();
10172
+ await handle.close();
10173
+ handle = void 0;
10174
+ options.signal?.throwIfAborted();
10175
+ if (options.isCurrent !== void 0 && !options.isCurrent()) return;
10176
+ await rename(temporary, filename);
10177
+ } finally {
10178
+ await handle?.close().catch(() => void 0);
10179
+ await rm(temporary, { force: true }).catch(() => void 0);
10180
+ }
10181
+ }
10182
+ /**
10183
+ * 根据账号标识生成只含摘要的缓存路径。
10184
+ * @param {string} accountId - OAuth 账号标识
10185
+ * @param {string | undefined} directory - 可选缓存目录
10186
+ * @returns {{ accountKey: string, filename: string }} 账号摘要和缓存文件路径
10187
+ */
10188
+ function cacheLocation(accountId, directory) {
10189
+ if (typeof accountId !== "string" || accountId.length === 0) throw new Error("A current account is required for the model catalog cache");
10190
+ const accountKey = createHash("sha256").update(accountId).digest("hex");
10191
+ return {
10192
+ accountKey,
10193
+ filename: join(directory ?? dshHomePath("state", "codex-subscription", "model-catalog"), `${accountKey}.json`)
10194
+ };
10195
+ }
10196
+ /**
10197
+ * 判断值是否为普通记录。
10198
+ * @param {unknown} value - 待检查的值
10199
+ * @returns {boolean} 值是否为普通记录
10200
+ */
10201
+ function isRecord(value) {
10202
+ return value !== null && typeof value === "object" && !Array.isArray(value);
10203
+ }
10204
+ //#endregion
9858
10205
  //#region src/model-catalog.js
9859
10206
  const CODEX_MODELS_URL = `https://chatgpt.com/backend-api/codex/models?client_version=${encodeURIComponent(PACKAGE_VERSION)}`;
9860
10207
  const LEVELS = [
@@ -10044,161 +10391,292 @@ function mergeModel(baseModels, remote) {
10044
10391
  } }
10045
10392
  };
10046
10393
  }
10394
+ /**
10395
+ * 创建带账号缓存、远端刷新和模型能力元数据的官方目录。
10396
+ * @param {object} options - 凭据、模型来源、网络和目录更新配置
10397
+ * @returns {object} 可初始化、刷新、查询和清除的模型目录
10398
+ */
10047
10399
  function createOfficialModelCatalog(options = {}) {
10048
10400
  const fetchCatalog = options.fetch ?? fetch;
10049
10401
  const getNow = options.now ?? Date.now;
10050
- const scheduleTimeout = options.setTimeout ?? setTimeout;
10051
- const cancelTimeout = options.clearTimeout ?? clearTimeout;
10402
+ const schedule = options.setTimeout ?? setTimeout;
10403
+ const cancelTimer = options.clearTimeout ?? clearTimeout;
10052
10404
  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;
10405
+ const loadCache = options.loadCache ?? loadModelCatalogCache;
10406
+ const saveCache = options.saveCache ?? saveModelCatalogCache;
10407
+ const retryDelays = (options.retryDelaysMs ?? []).filter((delay) => Number.isFinite(delay) && delay > 0);
10408
+ let models, rawCatalog, etag, accountId, initializing, refreshing, retryTimer;
10409
+ let metadata = /* @__PURE__ */ new Map(), generation = 0, revision = 0, retries = 0, initialized = false;
10410
+ let source = "unavailable", refreshStatus = "idle", writeSequence = 0;
10411
+ const writes = /* @__PURE__ */ new Set();
10412
+ const notify = () => {
10413
+ try {
10414
+ options.onUpdated?.();
10415
+ } catch {}
10416
+ };
10417
+ const cacheError = (error) => {
10418
+ try {
10419
+ options.onCacheError?.(error);
10420
+ } catch {}
10421
+ };
10064
10422
  const stopRetry = () => {
10065
- if (retryTimer !== void 0) cancelTimeout(retryTimer);
10423
+ if (retryTimer !== void 0) cancelTimer(retryTimer);
10066
10424
  retryTimer = void 0;
10067
10425
  };
10068
- const scheduleRetry = (currentGeneration) => {
10069
- if (models !== void 0 || currentGeneration !== generation || retryTimer !== void 0 || retries >= retryDelays.length) return;
10070
- retryTimer = scheduleTimeout(() => {
10426
+ const cancelled = () => Object.assign(/* @__PURE__ */ new Error("Codex model catalog operation cancelled"), { name: "AbortError" });
10427
+ const current = (flight) => flight.generation === generation && !flight.controller.signal.aborted;
10428
+ const wait = (promise, signal) => {
10429
+ if (!signal) return promise;
10430
+ if (signal.aborted) return Promise.reject(signal.reason ?? cancelled());
10431
+ let abort;
10432
+ const interrupted = new Promise((_, reject) => {
10433
+ abort = () => reject(signal.reason ?? cancelled());
10434
+ signal.addEventListener("abort", abort, { once: true });
10435
+ });
10436
+ return Promise.race([promise, interrupted]).finally(() => signal.removeEventListener("abort", abort));
10437
+ };
10438
+ const bounded = (label, work, signal) => {
10439
+ const controller = new AbortController();
10440
+ const abort = () => controller.abort(signal?.reason ?? cancelled());
10441
+ signal?.addEventListener("abort", abort, { once: true });
10442
+ if (signal?.aborted) abort();
10443
+ const flight = {
10444
+ generation,
10445
+ controller
10446
+ };
10447
+ const timer = schedule(() => controller.abort(/* @__PURE__ */ new Error(`Codex model catalog ${label} timed out`)), timeoutMs);
10448
+ timer.unref?.();
10449
+ const task = Promise.resolve().then(() => {
10450
+ controller.signal.throwIfAborted();
10451
+ return work(flight, controller.signal);
10452
+ });
10453
+ flight.promise = wait(task, controller.signal).finally(() => {
10454
+ cancelTimer(timer);
10455
+ signal?.removeEventListener("abort", abort);
10456
+ });
10457
+ return flight;
10458
+ };
10459
+ const scheduleRetry = (expected) => {
10460
+ if (expected !== generation || retryTimer !== void 0 || retries >= retryDelays.length) return;
10461
+ retryTimer = schedule(() => {
10071
10462
  retryTimer = void 0;
10072
- if (models !== void 0 || currentGeneration !== generation) return;
10073
- refresh().catch(() => {});
10463
+ if (expected === generation) refresh().catch(() => {});
10074
10464
  }, retryDelays[retries++]);
10075
10465
  retryTimer.unref?.();
10076
10466
  };
10467
+ const restore = async (nextAccountId, flight, signal) => {
10468
+ if (!current(flight)) return false;
10469
+ if (accountId !== nextAccountId) {
10470
+ const hadModels = models !== void 0;
10471
+ accountId = nextAccountId;
10472
+ models = rawCatalog = etag = void 0;
10473
+ metadata = /* @__PURE__ */ new Map();
10474
+ source = "unavailable";
10475
+ if (hadModels) {
10476
+ revision += 1;
10477
+ notify();
10478
+ }
10479
+ }
10480
+ let cached;
10481
+ if (nextAccountId && options.cacheDirectory !== void 0) try {
10482
+ cached = await loadCache(nextAccountId, {
10483
+ directory: options.cacheDirectory,
10484
+ now: getNow(),
10485
+ parseCatalog: parseOfficialModelCatalog,
10486
+ signal
10487
+ });
10488
+ } catch (error) {
10489
+ if (!current(flight)) throw error;
10490
+ cacheError(error);
10491
+ }
10492
+ if (!current(flight) || accountId !== nextAccountId) return false;
10493
+ if (cached !== void 0) {
10494
+ const remote = parseOfficialModelCatalog(cached.rawCatalog, getNow());
10495
+ const next = remote.map((model) => mergeModel(options.baseModels(), model)).filter(Boolean);
10496
+ if (next.length) {
10497
+ models = next;
10498
+ rawCatalog = cached.rawCatalog;
10499
+ etag = cached.etag;
10500
+ metadata = new Map(remote.map((model) => [model.id, model]));
10501
+ source = "cached";
10502
+ revision += 1;
10503
+ notify();
10504
+ }
10505
+ }
10506
+ return true;
10507
+ };
10508
+ const initialize = ({ signal } = {}) => {
10509
+ if (signal?.aborted) return Promise.reject(signal.reason ?? cancelled());
10510
+ if (initializing) return wait(initializing.promise, signal);
10511
+ if (initialized) return Promise.resolve(accountId !== void 0);
10512
+ const flight = bounded("initialization", async (flight, requestSignal) => {
10513
+ const credential = await options.readCredential?.({ signal: requestSignal });
10514
+ if (!current(flight)) return false;
10515
+ const id = credential?.type === "oauth" ? nonEmpty$1(credential.accountId) : void 0;
10516
+ await restore(id, flight, requestSignal);
10517
+ if (!current(flight)) return false;
10518
+ initialized = true;
10519
+ return id !== void 0;
10520
+ }, signal);
10521
+ initializing = flight;
10522
+ flight.promise = flight.promise.finally(() => {
10523
+ if (initializing === flight) initializing = void 0;
10524
+ });
10525
+ return flight.promise;
10526
+ };
10527
+ const persist = (id, raw, nextEtag) => {
10528
+ if (options.cacheDirectory === void 0) return;
10529
+ const expected = generation, sequence = ++writeSequence;
10530
+ const flight = bounded("cache write", async (flight, signal) => {
10531
+ await saveCache(id, {
10532
+ rawCatalog: raw,
10533
+ etag: nextEtag
10534
+ }, {
10535
+ directory: options.cacheDirectory,
10536
+ now: getNow(),
10537
+ parseCatalog: parseOfficialModelCatalog,
10538
+ signal,
10539
+ isCurrent: () => current(flight) && accountId === id && writeSequence === sequence
10540
+ });
10541
+ });
10542
+ writes.add(flight);
10543
+ flight.promise.catch((error) => {
10544
+ if (expected === generation) cacheError(error);
10545
+ }).finally(() => writes.delete(flight));
10546
+ };
10077
10547
  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;
10548
+ if (signal?.aborted) return Promise.reject(signal.reason ?? cancelled());
10549
+ if (refreshing) return wait(refreshing.promise, signal);
10081
10550
  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
- };
10551
+ const flight = bounded("refresh", async (flight, requestSignal) => {
10552
+ await initialize({ signal: requestSignal });
10553
+ if (!current(flight)) return false;
10554
+ const credentials = await readSubscriptionCredentials(options.getAuth, options.readCredential, requestSignal);
10555
+ if (!current(flight)) return false;
10556
+ if (!nonEmpty$1(credentials.access) || !nonEmpty$1(credentials.accountId)) {
10557
+ if (accountId !== void 0 || models !== void 0) throw new Error("Codex model catalog credentials are unavailable");
10558
+ refreshStatus = "idle";
10559
+ return false;
10560
+ }
10561
+ if (credentials.accountId !== accountId) {
10562
+ await restore(credentials.accountId, flight, requestSignal);
10563
+ if (!current(flight)) return false;
10564
+ initialized = true;
10565
+ }
10566
+ const id = credentials.accountId;
10103
10567
  const response = await fetchCatalog(CODEX_MODELS_URL, {
10104
10568
  method: "GET",
10105
10569
  redirect: "error",
10106
- headers,
10107
- signal: requestSignal
10570
+ signal: requestSignal,
10571
+ headers: {
10572
+ authorization: `Bearer ${credentials.access}`,
10573
+ "chatgpt-account-id": id,
10574
+ accept: "application/json",
10575
+ originator: "pi",
10576
+ "user-agent": USER_AGENT,
10577
+ ...etag === void 0 ? {} : { "if-none-match": etag }
10578
+ }
10108
10579
  });
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();
10580
+ if (!current(flight) || accountId !== id) return false;
10581
+ if (response.status !== 304 && !response.ok) throw new Error(`Codex model catalog failed (HTTP ${response.status})`);
10582
+ const raw = response.status === 304 ? rawCatalog : await response.json();
10583
+ if (!current(flight) || accountId !== id) return false;
10584
+ if (raw === void 0) throw new Error("Codex returned HTTP 304 without a cached model catalog");
10124
10585
  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;
10586
+ const next = remote.map((model) => mergeModel(options.baseModels(), model)).filter(Boolean);
10587
+ if (!next.length) throw new Error("Codex returned an empty or incompatible model catalog");
10588
+ const changed = response.status !== 304 || JSON.stringify(next) !== JSON.stringify(models);
10589
+ const previousSource = source;
10131
10590
  models = next;
10132
10591
  rawCatalog = raw;
10133
10592
  metadata = new Map(remote.map((model) => [model.id, model]));
10134
10593
  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") {
10594
+ source = "online";
10595
+ refreshStatus = "ok";
10596
+ if (changed) revision += 1;
10597
+ if (changed || previousSource !== "online") notify();
10598
+ if (current(flight) && accountId === id) persist(id, raw, etag);
10599
+ return changed;
10600
+ }, signal);
10601
+ refreshing = flight;
10602
+ flight.promise = flight.promise.then((value) => {
10603
+ if (current(flight)) {
10160
10604
  retries = 0;
10161
10605
  stopRetry();
10162
- } else if (outcome === "failed") scheduleRetry(currentGeneration);
10606
+ }
10607
+ return value;
10608
+ }, (error) => {
10609
+ if (flight.generation === generation) {
10610
+ refreshStatus = signal?.aborted ? "idle" : "failed";
10611
+ if (!signal?.aborted) scheduleRetry(flight.generation);
10612
+ }
10613
+ throw error;
10614
+ }).finally(() => {
10615
+ if (refreshing === flight) refreshing = void 0;
10163
10616
  });
10164
- refreshing = {
10165
- generation: currentGeneration,
10166
- promise,
10167
- cancel: () => controller.abort()
10168
- };
10169
- return promise;
10617
+ return flight.promise;
10170
10618
  };
10171
10619
  return Object.freeze({
10620
+ initialize,
10172
10621
  refresh,
10173
10622
  getModels: () => models ?? [],
10174
- metadata: (modelId) => metadata.get(modelId),
10175
- reviewModel: (parentId) => officialReviewModel(rawCatalog, parentId),
10623
+ metadata: (id) => metadata.get(id),
10624
+ reviewModel: (id) => officialReviewModel(rawCatalog, id),
10176
10625
  revision: () => revision,
10177
10626
  capabilityGaps: () => [...metadata.values()].filter((model) => model.unsupported && /^[a-z][a-z0-9._-]{0,79}$/u.test(model.id)).slice(0, 20).map((model) => ({
10178
10627
  model: model.id,
10179
10628
  ...structuredClone(model.unsupported)
10180
10629
  })),
10181
10630
  status: () => ({
10182
- source: models === void 0 ? "unavailable" : "online",
10631
+ source,
10183
10632
  refresh: refreshStatus
10184
10633
  }),
10634
+ flushCache: () => Promise.all([...writes].map((flight) => flight.promise.catch(() => {}))),
10185
10635
  clear() {
10186
10636
  generation += 1;
10187
- const flight = refreshing;
10188
- refreshing = void 0;
10189
- flight?.cancel();
10637
+ writeSequence += 1;
10638
+ initializing?.controller.abort(cancelled());
10639
+ refreshing?.controller.abort(cancelled());
10640
+ for (const flight of writes) flight.controller.abort(cancelled());
10641
+ initializing = refreshing = void 0;
10190
10642
  stopRetry();
10191
10643
  retries = 0;
10192
- models = void 0;
10193
- rawCatalog = void 0;
10644
+ initialized = false;
10645
+ models = rawCatalog = etag = accountId = void 0;
10194
10646
  metadata = /* @__PURE__ */ new Map();
10195
- etag = void 0;
10647
+ source = "unavailable";
10196
10648
  refreshStatus = "idle";
10197
10649
  revision += 1;
10198
- options.onUpdated?.();
10650
+ notify();
10199
10651
  }
10200
10652
  });
10201
10653
  }
10654
+ /** Gate actual asynchronous adapter entry points, while keeping the provider registered. */
10655
+ function withModelCatalogReady(adapter, catalog, { signal: lifetime } = {}) {
10656
+ const ready = async (signal) => {
10657
+ const active = lifetime && signal ? AbortSignal.any([lifetime, signal]) : lifetime ?? signal;
10658
+ active?.throwIfAborted();
10659
+ await catalog.initialize({ signal: active });
10660
+ if (catalog.getModels().length === 0) await catalog.refresh({ signal: active });
10661
+ active?.throwIfAborted();
10662
+ };
10663
+ return new Proxy(adapter, { get(target, property) {
10664
+ const value = Reflect.get(target, property, target);
10665
+ if (typeof value === "function" && [
10666
+ "resolveModel",
10667
+ "prepareCall",
10668
+ "listModels"
10669
+ ].includes(property)) return async (...args) => {
10670
+ await ready(args[2]);
10671
+ return value.apply(target, args);
10672
+ };
10673
+ if (property === "stream" && typeof value === "function") return async function* (options) {
10674
+ await ready(options?.signal);
10675
+ yield* value.call(target, options);
10676
+ };
10677
+ return typeof value === "function" ? value.bind(target) : value;
10678
+ } });
10679
+ }
10202
10680
  //#endregion
10203
10681
  //#region src/dsh-search.js
10204
10682
  const DSH_SEARCH_PROVIDER_ID = "codex-subscription-dsh";
@@ -10448,6 +10926,135 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
10448
10926
  } });
10449
10927
  }
10450
10928
  //#endregion
10929
+ //#region src/codex-fetch.js
10930
+ const CODEX_FETCH_PROVIDER_ID = "codex-subscription-fetch";
10931
+ const MAX_CONTENT = 64e3;
10932
+ const httpUrl = (value) => {
10933
+ try {
10934
+ const url = new URL(value);
10935
+ return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password ? url.href : void 0;
10936
+ } catch {
10937
+ return;
10938
+ }
10939
+ };
10940
+ /** Read public page text through Codex commands.open; never call another provider. */
10941
+ function createCodexFetchProvider(options) {
10942
+ const fetchPage = options.fetch ?? fetch;
10943
+ return Object.freeze({
10944
+ id: CODEX_FETCH_PROVIDER_ID,
10945
+ available: () => true,
10946
+ async fetch(request, signal) {
10947
+ signal?.throwIfAborted();
10948
+ if (options.allowed?.() === false) throw new WebError("Codex webpage reading is disabled for this model", "WEB_PROVIDER_UNAVAILABLE");
10949
+ const url = typeof request?.url === "string" && request.url.length <= 8192 ? httpUrl(request.url) : void 0;
10950
+ if (url === void 0) throw new WebError("Codex webpage reading requires an HTTP or HTTPS URL without credentials", "WEB_INVALID_URL");
10951
+ let credentials;
10952
+ try {
10953
+ credentials = await readSubscriptionCredentials(options.getAuth, options.readCredential, signal);
10954
+ } catch {
10955
+ if (signal?.aborted) throw new WebError("Codex webpage request aborted", "WEB_ABORTED");
10956
+ throw new WebError("Could not read ChatGPT subscription sign-in", "WEB_PROVIDER_CREDENTIAL_MISSING");
10957
+ }
10958
+ const { access, accountId } = credentials;
10959
+ if (typeof access !== "string" || !access || typeof accountId !== "string" || !accountId) throw new WebError("ChatGPT subscription is not signed in", "WEB_PROVIDER_CREDENTIAL_MISSING");
10960
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 3e4);
10961
+ const activeSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
10962
+ try {
10963
+ const response = await fetchPage(CODEX_SEARCH_URL, {
10964
+ method: "POST",
10965
+ redirect: "error",
10966
+ headers: {
10967
+ authorization: `Bearer ${access}`,
10968
+ "chatgpt-account-id": accountId,
10969
+ accept: "application/json",
10970
+ "content-type": "application/json",
10971
+ originator: "pi",
10972
+ "user-agent": USER_AGENT
10973
+ },
10974
+ body: JSON.stringify({
10975
+ id: options.resolveSessionId?.() || randomUUID(),
10976
+ model: options.resolveModel?.() || "gpt-5.6-luna",
10977
+ input: url,
10978
+ commands: {
10979
+ open: [{ ref_id: url }],
10980
+ response_length: "long"
10981
+ },
10982
+ settings: {
10983
+ allowed_callers: ["direct"],
10984
+ external_web_access: true
10985
+ },
10986
+ max_output_tokens: 4096
10987
+ }),
10988
+ signal: activeSignal
10989
+ });
10990
+ activeSignal.throwIfAborted();
10991
+ if (!response.ok) {
10992
+ const authFailure = await authFailureMessage(response);
10993
+ 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");
10994
+ }
10995
+ const value = await response.json();
10996
+ activeSignal.throwIfAborted();
10997
+ const source = Array.isArray(value?.results) ? value.results.find((item) => httpUrl(item?.url) !== void 0 && item?.type !== "error" && item?.title !== "Internal Error") : void 0;
10998
+ const output = typeof value?.output === "string" ? value.output : "";
10999
+ const heading = output.split(/\r?\n/u, 1)[0].trim();
11000
+ const headingUrl = heading.endsWith(")") ? httpUrl(heading.slice(heading.lastIndexOf(" (") + 2, -1)) : void 0;
11001
+ const metadata = output.slice(0, 1024);
11002
+ const pageUrl = source ? httpUrl(source.url) : headingUrl && /Content type:/u.test(metadata) && /Source: open\(/u.test(metadata) ? headingUrl : void 0;
11003
+ if (!pageUrl || output.trim() === "" || /^Internal Error(?:\s|\()/iu.test(heading)) throw new WebError("Codex could not read this webpage", "WEB_PROVIDER_ERROR");
11004
+ const lineCount = Number(metadata.match(/Total lines: (\d+)/u)?.[1]);
11005
+ const shownLines = new Set([...output.matchAll(/^L(\d+):/gmu)].map((match) => Number(match[1]))).size;
11006
+ const partialPage = Number.isSafeInteger(lineCount) && lineCount > 0 && shownLines > 0 && shownLines < lineCount;
11007
+ return {
11008
+ url: pageUrl,
11009
+ statusCode: 200,
11010
+ body: {
11011
+ kind: "text",
11012
+ content: output.slice(0, MAX_CONTENT)
11013
+ },
11014
+ truncated: output.length > MAX_CONTENT || partialPage
11015
+ };
11016
+ } catch (error) {
11017
+ if (signal?.aborted || error?.name === "AbortError") throw new WebError("Codex webpage request aborted", "WEB_ABORTED");
11018
+ if (activeSignal.aborted) throw new WebError("Codex webpage request timed out", "WEB_FETCH_TIMEOUT");
11019
+ if (error instanceof WebError) throw error;
11020
+ throw new WebError("Codex webpage request failed", "WEB_PROVIDER_ERROR");
11021
+ }
11022
+ }
11023
+ });
11024
+ }
11025
+ /** Preserve DSH's configured fetch provider; only an explicit plugin choice changes dispatch. */
11026
+ function createCodexFetchRouter({ registry, configuredId, mode, codex }) {
11027
+ if (!(registry instanceof Map)) return void 0;
11028
+ const wrappers = /* @__PURE__ */ new Map();
11029
+ const wrapper = (id) => {
11030
+ if (!wrappers.has(id)) wrappers.set(id, Object.freeze({
11031
+ id,
11032
+ available: () => mode() === "codex",
11033
+ fetch(request, signal) {
11034
+ if (mode() !== "codex") throw new WebError("Codex webpage reading is no longer selected", "WEB_PROVIDER_UNAVAILABLE");
11035
+ return codex.fetch(request, signal);
11036
+ }
11037
+ }));
11038
+ return wrappers.get(id);
11039
+ };
11040
+ return new Proxy(registry, { get(target, property) {
11041
+ if (property === "get") return (id) => mode() === "codex" && id === configuredId() ? wrapper(id) : target.get(id);
11042
+ if (property === "values" && mode() === "codex" && configuredId() === void 0) return () => [wrapper(CODEX_FETCH_PROVIDER_ID)].values();
11043
+ const value = Reflect.get(target, property, target);
11044
+ return typeof value === "function" ? value.bind(target) : value;
11045
+ } });
11046
+ }
11047
+ /** Match the runtime's live volatile selection and constructor-time env snapshot. */
11048
+ function configuredFetchProviderId(web, entries = [], ambient = process.env.DSH_WEB_FETCH_PROVIDER) {
11049
+ if ("fetchProviderId" in web) return web.fetchProviderId;
11050
+ const environment = "fetchProviderEnv" in web ? web.fetchProviderEnv : ambient;
11051
+ if (typeof web.config?.fetchProvider?.get === "function") return web.config.fetchProvider.get() ?? environment;
11052
+ const entry = [...entries].find((item) => item.options?.id === "web");
11053
+ const value = entry?.fiber?.config?.fetchProvider;
11054
+ if (typeof value?.get === "function") return value.get() ?? environment;
11055
+ return value ?? entry?.options?.config?.fetchProvider ?? environment;
11056
+ }
11057
+ //#endregion
10451
11058
  //#region src/image-tool-registration.js
10452
11059
  /** Removing the tool also removes its schema from subsequent model requests. */
10453
11060
  function watchImageTool(settings, register) {
@@ -10688,6 +11295,7 @@ const areas = {
10688
11295
  search: "search",
10689
11296
  image: "images",
10690
11297
  model: "transport",
11298
+ voice: "transport",
10691
11299
  login: "account",
10692
11300
  "quota-reset": "quota"
10693
11301
  };
@@ -10754,8 +11362,8 @@ function capabilityCoverage({ account, preference, runtime, catalog, tools, stor
10754
11362
  readiness = runtime.installed && !runtime.restartRequired ? "pass" : "warn";
10755
11363
  reason = runtime.restartRequired ? "restart-required" : runtime.installed ? "runtime-present" : "runtime-missing";
10756
11364
  } else if (id === "models" && catalog) {
10757
- readiness = catalog.source === "online" ? "pass" : "warn";
10758
- reason = catalog.source === "online" ? "catalog-online" : "catalog-unavailable";
11365
+ readiness = catalog.source === "online" || catalog.source === "cached" ? "pass" : "warn";
11366
+ reason = catalog.source === "online" ? "catalog-online" : catalog.source === "cached" ? "catalog-cached" : "catalog-unavailable";
10759
11367
  } else if (id === "storage" && storage?.readable) {
10760
11368
  readiness = "pass";
10761
11369
  reason = "storage-readable";
@@ -10900,7 +11508,8 @@ const requestAreas = /* @__PURE__ */ new Set([
10900
11508
  "quota",
10901
11509
  "quota-reset",
10902
11510
  "search",
10903
- "image"
11511
+ "image",
11512
+ "voice"
10904
11513
  ]);
10905
11514
  const statuses = /* @__PURE__ */ new Set(["ok", "failed"]);
10906
11515
  const stages = /* @__PURE__ */ new Set(["transport", "http"]);
@@ -11161,7 +11770,11 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
11161
11770
  ...collected.compaction ? { compaction: collected.compaction } : {},
11162
11771
  ...collected.review ? { review: collected.review } : {},
11163
11772
  ...collected.streamFailure ? { streamFailure: collected.streamFailure } : {},
11164
- ...catalog && ["unavailable", "online"].includes(catalog.source) && [
11773
+ ...catalog && [
11774
+ "unavailable",
11775
+ "cached",
11776
+ "online"
11777
+ ].includes(catalog.source) && [
11165
11778
  "idle",
11166
11779
  "refreshing",
11167
11780
  "ok",
@@ -11597,7 +12210,7 @@ const timestamp = (value) => {
11597
12210
  const parsed = typeof value === "string" ? Date.parse(value) : NaN;
11598
12211
  return Number.isFinite(parsed) ? parsed : void 0;
11599
12212
  };
11600
- const percent = (basisPoints) => Number.isFinite(basisPoints) && basisPoints >= 0 ? Math.round(basisPoints) / 100 : void 0;
12213
+ const percent = (basisPoints) => Number.isFinite(basisPoints) && basisPoints >= 0 ? basisPoints / 100 : void 0;
11601
12214
  /** Reduce the provider payload to a browser-safe projection; anything malformed is dropped, never an error. */
11602
12215
  function parsePlanHistory(value) {
11603
12216
  if (!record$3(value) || !Array.isArray(value.periods)) throw new Error("Codex returned a malformed usage history");
@@ -12323,12 +12936,19 @@ function refineQuotaRate(samples, conservative) {
12323
12936
  }
12324
12937
  if (crossings < 3) return conservative;
12325
12938
  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;
12939
+ if (!candidate.feasible) return {
12940
+ ...conservative,
12941
+ steadyHypothesisFailed: true
12942
+ };
12943
+ if (candidate.min <= 0 || candidate.max - candidate.min >= conservative.max - conservative.min) return {
12944
+ ...conservative,
12945
+ steadyHypothesisFailed: false
12946
+ };
12328
12947
  return {
12329
12948
  ...candidate,
12330
12949
  method: "shared-offset",
12331
- maxLagMs: 12e4
12950
+ maxLagMs: 12e4,
12951
+ steadyHypothesisFailed: false
12332
12952
  };
12333
12953
  }
12334
12954
  //#endregion
@@ -12395,14 +13015,15 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
12395
13015
  status: "calibrating",
12396
13016
  reason: "stale"
12397
13017
  };
12398
- let bounds = quotaRateInterval(samples);
13018
+ const rateBounds = (readings) => refineQuotaRate(readings, quotaRateInterval(readings));
13019
+ const contradicted = (range) => !range.feasible || range.steadyHypothesisFailed === true || range.min > 1e-9 && range.max - range.min <= 1e-9;
13020
+ let bounds = rateBounds(samples);
12399
13021
  let changedIntensity = false;
12400
- while (!bounds.feasible && samples.length > 3) {
13022
+ while (contradicted(bounds) && samples.length > 3) {
12401
13023
  samples = samples.slice(1);
12402
- bounds = quotaRateInterval(samples);
13024
+ bounds = rateBounds(samples);
12403
13025
  changedIntensity = true;
12404
13026
  }
12405
- bounds = refineQuotaRate(samples, bounds);
12406
13027
  const spanMs = samples.at(-1).at - samples[0].at;
12407
13028
  const common = {
12408
13029
  sampleCount: samples.length,
@@ -12413,7 +13034,8 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
12413
13034
  changedIntensity,
12414
13035
  rateMethod: bounds.method ?? "conservative"
12415
13036
  };
12416
- if (!bounds.feasible) return {
13037
+ const integerReports = samples.every((sample) => Number.isInteger(sample.remainingPercent));
13038
+ if (contradicted(bounds) || changedIntensity && (samples.length < 4 || spanMs < 20 * 6e4 || integerReports && bounds.steadyHypothesisFailed !== false)) return {
12417
13039
  ...common,
12418
13040
  status: "calibrating",
12419
13041
  reason: "changing-pace"
@@ -12423,17 +13045,16 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
12423
13045
  status: "calibrating",
12424
13046
  reason: "stale"
12425
13047
  };
12426
- if (spanMs >= 5 * 6e4 && samples.length >= 3 && bounds.min <= 1e-9 && common.consumedPercent >= 1) {
13048
+ if (spanMs >= 5 * 6e4 && samples.length >= 3 && (changedIntensity || bounds.min <= 1e-9) && common.consumedPercent >= 1) {
12427
13049
  const pacePerHour = common.consumedPercent / (spanMs / HOUR_MS);
12428
13050
  const runwaySeconds = clampPercent(window.remainingPercent) / pacePerHour * 3600;
12429
- const untilReset = resetsAt === null ? null : resetsAt - now / 1e3;
12430
13051
  return {
12431
13052
  ...common,
12432
13053
  status: "ready",
12433
13054
  provisional: true,
12434
13055
  pacePerHour,
12435
13056
  runwaySeconds,
12436
- survivesReset: untilReset !== null && runwaySeconds >= untilReset
13057
+ survivesReset: false
12437
13058
  };
12438
13059
  }
12439
13060
  if (spanMs < 6e4 || bounds.min <= 1e-9) return {
@@ -13026,7 +13647,8 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13026
13647
  sessionId: payload.sessionId,
13027
13648
  sdp: payload.sdp,
13028
13649
  voice: current.voiceVoice,
13029
- language: current.voiceLanguage
13650
+ language: current.voiceLanguage,
13651
+ signal
13030
13652
  })
13031
13653
  };
13032
13654
  } catch (error) {
@@ -13038,16 +13660,20 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13038
13660
  if (!voicePreview) return publicError("unavailable", "Voice preview is unavailable");
13039
13661
  if (endpoint === "voice/catalog") return {
13040
13662
  ok: true,
13041
- value: { voices: await voicePreview.available(payload?.language) }
13663
+ value: { voices: await voicePreview.available(payload?.language, signal) }
13042
13664
  };
13043
- const value = await voicePreview.preview(payload?.voice, payload?.language);
13665
+ const value = await voicePreview.preview(payload?.voice, payload?.language, signal);
13044
13666
  return value === void 0 ? publicError("not-found", "No sample for this voice") : {
13045
13667
  ok: true,
13046
13668
  value
13047
13669
  };
13048
13670
  } catch (error) {
13049
13671
  if (signal.aborted) throw error;
13050
- return publicError("operation-error", "Could not load the voice sample");
13672
+ return publicError([
13673
+ "voice-auth",
13674
+ "voice-catalog",
13675
+ "voice-download"
13676
+ ].includes(error?.code) ? error.code : "operation-error", "Could not load the voice sample");
13051
13677
  }
13052
13678
  if ([
13053
13679
  "remote/status",
@@ -13305,7 +13931,9 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13305
13931
  ];
13306
13932
  if (endpoint === "logout") tasks.push(() => usageReader.clear(), () => accountUsageReader?.clear());
13307
13933
  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 {
13934
+ const outcomes = await Promise.allSettled(tasks.map((task) => Promise.resolve().then(task)));
13935
+ const catalogOutcomes = endpoint === "logout" ? [] : await Promise.allSettled([Promise.resolve().then(() => modelCatalog?.initialize())]);
13936
+ if ([...outcomes, ...catalogOutcomes].some((value) => value.status === "rejected")) try {
13309
13937
  onCleanupFailure?.();
13310
13938
  } catch {}
13311
13939
  if (endpoint !== "logout") Promise.resolve().then(() => modelCatalog?.refresh({ signal: void 0 })).catch(() => {});
@@ -13319,6 +13947,7 @@ const BASE = "https://chatgpt.com/backend-api";
13319
13947
  const CATALOG_TTL_MS = 10 * 6e4;
13320
13948
  const MAX_CLIP_BYTES = 2 * 1024 * 1024;
13321
13949
  const PREVIEW_HOSTS = /^https:\/\/[a-z0-9.-]*oaistatic\.com\//u;
13950
+ const failure = (code, message) => Object.assign(new Error(message), { code });
13322
13951
  function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, base = BASE }) {
13323
13952
  const catalogs = /* @__PURE__ */ new Map();
13324
13953
  const clips = /* @__PURE__ */ new Map();
@@ -13326,21 +13955,33 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
13326
13955
  const language = normalizeVoiceLanguage(value);
13327
13956
  return language === "auto" ? "en" : language;
13328
13957
  };
13329
- const readCatalog = async (language) => {
13958
+ const readCatalog = async (language, signal) => {
13959
+ signal?.throwIfAborted();
13330
13960
  const catalog = catalogs.get(language);
13331
13961
  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();
13962
+ let value;
13963
+ try {
13964
+ const { access, accountId } = await credentials(signal);
13965
+ if (!access || !accountId) throw failure("voice-auth", "ChatGPT sign-in is required");
13966
+ const response = await fetch(`${base}/settings/voices?spoken_language=${language}`, {
13967
+ headers: {
13968
+ authorization: `Bearer ${access}`,
13969
+ "chatgpt-account-id": accountId,
13970
+ accept: "application/json",
13971
+ "user-agent": userAgent
13972
+ },
13973
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3)
13974
+ });
13975
+ if (response.status === 401) throw failure("voice-auth", "ChatGPT sign-in needs renewal");
13976
+ if (!response.ok) throw failure("voice-catalog", `voice catalog HTTP ${response.status}`);
13977
+ value = await response.json();
13978
+ if (!Array.isArray(value?.voices)) throw failure("voice-catalog", "Invalid voice catalog");
13979
+ signal?.throwIfAborted();
13980
+ } catch (error) {
13981
+ signal?.throwIfAborted();
13982
+ if (error?.code === "voice-auth" || error?.code === "voice-catalog") throw error;
13983
+ throw failure("voice-catalog", "Could not load the voice catalog");
13984
+ }
13344
13985
  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
13986
  catalogs.set(language, {
13346
13987
  at: now(),
@@ -13350,21 +13991,29 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
13350
13991
  };
13351
13992
  return {
13352
13993
  /** 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());
13994
+ async available(language, signal) {
13995
+ return (await readCatalog(languageOf(language), signal)).map((entry) => entry.name.toLowerCase());
13355
13996
  },
13356
13997
  /** 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) {
13998
+ async preview(voice, selectedLanguage, signal) {
13999
+ signal?.throwIfAborted();
13358
14000
  if (typeof voice !== "string" || !/^[a-z]{2,16}$/u.test(voice)) return void 0;
13359
14001
  const language = languageOf(selectedLanguage);
13360
14002
  const key = `${language}:${voice}`;
13361
14003
  if (clips.has(key)) return clips.get(key);
13362
- const entry = (await readCatalog(language)).find((item) => item.name.toLowerCase() === voice || item.voice === voice);
14004
+ const entry = (await readCatalog(language, signal)).find((item) => item.name.toLowerCase() === voice || item.voice === voice);
13363
14005
  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");
14006
+ let bytes;
14007
+ try {
14008
+ const response = await fetch(entry.preview_url, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3) });
14009
+ if (!response.ok) throw failure("voice-download", `voice sample HTTP ${response.status}`);
14010
+ bytes = Buffer.from(await response.arrayBuffer());
14011
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_CLIP_BYTES) throw failure("voice-download", "voice sample has an unexpected size");
14012
+ signal?.throwIfAborted();
14013
+ } catch {
14014
+ signal?.throwIfAborted();
14015
+ throw failure("voice-download", "Could not download the voice sample");
14016
+ }
13368
14017
  const type = /\.mp3(?:$|\?)/u.test(entry.preview_url) ? "audio/mpeg" : "audio/mp4";
13369
14018
  const result = {
13370
14019
  name: entry.name,
@@ -13558,6 +14207,8 @@ function apply(ctx, config = {}) {
13558
14207
  ctx.effect(() => ctx.on?.("plugin-manager/install-state", (value) => runtimeManagement.progress(value)));
13559
14208
  const modelCatalog = createOfficialModelCatalog({
13560
14209
  onUpdated: () => ctx.llm.emitAdaptersUpdated?.(),
14210
+ onCacheError: (error) => ctx.logger?.debug?.("could not access the Codex model catalog cache (%s)", error?.code ?? error?.name ?? "unknown error"),
14211
+ cacheDirectory: dshHomePath("state", "codex-subscription", "model-catalog"),
13561
14212
  getAuth: (options) => resolveAuth(options),
13562
14213
  readCredential: (options) => store.read(PROVIDER, options),
13563
14214
  baseModels: () => baseProvider.getModels(),
@@ -13618,6 +14269,7 @@ function apply(ctx, config = {}) {
13618
14269
  catalog: modelCatalog,
13619
14270
  runNetwork: network.run
13620
14271
  });
14272
+ let fetchRouted = false;
13621
14273
  const preferences = {
13622
14274
  status: () => {
13623
14275
  const models = modelCatalog.getModels();
@@ -13636,6 +14288,8 @@ function apply(ctx, config = {}) {
13636
14288
  ...readCapabilitySettings(settings.get()),
13637
14289
  [QUICK_QUOTA_MODE_FIELD]: normalizeQuickQuotaMode(settings.get()[QUICK_QUOTA_MODE_FIELD], settings.get()[LEGACY_QUICK_QUOTA_FIELD]),
13638
14290
  [SEARCH_PROVIDER_FIELD]: settings.get()[SEARCH_PROVIDER_FIELD],
14291
+ [FETCH_PROVIDER_FIELD]: normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]),
14292
+ fetchRoutingAvailable: fetchRouted,
13639
14293
  [SPEED_MODE_FIELD]: settings.get()[SPEED_MODE_FIELD],
13640
14294
  [OUTPUT_VERBOSITY_FIELD]: normalizeOutputVerbosity(settings.get()[OUTPUT_VERBOSITY_FIELD]),
13641
14295
  [INPUT_IMAGE_DETAIL_FIELD]: normalizeInputImageDetail(settings.get()[INPUT_IMAGE_DETAIL_FIELD]),
@@ -13662,6 +14316,7 @@ function apply(ctx, config = {}) {
13662
14316
  };
13663
14317
  },
13664
14318
  update: async (patch) => {
14319
+ if (patch["fetchProvider"] === "codex" && !fetchRouted) throw new Error("This DSH version does not support Codex webpage reading");
13665
14320
  if (Object.hasOwn(patch, "subagentBackend")) {
13666
14321
  if (!subagentBackend) throw new Error("DSH subagent services are unavailable");
13667
14322
  await subagentBackend.select(patch.subagentBackend);
@@ -13852,8 +14507,65 @@ function apply(ctx, config = {}) {
13852
14507
  ctx.effect(() => ctx.on?.("session/event", (_session, event) => {
13853
14508
  if (event?.type === "request/context") hiddenDirectory.dependenciesChanged();
13854
14509
  }), "codex-subscription: hidden model dependencies");
13855
- ctx.llm.registerAdapter([PROVIDER], hiddenDirectory.wrap(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(adapter)), provider)));
14510
+ ctx.effect(() => {
14511
+ const lifetime = new AbortController();
14512
+ const readyAdapter = withModelCatalogReady(hiddenDirectory.wrap(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(provider.wrapRetryAdapter(adapter))), provider)), modelCatalog, { signal: lifetime.signal });
14513
+ const disposeAdapter = ctx.llm.registerAdapter([PROVIDER], readyAdapter);
14514
+ Promise.resolve().then(() => modelCatalog.refresh({ signal: lifetime.signal })).catch((error) => {
14515
+ if (!lifetime.signal.aborted) ctx.logger?.debug?.("could not refresh Codex model catalog (%s)", error?.code ?? error?.name ?? "unknown error");
14516
+ });
14517
+ return () => {
14518
+ lifetime.abort();
14519
+ disposeAdapter?.();
14520
+ modelCatalog.clear();
14521
+ };
14522
+ }, "codex-subscription: official model catalog");
13856
14523
  const currentAgent = () => ctx.get?.("agents")?.currentInitiator?.();
14524
+ const codexFetch = createCodexFetchProvider({
14525
+ allowed: () => fetchRouted && (settings.get().otherModels !== "off" || currentAgent()?.session.requestContext?.()?.provider === PROVIDER),
14526
+ getAuth: resolveAuth,
14527
+ readCredential: (options) => store.read(PROVIDER, options),
14528
+ resolveModel: () => {
14529
+ const request = currentAgent()?.session.requestContext?.();
14530
+ return request?.provider === PROVIDER ? request.model : void 0;
14531
+ },
14532
+ resolveSessionId: () => currentAgent()?.session.id,
14533
+ fetch: (input, init) => network.fetch("search", input, init)
14534
+ });
14535
+ const realFetchProviders = ctx.web.fetchProviders;
14536
+ ctx.web.registerFetchProvider?.({
14537
+ ...codexFetch,
14538
+ available: () => fetchRouted && normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex"
14539
+ });
14540
+ ctx.effect(() => {
14541
+ const web = ctx.web;
14542
+ const configuredId = () => configuredFetchProviderId(web, ctx.loader.entries());
14543
+ const router = createCodexFetchRouter({
14544
+ registry: realFetchProviders,
14545
+ configuredId,
14546
+ mode: () => fetchRouted ? normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]) : "dsh",
14547
+ codex: codexFetch
14548
+ });
14549
+ if (router !== void 0) {
14550
+ try {
14551
+ web.fetchProviders = router;
14552
+ } catch {}
14553
+ fetchRouted = web.fetchProviders === router;
14554
+ }
14555
+ if (!fetchRouted) {
14556
+ diagnosticLog.warn("fetch", "Codex webpage reading is unavailable: DSH does not support fetch routing");
14557
+ if (normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex") {
14558
+ diagnosticLog.error("fetch", "Configured Codex webpage reading could not be activated; select DSH or update the host");
14559
+ throw new Error("Configured Codex webpage reading could not be activated; select DSH or update the host");
14560
+ }
14561
+ return;
14562
+ }
14563
+ diagnosticLog.info("fetch", "webpage reading is routed without replacing the configured DSH provider");
14564
+ return () => {
14565
+ fetchRouted = false;
14566
+ if (web.fetchProviders === router) web.fetchProviders = realFetchProviders;
14567
+ };
14568
+ }, "codex-subscription: fetch router");
13857
14569
  const servesCurrentModel = () => {
13858
14570
  if (settings.get().otherModels !== "off") return true;
13859
14571
  const provider = currentAgent()?.session.requestContext?.()?.provider;
@@ -13993,6 +14705,7 @@ function apply(ctx, config = {}) {
13993
14705
  }), signal)
13994
14706
  }
13995
14707
  });
14708
+ ctx.effect(() => () => remoteBridge.close());
13996
14709
  const remoteControl = createRemoteControl({
13997
14710
  credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
13998
14711
  ...options,
@@ -14162,7 +14875,7 @@ function apply(ctx, config = {}) {
14162
14875
  remoteControl,
14163
14876
  desktopVoice: withEndCallTool(remoteBridge.desktopVoice, (tool) => ctx.tools.register(tool)),
14164
14877
  voicePreview: createVoicePreview({
14165
- fetch: (input, init) => network.fetch("remote", input, init),
14878
+ fetch: (input, init) => network.fetch("voice", input, init, { standardHttps: true }),
14166
14879
  credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
14167
14880
  ...options,
14168
14881
  signal
@@ -14195,9 +14908,6 @@ function apply(ctx, config = {}) {
14195
14908
  resolveInheritedOriginal: (sessionId, assetId) => inheritedOriginalImageRef(ctx.get?.("sessions")?.get?.(sessionId), assetId)
14196
14909
  });
14197
14910
  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
14911
  ctx.inject(["connection"], (connectionContext) => connectionContext.effect(() => registerSubscriptionTransport(connectionContext.connection, handler), "codex-subscription: DSH-trusted account RPC"));
14202
14912
  }
14203
14913
  //#endregion