dsh-codex-subscription 3.2.2 → 3.2.4

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
@@ -24,7 +24,7 @@ import { setTimeout as setTimeout$1 } from "node:timers/promises";
24
24
  import { dshHomePath, resolveDshHome } from "@deepseek-ai/dsh-home-paths";
25
25
  import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
26
26
  import { WebError } from "@deepseek-ai/dsh-web";
27
- import { performance } from "node:perf_hooks";
27
+ import { performance as performance$1 } from "node:perf_hooks";
28
28
  //#region src/settings-adapter.js
29
29
  function createSettingsAdapter(ctx, config) {
30
30
  if (typeof ctx.settings.configure !== "function" || typeof ctx.settings.update !== "function") throw new Error("DSH settings API is unavailable");
@@ -863,6 +863,253 @@ const PREFERENCE_FIELDS = Object.freeze({
863
863
  });
864
864
  const normalizeReasoningCache = (value) => value === void 0 || value === "on" || value === "sol" ? "on" : "off";
865
865
  //#endregion
866
+ //#region src/http-failure.js
867
+ let logAuthFailure;
868
+ const setAuthFailureLogger = (fn) => {
869
+ logAuthFailure = fn;
870
+ };
871
+ const SIGN_IN_RENEW = "ChatGPT sign-in needs to be renewed";
872
+ const ACCESS_DENIED = "ChatGPT denied this request (HTTP 403). Check account access or contact OpenAI Support; signing in again may not resolve it.";
873
+ const DEVICE_LIMIT = "ChatGPT does not allow this paid account on this device. Use another permitted account you own or contact OpenAI Support. Signing out or resetting usage does not clear this restriction.";
874
+ const PURCHASE_LIMIT = "ChatGPT blocked this purchase because too many subscriptions are associated with this card or device. Contact OpenAI Support if this is unexpected.";
875
+ const PUBLIC_ACCESS_MESSAGES = /* @__PURE__ */ new Set([
876
+ ACCESS_DENIED,
877
+ DEVICE_LIMIT,
878
+ PURCHASE_LIMIT
879
+ ]);
880
+ const isAccessFailureMessage = (message) => PUBLIC_ACCESS_MESSAGES.has(message);
881
+ const isRestrictionFailureMessage = (message) => message === "ChatGPT does not allow this paid account on this device. Use another permitted account you own or contact OpenAI Support. Signing out or resetting usage does not clear this restriction." || message === "ChatGPT blocked this purchase because too many subscriptions are associated with this card or device. Contact OpenAI Support if this is unexpected.";
882
+ function restrictionMessage(value) {
883
+ if (typeof value !== "string" || value.length > 8192) return void 0;
884
+ let text = value.trim().replace(/^Codex error:\s*/u, "");
885
+ try {
886
+ const body = JSON.parse(text);
887
+ text = body?.error?.message ?? body?.detail?.message ?? body?.detail ?? body?.message;
888
+ } catch {}
889
+ if (typeof text !== "string") return void 0;
890
+ text = text.trim().replace(/\s+/gu, " ");
891
+ if (PUBLIC_ACCESS_MESSAGES.has(text)) return text;
892
+ if (/^Device limit reached[.!]?$/iu.test(text)) return DEVICE_LIMIT;
893
+ if (/^Too many subscriptions associated with this card or device\. We can[’']t complete this purchase\.$/u.test(text)) return PURCHASE_LIMIT;
894
+ }
895
+ async function responseRestrictionMessage(response) {
896
+ if (typeof response?.clone !== "function") return void 0;
897
+ if (!/json|text\/plain/iu.test(response.headers?.get?.("content-type") ?? "")) return void 0;
898
+ let reader;
899
+ try {
900
+ reader = response.clone().body?.getReader();
901
+ if (!reader) return void 0;
902
+ const decoder = new TextDecoder();
903
+ let text = "", size = 0;
904
+ while (true) {
905
+ const { done, value } = await reader.read();
906
+ if (done) return restrictionMessage(text + decoder.decode());
907
+ size += value.byteLength;
908
+ if (size > 8192) return void 0;
909
+ text += decoder.decode(value, { stream: true });
910
+ }
911
+ } catch {
912
+ return;
913
+ } finally {
914
+ reader?.cancel().catch(() => {});
915
+ }
916
+ }
917
+ const REQUEST_BLOCKED = "ChatGPT blocked this request before it reached your account (HTTP 403); your sign-in is fine, try again later or check your network, proxy or VPN";
918
+ const CHALLENGE_MARKERS = /just a moment|cf-chl|_cf_chl_opt|attention required|enable javascript and cookies|challenge-platform/iu;
919
+ /** Whether error text is a Cloudflare / network-protection page (pi-ai keeps only the body of a failed request, not its status). */
920
+ const isChallengePage = (text) => typeof text === "string" && /^\s*<(?:!doctype|html)/iu.test(text) && CHALLENGE_MARKERS.test(text);
921
+ /** Whether a 403 response is a Cloudflare / network-protection page rather than an answer from the ChatGPT backend. */
922
+ async function isBlockedByNetwork(response) {
923
+ if (response?.status !== 403) return false;
924
+ try {
925
+ const header = (name) => String(response.headers?.get?.(name) ?? "");
926
+ if (/challenge/iu.test(header("cf-mitigated"))) return true;
927
+ if (!/html/iu.test(header("content-type"))) return false;
928
+ if (/cloudflare/iu.test(header("server"))) return true;
929
+ const text = typeof response.clone === "function" ? (await response.clone().text()).slice(0, 8192) : "";
930
+ return CHALLENGE_MARKERS.test(text);
931
+ } catch {
932
+ return false;
933
+ }
934
+ }
935
+ /** Known restrictions take precedence over status-based authentication advice. */
936
+ async function authFailureMessage(response) {
937
+ if (!response || response.ok || response.status < 400) return void 0;
938
+ const restriction = await responseRestrictionMessage(response);
939
+ if (restriction !== void 0) return restriction;
940
+ if (response.status !== 401 && response.status !== 403) return void 0;
941
+ const blocked = response.status === 403 && await isBlockedByNetwork(response);
942
+ await noteAuthFailure(response, blocked);
943
+ return blocked ? REQUEST_BLOCKED : response.status === 401 ? SIGN_IN_RENEW : ACCESS_DENIED;
944
+ }
945
+ async function noteAuthFailure(response, blocked) {
946
+ if (typeof logAuthFailure !== "function") return;
947
+ try {
948
+ const text = blocked || typeof response.clone !== "function" ? "" : (await response.clone().text()).slice(0, 400);
949
+ logAuthFailure?.(blocked ? "HTTP 403 from the network layer in front of ChatGPT" : `ChatGPT answered HTTP ${response.status}`, text === "" ? void 0 : text);
950
+ } catch {}
951
+ }
952
+ //#endregion
953
+ //#region src/transport-failure.js
954
+ const TRANSIENT_WEBSOCKET_CLOSE = /^WebSocket closed (?:1000|1006|1011|1012|1013)(?:\s|$)/;
955
+ const GATEWAY_REPLAY_BUFFER_EXCEEDED = /^\s*exceeded request buffer limit while retrying upstream\s*$/;
956
+ const NETWORK_CODES = /* @__PURE__ */ new Set([
957
+ "ECONNRESET",
958
+ "ECONNREFUSED",
959
+ "ETIMEDOUT",
960
+ "ENOTFOUND",
961
+ "EAI_AGAIN",
962
+ "ENETUNREACH",
963
+ "EHOSTUNREACH",
964
+ "EPIPE",
965
+ "UND_ERR_SOCKET",
966
+ "UND_ERR_CONNECT_TIMEOUT",
967
+ "UND_ERR_HEADERS_TIMEOUT",
968
+ "UND_ERR_BODY_TIMEOUT",
969
+ "CERT_HAS_EXPIRED",
970
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
971
+ "DEPTH_ZERO_SELF_SIGNED_CERT"
972
+ ]);
973
+ function safeFetchFailure(error) {
974
+ const pending = [error], seen = /* @__PURE__ */ new Set(), codes = /* @__PURE__ */ new Set();
975
+ for (let i = 0; pending.length && i < 12; i++) {
976
+ const value = pending.shift();
977
+ if (!value || typeof value !== "object" || seen.has(value)) continue;
978
+ seen.add(value);
979
+ if (NETWORK_CODES.has(value.code)) codes.add(value.code);
980
+ if (value.cause) pending.push(value.cause);
981
+ if (Array.isArray(value.errors)) pending.push(...value.errors.slice(0, 8));
982
+ }
983
+ return "fetch failed" + (codes.size ? " [" + [...codes].join(", ") + "]" : "");
984
+ }
985
+ function normalizeTransportEvent(event, signal) {
986
+ if (signal?.aborted || event?.type !== "error" || event.reason !== "error") return event;
987
+ const message = event.error?.errorMessage;
988
+ if (typeof message !== "string") return event;
989
+ if (isChallengePage(message)) return {
990
+ ...event,
991
+ error: {
992
+ ...event.error,
993
+ errorMessage: REQUEST_BLOCKED
994
+ }
995
+ };
996
+ if (!TRANSIENT_WEBSOCKET_CLOSE.test(message) && !GATEWAY_REPLAY_BUFFER_EXCEEDED.test(message)) return event;
997
+ return {
998
+ ...event,
999
+ error: {
1000
+ ...event.error,
1001
+ errorMessage: `Network transport failure: ${message}`
1002
+ }
1003
+ };
1004
+ }
1005
+ //#endregion
1006
+ //#region src/model-attempt.js
1007
+ const transports = /* @__PURE__ */ new Set(["sse", "websocket"]);
1008
+ const choices = /* @__PURE__ */ new Set([
1009
+ "sse",
1010
+ "websocket",
1011
+ "websocket-cached",
1012
+ "auto",
1013
+ "unknown"
1014
+ ]);
1015
+ const routes$1 = /* @__PURE__ */ new Set([
1016
+ "direct",
1017
+ "environment",
1018
+ "system",
1019
+ "bypass",
1020
+ "proxy",
1021
+ "unknown"
1022
+ ]);
1023
+ const phases = /* @__PURE__ */ new Set([
1024
+ "prepare",
1025
+ "request",
1026
+ "payload",
1027
+ "stream"
1028
+ ]);
1029
+ const elapsedBuckets$1 = /* @__PURE__ */ new Set([
1030
+ "under-1s",
1031
+ "1-5s",
1032
+ "5-15s",
1033
+ "over-15s"
1034
+ ]);
1035
+ const MODEL_OUTCOMES = /* @__PURE__ */ new Set([
1036
+ "ok",
1037
+ "failed",
1038
+ "cancelled",
1039
+ "abandoned"
1040
+ ]);
1041
+ /** One bounded, text-free attempt, not one iterator.next() or HTTP header receipt. */
1042
+ function safeAttempt(value = {}) {
1043
+ const identified = typeof value.attemptId === "string" && /^[a-f0-9-]{36}$/.test(value.attemptId);
1044
+ return {
1045
+ ...identified && routes$1.has(value.route) ? { route: value.route } : {},
1046
+ ...identified && phases.has(value.stage) ? { stage: value.stage } : {},
1047
+ ...identified && elapsedBuckets$1.has(value.elapsed) ? { elapsed: value.elapsed } : {},
1048
+ ...typeof value.attemptId === "string" && /^[a-f0-9-]{36}$/.test(value.attemptId) ? { attemptId: value.attemptId } : {},
1049
+ ...choices.has(value.preference) ? { preference: value.preference } : {},
1050
+ ...choices.has(value.requestedTransport) ? { requestedTransport: value.requestedTransport } : {},
1051
+ ...Array.isArray(value.transports) ? { transports: value.transports.filter((item) => transports.has(item)).slice(0, 8) } : {},
1052
+ ...typeof value.headersReceived === "boolean" ? { headersReceived: value.headersReceived } : {},
1053
+ ...typeof value.eventDelivered === "boolean" ? { eventDelivered: value.eventDelivered } : {},
1054
+ ...typeof value.contentDelivered === "boolean" ? { contentDelivered: value.contentDelivered } : {},
1055
+ ...typeof value.networkFailure === "string" && value.networkFailure.length <= 256 && /^fetch failed(?: \[[A-Z_, ]+\])?$/.test(value.networkFailure) && safeFetchFailure({ errors: (value.networkFailure.match(/[A-Z][A-Z_]+/g) ?? []).map((code) => ({ code })) }) === value.networkFailure ? { networkFailure: value.networkFailure } : {}
1056
+ };
1057
+ }
1058
+ function createModelAttempt({ now = Date.now, publish = () => {} } = {}) {
1059
+ const started = now();
1060
+ const data = {
1061
+ attemptId: randomUUID(),
1062
+ route: "unknown",
1063
+ transports: [],
1064
+ headersReceived: false,
1065
+ eventDelivered: false,
1066
+ contentDelivered: false
1067
+ };
1068
+ let finished = false;
1069
+ return {
1070
+ configure(value) {
1071
+ if (!finished) Object.assign(data, safeAttempt(value));
1072
+ },
1073
+ route(value) {
1074
+ if (!finished && routes$1.has(value)) data.route = value;
1075
+ },
1076
+ transport(value) {
1077
+ if (!finished && transports.has(value) && data.transports.at(-1) !== value && data.transports.length < 8) data.transports.push(value);
1078
+ },
1079
+ response() {
1080
+ if (!finished) data.headersReceived = true;
1081
+ },
1082
+ fetchFailure(error) {
1083
+ if (!finished) data.networkFailure = safeFetchFailure(error);
1084
+ },
1085
+ event(event) {
1086
+ if (finished || !event || ["error", "done"].includes(event.type)) return;
1087
+ data.eventDelivered = true;
1088
+ if (/_delta$|_end$/.test(event.type)) data.contentDelivered = true;
1089
+ },
1090
+ finish(status, stage) {
1091
+ if (finished || !MODEL_OUTCOMES.has(status)) return;
1092
+ finished = true;
1093
+ const elapsed = Math.max(0, now() - started);
1094
+ Object.assign(data, {
1095
+ status,
1096
+ stage,
1097
+ elapsed: elapsed < 1e3 ? "under-1s" : elapsed < 5e3 ? "1-5s" : elapsed < 15e3 ? "5-15s" : "over-15s"
1098
+ });
1099
+ try {
1100
+ publish({
1101
+ ...data,
1102
+ transports: [...data.transports]
1103
+ });
1104
+ } catch {}
1105
+ },
1106
+ snapshot: () => ({
1107
+ ...data,
1108
+ transports: [...data.transports]
1109
+ })
1110
+ };
1111
+ }
1112
+ //#endregion
866
1113
  //#region src/diagnostic-events.js
867
1114
  const areas$1 = /* @__PURE__ */ new Set([
868
1115
  "login",
@@ -889,12 +1136,13 @@ function createDiagnosticEvents({ limit = 32, now = Date.now } = {}) {
889
1136
  let dropped = 0, sequence = 0;
890
1137
  return {
891
1138
  record(area, value) {
892
- if (!areas$1.has(area) || !["ok", "failed"].includes(value?.status)) return;
1139
+ if (!areas$1.has(area) || !MODEL_OUTCOMES.has(value?.status)) return;
893
1140
  events.push({
894
1141
  sequence: ++sequence,
895
1142
  area,
896
1143
  status: value.status,
897
1144
  observedAt: now(),
1145
+ ...safeAttempt(value),
898
1146
  ...codes$1.has(value.code) ? { code: value.code } : {},
899
1147
  ...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {}
900
1148
  });
@@ -1234,10 +1482,24 @@ async function withCodexNetwork(run, options = {}) {
1234
1482
  const url = new URL(String(args[0]));
1235
1483
  if (!scope?.options.websocket || url.protocol !== "wss:" || url.hostname !== CODEX_SUBSCRIPTION_HOST) return Reflect.construct(target, args, newTarget);
1236
1484
  const proxy = scope.options.websocketProxy;
1237
- return new WebSocket(args[0], {
1485
+ const observe = () => {
1486
+ const options = networkScope.getStore()?.options;
1487
+ try {
1488
+ options?.onTransport?.("websocket");
1489
+ options?.onRoute?.(options.websocketProxy ? "proxy" : "direct");
1490
+ } catch {}
1491
+ };
1492
+ observe();
1493
+ const socket = new (scope.options.WebSocket ?? WebSocket)(args[0], {
1238
1494
  ...args[1],
1239
1495
  ...proxy ? { agent: new HttpsProxyAgent(proxy) } : {}
1240
1496
  });
1497
+ const send = socket.send;
1498
+ socket.send = function(...values) {
1499
+ observe();
1500
+ return Reflect.apply(send, this, values);
1501
+ };
1502
+ return socket;
1241
1503
  } });
1242
1504
  globalThis.WebSocket = scopedWebSocket;
1243
1505
  }
@@ -1262,7 +1524,18 @@ async function withCodexNetwork(run, options = {}) {
1262
1524
  }
1263
1525
  const route = await proxy;
1264
1526
  scopedOptions.onRoute?.(route.source);
1265
- const response = await (route.url === void 0 && !scopedOptions.standardHttps ? fetchBeforeScope(input, init) : proxyFetch(input, init, route.url));
1527
+ try {
1528
+ scopedOptions.onTransport?.("sse");
1529
+ } catch {}
1530
+ let response;
1531
+ try {
1532
+ response = await (route.url === void 0 && !scopedOptions.standardHttps ? fetchBeforeScope(input, init) : proxyFetch(input, init, route.url));
1533
+ } catch (error) {
1534
+ try {
1535
+ scopedOptions.onFetchFailure?.(error);
1536
+ } catch {}
1537
+ throw error;
1538
+ }
1266
1539
  return scopedOptions.transformResponse?.(response, target) ?? response;
1267
1540
  };
1268
1541
  globalThis.fetch = scopedFetch;
@@ -1307,10 +1580,11 @@ function createCodexNetworkTransport(options = {}) {
1307
1580
  const before = attempts.get(area);
1308
1581
  attempts.set(area, value);
1309
1582
  evidence.record(area, value);
1583
+ if (area === "model" && value.attemptId) return;
1310
1584
  if (value.status === "failed") {
1311
1585
  const what = value.stage === "http" ? `HTTP ${value.httpStatus}` : `network ${value.code}`;
1312
1586
  diagnosticLog.log(value.stage === "http" && value.httpStatus < 500 && value.httpStatus !== 401 && value.httpStatus !== 403 ? "warn" : "error", area, `request failed: ${what} (${value.route}, ${value.elapsed})`);
1313
- } else if (before?.status === "failed") diagnosticLog.info(area, "request works again");
1587
+ } else if (value.status === "ok" && before?.status === "failed") diagnosticLog.info(area, "request works again");
1314
1588
  };
1315
1589
  const run = async (area, operation, connection = {}) => {
1316
1590
  const startedAt = now();
@@ -1323,8 +1597,10 @@ function createCodexNetworkTransport(options = {}) {
1323
1597
  onRoute: (source) => {
1324
1598
  route = source;
1325
1599
  routed = true;
1600
+ connection.onRoute?.(source);
1326
1601
  }
1327
1602
  });
1603
+ if (connection.modelAttempt) return value;
1328
1604
  connection.signal?.throwIfAborted();
1329
1605
  if (value instanceof Response && !value.ok) remember(area, {
1330
1606
  status: "failed",
@@ -1342,7 +1618,7 @@ function createCodexNetworkTransport(options = {}) {
1342
1618
  return value;
1343
1619
  } catch (error) {
1344
1620
  if (connection.signal?.aborted && connection.signal.reason?.name !== "TimeoutError") throw error;
1345
- if (routed) remember(area, {
1621
+ if (routed && !connection.modelAttempt) remember(area, {
1346
1622
  status: "failed",
1347
1623
  stage: "transport",
1348
1624
  code: classifyTransportError(error),
@@ -1354,6 +1630,13 @@ function createCodexNetworkTransport(options = {}) {
1354
1630
  };
1355
1631
  return Object.freeze({
1356
1632
  run,
1633
+ beginModelAttempt: () => createModelAttempt({
1634
+ now,
1635
+ publish: (value) => remember("model", {
1636
+ ...value,
1637
+ ...value.status === "failed" && value.networkFailure ? { code: classifyTransportError({ code: value.networkFailure.match(/\[([A-Z_]+)/)?.[1] }) } : {}
1638
+ })
1639
+ }),
1357
1640
  history: evidence.snapshot,
1358
1641
  fetch: (area, input, init, connection) => run(area, () => globalThis.fetch(input, init), {
1359
1642
  ...connection,
@@ -1375,58 +1658,227 @@ function tokenScope(apiKey) {
1375
1658
  } catch {}
1376
1659
  return `token:${apiKey}`;
1377
1660
  }
1378
- function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy = resolveCodexOAuthProxy } = {}) {
1379
- const namespace = randomUUID();
1380
- const sessions = /* @__PURE__ */ new Set();
1661
+ const COUNTERS = [
1662
+ "requests",
1663
+ "connectionsCreated",
1664
+ "connectionsReused",
1665
+ "deltaRequests",
1666
+ "websocketFailures",
1667
+ "sseFallbacks"
1668
+ ];
1669
+ const defaultSdk = {
1670
+ close: closeOpenAICodexWebSocketSessions,
1671
+ reset: resetOpenAICodexWebSocketDebugStats,
1672
+ stats: getOpenAICodexWebSocketDebugStats
1673
+ };
1674
+ const hash$2 = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 56);
1675
+ const zero = () => Object.fromEntries(COUNTERS.map((key) => [key, 0]));
1676
+ /** Policy owns only recovery timing. SDK owns sockets, fallback and continuation. */
1677
+ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy = resolveCodexOAuthProxy, sdk = defaultSdk, now = () => performance.now(), random = Math.random, cooldownMs = 3e4, maxCooldownMs = 3e5, maxSessions = 256, idleMs = 30 * 6e4 } = {}) {
1678
+ let namespace = randomUUID(), epoch = 0;
1679
+ const sessions = /* @__PURE__ */ new Map(), retired = /* @__PURE__ */ new Set(), probes = /* @__PURE__ */ new Set();
1680
+ const totals = zero();
1681
+ const recovery = {
1682
+ recoveryAttempts: 0,
1683
+ recoverySuccesses: 0,
1684
+ recoveryDeferrals: 0,
1685
+ cooldownRequests: 0
1686
+ };
1687
+ const delay = (streak) => Math.min(maxCooldownMs, cooldownMs * 2 ** Math.min(10, Math.max(0, streak - 1)) * (.8 + .4 * random()));
1688
+ const observe = (entry) => {
1689
+ const stats = sdk.stats(entry.key) ?? {};
1690
+ const failures = Math.max(0, (stats.websocketFailures ?? 0) - entry.seen.websocketFailures);
1691
+ for (const key of COUNTERS) {
1692
+ const count = Number.isSafeInteger(stats[key]) && stats[key] >= 0 ? stats[key] : 0;
1693
+ totals[key] = Math.min(Number.MAX_SAFE_INTEGER, totals[key] + Math.max(0, count - entry.seen[key]));
1694
+ entry.seen[key] = count;
1695
+ }
1696
+ if (!entry.retired && stats.websocketFallbackActive === true && (!entry.cooling || failures > 0)) {
1697
+ entry.streak = Math.min(20, entry.streak + Math.max(1, failures));
1698
+ entry.cooling = true;
1699
+ entry.retryAt = now() + delay(entry.streak);
1700
+ }
1701
+ return stats;
1702
+ };
1703
+ const clear = (entry) => {
1704
+ observe(entry);
1705
+ sdk.close(entry.key);
1706
+ sdk.reset(entry.key);
1707
+ entry.seen = zero();
1708
+ };
1709
+ const evict = (entry) => {
1710
+ clear(entry);
1711
+ sessions.delete(entry.key);
1712
+ };
1713
+ const sse = (options, preference, selectionReason) => ({
1714
+ options: {
1715
+ ...options,
1716
+ transport: "sse"
1717
+ },
1718
+ diagnostic: {
1719
+ preference,
1720
+ selectionReason
1721
+ }
1722
+ });
1381
1723
  return {
1382
1724
  snapshot() {
1383
- const totals = Object.fromEntries([
1384
- "requests",
1385
- "connectionsCreated",
1386
- "connectionsReused",
1387
- "deltaRequests",
1388
- "websocketFailures",
1389
- "sseFallbacks"
1390
- ].map((key) => [key, 0]));
1391
- for (const session of sessions) {
1392
- const stats = getOpenAICodexWebSocketDebugStats(session);
1393
- for (const key of Object.keys(totals)) if (Number.isSafeInteger(stats?.[key]) && stats[key] >= 0) totals[key] = Math.min(Number.MAX_SAFE_INTEGER, totals[key] + stats[key]);
1394
- }
1395
- return totals;
1725
+ for (const entry of [...sessions.values(), ...retired]) observe(entry);
1726
+ return {
1727
+ ...totals,
1728
+ ...recovery
1729
+ };
1396
1730
  },
1397
- async prepare(options = {}) {
1398
- if (resolveMode() !== "websocket") return { options: {
1399
- ...options,
1400
- transport: "sse"
1401
- } };
1402
- const proxy = await resolveProxy({ target: new URL("https://chatgpt.com/") });
1403
- const sessionId = options.sessionId && `dsh-${createHash("sha256").update(JSON.stringify([
1731
+ recoverySnapshot() {
1732
+ const time = now();
1733
+ return {
1734
+ scope: "plugin-process",
1735
+ capacity: maxSessions,
1736
+ sessions: [...sessions.values()].map((entry) => {
1737
+ observe(entry);
1738
+ return {
1739
+ scope: entry.key,
1740
+ state: entry.probe ? "probing" : entry.cooling ? "cooldown" : "preferred",
1741
+ active: entry.active,
1742
+ cooldownMs: Math.max(0, Math.ceil(entry.retryAt - time))
1743
+ };
1744
+ })
1745
+ };
1746
+ },
1747
+ async prepare(options = {}, { model, allowWebSocket = true } = {}) {
1748
+ const preference = resolveMode() === "websocket" ? "websocket" : "sse";
1749
+ if (preference === "sse") return sse(options, preference, "configured-sse");
1750
+ if (!allowWebSocket) return sse(options, preference, "forced-sse");
1751
+ if (!options.sessionId || options.cacheRetention === "none") return sse(options, preference, "no-session");
1752
+ const startedEpoch = epoch;
1753
+ const endpoint = new URL(model?.baseUrl ?? "https://chatgpt.com/backend-api");
1754
+ const proxy = await resolveProxy({
1755
+ target: endpoint,
1756
+ signal: options.signal
1757
+ });
1758
+ options.signal?.throwIfAborted();
1759
+ if (startedEpoch !== epoch) throw new DOMException("Connection scope was cleared", "AbortError");
1760
+ const group = hash$2([
1761
+ namespace,
1762
+ tokenScope(options.apiKey),
1763
+ endpoint.href,
1764
+ proxy
1765
+ ]);
1766
+ const key = "dsh-" + hash$2([
1404
1767
  namespace,
1405
1768
  options.sessionId,
1406
1769
  tokenScope(options.apiKey),
1770
+ endpoint.href,
1407
1771
  proxy
1408
- ])).digest("hex").slice(0, 56)}`;
1409
- if (sessionId) sessions.add(sessionId);
1772
+ ]);
1773
+ const time = now();
1774
+ for (const entry of sessions.values()) if (!entry.active && time - entry.used >= idleMs) evict(entry);
1775
+ let entry = sessions.get(key);
1776
+ if (!entry) {
1777
+ if (sessions.size + retired.size >= maxSessions) {
1778
+ const oldest = [...sessions.values()].filter((item) => !item.active).sort((a, b) => a.used - b.used)[0];
1779
+ if (oldest) evict(oldest);
1780
+ else return sse(options, preference, "capacity");
1781
+ }
1782
+ entry = {
1783
+ key,
1784
+ group,
1785
+ active: 0,
1786
+ used: time,
1787
+ seen: zero(),
1788
+ streak: 0,
1789
+ retryAt: 0,
1790
+ cooling: false,
1791
+ probe: false,
1792
+ retired: false
1793
+ };
1794
+ sessions.set(key, entry);
1795
+ }
1796
+ observe(entry);
1797
+ let transport = "websocket-cached", selectionReason = "websocket-preferred", probe = false;
1798
+ if (entry.probe) {
1799
+ transport = "sse";
1800
+ selectionReason = "probe-busy";
1801
+ } else if (entry.cooling) if (time < entry.retryAt) {
1802
+ transport = "sse";
1803
+ selectionReason = "ws-cooldown";
1804
+ recovery.cooldownRequests++;
1805
+ } else if (entry.active || probes.has(group)) {
1806
+ transport = "sse";
1807
+ selectionReason = "probe-busy";
1808
+ recovery.recoveryDeferrals++;
1809
+ } else {
1810
+ probes.add(group);
1811
+ entry.probe = probe = true;
1812
+ try {
1813
+ clear(entry);
1814
+ } catch (error) {
1815
+ probes.delete(group);
1816
+ entry.probe = false;
1817
+ throw error;
1818
+ }
1819
+ entry.cooling = false;
1820
+ selectionReason = "ws-probe";
1821
+ recovery.recoveryAttempts++;
1822
+ }
1823
+ entry.active++;
1824
+ entry.used = time;
1825
+ let finished = false;
1410
1826
  return {
1411
1827
  options: {
1412
1828
  ...options,
1413
- sessionId,
1414
- transport: "websocket-cached",
1829
+ sessionId: key,
1830
+ transport,
1415
1831
  websocketConnectTimeoutMs: 1e4,
1416
1832
  env: {}
1417
1833
  },
1418
1834
  network: {
1419
1835
  websocket: true,
1420
1836
  websocketProxy: proxy
1837
+ },
1838
+ diagnostic: {
1839
+ preference,
1840
+ scope: key,
1841
+ selectionReason,
1842
+ cooldownMs: Math.max(0, Math.ceil(entry.retryAt - time))
1843
+ },
1844
+ finish(outcome = {}) {
1845
+ if (finished) return;
1846
+ finished = true;
1847
+ const stats = observe(entry);
1848
+ entry.active--;
1849
+ entry.used = now();
1850
+ if (probe) {
1851
+ probes.delete(group);
1852
+ entry.probe = false;
1853
+ if (!entry.retired && outcome.status === "ok" && outcome.transports?.at(-1) === "websocket" && !outcome.transports.includes("sse") && stats.websocketFallbackActive !== true) {
1854
+ entry.streak = 0;
1855
+ entry.retryAt = 0;
1856
+ entry.cooling = false;
1857
+ recovery.recoverySuccesses++;
1858
+ } else if (!entry.retired && !entry.cooling) {
1859
+ entry.cooling = true;
1860
+ entry.retryAt = now() + delay(entry.streak);
1861
+ }
1862
+ }
1863
+ if (entry.retired && !entry.active) {
1864
+ clear(entry);
1865
+ retired.delete(entry);
1866
+ }
1421
1867
  }
1422
1868
  };
1423
1869
  },
1424
1870
  dispose() {
1425
- for (const session of sessions) {
1426
- closeOpenAICodexWebSocketSessions(session);
1427
- resetOpenAICodexWebSocketDebugStats(session);
1871
+ epoch++;
1872
+ namespace = randomUUID();
1873
+ for (const entry of sessions.values()) {
1874
+ observe(entry);
1875
+ entry.retired = true;
1876
+ sdk.close(entry.key);
1877
+ if (entry.active) retired.add(entry);
1878
+ else clear(entry);
1428
1879
  }
1429
1880
  sessions.clear();
1881
+ probes.clear();
1430
1882
  }
1431
1883
  };
1432
1884
  }
@@ -1782,70 +2234,9 @@ function hoistLeadingSystem(context) {
1782
2234
  };
1783
2235
  }
1784
2236
  //#endregion
1785
- //#region src/http-failure.js
1786
- let logAuthFailure;
1787
- const setAuthFailureLogger = (fn) => {
1788
- logAuthFailure = fn;
1789
- };
1790
- const SIGN_IN_RENEW = "ChatGPT sign-in needs to be renewed";
1791
- const REQUEST_BLOCKED = "ChatGPT blocked this request before it reached your account (HTTP 403); your sign-in is fine, try again later or check your network, proxy or VPN";
1792
- const CHALLENGE_MARKERS = /just a moment|cf-chl|_cf_chl_opt|attention required|enable javascript and cookies|challenge-platform/iu;
1793
- /** Whether error text is a Cloudflare / network-protection page (pi-ai keeps only the body of a failed request, not its status). */
1794
- const isChallengePage = (text) => typeof text === "string" && /^\s*<(?:!doctype|html)/iu.test(text) && CHALLENGE_MARKERS.test(text);
1795
- /** Whether a 403 response is a Cloudflare / network-protection page rather than an answer from the ChatGPT backend. */
1796
- async function isBlockedByNetwork(response) {
1797
- if (response?.status !== 403) return false;
1798
- try {
1799
- const header = (name) => String(response.headers?.get?.(name) ?? "");
1800
- if (/challenge/iu.test(header("cf-mitigated"))) return true;
1801
- if (!/html/iu.test(header("content-type"))) return false;
1802
- if (/cloudflare/iu.test(header("server"))) return true;
1803
- const text = typeof response.clone === "function" ? (await response.clone().text()).slice(0, 8192) : "";
1804
- return CHALLENGE_MARKERS.test(text);
1805
- } catch {
1806
- return false;
1807
- }
1808
- }
1809
- /** The error message for a 401 or 403 answer, or undefined for any other status. */
1810
- async function authFailureMessage(response) {
1811
- if (response?.status !== 401 && response?.status !== 403) return void 0;
1812
- const blocked = response.status === 403 && await isBlockedByNetwork(response);
1813
- await noteAuthFailure(response, blocked);
1814
- return blocked ? REQUEST_BLOCKED : SIGN_IN_RENEW;
1815
- }
1816
- async function noteAuthFailure(response, blocked) {
1817
- try {
1818
- const text = blocked || typeof response.clone !== "function" ? "" : (await response.clone().text()).slice(0, 400);
1819
- logAuthFailure?.(blocked ? "HTTP 403 from the network layer in front of ChatGPT" : `ChatGPT answered HTTP ${response.status}`, text === "" ? void 0 : text);
1820
- } catch {}
1821
- }
1822
- //#endregion
1823
- //#region src/transport-failure.js
1824
- const TRANSIENT_WEBSOCKET_CLOSE = /^WebSocket closed (?:1000|1006|1011|1012|1013)(?:\s|$)/;
1825
- const GATEWAY_REPLAY_BUFFER_EXCEEDED = /^\s*exceeded request buffer limit while retrying upstream\s*$/;
1826
- function normalizeTransportEvent(event, signal) {
1827
- if (signal?.aborted || event?.type !== "error" || event.reason !== "error") return event;
1828
- const message = event.error?.errorMessage;
1829
- if (typeof message !== "string") return event;
1830
- if (isChallengePage(message)) return {
1831
- ...event,
1832
- error: {
1833
- ...event.error,
1834
- errorMessage: REQUEST_BLOCKED
1835
- }
1836
- };
1837
- if (!TRANSIENT_WEBSOCKET_CLOSE.test(message) && !GATEWAY_REPLAY_BUFFER_EXCEEDED.test(message)) return event;
1838
- return {
1839
- ...event,
1840
- error: {
1841
- ...event.error,
1842
- errorMessage: `Network transport failure: ${message}`
1843
- }
1844
- };
1845
- }
1846
- //#endregion
1847
2237
  //#region src/model-retry-hint.js
1848
2238
  const CODEX_OVERLOADED = /^\s*(?:Codex error:\s*)?Our servers are currently overloaded\. Please try again later\.\s*$/u;
2239
+ const CODEX_REQUEST_FAILED = /^\s*(?:Codex error:\s*)?An error occurred while processing your request\. You can retry your request, or contact us through our help center at help\.openai\.com if the error persists\. Please include the request ID [\w-]+ in your message\.?\s*$/u;
1849
2240
  /** Keep the provider's wait as a fact; only DSH decides whether and when to retry. */
1850
2241
  function providerRetryAfterMs(headers, at = Date.now()) {
1851
2242
  const read = (key) => typeof headers?.get === "function" ? headers.get(key) : headers?.[key];
@@ -1860,8 +2251,11 @@ function providerRetryAfterMs(headers, at = Date.now()) {
1860
2251
  return Number.isFinite(value) && value > 0 ? Math.min(value, Number.MAX_SAFE_INTEGER) : void 0;
1861
2252
  }
1862
2253
  function createModelRetryHint({ now = Date.now, ErrorClass = dshLlm.LlmError } = {}) {
1863
- let response, responseStatus, outputStarted = false;
2254
+ let response, responseStatus, accessFailure, outputStarted = false;
1864
2255
  return {
2256
+ onAccessFailure(message) {
2257
+ accessFailure = message;
2258
+ },
1865
2259
  onResponse(info) {
1866
2260
  responseStatus = info?.status;
1867
2261
  response = [429, 503].includes(info?.status) ? {
@@ -1877,7 +2271,18 @@ function createModelRetryHint({ now = Date.now, ErrorClass = dshLlm.LlmError } =
1877
2271
  ].includes(event.type)) outputStarted = true;
1878
2272
  },
1879
2273
  failure(original, signal) {
1880
- if (signal?.aborted || outputStarted || !original || typeof original.message !== "string" || [
2274
+ if (signal?.aborted || !original || original.code === "ABORTED" || typeof original.message !== "string") return original;
2275
+ const restriction = accessFailure ?? restrictionMessage(original.message) ?? (responseStatus === 403 ? "ChatGPT denied this request (HTTP 403). Check account access or contact OpenAI Support; signing in again may not resolve it." : responseStatus === 401 ? "ChatGPT sign-in needs to be renewed" : void 0);
2276
+ if (restriction !== void 0) {
2277
+ const { providerRetryAfterMs: _delay, ...failure } = original;
2278
+ return {
2279
+ ...failure,
2280
+ message: restriction,
2281
+ code: "AUTH",
2282
+ ...responseStatus === void 0 ? {} : { status: responseStatus }
2283
+ };
2284
+ }
2285
+ if (outputStarted || [
1881
2286
  "ABORTED",
1882
2287
  "AUTH",
1883
2288
  "INVALID_REQUEST",
@@ -1886,8 +2291,8 @@ function createModelRetryHint({ now = Date.now, ErrorClass = dshLlm.LlmError } =
1886
2291
  "QUOTA_EXCEEDED"
1887
2292
  ].includes(original.code) || typeof dshLlm.isQuotaExceededError === "function" && dshLlm.isQuotaExceededError(original.message)) return original;
1888
2293
  const status = responseStatus ?? original.status;
1889
- const overloaded = original.code === "PI_AI_ERROR" && CODEX_OVERLOADED.test(original.message) && (status === void 0 || status >= 200 && status < 300);
1890
- if (!response && !overloaded) return original;
2294
+ const transientStreamFailure = original.code === "PI_AI_ERROR" && (CODEX_OVERLOADED.test(original.message) || CODEX_REQUEST_FAILED.test(original.message)) && (status === void 0 || status >= 200 && status < 300);
2295
+ if (!response && !transientStreamFailure) return original;
1891
2296
  if (/You have hit your ChatGPT usage limit/iu.test(original.message) || response?.status === 429 && original.code !== "RATE_LIMIT") return original;
1892
2297
  const code = response?.status === 429 ? "RATE_LIMIT" : "SERVER";
1893
2298
  let error;
@@ -2146,8 +2551,8 @@ function isDshAutoReview(context) {
2146
2551
  * persistence, headers, transport, and model behavior remain owned by the
2147
2552
  * original provider.
2148
2553
  */
2149
- 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, ultra, runNetwork = (_area, operation) => operation() } = {}) {
2150
- const provider = createOpenAICodexProvider();
2554
+ 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, ultra, runNetwork = (_area, operation) => operation(), beginModelAttempt = createModelAttempt, providerFactory = createOpenAICodexProvider } = {}) {
2555
+ const provider = providerFactory();
2151
2556
  const streamHealth = createModelStreamHealth({ log: (level, message) => diagnosticLog.log(level, "model-stream", message) });
2152
2557
  const retryBridge = createModelRetryBridge();
2153
2558
  const requestToken = Object.freeze({
@@ -2241,10 +2646,11 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
2241
2646
  streamFailure.adapter = void 0;
2242
2647
  }
2243
2648
  };
2244
- const noteStreamFailure = (stage, error, source) => {
2649
+ const noteStreamFailure = (stage, error, source, networkFailure, attemptId) => {
2245
2650
  streamFailure.count += 1;
2246
- diagnosticLog.error("model", `request failed while ${stage === "prepare" ? "preparing" : stage === "request" ? "sending" : stage === "payload" ? "building the payload" : "streaming"}`, error);
2651
+ diagnosticLog.error("model", `request failed while ${stage === "prepare" ? "preparing" : stage === "request" ? "sending" : stage === "payload" ? "building the payload" : "streaming"}${networkFailure ? ": " + networkFailure : ""}`, error);
2247
2652
  streamFailure.stage = stage;
2653
+ streamFailure.attemptId = attemptId;
2248
2654
  try {
2249
2655
  streamFailure.request = source === void 0 ? void 0 : redactRequest(source);
2250
2656
  } catch {
@@ -2308,60 +2714,144 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
2308
2714
  return { [Symbol.asyncIterator]: () => replay ??= run() };
2309
2715
  };
2310
2716
  const networkIterable = (factory, options, direct = false, source) => {
2311
- let iterator;
2312
- let health;
2313
- let prepared;
2314
- let stage = "prepare";
2717
+ const attempt = beginModelAttempt();
2718
+ const cancellation = new AbortController();
2719
+ const signal = options?.signal ? AbortSignal.any([options.signal, cancellation.signal]) : cancellation.signal;
2720
+ let iterator, producer, prepared, request, health, effectiveSource = source, stopped = false;
2721
+ let stage = "prepare", networkFailure;
2315
2722
  const retryHint = direct ? void 0 : retryBridge.current();
2723
+ const cancelled = () => signal.aborted && signal.reason?.name !== "TimeoutError";
2724
+ const settle = (status, error, healthError = error) => {
2725
+ if (attempt.snapshot().status) return;
2726
+ health?.finish(status === "ok" ? "completed" : status === "abandoned" ? "cancelled" : status, healthError);
2727
+ if (status === "failed") noteStreamFailure(stage, error, effectiveSource, networkFailure, attempt.snapshot().attemptId);
2728
+ attempt.finish(status, stage);
2729
+ };
2730
+ const finish = () => {
2731
+ const { status, transports } = attempt.snapshot();
2732
+ request?.finish?.({
2733
+ status,
2734
+ transports
2735
+ });
2736
+ };
2737
+ const initialize = async () => {
2738
+ const overrides = direct ? void 0 : compaction?.networkOptions(void 0);
2739
+ request = await (direct ? void 0 : connection?.prepare({
2740
+ ...options,
2741
+ signal
2742
+ }, {
2743
+ model: source?.model,
2744
+ allowWebSocket: overrides?.websocket !== false
2745
+ })) ?? { options };
2746
+ const next = {
2747
+ ...direct ? {
2748
+ ...request.options,
2749
+ transport: "sse"
2750
+ } : compaction?.requestOptions(request.options) ?? request.options,
2751
+ signal
2752
+ };
2753
+ attempt.configure({
2754
+ preference: request.diagnostic?.preference ?? request.options?.transport ?? "auto",
2755
+ requestedTransport: next.transport ?? "auto"
2756
+ });
2757
+ effectiveSource = {
2758
+ ...source,
2759
+ options: next
2760
+ };
2761
+ health = streamHealth.begin({
2762
+ sessionId: direct ? void 0 : options?.sessionId,
2763
+ configured: request.options?.transport,
2764
+ selected: next.transport
2765
+ });
2766
+ const scopedNetwork = direct ? request.network : overrides ?? request.network;
2767
+ stage = "request";
2768
+ return {
2769
+ next,
2770
+ network: {
2771
+ ...scopedNetwork,
2772
+ modelAttempt: true,
2773
+ onRoute(route) {
2774
+ attempt.route(route);
2775
+ scopedNetwork?.onRoute?.(route);
2776
+ },
2777
+ onTransport(transport) {
2778
+ attempt.transport(transport);
2779
+ scopedNetwork?.onTransport?.(transport);
2780
+ },
2781
+ onFetchFailure(error) {
2782
+ networkFailure = safeFetchFailure(error);
2783
+ attempt.fetchFailure(error);
2784
+ scopedNetwork?.onFetchFailure?.(error);
2785
+ },
2786
+ async transformResponse(response, target) {
2787
+ const value = await (scopedNetwork?.transformResponse?.(response, target) ?? response);
2788
+ if (retryHint) retryHint.onAccessFailure(value.ok ? void 0 : await authFailureMessage(value));
2789
+ return value;
2790
+ }
2791
+ }
2792
+ };
2793
+ };
2316
2794
  const step = async (method, value) => {
2795
+ if (stopped) return {
2796
+ done: true,
2797
+ value: void 0
2798
+ };
2317
2799
  try {
2318
- const request = await (prepared ??= (direct ? void 0 : connection?.prepare(options)) ?? Promise.resolve({ options }));
2319
- if (stage === "prepare") stage = "request";
2800
+ const { next, network } = await (prepared ??= initialize());
2801
+ signal.throwIfAborted();
2320
2802
  const result = await runNetwork("model", () => {
2321
- const next = direct ? request.options : compaction?.requestOptions(request.options) ?? request.options;
2322
- health ??= streamHealth.begin({
2323
- sessionId: direct ? void 0 : options?.sessionId,
2324
- configured: request.options?.transport,
2325
- selected: next.transport
2326
- });
2327
- iterator ??= factory({
2328
- ...next,
2329
- async onResponse(info, requestModel) {
2330
- health.response(info);
2331
- retryHint?.onResponse(info);
2332
- return next.onResponse?.(info, requestModel);
2333
- },
2334
- onProviderStreamEvent(event) {
2335
- health.providerEvent();
2336
- return next.onProviderStreamEvent?.(event);
2337
- },
2338
- async onPayload(payload, requestModel) {
2339
- stage = "payload";
2340
- return next.onPayload?.(payload, requestModel);
2341
- }
2342
- })[Symbol.asyncIterator]();
2803
+ if (!iterator) {
2804
+ producer = factory({
2805
+ ...next,
2806
+ async onResponse(info, requestModel) {
2807
+ health.response(info);
2808
+ attempt.response();
2809
+ retryHint?.onResponse(info);
2810
+ return next.onResponse?.(info, requestModel);
2811
+ },
2812
+ onProviderStreamEvent(event) {
2813
+ health.providerEvent();
2814
+ return next.onProviderStreamEvent?.(event);
2815
+ },
2816
+ async onPayload(payload, requestModel) {
2817
+ stage = "payload";
2818
+ signal.throwIfAborted();
2819
+ const body = await next.onPayload?.(payload, requestModel);
2820
+ signal.throwIfAborted();
2821
+ stage = "request";
2822
+ return body;
2823
+ }
2824
+ });
2825
+ iterator = producer[Symbol.asyncIterator]();
2826
+ producer.result().then((message) => {
2827
+ const status = cancelled() ? stopped ? "abandoned" : "cancelled" : ["error", "aborted"].includes(message?.stopReason) ? "failed" : "ok";
2828
+ settle(status, void 0, message);
2829
+ finish();
2830
+ }, (error) => {
2831
+ settle(cancelled() ? "cancelled" : "failed", error);
2832
+ finish();
2833
+ });
2834
+ }
2343
2835
  return iterator[method]?.(value) ?? (method === "throw" ? Promise.reject(value) : Promise.resolve({
2344
2836
  done: true,
2345
2837
  value
2346
2838
  }));
2347
- }, direct ? request.network : compaction?.networkOptions(request.network) ?? request.network);
2839
+ }, network);
2348
2840
  if (!result.done) {
2349
2841
  health?.observe(result.value);
2350
- if (result.value?.type === "error") health?.finish(request.options?.signal?.aborted ? "cancelled" : "failed", result.value.error);
2351
- else if (result.value?.type === "done") health?.finish("completed");
2352
- retryHint?.observe(result.value, request.options?.signal);
2353
- if (result.value?.type === "error" && !request.options?.signal?.aborted) noteStreamFailure(stage, void 0, source);
2354
- else if (stage === "payload") stage = "stream";
2355
- }
2356
- if (method === "return") health?.finish("cancelled");
2357
- else if (result.done) health?.finish(request.options?.signal?.aborted ? "cancelled" : "completed");
2842
+ attempt.event(result.value);
2843
+ retryHint?.observe(result.value, signal);
2844
+ if (result.value?.type === "error") settle(cancelled() ? "cancelled" : "failed", void 0, result.value.error);
2845
+ else if (result.value?.type === "done") settle("ok");
2846
+ else if (stage === "payload" || stage === "request") stage = "stream";
2847
+ } else settle(cancelled() ? "cancelled" : "abandoned");
2358
2848
  return result.done ? result : {
2359
2849
  ...result,
2360
- value: normalizeTransportEvent(result.value, request.options?.signal)
2850
+ value: normalizeTransportEvent(result.value, signal)
2361
2851
  };
2362
2852
  } catch (error) {
2363
- health?.finish(options?.signal?.aborted ? "cancelled" : "failed", error);
2364
- noteStreamFailure(stage, error, source);
2853
+ settle(stopped ? "abandoned" : cancelled() || error?.name === "AbortError" ? "cancelled" : "failed", error);
2854
+ if (!producer) finish();
2365
2855
  throw error;
2366
2856
  }
2367
2857
  };
@@ -2370,11 +2860,19 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
2370
2860
  return this;
2371
2861
  },
2372
2862
  next: (value) => step("next", value),
2373
- return: (value) => iterator ? step("return", value) : Promise.resolve({
2374
- done: true,
2375
- value
2376
- }),
2377
- throw: (error) => iterator ? step("throw", error) : Promise.reject(error)
2863
+ async return(value) {
2864
+ const status = options?.signal?.aborted ? options.signal.reason?.name === "TimeoutError" ? "failed" : "cancelled" : "abandoned";
2865
+ stopped = true;
2866
+ cancellation.abort();
2867
+ settle(status);
2868
+ if (prepared) await prepared.catch(() => {});
2869
+ if (!producer) finish();
2870
+ return iterator?.return?.(value) ?? {
2871
+ done: true,
2872
+ value
2873
+ };
2874
+ },
2875
+ throw: (error) => step("throw", error)
2378
2876
  };
2379
2877
  };
2380
2878
  const routed = (method, model, transcript, options) => {
@@ -2386,7 +2884,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
2386
2884
  context,
2387
2885
  options
2388
2886
  };
2389
- const create = () => route === void 0 ? networkIterable((prepared) => provider[method](model, context, prepared), withPreferences(model, options), false, source) : networkIterable((prepared) => provider[method](model, context, prepared), withReview(route, options), true, source);
2887
+ const create = () => route === void 0 ? networkIterable((prepared) => provider[method](model, context, prepared), withPreferences(model, options), isDshAutoReview(context), source) : networkIterable((prepared) => provider[method](model, context, prepared), withReview(route, options), true, source);
2390
2888
  return isDshAutoReview(context) ? reviewIterable(create) : create();
2391
2889
  };
2392
2890
  return Object.freeze({
@@ -2411,7 +2909,8 @@ Object.freeze([
2411
2909
  "1.1.0",
2412
2910
  "1.2.0",
2413
2911
  "1.3.0",
2414
- "1.4.0"
2912
+ "1.4.0",
2913
+ "1.5.0"
2415
2914
  ]);
2416
2915
  //#endregion
2417
2916
  //#region src/reasoning-json.js
@@ -3306,6 +3805,11 @@ function presetEntries(ctx) {
3306
3805
  return [];
3307
3806
  }
3308
3807
  }
3808
+ function subagentConfigListener(switcher) {
3809
+ return function(fiberOrConfig, next) {
3810
+ return switcher.configure(this?.entry ? this : fiberOrConfig, next());
3811
+ };
3812
+ }
3309
3813
  /** Change only standard independent spawn tools; leave fork/custom tools untouched. */
3310
3814
  function createSubagentBackendSwitcher({ entries, prepare, persist }) {
3311
3815
  const originals = /* @__PURE__ */ new Map();
@@ -3895,7 +4399,7 @@ function inheritedOriginalImageRef(session, assetId) {
3895
4399
  }
3896
4400
  //#endregion
3897
4401
  //#region src/version.js
3898
- const PACKAGE_VERSION = "3.2.2";
4402
+ const PACKAGE_VERSION = "3.2.4";
3899
4403
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
3900
4404
  //#endregion
3901
4405
  //#region src/codex-images.js
@@ -4418,7 +4922,7 @@ function createCodexImageTool(options) {
4418
4922
  if (!response.ok) {
4419
4923
  const authFailure = await authFailureMessage(response);
4420
4924
  const requestId = supportId(response);
4421
- if (response.status === 403 && authFailure === "ChatGPT sign-in needs to be renewed") throw new Error(`${await refusalMessage(response, editing)}${requestId}`);
4925
+ if (response.status === 403 && authFailure === "ChatGPT denied this request (HTTP 403). Check account access or contact OpenAI Support; signing in again may not resolve it.") throw new Error(`${await refusalMessage(response, editing)}${requestId}`);
4422
4926
  if (authFailure !== void 0) throw new Error(authFailure);
4423
4927
  if (response.status === 429) throw new Error(`${await limitMessage(response)}${requestId}`);
4424
4928
  throw new Error(`Codex image ${editing ? "edit" : "generation"} failed (HTTP ${response.status})${requestId}`);
@@ -10274,6 +10778,15 @@ function emailFromAccessToken(access) {
10274
10778
  const payload = decodeJwtPayload(access);
10275
10779
  return normalizeAccountEmail(payload?.["https://api.openai.com/profile"]?.email ?? payload?.email);
10276
10780
  }
10781
+ function sameOAuthAccount(previous, next) {
10782
+ if (typeof previous.accountId !== "string" || previous.accountId.length === 0 || previous.accountId !== next.accountId) return false;
10783
+ const old = decodeJwtPayload(previous.access);
10784
+ const fresh = decodeJwtPayload(next.access);
10785
+ const oldUser = old?.["https://api.openai.com/auth"]?.chatgpt_user_id;
10786
+ const freshUser = fresh?.["https://api.openai.com/auth"]?.chatgpt_user_id;
10787
+ if (typeof oldUser === "string" && oldUser && typeof freshUser === "string" && freshUser) return oldUser === freshUser;
10788
+ return typeof old?.sub === "string" && old.sub.length > 0 && old.sub === fresh?.sub;
10789
+ }
10277
10790
  /** Normalize the one non-secret account attribute that may cross the UI boundary. */
10278
10791
  function sanitizeOAuthCredential(value) {
10279
10792
  const credential = assertOAuthCredential$1(value);
@@ -10486,6 +10999,18 @@ var DshOAuthAccountVault = class {
10486
10999
  activeId() {
10487
11000
  return this.#enqueue(async () => (await this.#ensurePayload())?.activeId);
10488
11001
  }
11002
+ renew(id, credential, signal) {
11003
+ const next = sanitizeOAuthCredential(credential);
11004
+ return this.modifyAccount(id, (current) => {
11005
+ signal?.throwIfAborted();
11006
+ if (!sameOAuthAccount(current, next)) {
11007
+ const error = /* @__PURE__ */ new Error("Codex login did not match the saved account");
11008
+ error.code = "account-mismatch";
11009
+ throw error;
11010
+ }
11011
+ return next;
11012
+ });
11013
+ }
10489
11014
  add(label, credential) {
10490
11015
  return this.#enqueue(async () => {
10491
11016
  const normalizedLabel = normalizeLabel(label);
@@ -10732,14 +11257,16 @@ function createCodexAuthService(models, store, options = {}) {
10732
11257
  };
10733
11258
  },
10734
11259
  login(interaction, input = {}) {
10735
- if (input.label !== void 0) {
11260
+ if (input.label !== void 0 || input.renewId !== void 0) {
10736
11261
  if (accountVault === void 0 || createLoginModels === void 0) throw new Error("Codex multi-account is unavailable");
10737
11262
  return runLogin(async () => {
10738
11263
  const pending = createPendingStore();
10739
11264
  await createLoginModels(pending).login(PROVIDER$2, "oauth", interaction);
10740
11265
  const credential = pending.credential();
10741
11266
  if (credential === void 0) throw new Error("Codex login did not return credentials");
10742
- await accountVault.add(input.label, credential);
11267
+ interaction.signal?.throwIfAborted();
11268
+ if (input.renewId !== void 0) await accountVault.renew(input.renewId, credential, interaction.signal);
11269
+ else await accountVault.add(input.label, credential);
10743
11270
  });
10744
11271
  }
10745
11272
  return runLogin(() => models.login(PROVIDER$2, "oauth", interaction));
@@ -10883,10 +11410,12 @@ const PUBLIC_FAILURES = /* @__PURE__ */ new Set([
10883
11410
  "account-claim",
10884
11411
  "network",
10885
11412
  "token-exchange",
10886
- "callback"
11413
+ "callback",
11414
+ "account-mismatch"
10887
11415
  ]);
10888
11416
  const publicFailure = (kind) => PUBLIC_FAILURES.has(kind) ? kind : void 0;
10889
11417
  function classifyLoginFailure(error) {
11418
+ if (error?.code === "account-mismatch") return "account-mismatch";
10890
11419
  const message = error instanceof Error ? error.message : "";
10891
11420
  if (/token exchange failed/iu.test(message)) return "token-exchange";
10892
11421
  if (/fetch failed|\b(?:ECONN|ENOTFOUND|ETIMEDOUT|CERT_|socket|network)\b/iu.test(message)) return "network";
@@ -10915,9 +11444,10 @@ var CodexLoginCoordinator = class {
10915
11444
  ...active.view.phase === "failed" ? { failure: classifyLoginFailure(active.hostError) } : {}
10916
11445
  };
10917
11446
  }
10918
- async start({ method, label }) {
11447
+ async start({ method, label, renewId }) {
10919
11448
  if (!LOGIN_METHODS.has(method)) throw new Error(`unsupported Codex login method: ${String(method)}`);
10920
11449
  if (label !== void 0 && (typeof label !== "string" || label.trim().length === 0 || label.trim().length > 48)) throw new Error("unsupported Codex account label");
11450
+ if (renewId !== void 0 && (label !== void 0 || typeof renewId !== "string" || !/^[\w-]{1,128}$/u.test(renewId))) throw new Error("unsupported Codex renewal target");
10921
11451
  const active = this.#activeId === void 0 ? void 0 : this.#sessions.get(this.#activeId);
10922
11452
  if (active !== void 0 && !TERMINAL_PHASES.has(active.view.phase)) {
10923
11453
  active.view = {
@@ -11002,7 +11532,7 @@ var CodexLoginCoordinator = class {
11002
11532
  publishReady();
11003
11533
  }
11004
11534
  };
11005
- session.run = Promise.resolve().then(() => this.auth.login(interaction, label === void 0 ? {} : { label: label.trim() })).then(async () => {
11535
+ session.run = Promise.resolve().then(() => this.auth.login(interaction, renewId !== void 0 ? { renewId } : label === void 0 ? {} : { label: label.trim() })).then(async () => {
11006
11536
  if (controller.signal.aborted) return;
11007
11537
  const status = await this.auth.status();
11008
11538
  session.view = {
@@ -11025,7 +11555,8 @@ var CodexLoginCoordinator = class {
11025
11555
  return;
11026
11556
  }
11027
11557
  try {
11028
- if (label !== void 0) throw error;
11558
+ if (restrictionMessage(error?.message) !== void 0) throw error;
11559
+ if (label !== void 0 || renewId !== void 0) throw error;
11029
11560
  const status = await this.auth.status();
11030
11561
  if (status.authenticated === true) {
11031
11562
  session.view = {
@@ -11046,7 +11577,7 @@ var CodexLoginCoordinator = class {
11046
11577
  method,
11047
11578
  phase: "failed",
11048
11579
  authenticated: false,
11049
- error: "Codex login failed",
11580
+ error: restrictionMessage(error?.message) ?? "Codex login failed",
11050
11581
  failure: publicFailure(classifyLoginFailure(error))
11051
11582
  };
11052
11583
  session.hostError = error;
@@ -11120,7 +11651,8 @@ function createCodexRpcHandler(coordinator, options = {}) {
11120
11651
  if (endpoint === "login/start") {
11121
11652
  const started = await coordinator.start({
11122
11653
  method: input.method,
11123
- label: input.label
11654
+ label: input.label,
11655
+ renewId: input.renewId
11124
11656
  });
11125
11657
  if (input.openExternal !== true) return ok(started);
11126
11658
  const url = started.authUrl ?? started.deviceCode?.verificationUri;
@@ -11670,7 +12202,7 @@ function createOfficialModelCatalog(options = {}) {
11670
12202
  }
11671
12203
  });
11672
12204
  if (!current(flight) || accountId !== id) return false;
11673
- if (response.status !== 304 && !response.ok) throw new Error(`Codex model catalog failed (HTTP ${response.status})`);
12205
+ if (response.status !== 304 && !response.ok) throw new Error(await authFailureMessage(response) ?? `Codex model catalog failed (HTTP ${response.status})`);
11674
12206
  const raw = response.status === 304 ? rawCatalog : await response.json();
11675
12207
  if (!current(flight) || accountId !== id) return false;
11676
12208
  if (raw === void 0) throw new Error("Codex returned HTTP 304 without a cached model catalog");
@@ -11700,7 +12232,7 @@ function createOfficialModelCatalog(options = {}) {
11700
12232
  }, (error) => {
11701
12233
  if (flight.generation === generation) {
11702
12234
  refreshStatus = signal?.aborted ? "idle" : "failed";
11703
- if (!signal?.aborted) scheduleRetry(flight.generation);
12235
+ if (!signal?.aborted && !isRestrictionFailureMessage(error?.message)) scheduleRetry(flight.generation);
11704
12236
  }
11705
12237
  throw error;
11706
12238
  }).finally(() => {
@@ -11867,7 +12399,7 @@ function createCodexSearchProvider(options) {
11867
12399
  if (typeof access !== "string" || access.length === 0 || typeof accountId !== "string" || accountId.length === 0) throw new WebError("ChatGPT subscription is not signed in", "WEB_PROVIDER_CREDENTIAL_MISSING");
11868
12400
  const model = nonEmpty(options.resolveModel?.()) ?? DEFAULT_MODEL;
11869
12401
  const id = nonEmpty(options.resolveSessionId?.()) ?? randomUUID();
11870
- let response;
12402
+ let response, authFailure;
11871
12403
  try {
11872
12404
  const init = {
11873
12405
  method: "POST",
@@ -11899,9 +12431,10 @@ function createCodexSearchProvider(options) {
11899
12431
  for (let attempt = 0; attempt < 2; attempt++) {
11900
12432
  response = await fetchSearch(CODEX_SEARCH_URL, init);
11901
12433
  signal?.throwIfAborted();
12434
+ authFailure = response.ok ? void 0 : await authFailureMessage(response);
11902
12435
  const requestId = response.headers?.get?.("x-request-id") ?? response.headers?.get?.("cf-ray");
11903
12436
  const detail = `model=${model}, mode=${preferences.searchMode}, attempt=${attempt + 1}${typeof requestId === "string" && /^[a-zA-Z0-9._:-]{1,128}$/u.test(requestId) ? `, requestId=${requestId}` : ""}`;
11904
- const retry = attempt === 0 && RETRYABLE_STATUSES.has(response.status);
12437
+ const retry = authFailure === void 0 && attempt === 0 && RETRYABLE_STATUSES.has(response.status);
11905
12438
  diagnosticLog.log(response.ok ? "info" : "warn", "search", `Codex search HTTP ${response.status}${retry ? "; retrying once on the same source" : ""}`, detail);
11906
12439
  if (!retry) break;
11907
12440
  try {
@@ -11914,7 +12447,6 @@ function createCodexSearchProvider(options) {
11914
12447
  throw new WebError("Codex search request failed", "WEB_PROVIDER_ERROR", { cause: error });
11915
12448
  }
11916
12449
  if (!response.ok) {
11917
- const authFailure = await authFailureMessage(response);
11918
12450
  if (signal?.aborted) throw new WebError("Codex search aborted", "WEB_ABORTED", { cause: signal.reason });
11919
12451
  throw authFailure === "ChatGPT sign-in needs to be renewed" ? new WebError(authFailure, "WEB_PROVIDER_CREDENTIAL_MISSING") : authFailure !== void 0 ? new WebError(authFailure, "WEB_PROVIDER_ERROR") : new WebError(`Codex search request failed (HTTP ${response.status})`, "WEB_PROVIDER_ERROR");
11920
12452
  }
@@ -12137,12 +12669,12 @@ function createCodexFetchProvider(options) {
12137
12669
  activeSignal.throwIfAborted();
12138
12670
  diagnosticLog.info("fetch", `Codex webpage HTTP ${response.status}`, `attempt=${attempt}`);
12139
12671
  if (!response.ok) {
12140
- if (RETRYABLE.has(response.status) && attempt === 1) {
12672
+ const authFailure = await authFailureMessage(response);
12673
+ if (authFailure === void 0 && RETRYABLE.has(response.status) && attempt === 1) {
12141
12674
  await response.body?.cancel();
12142
12675
  await setTimeout$1(options.retryDelayMs ?? 250, void 0, { signal: activeSignal });
12143
12676
  continue;
12144
12677
  }
12145
- const authFailure = await authFailureMessage(response);
12146
12678
  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");
12147
12679
  }
12148
12680
  const value = await response.json();
@@ -12369,17 +12901,40 @@ var OriginalImageStore = class {
12369
12901
  }
12370
12902
  }
12371
12903
  async chunk(sessionId, assetId, offset, inherited) {
12372
- if (!Number.isSafeInteger(offset) || offset < 0) return void 0;
12373
- const stored = await this.read(sessionId, assetId, inherited);
12374
- if (stored === void 0 || offset >= stored.data.byteLength || offset % 4194304 !== 0) return void 0;
12375
- const end = Math.min(stored.data.byteLength, offset + ORIGINAL_IMAGE_CHUNK_BYTES);
12376
- const chunk = Buffer.from(stored.data.buffer, stored.data.byteOffset + offset, end - offset);
12377
- return {
12378
- ref: stored.ref,
12379
- offset,
12380
- encoded: chunk.toString("base64"),
12381
- done: end === stored.data.byteLength
12382
- };
12904
+ if (!validSessionId(sessionId) || !ORIGINAL_IMAGE_ID_PATTERN.test(assetId) || !Number.isSafeInteger(offset) || offset < 0 || offset % 4194304 !== 0) return void 0;
12905
+ let handle;
12906
+ try {
12907
+ const metadataFile = join(this.directory(assetId), "metadata.json");
12908
+ const originalFile = this.originalPath(assetId);
12909
+ await Promise.all([assertPrivateFile(metadataFile), assertPrivateFile(originalFile)]);
12910
+ const metadata = parseMetadata(await readFile(metadataFile, "utf8"));
12911
+ if (!metadata || metadata.image.assetId !== assetId || metadata.sessionId !== sessionId && !originalImageRefsEqual(metadata.image, inherited)) return void 0;
12912
+ handle = await open(originalFile, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
12913
+ const stat = await handle.stat();
12914
+ if (!stat.isFile() || stat.size !== metadata.image.bytes || offset >= stat.size || process.platform !== "win32" && (stat.mode & 63) !== 0) return void 0;
12915
+ const header = Buffer.alloc(24);
12916
+ if ((await handle.read(header, 0, 24, 0)).bytesRead !== 24) return void 0;
12917
+ const dimensions = pngDimensions(header);
12918
+ if (dimensions.width !== metadata.image.width || dimensions.height !== metadata.image.height) return void 0;
12919
+ const length = Math.min(ORIGINAL_IMAGE_CHUNK_BYTES, stat.size - offset);
12920
+ const chunk = Buffer.alloc(length);
12921
+ let read = 0;
12922
+ while (read < length) {
12923
+ const result = await handle.read(chunk, read, length - read, offset + read);
12924
+ if (!result.bytesRead) return void 0;
12925
+ read += result.bytesRead;
12926
+ }
12927
+ return {
12928
+ ref: metadata.image,
12929
+ offset,
12930
+ encoded: chunk.toString("base64"),
12931
+ done: offset + length === stat.size
12932
+ };
12933
+ } catch {
12934
+ return;
12935
+ } finally {
12936
+ await handle?.close();
12937
+ }
12383
12938
  }
12384
12939
  };
12385
12940
  //#endregion
@@ -12476,7 +13031,7 @@ function diagnosticEvidence({ operations, history }, now) {
12476
13031
  capability: areas[e.area],
12477
13032
  action: e.area,
12478
13033
  source: "network",
12479
- status: e.status === "ok" ? "completed" : "failed",
13034
+ status: e.status === "ok" ? "completed" : e.status,
12480
13035
  observedAt: e.observedAt
12481
13036
  }))].filter((e) => Number.isSafeInteger(e.observedAt) && now >= e.observedAt && now - e.observedAt <= 9e5).sort((a, b) => a.observedAt - b.observedAt);
12482
13037
  }
@@ -12688,8 +13243,15 @@ const requestAreas = /* @__PURE__ */ new Set([
12688
13243
  "image",
12689
13244
  "voice"
12690
13245
  ]);
12691
- const statuses = /* @__PURE__ */ new Set(["ok", "failed"]);
12692
- const stages = /* @__PURE__ */ new Set(["transport", "http"]);
13246
+ const statuses = MODEL_OUTCOMES;
13247
+ const stages = /* @__PURE__ */ new Set([
13248
+ "transport",
13249
+ "http",
13250
+ "prepare",
13251
+ "request",
13252
+ "payload",
13253
+ "stream"
13254
+ ]);
12693
13255
  const codes = /* @__PURE__ */ new Set([
12694
13256
  "timeout",
12695
13257
  "dns",
@@ -12702,7 +13264,9 @@ const routes = /* @__PURE__ */ new Set([
12702
13264
  "direct",
12703
13265
  "environment",
12704
13266
  "system",
12705
- "bypass"
13267
+ "bypass",
13268
+ "proxy",
13269
+ "unknown"
12706
13270
  ]);
12707
13271
  const elapsedBuckets = /* @__PURE__ */ new Set([
12708
13272
  "under-1s",
@@ -12719,6 +13283,7 @@ function safeHistory(raw) {
12719
13283
  status: value.status,
12720
13284
  sequence: value.sequence,
12721
13285
  observedAt: value.observedAt,
13286
+ ...safeAttempt(value),
12722
13287
  ...codes.has(value.code) ? { code: value.code } : {},
12723
13288
  ...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {}
12724
13289
  }];
@@ -12738,6 +13303,7 @@ function safeRequests(network) {
12738
13303
  if (!statuses.has(value.status) || !routes.has(value.route) || !elapsedBuckets.has(value.elapsed)) continue;
12739
13304
  result[area] = {
12740
13305
  status: value.status,
13306
+ ...safeAttempt(value),
12741
13307
  ...stages.has(value.stage) ? { stage: value.stage } : {},
12742
13308
  ...codes.has(value.code) ? { code: value.code } : {},
12743
13309
  ...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {},
@@ -12799,9 +13365,40 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
12799
13365
  "connectionsReused",
12800
13366
  "deltaRequests",
12801
13367
  "websocketFailures",
12802
- "sseFallbacks"
13368
+ "sseFallbacks",
13369
+ "recoveryAttempts",
13370
+ "recoverySuccesses",
13371
+ "recoveryDeferrals",
13372
+ "cooldownRequests"
12803
13373
  ]) : void 0
12804
13374
  ],
13375
+ [
13376
+ "transportRecovery",
13377
+ "transport",
13378
+ () => {
13379
+ const value = connection?.recoverySnapshot?.();
13380
+ if (!Array.isArray(value?.sessions)) return void 0;
13381
+ return {
13382
+ scope: "plugin-process",
13383
+ capacity: 32,
13384
+ dropped: Math.max(0, value.sessions.length - 32),
13385
+ sessions: value.sessions.slice(-32).flatMap((item) => {
13386
+ if (!/^dsh-[a-f0-9]{56}$/.test(item?.scope) || ![
13387
+ "preferred",
13388
+ "probing",
13389
+ "cooldown"
13390
+ ].includes(item.state)) return [];
13391
+ if (!Number.isSafeInteger(item.active) || item.active < 0 || !Number.isSafeInteger(item.cooldownMs) || item.cooldownMs < 0 || item.cooldownMs > 36e4) return [];
13392
+ return [{
13393
+ scope: item.scope,
13394
+ state: item.state,
13395
+ active: item.active,
13396
+ cooldownMs: item.cooldownMs
13397
+ }];
13398
+ })
13399
+ };
13400
+ }
13401
+ ],
12805
13402
  [
12806
13403
  "compaction",
12807
13404
  "compaction",
@@ -12829,6 +13426,7 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
12829
13426
  if (!Number.isSafeInteger(value?.count)) return void 0;
12830
13427
  return {
12831
13428
  count: value.count,
13429
+ ...typeof value.attemptId === "string" && /^[a-f0-9-]{36}$/.test(value.attemptId) ? { attemptId: value.attemptId } : {},
12832
13430
  ...[
12833
13431
  "prepare",
12834
13432
  "request",
@@ -12949,6 +13547,7 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
12949
13547
  ...collected.history ? { requestHistory: collected.history } : {},
12950
13548
  ...collected.operations ? { operations: collected.operations } : {},
12951
13549
  ...collected.websocket ? { websocket: collected.websocket } : {},
13550
+ ...collected.transportRecovery ? { transportRecovery: collected.transportRecovery } : {},
12952
13551
  ...collected.compaction ? { compaction: collected.compaction } : {},
12953
13552
  ...collected.review ? { review: collected.review } : {},
12954
13553
  ...collected.streamFailure ? { streamFailure: collected.streamFailure } : {},
@@ -13304,7 +13903,7 @@ function createCodexUsageReader(options) {
13304
13903
  read({ force = false, signal } = {}) {
13305
13904
  if (signal?.aborted) return Promise.reject(signal.reason);
13306
13905
  if (failed !== void 0 && now() < failed.retryAt) return Promise.reject(new Error(failed.message));
13307
- if (!force && cached !== void 0 && now() - cached.fetchedAt < ttlFor(cached)) return Promise.resolve(structuredClone(cached));
13906
+ if (!force && failed === void 0 && cached !== void 0 && now() - cached.fetchedAt < ttlFor(cached)) return Promise.resolve(structuredClone(cached));
13308
13907
  return requests.run("read", async (sharedSignal) => {
13309
13908
  const currentGeneration = generation;
13310
13909
  try {
@@ -13394,7 +13993,7 @@ function createAccountUsageReader({ vault, createModels, fetch, expirySkewMs = 0
13394
13993
  const summarize = (error, signal) => {
13395
13994
  if (signal?.aborted) throw error;
13396
13995
  const message = error instanceof Error ? error.message : "";
13397
- return ["ChatGPT subscription is not signed in", "ChatGPT sign-in needs to be renewed"].includes(message) || message.includes("blocked this request") ? message : "Could not read ChatGPT usage";
13996
+ return isAccessFailureMessage(message) || ["ChatGPT subscription is not signed in", "ChatGPT sign-in needs to be renewed"].includes(message) || message.includes("blocked this request") ? message : "Could not read ChatGPT usage";
13398
13997
  };
13399
13998
  return Object.freeze({
13400
13999
  /** One entry per account: its usage reading, or the reason it could not be read. */
@@ -13513,7 +14112,10 @@ function createReportReader({ url, parse, label, getAuth, readCredential, fetch:
13513
14112
  available: false,
13514
14113
  fetchedAt: now()
13515
14114
  };
13516
- if (!response.ok) throw new Error(response.status === 401 ? SIGN_IN_RENEW : response.status === 403 ? await isBlockedByNetwork(response) ? REQUEST_BLOCKED : `ChatGPT does not offer the ${label} to this account` : `ChatGPT ${label} request failed (HTTP ${response.status})`);
14115
+ if (!response.ok) {
14116
+ const failure = await authFailureMessage(response);
14117
+ throw new Error(failure === "ChatGPT denied this request (HTTP 403). Check account access or contact OpenAI Support; signing in again may not resolve it." ? `ChatGPT does not offer the ${label} to this account` : failure ?? `ChatGPT ${label} request failed (HTTP ${response.status})`);
14118
+ }
13517
14119
  let body;
13518
14120
  try {
13519
14121
  body = await response.json();
@@ -13695,9 +14297,10 @@ function createConnectorsClient({ getAuth, readCredential, fetch: fetchRpc = fet
13695
14297
  }),
13696
14298
  signal: signal === void 0 ? timeout : AbortSignal.any([signal, timeout])
13697
14299
  });
13698
- if (response.status === 401) throw new Error(SIGN_IN_RENEW);
13699
- if (response.status === 403) throw new Error(await isBlockedByNetwork(response) ? REQUEST_BLOCKED : "ChatGPT does not offer connectors to this account");
13700
- if (!response.ok) throw new Error(`ChatGPT connectors request failed (HTTP ${response.status})`);
14300
+ if (!response.ok) {
14301
+ const failure = await authFailureMessage(response);
14302
+ throw new Error(failure === "ChatGPT denied this request (HTTP 403). Check account access or contact OpenAI Support; signing in again may not resolve it." ? "ChatGPT does not offer connectors to this account" : failure ?? `ChatGPT connectors request failed (HTTP ${response.status})`);
14303
+ }
13701
14304
  const message = await readRpc(response);
13702
14305
  if (record$1(message.error)) throw new Error(`Connector error: ${clip(oneLine(String(message.error.message ?? message.error.code ?? "failed")), 200)}`);
13703
14306
  return {
@@ -14072,6 +14675,7 @@ function createCodexQuotaRetryHandler({ usageReader, provider = "openai-codex",
14072
14675
  } catch {}
14073
14676
  };
14074
14677
  const handler = async ({ agent, turn, step, provider: requestProvider, failure, signal }, next) => {
14678
+ if (requestProvider === provider && isRestrictionFailureMessage(failure?.message)) return void 0;
14075
14679
  if (requestProvider !== provider || !isCodexRateLimit(failure) || !enabled()) return next();
14076
14680
  if (signal?.aborted) return void 0;
14077
14681
  let wakeRevision = wakeSignal.revision();
@@ -15141,7 +15745,7 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
15141
15745
  "ChatGPT sign-in needs to be renewed",
15142
15746
  REQUEST_BLOCKED
15143
15747
  ]);
15144
- const message = error instanceof Error && known.has(error.message) ? error.message : "Could not read ChatGPT usage";
15748
+ const message = error instanceof Error && (known.has(error.message) || isAccessFailureMessage(error.message)) ? error.message : "Could not read ChatGPT usage";
15145
15749
  return publicError("internal", message);
15146
15750
  }
15147
15751
  if (endpoint === "usage/profile") try {
@@ -15160,7 +15764,7 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
15160
15764
  "ChatGPT sign-in needs to be renewed",
15161
15765
  REQUEST_BLOCKED
15162
15766
  ]);
15163
- return publicError("internal", error instanceof Error && known.has(error.message) ? error.message : "Could not read ChatGPT usage profile");
15767
+ return publicError("internal", error instanceof Error && (known.has(error.message) || isAccessFailureMessage(error.message)) ? error.message : "Could not read ChatGPT usage profile");
15164
15768
  }
15165
15769
  if (endpoint === "usage/accounts") try {
15166
15770
  signal.throwIfAborted();
@@ -15191,7 +15795,7 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
15191
15795
  "ChatGPT sign-in needs to be renewed",
15192
15796
  REQUEST_BLOCKED
15193
15797
  ]);
15194
- return publicError("internal", error instanceof Error && known.has(error.message) ? error.message : "Could not read ChatGPT usage history");
15798
+ return publicError("internal", error instanceof Error && (known.has(error.message) || isAccessFailureMessage(error.message)) ? error.message : "Could not read ChatGPT usage history");
15195
15799
  }
15196
15800
  if (endpoint === "reset-credit/inspect" || endpoint === "reset-credit/prepare" || endpoint === "reset-credit/consume") try {
15197
15801
  signal.throwIfAborted();
@@ -15222,7 +15826,7 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
15222
15826
  "The signed-in ChatGPT account changed"
15223
15827
  ]);
15224
15828
  const fallback = endpoint === "reset-credit/inspect" ? "Could not read quota reset details" : endpoint === "reset-credit/prepare" ? "Could not prepare a quota reset" : "Could not use the quota reset";
15225
- const message = error instanceof Error && known.has(error.message) ? error.message : fallback;
15829
+ const message = error instanceof Error && (known.has(error.message) || isAccessFailureMessage(error.message)) ? error.message : fallback;
15226
15830
  return publicError("internal", message);
15227
15831
  }
15228
15832
  const result = await authHandler(endpoint, payload, signal);
@@ -15237,6 +15841,7 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
15237
15841
  () => onAccountChanged?.()
15238
15842
  ];
15239
15843
  if (endpoint === "logout") tasks.push(() => usageReader.clear(), () => accountUsageReader?.clear());
15844
+ if (endpoint === "login/status") tasks.push(() => accountUsageReader?.clear());
15240
15845
  if (endpoint === "account/remove" && typeof payload?.id === "string") tasks.push(() => usageReader.clearScope(payload.id));
15241
15846
  const outcomes = await Promise.allSettled(tasks.map((task) => Promise.resolve().then(task)));
15242
15847
  const catalogOutcomes = endpoint === "logout" ? [] : await Promise.allSettled([Promise.resolve().then(() => modelCatalog?.initialize())]);
@@ -16129,7 +16734,7 @@ function createNativeVoiceHost({ desktopVoice, spawn: spawn$1 = spawn, platform
16129
16734
  if (call.state === "connected") gate.sample({
16130
16735
  mic: call.levels.mic,
16131
16736
  output: call.levels.assistant,
16132
- now: performance.now()
16737
+ now: performance$1.now()
16133
16738
  });
16134
16739
  }, (error) => {
16135
16740
  closeCall(call, error.code);
@@ -16188,13 +16793,13 @@ function createNativeVoiceHost({ desktopVoice, spawn: spawn$1 = spawn, platform
16188
16793
  clearTimeout(readyTimer);
16189
16794
  }
16190
16795
  call.state = "connected";
16191
- call.renewed = performance.now();
16796
+ call.renewed = performance$1.now();
16192
16797
  info("native-connected");
16193
16798
  clearTimeout(call.deadline);
16194
16799
  call.removeAbort?.();
16195
16800
  call.removeAbort = void 0;
16196
16801
  call.heartbeat = setInterval(() => {
16197
- if (performance.now() - call.renewed >= LEASE_TIMEOUT) {
16802
+ if (performance$1.now() - call.renewed >= LEASE_TIMEOUT) {
16198
16803
  closeCall(call, "native-lease-expired");
16199
16804
  return;
16200
16805
  }
@@ -16221,7 +16826,7 @@ function createNativeVoiceHost({ desktopVoice, spawn: spawn$1 = spawn, platform
16221
16826
  status(sessionId, leaseToken) {
16222
16827
  if (!owns(current, sessionId, leaseToken) || current.ended) return inactive(owns(last, sessionId, leaseToken) ? last.code : "native-voice-owner");
16223
16828
  const call = current;
16224
- call.renewed = performance.now();
16829
+ call.renewed = performance$1.now();
16225
16830
  let remote;
16226
16831
  try {
16227
16832
  remote = desktopVoice.status(sessionId);
@@ -16485,7 +17090,8 @@ function apply(ctx, config = {}) {
16485
17090
  },
16486
17091
  resolveReviewModel: () => settings.get().reviewModel,
16487
17092
  catalog: modelCatalog,
16488
- runNetwork: network.run
17093
+ runNetwork: network.run,
17094
+ beginModelAttempt: network.beginModelAttempt
16489
17095
  });
16490
17096
  let fetchRouted = false;
16491
17097
  const preferences = {
@@ -16610,9 +17216,7 @@ function apply(ctx, config = {}) {
16610
17216
  prepare: instance.prepare,
16611
17217
  persist: (mode) => settings.update({ subagentBackend: mode })
16612
17218
  });
16613
- const unconfigure = scoped.on("internal/config", function(_config, next) {
16614
- return switcher.configure(this, next());
16615
- }, { global: true });
17219
+ const unconfigure = scoped.on("internal/config", subagentConfigListener(switcher), { global: true });
16616
17220
  let requested = "dsh";
16617
17221
  const select = async (mode) => {
16618
17222
  requested = mode;
@@ -17047,7 +17651,7 @@ function apply(ctx, config = {}) {
17047
17651
  }, next).finally(() => activeQuotaRetries.delete(tracked));
17048
17652
  activeQuotaRetries.add(tracked);
17049
17653
  return tracked;
17050
- });
17654
+ }, true);
17051
17655
  ctx.effect(() => async () => {
17052
17656
  disposeQuotaRetry();
17053
17657
  quotaRetryLifetime.abort(/* @__PURE__ */ new Error("codex-subscription quota retry disposed"));