dsh-codex-subscription 3.2.1 → 3.2.3
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/README.en.md +7 -6
- package/README.md +7 -6
- package/compatibility.json +3 -2
- package/lib/client.image-viewer.js +336 -171
- package/lib/client.js +338 -157
- package/lib/index.js +858 -180
- package/package.json +36 -36
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,204 @@ 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 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";
|
|
873
|
+
const CHALLENGE_MARKERS = /just a moment|cf-chl|_cf_chl_opt|attention required|enable javascript and cookies|challenge-platform/iu;
|
|
874
|
+
/** Whether error text is a Cloudflare / network-protection page (pi-ai keeps only the body of a failed request, not its status). */
|
|
875
|
+
const isChallengePage = (text) => typeof text === "string" && /^\s*<(?:!doctype|html)/iu.test(text) && CHALLENGE_MARKERS.test(text);
|
|
876
|
+
/** Whether a 403 response is a Cloudflare / network-protection page rather than an answer from the ChatGPT backend. */
|
|
877
|
+
async function isBlockedByNetwork(response) {
|
|
878
|
+
if (response?.status !== 403) return false;
|
|
879
|
+
try {
|
|
880
|
+
const header = (name) => String(response.headers?.get?.(name) ?? "");
|
|
881
|
+
if (/challenge/iu.test(header("cf-mitigated"))) return true;
|
|
882
|
+
if (!/html/iu.test(header("content-type"))) return false;
|
|
883
|
+
if (/cloudflare/iu.test(header("server"))) return true;
|
|
884
|
+
const text = typeof response.clone === "function" ? (await response.clone().text()).slice(0, 8192) : "";
|
|
885
|
+
return CHALLENGE_MARKERS.test(text);
|
|
886
|
+
} catch {
|
|
887
|
+
return false;
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
/** The error message for a 401 or 403 answer, or undefined for any other status. */
|
|
891
|
+
async function authFailureMessage(response) {
|
|
892
|
+
if (response?.status !== 401 && response?.status !== 403) return void 0;
|
|
893
|
+
const blocked = response.status === 403 && await isBlockedByNetwork(response);
|
|
894
|
+
await noteAuthFailure(response, blocked);
|
|
895
|
+
return blocked ? REQUEST_BLOCKED : SIGN_IN_RENEW;
|
|
896
|
+
}
|
|
897
|
+
async function noteAuthFailure(response, blocked) {
|
|
898
|
+
try {
|
|
899
|
+
const text = blocked || typeof response.clone !== "function" ? "" : (await response.clone().text()).slice(0, 400);
|
|
900
|
+
logAuthFailure?.(blocked ? "HTTP 403 from the network layer in front of ChatGPT" : `ChatGPT answered HTTP ${response.status}`, text === "" ? void 0 : text);
|
|
901
|
+
} catch {}
|
|
902
|
+
}
|
|
903
|
+
//#endregion
|
|
904
|
+
//#region src/transport-failure.js
|
|
905
|
+
const TRANSIENT_WEBSOCKET_CLOSE = /^WebSocket closed (?:1000|1006|1011|1012|1013)(?:\s|$)/;
|
|
906
|
+
const GATEWAY_REPLAY_BUFFER_EXCEEDED = /^\s*exceeded request buffer limit while retrying upstream\s*$/;
|
|
907
|
+
const NETWORK_CODES = /* @__PURE__ */ new Set([
|
|
908
|
+
"ECONNRESET",
|
|
909
|
+
"ECONNREFUSED",
|
|
910
|
+
"ETIMEDOUT",
|
|
911
|
+
"ENOTFOUND",
|
|
912
|
+
"EAI_AGAIN",
|
|
913
|
+
"ENETUNREACH",
|
|
914
|
+
"EHOSTUNREACH",
|
|
915
|
+
"EPIPE",
|
|
916
|
+
"UND_ERR_SOCKET",
|
|
917
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
918
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
919
|
+
"UND_ERR_BODY_TIMEOUT",
|
|
920
|
+
"CERT_HAS_EXPIRED",
|
|
921
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
922
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT"
|
|
923
|
+
]);
|
|
924
|
+
function safeFetchFailure(error) {
|
|
925
|
+
const pending = [error], seen = /* @__PURE__ */ new Set(), codes = /* @__PURE__ */ new Set();
|
|
926
|
+
for (let i = 0; pending.length && i < 12; i++) {
|
|
927
|
+
const value = pending.shift();
|
|
928
|
+
if (!value || typeof value !== "object" || seen.has(value)) continue;
|
|
929
|
+
seen.add(value);
|
|
930
|
+
if (NETWORK_CODES.has(value.code)) codes.add(value.code);
|
|
931
|
+
if (value.cause) pending.push(value.cause);
|
|
932
|
+
if (Array.isArray(value.errors)) pending.push(...value.errors.slice(0, 8));
|
|
933
|
+
}
|
|
934
|
+
return "fetch failed" + (codes.size ? " [" + [...codes].join(", ") + "]" : "");
|
|
935
|
+
}
|
|
936
|
+
function normalizeTransportEvent(event, signal) {
|
|
937
|
+
if (signal?.aborted || event?.type !== "error" || event.reason !== "error") return event;
|
|
938
|
+
const message = event.error?.errorMessage;
|
|
939
|
+
if (typeof message !== "string") return event;
|
|
940
|
+
if (isChallengePage(message)) return {
|
|
941
|
+
...event,
|
|
942
|
+
error: {
|
|
943
|
+
...event.error,
|
|
944
|
+
errorMessage: REQUEST_BLOCKED
|
|
945
|
+
}
|
|
946
|
+
};
|
|
947
|
+
if (!TRANSIENT_WEBSOCKET_CLOSE.test(message) && !GATEWAY_REPLAY_BUFFER_EXCEEDED.test(message)) return event;
|
|
948
|
+
return {
|
|
949
|
+
...event,
|
|
950
|
+
error: {
|
|
951
|
+
...event.error,
|
|
952
|
+
errorMessage: `Network transport failure: ${message}`
|
|
953
|
+
}
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
//#endregion
|
|
957
|
+
//#region src/model-attempt.js
|
|
958
|
+
const transports = /* @__PURE__ */ new Set(["sse", "websocket"]);
|
|
959
|
+
const choices = /* @__PURE__ */ new Set([
|
|
960
|
+
"sse",
|
|
961
|
+
"websocket",
|
|
962
|
+
"websocket-cached",
|
|
963
|
+
"auto",
|
|
964
|
+
"unknown"
|
|
965
|
+
]);
|
|
966
|
+
const routes$1 = /* @__PURE__ */ new Set([
|
|
967
|
+
"direct",
|
|
968
|
+
"environment",
|
|
969
|
+
"system",
|
|
970
|
+
"bypass",
|
|
971
|
+
"proxy",
|
|
972
|
+
"unknown"
|
|
973
|
+
]);
|
|
974
|
+
const phases = /* @__PURE__ */ new Set([
|
|
975
|
+
"prepare",
|
|
976
|
+
"request",
|
|
977
|
+
"payload",
|
|
978
|
+
"stream"
|
|
979
|
+
]);
|
|
980
|
+
const elapsedBuckets$1 = /* @__PURE__ */ new Set([
|
|
981
|
+
"under-1s",
|
|
982
|
+
"1-5s",
|
|
983
|
+
"5-15s",
|
|
984
|
+
"over-15s"
|
|
985
|
+
]);
|
|
986
|
+
const MODEL_OUTCOMES = /* @__PURE__ */ new Set([
|
|
987
|
+
"ok",
|
|
988
|
+
"failed",
|
|
989
|
+
"cancelled",
|
|
990
|
+
"abandoned"
|
|
991
|
+
]);
|
|
992
|
+
/** One bounded, text-free attempt, not one iterator.next() or HTTP header receipt. */
|
|
993
|
+
function safeAttempt(value = {}) {
|
|
994
|
+
const identified = typeof value.attemptId === "string" && /^[a-f0-9-]{36}$/.test(value.attemptId);
|
|
995
|
+
return {
|
|
996
|
+
...identified && routes$1.has(value.route) ? { route: value.route } : {},
|
|
997
|
+
...identified && phases.has(value.stage) ? { stage: value.stage } : {},
|
|
998
|
+
...identified && elapsedBuckets$1.has(value.elapsed) ? { elapsed: value.elapsed } : {},
|
|
999
|
+
...typeof value.attemptId === "string" && /^[a-f0-9-]{36}$/.test(value.attemptId) ? { attemptId: value.attemptId } : {},
|
|
1000
|
+
...choices.has(value.preference) ? { preference: value.preference } : {},
|
|
1001
|
+
...choices.has(value.requestedTransport) ? { requestedTransport: value.requestedTransport } : {},
|
|
1002
|
+
...Array.isArray(value.transports) ? { transports: value.transports.filter((item) => transports.has(item)).slice(0, 8) } : {},
|
|
1003
|
+
...typeof value.headersReceived === "boolean" ? { headersReceived: value.headersReceived } : {},
|
|
1004
|
+
...typeof value.eventDelivered === "boolean" ? { eventDelivered: value.eventDelivered } : {},
|
|
1005
|
+
...typeof value.contentDelivered === "boolean" ? { contentDelivered: value.contentDelivered } : {},
|
|
1006
|
+
...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 } : {}
|
|
1007
|
+
};
|
|
1008
|
+
}
|
|
1009
|
+
function createModelAttempt({ now = Date.now, publish = () => {} } = {}) {
|
|
1010
|
+
const started = now();
|
|
1011
|
+
const data = {
|
|
1012
|
+
attemptId: randomUUID(),
|
|
1013
|
+
route: "unknown",
|
|
1014
|
+
transports: [],
|
|
1015
|
+
headersReceived: false,
|
|
1016
|
+
eventDelivered: false,
|
|
1017
|
+
contentDelivered: false
|
|
1018
|
+
};
|
|
1019
|
+
let finished = false;
|
|
1020
|
+
return {
|
|
1021
|
+
configure(value) {
|
|
1022
|
+
if (!finished) Object.assign(data, safeAttempt(value));
|
|
1023
|
+
},
|
|
1024
|
+
route(value) {
|
|
1025
|
+
if (!finished && routes$1.has(value)) data.route = value;
|
|
1026
|
+
},
|
|
1027
|
+
transport(value) {
|
|
1028
|
+
if (!finished && transports.has(value) && data.transports.at(-1) !== value && data.transports.length < 8) data.transports.push(value);
|
|
1029
|
+
},
|
|
1030
|
+
response() {
|
|
1031
|
+
if (!finished) data.headersReceived = true;
|
|
1032
|
+
},
|
|
1033
|
+
fetchFailure(error) {
|
|
1034
|
+
if (!finished) data.networkFailure = safeFetchFailure(error);
|
|
1035
|
+
},
|
|
1036
|
+
event(event) {
|
|
1037
|
+
if (finished || !event || ["error", "done"].includes(event.type)) return;
|
|
1038
|
+
data.eventDelivered = true;
|
|
1039
|
+
if (/_delta$|_end$/.test(event.type)) data.contentDelivered = true;
|
|
1040
|
+
},
|
|
1041
|
+
finish(status, stage) {
|
|
1042
|
+
if (finished || !MODEL_OUTCOMES.has(status)) return;
|
|
1043
|
+
finished = true;
|
|
1044
|
+
const elapsed = Math.max(0, now() - started);
|
|
1045
|
+
Object.assign(data, {
|
|
1046
|
+
status,
|
|
1047
|
+
stage,
|
|
1048
|
+
elapsed: elapsed < 1e3 ? "under-1s" : elapsed < 5e3 ? "1-5s" : elapsed < 15e3 ? "5-15s" : "over-15s"
|
|
1049
|
+
});
|
|
1050
|
+
try {
|
|
1051
|
+
publish({
|
|
1052
|
+
...data,
|
|
1053
|
+
transports: [...data.transports]
|
|
1054
|
+
});
|
|
1055
|
+
} catch {}
|
|
1056
|
+
},
|
|
1057
|
+
snapshot: () => ({
|
|
1058
|
+
...data,
|
|
1059
|
+
transports: [...data.transports]
|
|
1060
|
+
})
|
|
1061
|
+
};
|
|
1062
|
+
}
|
|
1063
|
+
//#endregion
|
|
866
1064
|
//#region src/diagnostic-events.js
|
|
867
1065
|
const areas$1 = /* @__PURE__ */ new Set([
|
|
868
1066
|
"login",
|
|
@@ -889,12 +1087,13 @@ function createDiagnosticEvents({ limit = 32, now = Date.now } = {}) {
|
|
|
889
1087
|
let dropped = 0, sequence = 0;
|
|
890
1088
|
return {
|
|
891
1089
|
record(area, value) {
|
|
892
|
-
if (!areas$1.has(area) || !
|
|
1090
|
+
if (!areas$1.has(area) || !MODEL_OUTCOMES.has(value?.status)) return;
|
|
893
1091
|
events.push({
|
|
894
1092
|
sequence: ++sequence,
|
|
895
1093
|
area,
|
|
896
1094
|
status: value.status,
|
|
897
1095
|
observedAt: now(),
|
|
1096
|
+
...safeAttempt(value),
|
|
898
1097
|
...codes$1.has(value.code) ? { code: value.code } : {},
|
|
899
1098
|
...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {}
|
|
900
1099
|
});
|
|
@@ -1234,10 +1433,24 @@ async function withCodexNetwork(run, options = {}) {
|
|
|
1234
1433
|
const url = new URL(String(args[0]));
|
|
1235
1434
|
if (!scope?.options.websocket || url.protocol !== "wss:" || url.hostname !== CODEX_SUBSCRIPTION_HOST) return Reflect.construct(target, args, newTarget);
|
|
1236
1435
|
const proxy = scope.options.websocketProxy;
|
|
1237
|
-
|
|
1436
|
+
const observe = () => {
|
|
1437
|
+
const options = networkScope.getStore()?.options;
|
|
1438
|
+
try {
|
|
1439
|
+
options?.onTransport?.("websocket");
|
|
1440
|
+
options?.onRoute?.(options.websocketProxy ? "proxy" : "direct");
|
|
1441
|
+
} catch {}
|
|
1442
|
+
};
|
|
1443
|
+
observe();
|
|
1444
|
+
const socket = new (scope.options.WebSocket ?? WebSocket)(args[0], {
|
|
1238
1445
|
...args[1],
|
|
1239
1446
|
...proxy ? { agent: new HttpsProxyAgent(proxy) } : {}
|
|
1240
1447
|
});
|
|
1448
|
+
const send = socket.send;
|
|
1449
|
+
socket.send = function(...values) {
|
|
1450
|
+
observe();
|
|
1451
|
+
return Reflect.apply(send, this, values);
|
|
1452
|
+
};
|
|
1453
|
+
return socket;
|
|
1241
1454
|
} });
|
|
1242
1455
|
globalThis.WebSocket = scopedWebSocket;
|
|
1243
1456
|
}
|
|
@@ -1262,7 +1475,18 @@ async function withCodexNetwork(run, options = {}) {
|
|
|
1262
1475
|
}
|
|
1263
1476
|
const route = await proxy;
|
|
1264
1477
|
scopedOptions.onRoute?.(route.source);
|
|
1265
|
-
|
|
1478
|
+
try {
|
|
1479
|
+
scopedOptions.onTransport?.("sse");
|
|
1480
|
+
} catch {}
|
|
1481
|
+
let response;
|
|
1482
|
+
try {
|
|
1483
|
+
response = await (route.url === void 0 && !scopedOptions.standardHttps ? fetchBeforeScope(input, init) : proxyFetch(input, init, route.url));
|
|
1484
|
+
} catch (error) {
|
|
1485
|
+
try {
|
|
1486
|
+
scopedOptions.onFetchFailure?.(error);
|
|
1487
|
+
} catch {}
|
|
1488
|
+
throw error;
|
|
1489
|
+
}
|
|
1266
1490
|
return scopedOptions.transformResponse?.(response, target) ?? response;
|
|
1267
1491
|
};
|
|
1268
1492
|
globalThis.fetch = scopedFetch;
|
|
@@ -1307,10 +1531,11 @@ function createCodexNetworkTransport(options = {}) {
|
|
|
1307
1531
|
const before = attempts.get(area);
|
|
1308
1532
|
attempts.set(area, value);
|
|
1309
1533
|
evidence.record(area, value);
|
|
1534
|
+
if (area === "model" && value.attemptId) return;
|
|
1310
1535
|
if (value.status === "failed") {
|
|
1311
1536
|
const what = value.stage === "http" ? `HTTP ${value.httpStatus}` : `network ${value.code}`;
|
|
1312
1537
|
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");
|
|
1538
|
+
} else if (value.status === "ok" && before?.status === "failed") diagnosticLog.info(area, "request works again");
|
|
1314
1539
|
};
|
|
1315
1540
|
const run = async (area, operation, connection = {}) => {
|
|
1316
1541
|
const startedAt = now();
|
|
@@ -1323,8 +1548,10 @@ function createCodexNetworkTransport(options = {}) {
|
|
|
1323
1548
|
onRoute: (source) => {
|
|
1324
1549
|
route = source;
|
|
1325
1550
|
routed = true;
|
|
1551
|
+
connection.onRoute?.(source);
|
|
1326
1552
|
}
|
|
1327
1553
|
});
|
|
1554
|
+
if (connection.modelAttempt) return value;
|
|
1328
1555
|
connection.signal?.throwIfAborted();
|
|
1329
1556
|
if (value instanceof Response && !value.ok) remember(area, {
|
|
1330
1557
|
status: "failed",
|
|
@@ -1342,7 +1569,7 @@ function createCodexNetworkTransport(options = {}) {
|
|
|
1342
1569
|
return value;
|
|
1343
1570
|
} catch (error) {
|
|
1344
1571
|
if (connection.signal?.aborted && connection.signal.reason?.name !== "TimeoutError") throw error;
|
|
1345
|
-
if (routed) remember(area, {
|
|
1572
|
+
if (routed && !connection.modelAttempt) remember(area, {
|
|
1346
1573
|
status: "failed",
|
|
1347
1574
|
stage: "transport",
|
|
1348
1575
|
code: classifyTransportError(error),
|
|
@@ -1354,6 +1581,13 @@ function createCodexNetworkTransport(options = {}) {
|
|
|
1354
1581
|
};
|
|
1355
1582
|
return Object.freeze({
|
|
1356
1583
|
run,
|
|
1584
|
+
beginModelAttempt: () => createModelAttempt({
|
|
1585
|
+
now,
|
|
1586
|
+
publish: (value) => remember("model", {
|
|
1587
|
+
...value,
|
|
1588
|
+
...value.status === "failed" && value.networkFailure ? { code: classifyTransportError({ code: value.networkFailure.match(/\[([A-Z_]+)/)?.[1] }) } : {}
|
|
1589
|
+
})
|
|
1590
|
+
}),
|
|
1357
1591
|
history: evidence.snapshot,
|
|
1358
1592
|
fetch: (area, input, init, connection) => run(area, () => globalThis.fetch(input, init), {
|
|
1359
1593
|
...connection,
|
|
@@ -1375,62 +1609,252 @@ function tokenScope(apiKey) {
|
|
|
1375
1609
|
} catch {}
|
|
1376
1610
|
return `token:${apiKey}`;
|
|
1377
1611
|
}
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1612
|
+
const COUNTERS = [
|
|
1613
|
+
"requests",
|
|
1614
|
+
"connectionsCreated",
|
|
1615
|
+
"connectionsReused",
|
|
1616
|
+
"deltaRequests",
|
|
1617
|
+
"websocketFailures",
|
|
1618
|
+
"sseFallbacks"
|
|
1619
|
+
];
|
|
1620
|
+
const defaultSdk = {
|
|
1621
|
+
close: closeOpenAICodexWebSocketSessions,
|
|
1622
|
+
reset: resetOpenAICodexWebSocketDebugStats,
|
|
1623
|
+
stats: getOpenAICodexWebSocketDebugStats
|
|
1624
|
+
};
|
|
1625
|
+
const hash$2 = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 56);
|
|
1626
|
+
const zero = () => Object.fromEntries(COUNTERS.map((key) => [key, 0]));
|
|
1627
|
+
/** Policy owns only recovery timing. SDK owns sockets, fallback and continuation. */
|
|
1628
|
+
function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy = resolveCodexOAuthProxy, sdk = defaultSdk, now = () => performance.now(), random = Math.random, cooldownMs = 3e4, maxCooldownMs = 3e5, maxSessions = 256, idleMs = 30 * 6e4 } = {}) {
|
|
1629
|
+
let namespace = randomUUID(), epoch = 0;
|
|
1630
|
+
const sessions = /* @__PURE__ */ new Map(), retired = /* @__PURE__ */ new Set(), probes = /* @__PURE__ */ new Set();
|
|
1631
|
+
const totals = zero();
|
|
1632
|
+
const recovery = {
|
|
1633
|
+
recoveryAttempts: 0,
|
|
1634
|
+
recoverySuccesses: 0,
|
|
1635
|
+
recoveryDeferrals: 0,
|
|
1636
|
+
cooldownRequests: 0
|
|
1637
|
+
};
|
|
1638
|
+
const delay = (streak) => Math.min(maxCooldownMs, cooldownMs * 2 ** Math.min(10, Math.max(0, streak - 1)) * (.8 + .4 * random()));
|
|
1639
|
+
const observe = (entry) => {
|
|
1640
|
+
const stats = sdk.stats(entry.key) ?? {};
|
|
1641
|
+
const failures = Math.max(0, (stats.websocketFailures ?? 0) - entry.seen.websocketFailures);
|
|
1642
|
+
for (const key of COUNTERS) {
|
|
1643
|
+
const count = Number.isSafeInteger(stats[key]) && stats[key] >= 0 ? stats[key] : 0;
|
|
1644
|
+
totals[key] = Math.min(Number.MAX_SAFE_INTEGER, totals[key] + Math.max(0, count - entry.seen[key]));
|
|
1645
|
+
entry.seen[key] = count;
|
|
1646
|
+
}
|
|
1647
|
+
if (!entry.retired && stats.websocketFallbackActive === true && (!entry.cooling || failures > 0)) {
|
|
1648
|
+
entry.streak = Math.min(20, entry.streak + Math.max(1, failures));
|
|
1649
|
+
entry.cooling = true;
|
|
1650
|
+
entry.retryAt = now() + delay(entry.streak);
|
|
1651
|
+
}
|
|
1652
|
+
return stats;
|
|
1653
|
+
};
|
|
1654
|
+
const clear = (entry) => {
|
|
1655
|
+
observe(entry);
|
|
1656
|
+
sdk.close(entry.key);
|
|
1657
|
+
sdk.reset(entry.key);
|
|
1658
|
+
entry.seen = zero();
|
|
1659
|
+
};
|
|
1660
|
+
const evict = (entry) => {
|
|
1661
|
+
clear(entry);
|
|
1662
|
+
sessions.delete(entry.key);
|
|
1663
|
+
};
|
|
1664
|
+
const sse = (options, preference, selectionReason) => ({
|
|
1665
|
+
options: {
|
|
1666
|
+
...options,
|
|
1667
|
+
transport: "sse"
|
|
1668
|
+
},
|
|
1669
|
+
diagnostic: {
|
|
1670
|
+
preference,
|
|
1671
|
+
selectionReason
|
|
1672
|
+
}
|
|
1673
|
+
});
|
|
1381
1674
|
return {
|
|
1382
1675
|
snapshot() {
|
|
1383
|
-
const
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
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;
|
|
1676
|
+
for (const entry of [...sessions.values(), ...retired]) observe(entry);
|
|
1677
|
+
return {
|
|
1678
|
+
...totals,
|
|
1679
|
+
...recovery
|
|
1680
|
+
};
|
|
1396
1681
|
},
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1682
|
+
recoverySnapshot() {
|
|
1683
|
+
const time = now();
|
|
1684
|
+
return {
|
|
1685
|
+
scope: "plugin-process",
|
|
1686
|
+
capacity: maxSessions,
|
|
1687
|
+
sessions: [...sessions.values()].map((entry) => {
|
|
1688
|
+
observe(entry);
|
|
1689
|
+
return {
|
|
1690
|
+
scope: entry.key,
|
|
1691
|
+
state: entry.probe ? "probing" : entry.cooling ? "cooldown" : "preferred",
|
|
1692
|
+
active: entry.active,
|
|
1693
|
+
cooldownMs: Math.max(0, Math.ceil(entry.retryAt - time))
|
|
1694
|
+
};
|
|
1695
|
+
})
|
|
1696
|
+
};
|
|
1697
|
+
},
|
|
1698
|
+
async prepare(options = {}, { model, allowWebSocket = true } = {}) {
|
|
1699
|
+
const preference = resolveMode() === "websocket" ? "websocket" : "sse";
|
|
1700
|
+
if (preference === "sse") return sse(options, preference, "configured-sse");
|
|
1701
|
+
if (!allowWebSocket) return sse(options, preference, "forced-sse");
|
|
1702
|
+
if (!options.sessionId || options.cacheRetention === "none") return sse(options, preference, "no-session");
|
|
1703
|
+
const startedEpoch = epoch;
|
|
1704
|
+
const endpoint = new URL(model?.baseUrl ?? "https://chatgpt.com/backend-api");
|
|
1705
|
+
const proxy = await resolveProxy({
|
|
1706
|
+
target: endpoint,
|
|
1707
|
+
signal: options.signal
|
|
1708
|
+
});
|
|
1709
|
+
options.signal?.throwIfAborted();
|
|
1710
|
+
if (startedEpoch !== epoch) throw new DOMException("Connection scope was cleared", "AbortError");
|
|
1711
|
+
const group = hash$2([
|
|
1712
|
+
namespace,
|
|
1713
|
+
tokenScope(options.apiKey),
|
|
1714
|
+
endpoint.href,
|
|
1715
|
+
proxy
|
|
1716
|
+
]);
|
|
1717
|
+
const key = "dsh-" + hash$2([
|
|
1404
1718
|
namespace,
|
|
1405
1719
|
options.sessionId,
|
|
1406
1720
|
tokenScope(options.apiKey),
|
|
1721
|
+
endpoint.href,
|
|
1407
1722
|
proxy
|
|
1408
|
-
])
|
|
1409
|
-
|
|
1723
|
+
]);
|
|
1724
|
+
const time = now();
|
|
1725
|
+
for (const entry of sessions.values()) if (!entry.active && time - entry.used >= idleMs) evict(entry);
|
|
1726
|
+
let entry = sessions.get(key);
|
|
1727
|
+
if (!entry) {
|
|
1728
|
+
if (sessions.size + retired.size >= maxSessions) {
|
|
1729
|
+
const oldest = [...sessions.values()].filter((item) => !item.active).sort((a, b) => a.used - b.used)[0];
|
|
1730
|
+
if (oldest) evict(oldest);
|
|
1731
|
+
else return sse(options, preference, "capacity");
|
|
1732
|
+
}
|
|
1733
|
+
entry = {
|
|
1734
|
+
key,
|
|
1735
|
+
group,
|
|
1736
|
+
active: 0,
|
|
1737
|
+
used: time,
|
|
1738
|
+
seen: zero(),
|
|
1739
|
+
streak: 0,
|
|
1740
|
+
retryAt: 0,
|
|
1741
|
+
cooling: false,
|
|
1742
|
+
probe: false,
|
|
1743
|
+
retired: false
|
|
1744
|
+
};
|
|
1745
|
+
sessions.set(key, entry);
|
|
1746
|
+
}
|
|
1747
|
+
observe(entry);
|
|
1748
|
+
let transport = "websocket-cached", selectionReason = "websocket-preferred", probe = false;
|
|
1749
|
+
if (entry.probe) {
|
|
1750
|
+
transport = "sse";
|
|
1751
|
+
selectionReason = "probe-busy";
|
|
1752
|
+
} else if (entry.cooling) if (time < entry.retryAt) {
|
|
1753
|
+
transport = "sse";
|
|
1754
|
+
selectionReason = "ws-cooldown";
|
|
1755
|
+
recovery.cooldownRequests++;
|
|
1756
|
+
} else if (entry.active || probes.has(group)) {
|
|
1757
|
+
transport = "sse";
|
|
1758
|
+
selectionReason = "probe-busy";
|
|
1759
|
+
recovery.recoveryDeferrals++;
|
|
1760
|
+
} else {
|
|
1761
|
+
probes.add(group);
|
|
1762
|
+
entry.probe = probe = true;
|
|
1763
|
+
try {
|
|
1764
|
+
clear(entry);
|
|
1765
|
+
} catch (error) {
|
|
1766
|
+
probes.delete(group);
|
|
1767
|
+
entry.probe = false;
|
|
1768
|
+
throw error;
|
|
1769
|
+
}
|
|
1770
|
+
entry.cooling = false;
|
|
1771
|
+
selectionReason = "ws-probe";
|
|
1772
|
+
recovery.recoveryAttempts++;
|
|
1773
|
+
}
|
|
1774
|
+
entry.active++;
|
|
1775
|
+
entry.used = time;
|
|
1776
|
+
let finished = false;
|
|
1410
1777
|
return {
|
|
1411
1778
|
options: {
|
|
1412
1779
|
...options,
|
|
1413
|
-
sessionId,
|
|
1414
|
-
transport
|
|
1780
|
+
sessionId: key,
|
|
1781
|
+
transport,
|
|
1415
1782
|
websocketConnectTimeoutMs: 1e4,
|
|
1416
1783
|
env: {}
|
|
1417
1784
|
},
|
|
1418
1785
|
network: {
|
|
1419
1786
|
websocket: true,
|
|
1420
1787
|
websocketProxy: proxy
|
|
1788
|
+
},
|
|
1789
|
+
diagnostic: {
|
|
1790
|
+
preference,
|
|
1791
|
+
scope: key,
|
|
1792
|
+
selectionReason,
|
|
1793
|
+
cooldownMs: Math.max(0, Math.ceil(entry.retryAt - time))
|
|
1794
|
+
},
|
|
1795
|
+
finish(outcome = {}) {
|
|
1796
|
+
if (finished) return;
|
|
1797
|
+
finished = true;
|
|
1798
|
+
const stats = observe(entry);
|
|
1799
|
+
entry.active--;
|
|
1800
|
+
entry.used = now();
|
|
1801
|
+
if (probe) {
|
|
1802
|
+
probes.delete(group);
|
|
1803
|
+
entry.probe = false;
|
|
1804
|
+
if (!entry.retired && outcome.status === "ok" && outcome.transports?.at(-1) === "websocket" && !outcome.transports.includes("sse") && stats.websocketFallbackActive !== true) {
|
|
1805
|
+
entry.streak = 0;
|
|
1806
|
+
entry.retryAt = 0;
|
|
1807
|
+
entry.cooling = false;
|
|
1808
|
+
recovery.recoverySuccesses++;
|
|
1809
|
+
} else if (!entry.retired && !entry.cooling) {
|
|
1810
|
+
entry.cooling = true;
|
|
1811
|
+
entry.retryAt = now() + delay(entry.streak);
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
if (entry.retired && !entry.active) {
|
|
1815
|
+
clear(entry);
|
|
1816
|
+
retired.delete(entry);
|
|
1817
|
+
}
|
|
1421
1818
|
}
|
|
1422
1819
|
};
|
|
1423
1820
|
},
|
|
1424
1821
|
dispose() {
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1822
|
+
epoch++;
|
|
1823
|
+
namespace = randomUUID();
|
|
1824
|
+
for (const entry of sessions.values()) {
|
|
1825
|
+
observe(entry);
|
|
1826
|
+
entry.retired = true;
|
|
1827
|
+
sdk.close(entry.key);
|
|
1828
|
+
if (entry.active) retired.add(entry);
|
|
1829
|
+
else clear(entry);
|
|
1428
1830
|
}
|
|
1429
1831
|
sessions.clear();
|
|
1832
|
+
probes.clear();
|
|
1430
1833
|
}
|
|
1431
1834
|
};
|
|
1432
1835
|
}
|
|
1433
1836
|
//#endregion
|
|
1837
|
+
//#region src/context-budget.js
|
|
1838
|
+
const effectiveContextPercent = (value) => Number.isInteger(value) && value > 0 && value <= 100 ? value : 95;
|
|
1839
|
+
function effectiveContextWindow(window, percent) {
|
|
1840
|
+
return Number.isSafeInteger(window) && window > 0 ? Math.floor(window * effectiveContextPercent(percent) / 100) : window;
|
|
1841
|
+
}
|
|
1842
|
+
/** Match DSH basic compaction's default pressure budget, using an already effective window.
|
|
1843
|
+
* maxTokens is the routed request's local output reservation, not the model's output ceiling.
|
|
1844
|
+
* Ratio and headroom are alternative pressure limits: do not subtract them successively.
|
|
1845
|
+
*/
|
|
1846
|
+
function compactionThreshold(window, maxTokens, configured) {
|
|
1847
|
+
if (configured !== void 0 && (!Number.isSafeInteger(configured) || configured < 1e3)) throw new Error("Invalid compaction threshold");
|
|
1848
|
+
const reserved = maxTokens ?? 0;
|
|
1849
|
+
if (!Number.isSafeInteger(reserved) || reserved < 0) throw new Error("Invalid compaction output reservation");
|
|
1850
|
+
if (window === void 0 || window === null) return configured ?? 1e5;
|
|
1851
|
+
if (!Number.isSafeInteger(window) || window <= 0) throw new Error("Invalid Codex context window");
|
|
1852
|
+
const pressure = window - reserved - 65536;
|
|
1853
|
+
const limit = Math.floor(Math.min(window * .8, pressure, configured ?? Infinity));
|
|
1854
|
+
if (limit < 1e3) throw new Error("Codex context budget is too small for the requested output reservation and compaction headroom");
|
|
1855
|
+
return limit;
|
|
1856
|
+
}
|
|
1857
|
+
//#endregion
|
|
1434
1858
|
//#region src/subscription-compaction.js
|
|
1435
1859
|
/** Experimental SSE bridge; callers must explicitly opt in. */
|
|
1436
1860
|
const clone$2 = (value) => JSON.parse(JSON.stringify(value));
|
|
@@ -1453,7 +1877,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
|
|
|
1453
1877
|
checkpointsSaved: 0,
|
|
1454
1878
|
checkpointsReused: 0
|
|
1455
1879
|
};
|
|
1456
|
-
const wrapStream = (factory, options) => (async function* () {
|
|
1880
|
+
const wrapStream = (factory, options, modelInfo) => (async function* () {
|
|
1457
1881
|
if (!enabled() || options.provider !== "openai-codex") {
|
|
1458
1882
|
yield* factory(options);
|
|
1459
1883
|
return;
|
|
@@ -1465,7 +1889,8 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
|
|
|
1465
1889
|
original: options.messages,
|
|
1466
1890
|
blocks: [],
|
|
1467
1891
|
suffix: void 0,
|
|
1468
|
-
completed: false
|
|
1892
|
+
completed: false,
|
|
1893
|
+
outputReserve: options.maxTokens ?? modelInfo?.defaultMaxTokens
|
|
1469
1894
|
};
|
|
1470
1895
|
let messages = options.messages;
|
|
1471
1896
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
@@ -1524,19 +1949,29 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
|
|
|
1524
1949
|
snapshot: () => ({ ...stats }),
|
|
1525
1950
|
wrapAdapter(adapter) {
|
|
1526
1951
|
return new Proxy(adapter, { get(target, property) {
|
|
1527
|
-
if (property === "stream") return (options) =>
|
|
1952
|
+
if (property === "stream") return (options) => (async function* () {
|
|
1953
|
+
if (!enabled() || options.provider !== "openai-codex") {
|
|
1954
|
+
yield* target.stream(options);
|
|
1955
|
+
return;
|
|
1956
|
+
}
|
|
1957
|
+
const call = typeof target.prepareCall === "function" ? await target.prepareCall(options.provider, options.model, options.signal) : {
|
|
1958
|
+
model: await target.resolveModel?.(options.provider, options.model),
|
|
1959
|
+
stream: (o) => target.stream(o)
|
|
1960
|
+
};
|
|
1961
|
+
yield* wrapStream((o) => call.stream(o), options, call.model);
|
|
1962
|
+
})();
|
|
1528
1963
|
if (property === "prepareCall") return async (...args) => {
|
|
1529
1964
|
const call = await target.prepareCall(...args);
|
|
1530
1965
|
return {
|
|
1531
1966
|
...call,
|
|
1532
|
-
stream: (options) => wrapStream((o) => call.stream(o), options)
|
|
1967
|
+
stream: (options) => wrapStream((o) => call.stream(o), options, call.model)
|
|
1533
1968
|
};
|
|
1534
1969
|
};
|
|
1535
1970
|
const value = Reflect.get(target, property, target);
|
|
1536
1971
|
return typeof value === "function" ? value.bind(target) : value;
|
|
1537
1972
|
} });
|
|
1538
1973
|
},
|
|
1539
|
-
preparePayload(payload, contextWindow) {
|
|
1974
|
+
preparePayload(payload, contextWindow, maxTokens) {
|
|
1540
1975
|
const state = scope.getStore();
|
|
1541
1976
|
if (!state) return payload;
|
|
1542
1977
|
if (!state.counted) {
|
|
@@ -1544,12 +1979,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
|
|
|
1544
1979
|
stats.requests = Math.min(Number.MAX_SAFE_INTEGER, stats.requests + 1);
|
|
1545
1980
|
if (state.suffix) stats.checkpointsReused = Math.min(Number.MAX_SAFE_INTEGER, stats.checkpointsReused + 1);
|
|
1546
1981
|
}
|
|
1547
|
-
const
|
|
1548
|
-
const configured = threshold?.();
|
|
1549
|
-
if (configured !== void 0 && (!Number.isSafeInteger(configured) || configured < 1e3)) throw new Error("Invalid compaction threshold");
|
|
1550
|
-
const byWindow = windowKnown ? Math.floor(Math.min(contextWindow * .8, contextWindow - Math.min(65536, contextWindow / 4))) : 1e5;
|
|
1551
|
-
const limit = configured === void 0 ? byWindow : windowKnown ? Math.min(configured, Math.floor(contextWindow / 2)) : configured;
|
|
1552
|
-
if (!Number.isSafeInteger(limit) || limit < 1e3) throw new Error("Invalid compaction threshold");
|
|
1982
|
+
const limit = compactionThreshold(contextWindow, maxTokens ?? state.outputReserve, threshold?.());
|
|
1553
1983
|
return {
|
|
1554
1984
|
...payload,
|
|
1555
1985
|
input: [...state.suffix ?? [], ...payload.input],
|
|
@@ -1755,68 +2185,6 @@ function hoistLeadingSystem(context) {
|
|
|
1755
2185
|
};
|
|
1756
2186
|
}
|
|
1757
2187
|
//#endregion
|
|
1758
|
-
//#region src/http-failure.js
|
|
1759
|
-
let logAuthFailure;
|
|
1760
|
-
const setAuthFailureLogger = (fn) => {
|
|
1761
|
-
logAuthFailure = fn;
|
|
1762
|
-
};
|
|
1763
|
-
const SIGN_IN_RENEW = "ChatGPT sign-in needs to be renewed";
|
|
1764
|
-
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";
|
|
1765
|
-
const CHALLENGE_MARKERS = /just a moment|cf-chl|_cf_chl_opt|attention required|enable javascript and cookies|challenge-platform/iu;
|
|
1766
|
-
/** Whether error text is a Cloudflare / network-protection page (pi-ai keeps only the body of a failed request, not its status). */
|
|
1767
|
-
const isChallengePage = (text) => typeof text === "string" && /^\s*<(?:!doctype|html)/iu.test(text) && CHALLENGE_MARKERS.test(text);
|
|
1768
|
-
/** Whether a 403 response is a Cloudflare / network-protection page rather than an answer from the ChatGPT backend. */
|
|
1769
|
-
async function isBlockedByNetwork(response) {
|
|
1770
|
-
if (response?.status !== 403) return false;
|
|
1771
|
-
try {
|
|
1772
|
-
const header = (name) => String(response.headers?.get?.(name) ?? "");
|
|
1773
|
-
if (/challenge/iu.test(header("cf-mitigated"))) return true;
|
|
1774
|
-
if (!/html/iu.test(header("content-type"))) return false;
|
|
1775
|
-
if (/cloudflare/iu.test(header("server"))) return true;
|
|
1776
|
-
const text = typeof response.clone === "function" ? (await response.clone().text()).slice(0, 8192) : "";
|
|
1777
|
-
return CHALLENGE_MARKERS.test(text);
|
|
1778
|
-
} catch {
|
|
1779
|
-
return false;
|
|
1780
|
-
}
|
|
1781
|
-
}
|
|
1782
|
-
/** The error message for a 401 or 403 answer, or undefined for any other status. */
|
|
1783
|
-
async function authFailureMessage(response) {
|
|
1784
|
-
if (response?.status !== 401 && response?.status !== 403) return void 0;
|
|
1785
|
-
const blocked = response.status === 403 && await isBlockedByNetwork(response);
|
|
1786
|
-
await noteAuthFailure(response, blocked);
|
|
1787
|
-
return blocked ? REQUEST_BLOCKED : SIGN_IN_RENEW;
|
|
1788
|
-
}
|
|
1789
|
-
async function noteAuthFailure(response, blocked) {
|
|
1790
|
-
try {
|
|
1791
|
-
const text = blocked || typeof response.clone !== "function" ? "" : (await response.clone().text()).slice(0, 400);
|
|
1792
|
-
logAuthFailure?.(blocked ? "HTTP 403 from the network layer in front of ChatGPT" : `ChatGPT answered HTTP ${response.status}`, text === "" ? void 0 : text);
|
|
1793
|
-
} catch {}
|
|
1794
|
-
}
|
|
1795
|
-
//#endregion
|
|
1796
|
-
//#region src/transport-failure.js
|
|
1797
|
-
const TRANSIENT_WEBSOCKET_CLOSE = /^WebSocket closed (?:1000|1006|1011|1012|1013)(?:\s|$)/;
|
|
1798
|
-
const GATEWAY_REPLAY_BUFFER_EXCEEDED = /^\s*exceeded request buffer limit while retrying upstream\s*$/;
|
|
1799
|
-
function normalizeTransportEvent(event, signal) {
|
|
1800
|
-
if (signal?.aborted || event?.type !== "error" || event.reason !== "error") return event;
|
|
1801
|
-
const message = event.error?.errorMessage;
|
|
1802
|
-
if (typeof message !== "string") return event;
|
|
1803
|
-
if (isChallengePage(message)) return {
|
|
1804
|
-
...event,
|
|
1805
|
-
error: {
|
|
1806
|
-
...event.error,
|
|
1807
|
-
errorMessage: REQUEST_BLOCKED
|
|
1808
|
-
}
|
|
1809
|
-
};
|
|
1810
|
-
if (!TRANSIENT_WEBSOCKET_CLOSE.test(message) && !GATEWAY_REPLAY_BUFFER_EXCEEDED.test(message)) return event;
|
|
1811
|
-
return {
|
|
1812
|
-
...event,
|
|
1813
|
-
error: {
|
|
1814
|
-
...event.error,
|
|
1815
|
-
errorMessage: `Network transport failure: ${message}`
|
|
1816
|
-
}
|
|
1817
|
-
};
|
|
1818
|
-
}
|
|
1819
|
-
//#endregion
|
|
1820
2188
|
//#region src/model-retry-hint.js
|
|
1821
2189
|
const CODEX_OVERLOADED = /^\s*(?:Codex error:\s*)?Our servers are currently overloaded\. Please try again later\.\s*$/u;
|
|
1822
2190
|
/** Keep the provider's wait as a fact; only DSH decides whether and when to retry. */
|
|
@@ -1922,6 +2290,134 @@ function createModelRetryBridge() {
|
|
|
1922
2290
|
};
|
|
1923
2291
|
}
|
|
1924
2292
|
//#endregion
|
|
2293
|
+
//#region src/model-stream-health.js
|
|
2294
|
+
const transportOf = (value) => value?.startsWith("websocket") ? "websocket" : value === "sse" ? "sse" : "unknown";
|
|
2295
|
+
const failureCode = (error) => {
|
|
2296
|
+
const text = String(error?.errorMessage ?? error?.message ?? "");
|
|
2297
|
+
return [
|
|
2298
|
+
"ECONNRESET",
|
|
2299
|
+
"ETIMEDOUT",
|
|
2300
|
+
"ECONNREFUSED",
|
|
2301
|
+
"ERR_STREAM_PREMATURE_CLOSE"
|
|
2302
|
+
].find((code) => error?.code === code || text.includes(code)) ?? (/timeout/i.test(text) ? "TIMEOUT" : /WebSocket closed/i.test(text) ? "WS_CLOSED" : "OTHER");
|
|
2303
|
+
};
|
|
2304
|
+
/** Bounded request-level facts; no prompts, response bodies, credentials or public session ids. */
|
|
2305
|
+
function createModelStreamHealth({ now = Date.now, log = () => {} } = {}) {
|
|
2306
|
+
const recent = [], streaks = /* @__PURE__ */ new Map();
|
|
2307
|
+
return {
|
|
2308
|
+
snapshot: () => recent.map((value) => ({ ...value })),
|
|
2309
|
+
begin({ sessionId, configured, selected }) {
|
|
2310
|
+
const start = now(), configuredTransport = transportOf(configured), selectedTransport = transportOf(selected);
|
|
2311
|
+
let done = false, providerEvents = false, lastEvent, firstEvent, count = 0, output = false, httpStatus;
|
|
2312
|
+
let effectiveTransport = "unknown";
|
|
2313
|
+
const event = () => {
|
|
2314
|
+
const at = now();
|
|
2315
|
+
firstEvent ??= at;
|
|
2316
|
+
lastEvent = at;
|
|
2317
|
+
count++;
|
|
2318
|
+
};
|
|
2319
|
+
return {
|
|
2320
|
+
response(info) {
|
|
2321
|
+
effectiveTransport = "sse";
|
|
2322
|
+
if (Number.isInteger(info?.status)) httpStatus = info.status;
|
|
2323
|
+
},
|
|
2324
|
+
providerEvent() {
|
|
2325
|
+
providerEvents = true;
|
|
2326
|
+
event();
|
|
2327
|
+
if (effectiveTransport === "unknown" && selectedTransport === "websocket") effectiveTransport = "websocket";
|
|
2328
|
+
},
|
|
2329
|
+
observe(value) {
|
|
2330
|
+
if (value?.type?.endsWith("_delta")) output = true;
|
|
2331
|
+
if (!providerEvents && ![
|
|
2332
|
+
"start",
|
|
2333
|
+
"error",
|
|
2334
|
+
"done"
|
|
2335
|
+
].includes(value?.type)) {
|
|
2336
|
+
event();
|
|
2337
|
+
if (effectiveTransport === "unknown" && selectedTransport === "websocket") effectiveTransport = "websocket";
|
|
2338
|
+
}
|
|
2339
|
+
},
|
|
2340
|
+
finish(status, error) {
|
|
2341
|
+
if (done) return;
|
|
2342
|
+
done = true;
|
|
2343
|
+
const end = now(), code = status === "failed" ? failureCode(error) : void 0;
|
|
2344
|
+
const previous = typeof sessionId === "string" ? streaks.get(sessionId) : void 0;
|
|
2345
|
+
const signature = `${effectiveTransport}:${code}`;
|
|
2346
|
+
const consecutiveFailures = status === "failed" && typeof sessionId === "string" ? previous?.signature === signature ? Math.min(previous.count + 1, 1e3) : 1 : 0;
|
|
2347
|
+
if (typeof sessionId === "string") {
|
|
2348
|
+
streaks.delete(sessionId);
|
|
2349
|
+
if (consecutiveFailures) streaks.set(sessionId, {
|
|
2350
|
+
signature,
|
|
2351
|
+
count: consecutiveFailures
|
|
2352
|
+
});
|
|
2353
|
+
if (streaks.size > 100) streaks.delete(streaks.keys().next().value);
|
|
2354
|
+
}
|
|
2355
|
+
const value = {
|
|
2356
|
+
status,
|
|
2357
|
+
configured: configuredTransport,
|
|
2358
|
+
selected: selectedTransport,
|
|
2359
|
+
effective: effectiveTransport,
|
|
2360
|
+
durationMs: Math.max(0, end - start),
|
|
2361
|
+
eventCount: count,
|
|
2362
|
+
eventSource: providerEvents ? "provider" : "adapter",
|
|
2363
|
+
outputStarted: output,
|
|
2364
|
+
...firstEvent === void 0 ? {} : {
|
|
2365
|
+
firstEventMs: Math.max(0, firstEvent - start),
|
|
2366
|
+
lastEventAgoMs: Math.max(0, end - lastEvent)
|
|
2367
|
+
},
|
|
2368
|
+
...httpStatus === void 0 ? {} : { httpStatus },
|
|
2369
|
+
...code === void 0 ? {} : {
|
|
2370
|
+
code,
|
|
2371
|
+
consecutiveFailures
|
|
2372
|
+
}
|
|
2373
|
+
};
|
|
2374
|
+
recent.push(value);
|
|
2375
|
+
if (recent.length > 20) recent.shift();
|
|
2376
|
+
if (status !== "cancelled") log(status === "failed" ? "warn" : "info", `stream ${status}: configured=${configuredTransport} selected=${selectedTransport} effective=${effectiveTransport} duration_ms=${value.durationMs} first_event_ms=${value.firstEventMs ?? "none"} last_event_ago_ms=${value.lastEventAgoMs ?? "none"} events=${count}${code ? ` failure=${code} consecutive=${consecutiveFailures}` : ""}`);
|
|
2377
|
+
}
|
|
2378
|
+
};
|
|
2379
|
+
}
|
|
2380
|
+
};
|
|
2381
|
+
}
|
|
2382
|
+
function safeStreamHealth(value) {
|
|
2383
|
+
if (!Array.isArray(value)) return [];
|
|
2384
|
+
return value.slice(-20).filter((item) => [
|
|
2385
|
+
"completed",
|
|
2386
|
+
"failed",
|
|
2387
|
+
"cancelled"
|
|
2388
|
+
].includes(item?.status)).map((item) => ({
|
|
2389
|
+
status: item.status,
|
|
2390
|
+
...Object.fromEntries([
|
|
2391
|
+
"configured",
|
|
2392
|
+
"selected",
|
|
2393
|
+
"effective"
|
|
2394
|
+
].filter((key) => [
|
|
2395
|
+
"sse",
|
|
2396
|
+
"websocket",
|
|
2397
|
+
"unknown"
|
|
2398
|
+
].includes(item[key])).map((key) => [key, item[key]])),
|
|
2399
|
+
...Object.fromEntries([
|
|
2400
|
+
"durationMs",
|
|
2401
|
+
"firstEventMs",
|
|
2402
|
+
"lastEventAgoMs",
|
|
2403
|
+
"eventCount",
|
|
2404
|
+
"consecutiveFailures",
|
|
2405
|
+
"httpStatus"
|
|
2406
|
+
].filter((key) => Number.isSafeInteger(item[key]) && item[key] >= 0).map((key) => [key, item[key]])),
|
|
2407
|
+
...["provider", "adapter"].includes(item.eventSource) ? { eventSource: item.eventSource } : {},
|
|
2408
|
+
...typeof item.outputStarted === "boolean" ? { outputStarted: item.outputStarted } : {},
|
|
2409
|
+
...[
|
|
2410
|
+
"ECONNRESET",
|
|
2411
|
+
"ETIMEDOUT",
|
|
2412
|
+
"ECONNREFUSED",
|
|
2413
|
+
"ERR_STREAM_PREMATURE_CLOSE",
|
|
2414
|
+
"TIMEOUT",
|
|
2415
|
+
"WS_CLOSED",
|
|
2416
|
+
"OTHER"
|
|
2417
|
+
].includes(item.code) ? { code: item.code } : {}
|
|
2418
|
+
}));
|
|
2419
|
+
}
|
|
2420
|
+
//#endregion
|
|
1925
2421
|
//#region src/pi-ai-runtime.js
|
|
1926
2422
|
const FAST_SERVICE_TIER = "priority";
|
|
1927
2423
|
const ULTRAFAST_SERVICE_TIER = "ultrafast";
|
|
@@ -1991,8 +2487,9 @@ function isDshAutoReview(context) {
|
|
|
1991
2487
|
* persistence, headers, transport, and model behavior remain owned by the
|
|
1992
2488
|
* original provider.
|
|
1993
2489
|
*/
|
|
1994
|
-
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() } = {}) {
|
|
1995
|
-
const provider =
|
|
2490
|
+
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 } = {}) {
|
|
2491
|
+
const provider = providerFactory();
|
|
2492
|
+
const streamHealth = createModelStreamHealth({ log: (level, message) => diagnosticLog.log(level, "model-stream", message) });
|
|
1996
2493
|
const retryBridge = createModelRetryBridge();
|
|
1997
2494
|
const requestToken = Object.freeze({
|
|
1998
2495
|
name: "DSH-managed Codex OAuth request token",
|
|
@@ -2005,7 +2502,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2005
2502
|
};
|
|
2006
2503
|
}
|
|
2007
2504
|
});
|
|
2008
|
-
const modelMetadata = (model) => catalog?.metadata(model?.id);
|
|
2505
|
+
const modelMetadata = (model) => catalog?.metadata?.(model?.id);
|
|
2009
2506
|
const supportsVerbosity = (model) => modelMetadata(model)?.supportVerbosity ?? model?.id !== "gpt-5.3-codex-spark";
|
|
2010
2507
|
const withPreferences = (model, options = {}) => {
|
|
2011
2508
|
const metadata = modelMetadata(model);
|
|
@@ -2030,7 +2527,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2030
2527
|
} },
|
|
2031
2528
|
...serviceTier === void 0 ? {} : { service_tier: serviceTier }
|
|
2032
2529
|
};
|
|
2033
|
-
const managed = compaction?.preparePayload(preferred, model?.contextWindow) ?? preferred;
|
|
2530
|
+
const managed = compaction?.preparePayload(preferred, model?.contextWindow, options.maxTokens) ?? preferred;
|
|
2034
2531
|
const next = await onPayload?.(managed, requestModel);
|
|
2035
2532
|
const detailed = inputImageDetail === "auto" ? next ?? managed : withInputImageDetail(next ?? managed, inputImageDetail);
|
|
2036
2533
|
const { temperature: _dropped, ...accepted } = withReasoningSummary(detailed, reasoningSummary);
|
|
@@ -2050,18 +2547,14 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2050
2547
|
const getModels = () => (catalog?.getModels() ?? provider.getModels()).map((model) => {
|
|
2051
2548
|
const maximum = modelContextMaximum(model);
|
|
2052
2549
|
const mode = resolveContextMode();
|
|
2053
|
-
|
|
2054
|
-
if (
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
...model,
|
|
2058
|
-
contextWindow
|
|
2059
|
-
};
|
|
2550
|
+
let window = model.contextWindow;
|
|
2551
|
+
if (model.id !== "gpt-5.3-codex-spark") {
|
|
2552
|
+
if (mode === "extended") window = maximum;
|
|
2553
|
+
else if (mode === "custom") window = clampModelContext(resolveCustomContextWindow(customContextModelKey(model.id)), maximum, window);
|
|
2060
2554
|
}
|
|
2061
|
-
|
|
2062
|
-
return {
|
|
2555
|
+
return window === void 0 ? model : {
|
|
2063
2556
|
...model,
|
|
2064
|
-
contextWindow:
|
|
2557
|
+
contextWindow: effectiveContextWindow(window, modelMetadata(model)?.effectiveContextWindowPercent)
|
|
2065
2558
|
};
|
|
2066
2559
|
});
|
|
2067
2560
|
const review = {
|
|
@@ -2089,10 +2582,11 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2089
2582
|
streamFailure.adapter = void 0;
|
|
2090
2583
|
}
|
|
2091
2584
|
};
|
|
2092
|
-
const noteStreamFailure = (stage, error, source) => {
|
|
2585
|
+
const noteStreamFailure = (stage, error, source, networkFailure, attemptId) => {
|
|
2093
2586
|
streamFailure.count += 1;
|
|
2094
|
-
diagnosticLog.error("model", `request failed while ${stage === "prepare" ? "preparing" : stage === "request" ? "sending" : stage === "payload" ? "building the payload" : "streaming"}`, error);
|
|
2587
|
+
diagnosticLog.error("model", `request failed while ${stage === "prepare" ? "preparing" : stage === "request" ? "sending" : stage === "payload" ? "building the payload" : "streaming"}${networkFailure ? ": " + networkFailure : ""}`, error);
|
|
2095
2588
|
streamFailure.stage = stage;
|
|
2589
|
+
streamFailure.attemptId = attemptId;
|
|
2096
2590
|
try {
|
|
2097
2591
|
streamFailure.request = source === void 0 ? void 0 : redactRequest(source);
|
|
2098
2592
|
} catch {
|
|
@@ -2156,43 +2650,139 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2156
2650
|
return { [Symbol.asyncIterator]: () => replay ??= run() };
|
|
2157
2651
|
};
|
|
2158
2652
|
const networkIterable = (factory, options, direct = false, source) => {
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2653
|
+
const attempt = beginModelAttempt();
|
|
2654
|
+
const cancellation = new AbortController();
|
|
2655
|
+
const signal = options?.signal ? AbortSignal.any([options.signal, cancellation.signal]) : cancellation.signal;
|
|
2656
|
+
let iterator, producer, prepared, request, health, effectiveSource = source, stopped = false;
|
|
2657
|
+
let stage = "prepare", networkFailure;
|
|
2162
2658
|
const retryHint = direct ? void 0 : retryBridge.current();
|
|
2659
|
+
const cancelled = () => signal.aborted && signal.reason?.name !== "TimeoutError";
|
|
2660
|
+
const settle = (status, error, healthError = error) => {
|
|
2661
|
+
if (attempt.snapshot().status) return;
|
|
2662
|
+
health?.finish(status === "ok" ? "completed" : status === "abandoned" ? "cancelled" : status, healthError);
|
|
2663
|
+
if (status === "failed") noteStreamFailure(stage, error, effectiveSource, networkFailure, attempt.snapshot().attemptId);
|
|
2664
|
+
attempt.finish(status, stage);
|
|
2665
|
+
};
|
|
2666
|
+
const finish = () => {
|
|
2667
|
+
const { status, transports } = attempt.snapshot();
|
|
2668
|
+
request?.finish?.({
|
|
2669
|
+
status,
|
|
2670
|
+
transports
|
|
2671
|
+
});
|
|
2672
|
+
};
|
|
2673
|
+
const initialize = async () => {
|
|
2674
|
+
const overrides = direct ? void 0 : compaction?.networkOptions(void 0);
|
|
2675
|
+
request = await (direct ? void 0 : connection?.prepare({
|
|
2676
|
+
...options,
|
|
2677
|
+
signal
|
|
2678
|
+
}, {
|
|
2679
|
+
model: source?.model,
|
|
2680
|
+
allowWebSocket: overrides?.websocket !== false
|
|
2681
|
+
})) ?? { options };
|
|
2682
|
+
const next = {
|
|
2683
|
+
...direct ? {
|
|
2684
|
+
...request.options,
|
|
2685
|
+
transport: "sse"
|
|
2686
|
+
} : compaction?.requestOptions(request.options) ?? request.options,
|
|
2687
|
+
signal
|
|
2688
|
+
};
|
|
2689
|
+
attempt.configure({
|
|
2690
|
+
preference: request.diagnostic?.preference ?? request.options?.transport ?? "auto",
|
|
2691
|
+
requestedTransport: next.transport ?? "auto"
|
|
2692
|
+
});
|
|
2693
|
+
effectiveSource = {
|
|
2694
|
+
...source,
|
|
2695
|
+
options: next
|
|
2696
|
+
};
|
|
2697
|
+
health = streamHealth.begin({
|
|
2698
|
+
sessionId: direct ? void 0 : options?.sessionId,
|
|
2699
|
+
configured: request.options?.transport,
|
|
2700
|
+
selected: next.transport
|
|
2701
|
+
});
|
|
2702
|
+
const scopedNetwork = direct ? request.network : overrides ?? request.network;
|
|
2703
|
+
stage = "request";
|
|
2704
|
+
return {
|
|
2705
|
+
next,
|
|
2706
|
+
network: {
|
|
2707
|
+
...scopedNetwork,
|
|
2708
|
+
modelAttempt: true,
|
|
2709
|
+
onRoute(route) {
|
|
2710
|
+
attempt.route(route);
|
|
2711
|
+
scopedNetwork?.onRoute?.(route);
|
|
2712
|
+
},
|
|
2713
|
+
onTransport(transport) {
|
|
2714
|
+
attempt.transport(transport);
|
|
2715
|
+
scopedNetwork?.onTransport?.(transport);
|
|
2716
|
+
},
|
|
2717
|
+
onFetchFailure(error) {
|
|
2718
|
+
networkFailure = safeFetchFailure(error);
|
|
2719
|
+
attempt.fetchFailure(error);
|
|
2720
|
+
scopedNetwork?.onFetchFailure?.(error);
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
};
|
|
2724
|
+
};
|
|
2163
2725
|
const step = async (method, value) => {
|
|
2726
|
+
if (stopped) return {
|
|
2727
|
+
done: true,
|
|
2728
|
+
value: void 0
|
|
2729
|
+
};
|
|
2164
2730
|
try {
|
|
2165
|
-
const
|
|
2166
|
-
|
|
2731
|
+
const { next, network } = await (prepared ??= initialize());
|
|
2732
|
+
signal.throwIfAborted();
|
|
2167
2733
|
const result = await runNetwork("model", () => {
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2734
|
+
if (!iterator) {
|
|
2735
|
+
producer = factory({
|
|
2736
|
+
...next,
|
|
2737
|
+
async onResponse(info, requestModel) {
|
|
2738
|
+
health.response(info);
|
|
2739
|
+
attempt.response();
|
|
2740
|
+
retryHint?.onResponse(info);
|
|
2741
|
+
return next.onResponse?.(info, requestModel);
|
|
2742
|
+
},
|
|
2743
|
+
onProviderStreamEvent(event) {
|
|
2744
|
+
health.providerEvent();
|
|
2745
|
+
return next.onProviderStreamEvent?.(event);
|
|
2746
|
+
},
|
|
2747
|
+
async onPayload(payload, requestModel) {
|
|
2748
|
+
stage = "payload";
|
|
2749
|
+
signal.throwIfAborted();
|
|
2750
|
+
const body = await next.onPayload?.(payload, requestModel);
|
|
2751
|
+
signal.throwIfAborted();
|
|
2752
|
+
stage = "request";
|
|
2753
|
+
return body;
|
|
2754
|
+
}
|
|
2755
|
+
});
|
|
2756
|
+
iterator = producer[Symbol.asyncIterator]();
|
|
2757
|
+
producer.result().then((message) => {
|
|
2758
|
+
const status = cancelled() ? stopped ? "abandoned" : "cancelled" : ["error", "aborted"].includes(message?.stopReason) ? "failed" : "ok";
|
|
2759
|
+
settle(status, void 0, message);
|
|
2760
|
+
finish();
|
|
2761
|
+
}, (error) => {
|
|
2762
|
+
settle(cancelled() ? "cancelled" : "failed", error);
|
|
2763
|
+
finish();
|
|
2764
|
+
});
|
|
2765
|
+
}
|
|
2180
2766
|
return iterator[method]?.(value) ?? (method === "throw" ? Promise.reject(value) : Promise.resolve({
|
|
2181
2767
|
done: true,
|
|
2182
2768
|
value
|
|
2183
2769
|
}));
|
|
2184
|
-
},
|
|
2770
|
+
}, network);
|
|
2185
2771
|
if (!result.done) {
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2772
|
+
health?.observe(result.value);
|
|
2773
|
+
attempt.event(result.value);
|
|
2774
|
+
retryHint?.observe(result.value, signal);
|
|
2775
|
+
if (result.value?.type === "error") settle(cancelled() ? "cancelled" : "failed", void 0, result.value.error);
|
|
2776
|
+
else if (result.value?.type === "done") settle("ok");
|
|
2777
|
+
else if (stage === "payload" || stage === "request") stage = "stream";
|
|
2778
|
+
} else settle(cancelled() ? "cancelled" : "abandoned");
|
|
2190
2779
|
return result.done ? result : {
|
|
2191
2780
|
...result,
|
|
2192
|
-
value: normalizeTransportEvent(result.value,
|
|
2781
|
+
value: normalizeTransportEvent(result.value, signal)
|
|
2193
2782
|
};
|
|
2194
2783
|
} catch (error) {
|
|
2195
|
-
|
|
2784
|
+
settle(stopped ? "abandoned" : cancelled() || error?.name === "AbortError" ? "cancelled" : "failed", error);
|
|
2785
|
+
if (!producer) finish();
|
|
2196
2786
|
throw error;
|
|
2197
2787
|
}
|
|
2198
2788
|
};
|
|
@@ -2201,11 +2791,19 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2201
2791
|
return this;
|
|
2202
2792
|
},
|
|
2203
2793
|
next: (value) => step("next", value),
|
|
2204
|
-
return
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
|
|
2208
|
-
|
|
2794
|
+
async return(value) {
|
|
2795
|
+
const status = options?.signal?.aborted ? options.signal.reason?.name === "TimeoutError" ? "failed" : "cancelled" : "abandoned";
|
|
2796
|
+
stopped = true;
|
|
2797
|
+
cancellation.abort();
|
|
2798
|
+
settle(status);
|
|
2799
|
+
if (prepared) await prepared.catch(() => {});
|
|
2800
|
+
if (!producer) finish();
|
|
2801
|
+
return iterator?.return?.(value) ?? {
|
|
2802
|
+
done: true,
|
|
2803
|
+
value
|
|
2804
|
+
};
|
|
2805
|
+
},
|
|
2806
|
+
throw: (error) => step("throw", error)
|
|
2209
2807
|
};
|
|
2210
2808
|
};
|
|
2211
2809
|
const routed = (method, model, transcript, options) => {
|
|
@@ -2217,7 +2815,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2217
2815
|
context,
|
|
2218
2816
|
options
|
|
2219
2817
|
};
|
|
2220
|
-
const create = () => route === void 0 ? networkIterable((prepared) => provider[method](model, context, prepared), withPreferences(model, options),
|
|
2818
|
+
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);
|
|
2221
2819
|
return isDshAutoReview(context) ? reviewIterable(create) : create();
|
|
2222
2820
|
};
|
|
2223
2821
|
return Object.freeze({
|
|
@@ -2231,6 +2829,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2231
2829
|
streamSimple: (model, context, options) => routed("streamSimple", model, context, options),
|
|
2232
2830
|
reviewCounters: () => ({ ...review }),
|
|
2233
2831
|
streamFailure: () => ({ ...streamFailure }),
|
|
2832
|
+
streamHealth: streamHealth.snapshot,
|
|
2234
2833
|
noteAdapterFailure,
|
|
2235
2834
|
wrapRetryAdapter: (adapter) => retryBridge.wrapAdapter(adapter)
|
|
2236
2835
|
});
|
|
@@ -2903,6 +3502,7 @@ const SUPPORTED_RUNTIME_VERSIONS = Object.freeze([
|
|
|
2903
3502
|
"0.2.1-rc.2",
|
|
2904
3503
|
"0.2.1-rc.3",
|
|
2905
3504
|
"0.2.1-rc.4",
|
|
3505
|
+
"0.2.1-rc.5",
|
|
2906
3506
|
"0.2.2-alpha.2"
|
|
2907
3507
|
]);
|
|
2908
3508
|
const require = createRequire(import.meta.url);
|
|
@@ -3135,6 +3735,11 @@ function presetEntries(ctx) {
|
|
|
3135
3735
|
return [];
|
|
3136
3736
|
}
|
|
3137
3737
|
}
|
|
3738
|
+
function subagentConfigListener(switcher) {
|
|
3739
|
+
return function(fiberOrConfig, next) {
|
|
3740
|
+
return switcher.configure(this?.entry ? this : fiberOrConfig, next());
|
|
3741
|
+
};
|
|
3742
|
+
}
|
|
3138
3743
|
/** Change only standard independent spawn tools; leave fork/custom tools untouched. */
|
|
3139
3744
|
function createSubagentBackendSwitcher({ entries, prepare, persist }) {
|
|
3140
3745
|
const originals = /* @__PURE__ */ new Map();
|
|
@@ -3724,7 +4329,7 @@ function inheritedOriginalImageRef(session, assetId) {
|
|
|
3724
4329
|
}
|
|
3725
4330
|
//#endregion
|
|
3726
4331
|
//#region src/version.js
|
|
3727
|
-
const PACKAGE_VERSION = "3.2.
|
|
4332
|
+
const PACKAGE_VERSION = "3.2.3";
|
|
3728
4333
|
const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
|
|
3729
4334
|
//#endregion
|
|
3730
4335
|
//#region src/codex-images.js
|
|
@@ -11242,6 +11847,7 @@ function visibleModel(value, displayNames, now) {
|
|
|
11242
11847
|
priority: Number.isFinite(value.priority) ? value.priority : 0,
|
|
11243
11848
|
input: input.length > 0 ? input : ["text"],
|
|
11244
11849
|
contextWindow: positiveInteger(value.context_window) ?? positiveInteger(value.max_context_window),
|
|
11850
|
+
effectiveContextWindowPercent: effectiveContextPercent(value.effective_context_window_percent),
|
|
11245
11851
|
...positiveInteger(value.max_context_window) === void 0 ? {} : { maxContextWindow: value.max_context_window },
|
|
11246
11852
|
reasoning: supported.length > 0,
|
|
11247
11853
|
supportsReasoningEffortUpdates: value.supports_reasoning_effort_updates === true,
|
|
@@ -12197,17 +12803,40 @@ var OriginalImageStore = class {
|
|
|
12197
12803
|
}
|
|
12198
12804
|
}
|
|
12199
12805
|
async chunk(sessionId, assetId, offset, inherited) {
|
|
12200
|
-
if (!Number.isSafeInteger(offset) || offset < 0) return void 0;
|
|
12201
|
-
|
|
12202
|
-
|
|
12203
|
-
|
|
12204
|
-
|
|
12205
|
-
|
|
12206
|
-
|
|
12207
|
-
|
|
12208
|
-
|
|
12209
|
-
|
|
12210
|
-
|
|
12806
|
+
if (!validSessionId(sessionId) || !ORIGINAL_IMAGE_ID_PATTERN.test(assetId) || !Number.isSafeInteger(offset) || offset < 0 || offset % 4194304 !== 0) return void 0;
|
|
12807
|
+
let handle;
|
|
12808
|
+
try {
|
|
12809
|
+
const metadataFile = join(this.directory(assetId), "metadata.json");
|
|
12810
|
+
const originalFile = this.originalPath(assetId);
|
|
12811
|
+
await Promise.all([assertPrivateFile(metadataFile), assertPrivateFile(originalFile)]);
|
|
12812
|
+
const metadata = parseMetadata(await readFile(metadataFile, "utf8"));
|
|
12813
|
+
if (!metadata || metadata.image.assetId !== assetId || metadata.sessionId !== sessionId && !originalImageRefsEqual(metadata.image, inherited)) return void 0;
|
|
12814
|
+
handle = await open(originalFile, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
12815
|
+
const stat = await handle.stat();
|
|
12816
|
+
if (!stat.isFile() || stat.size !== metadata.image.bytes || offset >= stat.size || process.platform !== "win32" && (stat.mode & 63) !== 0) return void 0;
|
|
12817
|
+
const header = Buffer.alloc(24);
|
|
12818
|
+
if ((await handle.read(header, 0, 24, 0)).bytesRead !== 24) return void 0;
|
|
12819
|
+
const dimensions = pngDimensions(header);
|
|
12820
|
+
if (dimensions.width !== metadata.image.width || dimensions.height !== metadata.image.height) return void 0;
|
|
12821
|
+
const length = Math.min(ORIGINAL_IMAGE_CHUNK_BYTES, stat.size - offset);
|
|
12822
|
+
const chunk = Buffer.alloc(length);
|
|
12823
|
+
let read = 0;
|
|
12824
|
+
while (read < length) {
|
|
12825
|
+
const result = await handle.read(chunk, read, length - read, offset + read);
|
|
12826
|
+
if (!result.bytesRead) return void 0;
|
|
12827
|
+
read += result.bytesRead;
|
|
12828
|
+
}
|
|
12829
|
+
return {
|
|
12830
|
+
ref: metadata.image,
|
|
12831
|
+
offset,
|
|
12832
|
+
encoded: chunk.toString("base64"),
|
|
12833
|
+
done: offset + length === stat.size
|
|
12834
|
+
};
|
|
12835
|
+
} catch {
|
|
12836
|
+
return;
|
|
12837
|
+
} finally {
|
|
12838
|
+
await handle?.close();
|
|
12839
|
+
}
|
|
12211
12840
|
}
|
|
12212
12841
|
};
|
|
12213
12842
|
//#endregion
|
|
@@ -12304,7 +12933,7 @@ function diagnosticEvidence({ operations, history }, now) {
|
|
|
12304
12933
|
capability: areas[e.area],
|
|
12305
12934
|
action: e.area,
|
|
12306
12935
|
source: "network",
|
|
12307
|
-
status: e.status === "ok" ? "completed" :
|
|
12936
|
+
status: e.status === "ok" ? "completed" : e.status,
|
|
12308
12937
|
observedAt: e.observedAt
|
|
12309
12938
|
}))].filter((e) => Number.isSafeInteger(e.observedAt) && now >= e.observedAt && now - e.observedAt <= 9e5).sort((a, b) => a.observedAt - b.observedAt);
|
|
12310
12939
|
}
|
|
@@ -12516,8 +13145,15 @@ const requestAreas = /* @__PURE__ */ new Set([
|
|
|
12516
13145
|
"image",
|
|
12517
13146
|
"voice"
|
|
12518
13147
|
]);
|
|
12519
|
-
const statuses =
|
|
12520
|
-
const stages = /* @__PURE__ */ new Set([
|
|
13148
|
+
const statuses = MODEL_OUTCOMES;
|
|
13149
|
+
const stages = /* @__PURE__ */ new Set([
|
|
13150
|
+
"transport",
|
|
13151
|
+
"http",
|
|
13152
|
+
"prepare",
|
|
13153
|
+
"request",
|
|
13154
|
+
"payload",
|
|
13155
|
+
"stream"
|
|
13156
|
+
]);
|
|
12521
13157
|
const codes = /* @__PURE__ */ new Set([
|
|
12522
13158
|
"timeout",
|
|
12523
13159
|
"dns",
|
|
@@ -12530,7 +13166,9 @@ const routes = /* @__PURE__ */ new Set([
|
|
|
12530
13166
|
"direct",
|
|
12531
13167
|
"environment",
|
|
12532
13168
|
"system",
|
|
12533
|
-
"bypass"
|
|
13169
|
+
"bypass",
|
|
13170
|
+
"proxy",
|
|
13171
|
+
"unknown"
|
|
12534
13172
|
]);
|
|
12535
13173
|
const elapsedBuckets = /* @__PURE__ */ new Set([
|
|
12536
13174
|
"under-1s",
|
|
@@ -12547,6 +13185,7 @@ function safeHistory(raw) {
|
|
|
12547
13185
|
status: value.status,
|
|
12548
13186
|
sequence: value.sequence,
|
|
12549
13187
|
observedAt: value.observedAt,
|
|
13188
|
+
...safeAttempt(value),
|
|
12550
13189
|
...codes.has(value.code) ? { code: value.code } : {},
|
|
12551
13190
|
...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {}
|
|
12552
13191
|
}];
|
|
@@ -12566,6 +13205,7 @@ function safeRequests(network) {
|
|
|
12566
13205
|
if (!statuses.has(value.status) || !routes.has(value.route) || !elapsedBuckets.has(value.elapsed)) continue;
|
|
12567
13206
|
result[area] = {
|
|
12568
13207
|
status: value.status,
|
|
13208
|
+
...safeAttempt(value),
|
|
12569
13209
|
...stages.has(value.stage) ? { stage: value.stage } : {},
|
|
12570
13210
|
...codes.has(value.code) ? { code: value.code } : {},
|
|
12571
13211
|
...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {},
|
|
@@ -12627,9 +13267,40 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
|
|
|
12627
13267
|
"connectionsReused",
|
|
12628
13268
|
"deltaRequests",
|
|
12629
13269
|
"websocketFailures",
|
|
12630
|
-
"sseFallbacks"
|
|
13270
|
+
"sseFallbacks",
|
|
13271
|
+
"recoveryAttempts",
|
|
13272
|
+
"recoverySuccesses",
|
|
13273
|
+
"recoveryDeferrals",
|
|
13274
|
+
"cooldownRequests"
|
|
12631
13275
|
]) : void 0
|
|
12632
13276
|
],
|
|
13277
|
+
[
|
|
13278
|
+
"transportRecovery",
|
|
13279
|
+
"transport",
|
|
13280
|
+
() => {
|
|
13281
|
+
const value = connection?.recoverySnapshot?.();
|
|
13282
|
+
if (!Array.isArray(value?.sessions)) return void 0;
|
|
13283
|
+
return {
|
|
13284
|
+
scope: "plugin-process",
|
|
13285
|
+
capacity: 32,
|
|
13286
|
+
dropped: Math.max(0, value.sessions.length - 32),
|
|
13287
|
+
sessions: value.sessions.slice(-32).flatMap((item) => {
|
|
13288
|
+
if (!/^dsh-[a-f0-9]{56}$/.test(item?.scope) || ![
|
|
13289
|
+
"preferred",
|
|
13290
|
+
"probing",
|
|
13291
|
+
"cooldown"
|
|
13292
|
+
].includes(item.state)) return [];
|
|
13293
|
+
if (!Number.isSafeInteger(item.active) || item.active < 0 || !Number.isSafeInteger(item.cooldownMs) || item.cooldownMs < 0 || item.cooldownMs > 36e4) return [];
|
|
13294
|
+
return [{
|
|
13295
|
+
scope: item.scope,
|
|
13296
|
+
state: item.state,
|
|
13297
|
+
active: item.active,
|
|
13298
|
+
cooldownMs: item.cooldownMs
|
|
13299
|
+
}];
|
|
13300
|
+
})
|
|
13301
|
+
};
|
|
13302
|
+
}
|
|
13303
|
+
],
|
|
12633
13304
|
[
|
|
12634
13305
|
"compaction",
|
|
12635
13306
|
"compaction",
|
|
@@ -12657,6 +13328,7 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
|
|
|
12657
13328
|
if (!Number.isSafeInteger(value?.count)) return void 0;
|
|
12658
13329
|
return {
|
|
12659
13330
|
count: value.count,
|
|
13331
|
+
...typeof value.attemptId === "string" && /^[a-f0-9-]{36}$/.test(value.attemptId) ? { attemptId: value.attemptId } : {},
|
|
12660
13332
|
...[
|
|
12661
13333
|
"prepare",
|
|
12662
13334
|
"request",
|
|
@@ -12669,6 +13341,11 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
|
|
|
12669
13341
|
};
|
|
12670
13342
|
}
|
|
12671
13343
|
],
|
|
13344
|
+
[
|
|
13345
|
+
"streamHealth",
|
|
13346
|
+
"transport",
|
|
13347
|
+
() => typeof review?.streamHealth === "function" ? safeStreamHealth(review.streamHealth()) : void 0
|
|
13348
|
+
],
|
|
12672
13349
|
[
|
|
12673
13350
|
"operations",
|
|
12674
13351
|
"transport",
|
|
@@ -12772,9 +13449,11 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
|
|
|
12772
13449
|
...collected.history ? { requestHistory: collected.history } : {},
|
|
12773
13450
|
...collected.operations ? { operations: collected.operations } : {},
|
|
12774
13451
|
...collected.websocket ? { websocket: collected.websocket } : {},
|
|
13452
|
+
...collected.transportRecovery ? { transportRecovery: collected.transportRecovery } : {},
|
|
12775
13453
|
...collected.compaction ? { compaction: collected.compaction } : {},
|
|
12776
13454
|
...collected.review ? { review: collected.review } : {},
|
|
12777
13455
|
...collected.streamFailure ? { streamFailure: collected.streamFailure } : {},
|
|
13456
|
+
...collected.streamHealth?.length ? { streamHealth: collected.streamHealth } : {},
|
|
12778
13457
|
...catalog && [
|
|
12779
13458
|
"unavailable",
|
|
12780
13459
|
"cached",
|
|
@@ -15951,7 +16630,7 @@ function createNativeVoiceHost({ desktopVoice, spawn: spawn$1 = spawn, platform
|
|
|
15951
16630
|
if (call.state === "connected") gate.sample({
|
|
15952
16631
|
mic: call.levels.mic,
|
|
15953
16632
|
output: call.levels.assistant,
|
|
15954
|
-
now: performance.now()
|
|
16633
|
+
now: performance$1.now()
|
|
15955
16634
|
});
|
|
15956
16635
|
}, (error) => {
|
|
15957
16636
|
closeCall(call, error.code);
|
|
@@ -16010,13 +16689,13 @@ function createNativeVoiceHost({ desktopVoice, spawn: spawn$1 = spawn, platform
|
|
|
16010
16689
|
clearTimeout(readyTimer);
|
|
16011
16690
|
}
|
|
16012
16691
|
call.state = "connected";
|
|
16013
|
-
call.renewed = performance.now();
|
|
16692
|
+
call.renewed = performance$1.now();
|
|
16014
16693
|
info("native-connected");
|
|
16015
16694
|
clearTimeout(call.deadline);
|
|
16016
16695
|
call.removeAbort?.();
|
|
16017
16696
|
call.removeAbort = void 0;
|
|
16018
16697
|
call.heartbeat = setInterval(() => {
|
|
16019
|
-
if (performance.now() - call.renewed >= LEASE_TIMEOUT) {
|
|
16698
|
+
if (performance$1.now() - call.renewed >= LEASE_TIMEOUT) {
|
|
16020
16699
|
closeCall(call, "native-lease-expired");
|
|
16021
16700
|
return;
|
|
16022
16701
|
}
|
|
@@ -16043,7 +16722,7 @@ function createNativeVoiceHost({ desktopVoice, spawn: spawn$1 = spawn, platform
|
|
|
16043
16722
|
status(sessionId, leaseToken) {
|
|
16044
16723
|
if (!owns(current, sessionId, leaseToken) || current.ended) return inactive(owns(last, sessionId, leaseToken) ? last.code : "native-voice-owner");
|
|
16045
16724
|
const call = current;
|
|
16046
|
-
call.renewed = performance.now();
|
|
16725
|
+
call.renewed = performance$1.now();
|
|
16047
16726
|
let remote;
|
|
16048
16727
|
try {
|
|
16049
16728
|
remote = desktopVoice.status(sessionId);
|
|
@@ -16307,7 +16986,8 @@ function apply(ctx, config = {}) {
|
|
|
16307
16986
|
},
|
|
16308
16987
|
resolveReviewModel: () => settings.get().reviewModel,
|
|
16309
16988
|
catalog: modelCatalog,
|
|
16310
|
-
runNetwork: network.run
|
|
16989
|
+
runNetwork: network.run,
|
|
16990
|
+
beginModelAttempt: network.beginModelAttempt
|
|
16311
16991
|
});
|
|
16312
16992
|
let fetchRouted = false;
|
|
16313
16993
|
const preferences = {
|
|
@@ -16432,9 +17112,7 @@ function apply(ctx, config = {}) {
|
|
|
16432
17112
|
prepare: instance.prepare,
|
|
16433
17113
|
persist: (mode) => settings.update({ subagentBackend: mode })
|
|
16434
17114
|
});
|
|
16435
|
-
const unconfigure = scoped.on("internal/config",
|
|
16436
|
-
return switcher.configure(this, next());
|
|
16437
|
-
}, { global: true });
|
|
17115
|
+
const unconfigure = scoped.on("internal/config", subagentConfigListener(switcher), { global: true });
|
|
16438
17116
|
let requested = "dsh";
|
|
16439
17117
|
const select = async (mode) => {
|
|
16440
17118
|
requested = mode;
|