dsh-codex-subscription 3.2.2 → 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 +4 -4
- package/README.md +4 -4
- package/lib/client.image-viewer.js +336 -171
- package/lib/client.js +281 -146
- package/lib/index.js +673 -173
- package/package.json +1 -1
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,58 +1609,227 @@ 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
|
}
|
|
@@ -1782,68 +2185,6 @@ function hoistLeadingSystem(context) {
|
|
|
1782
2185
|
};
|
|
1783
2186
|
}
|
|
1784
2187
|
//#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
2188
|
//#region src/model-retry-hint.js
|
|
1848
2189
|
const CODEX_OVERLOADED = /^\s*(?:Codex error:\s*)?Our servers are currently overloaded\. Please try again later\.\s*$/u;
|
|
1849
2190
|
/** Keep the provider's wait as a fact; only DSH decides whether and when to retry. */
|
|
@@ -2146,8 +2487,8 @@ function isDshAutoReview(context) {
|
|
|
2146
2487
|
* persistence, headers, transport, and model behavior remain owned by the
|
|
2147
2488
|
* original provider.
|
|
2148
2489
|
*/
|
|
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 =
|
|
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();
|
|
2151
2492
|
const streamHealth = createModelStreamHealth({ log: (level, message) => diagnosticLog.log(level, "model-stream", message) });
|
|
2152
2493
|
const retryBridge = createModelRetryBridge();
|
|
2153
2494
|
const requestToken = Object.freeze({
|
|
@@ -2241,10 +2582,11 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2241
2582
|
streamFailure.adapter = void 0;
|
|
2242
2583
|
}
|
|
2243
2584
|
};
|
|
2244
|
-
const noteStreamFailure = (stage, error, source) => {
|
|
2585
|
+
const noteStreamFailure = (stage, error, source, networkFailure, attemptId) => {
|
|
2245
2586
|
streamFailure.count += 1;
|
|
2246
|
-
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);
|
|
2247
2588
|
streamFailure.stage = stage;
|
|
2589
|
+
streamFailure.attemptId = attemptId;
|
|
2248
2590
|
try {
|
|
2249
2591
|
streamFailure.request = source === void 0 ? void 0 : redactRequest(source);
|
|
2250
2592
|
} catch {
|
|
@@ -2308,60 +2650,139 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2308
2650
|
return { [Symbol.asyncIterator]: () => replay ??= run() };
|
|
2309
2651
|
};
|
|
2310
2652
|
const networkIterable = (factory, options, direct = false, source) => {
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
let
|
|
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;
|
|
2315
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
|
+
};
|
|
2316
2725
|
const step = async (method, value) => {
|
|
2726
|
+
if (stopped) return {
|
|
2727
|
+
done: true,
|
|
2728
|
+
value: void 0
|
|
2729
|
+
};
|
|
2317
2730
|
try {
|
|
2318
|
-
const
|
|
2319
|
-
|
|
2731
|
+
const { next, network } = await (prepared ??= initialize());
|
|
2732
|
+
signal.throwIfAborted();
|
|
2320
2733
|
const result = await runNetwork("model", () => {
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
|
|
2329
|
-
|
|
2330
|
-
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
|
|
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
|
+
}
|
|
2343
2766
|
return iterator[method]?.(value) ?? (method === "throw" ? Promise.reject(value) : Promise.resolve({
|
|
2344
2767
|
done: true,
|
|
2345
2768
|
value
|
|
2346
2769
|
}));
|
|
2347
|
-
},
|
|
2770
|
+
}, network);
|
|
2348
2771
|
if (!result.done) {
|
|
2349
2772
|
health?.observe(result.value);
|
|
2350
|
-
|
|
2351
|
-
|
|
2352
|
-
|
|
2353
|
-
if (result.value?.type === "
|
|
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");
|
|
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");
|
|
2358
2779
|
return result.done ? result : {
|
|
2359
2780
|
...result,
|
|
2360
|
-
value: normalizeTransportEvent(result.value,
|
|
2781
|
+
value: normalizeTransportEvent(result.value, signal)
|
|
2361
2782
|
};
|
|
2362
2783
|
} catch (error) {
|
|
2363
|
-
|
|
2364
|
-
|
|
2784
|
+
settle(stopped ? "abandoned" : cancelled() || error?.name === "AbortError" ? "cancelled" : "failed", error);
|
|
2785
|
+
if (!producer) finish();
|
|
2365
2786
|
throw error;
|
|
2366
2787
|
}
|
|
2367
2788
|
};
|
|
@@ -2370,11 +2791,19 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2370
2791
|
return this;
|
|
2371
2792
|
},
|
|
2372
2793
|
next: (value) => step("next", value),
|
|
2373
|
-
return
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
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)
|
|
2378
2807
|
};
|
|
2379
2808
|
};
|
|
2380
2809
|
const routed = (method, model, transcript, options) => {
|
|
@@ -2386,7 +2815,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
|
|
|
2386
2815
|
context,
|
|
2387
2816
|
options
|
|
2388
2817
|
};
|
|
2389
|
-
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);
|
|
2390
2819
|
return isDshAutoReview(context) ? reviewIterable(create) : create();
|
|
2391
2820
|
};
|
|
2392
2821
|
return Object.freeze({
|
|
@@ -3306,6 +3735,11 @@ function presetEntries(ctx) {
|
|
|
3306
3735
|
return [];
|
|
3307
3736
|
}
|
|
3308
3737
|
}
|
|
3738
|
+
function subagentConfigListener(switcher) {
|
|
3739
|
+
return function(fiberOrConfig, next) {
|
|
3740
|
+
return switcher.configure(this?.entry ? this : fiberOrConfig, next());
|
|
3741
|
+
};
|
|
3742
|
+
}
|
|
3309
3743
|
/** Change only standard independent spawn tools; leave fork/custom tools untouched. */
|
|
3310
3744
|
function createSubagentBackendSwitcher({ entries, prepare, persist }) {
|
|
3311
3745
|
const originals = /* @__PURE__ */ new Map();
|
|
@@ -3895,7 +4329,7 @@ function inheritedOriginalImageRef(session, assetId) {
|
|
|
3895
4329
|
}
|
|
3896
4330
|
//#endregion
|
|
3897
4331
|
//#region src/version.js
|
|
3898
|
-
const PACKAGE_VERSION = "3.2.
|
|
4332
|
+
const PACKAGE_VERSION = "3.2.3";
|
|
3899
4333
|
const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
|
|
3900
4334
|
//#endregion
|
|
3901
4335
|
//#region src/codex-images.js
|
|
@@ -12369,17 +12803,40 @@ var OriginalImageStore = class {
|
|
|
12369
12803
|
}
|
|
12370
12804
|
}
|
|
12371
12805
|
async chunk(sessionId, assetId, offset, inherited) {
|
|
12372
|
-
if (!Number.isSafeInteger(offset) || offset < 0) return void 0;
|
|
12373
|
-
|
|
12374
|
-
|
|
12375
|
-
|
|
12376
|
-
|
|
12377
|
-
|
|
12378
|
-
|
|
12379
|
-
|
|
12380
|
-
|
|
12381
|
-
|
|
12382
|
-
|
|
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
|
+
}
|
|
12383
12840
|
}
|
|
12384
12841
|
};
|
|
12385
12842
|
//#endregion
|
|
@@ -12476,7 +12933,7 @@ function diagnosticEvidence({ operations, history }, now) {
|
|
|
12476
12933
|
capability: areas[e.area],
|
|
12477
12934
|
action: e.area,
|
|
12478
12935
|
source: "network",
|
|
12479
|
-
status: e.status === "ok" ? "completed" :
|
|
12936
|
+
status: e.status === "ok" ? "completed" : e.status,
|
|
12480
12937
|
observedAt: e.observedAt
|
|
12481
12938
|
}))].filter((e) => Number.isSafeInteger(e.observedAt) && now >= e.observedAt && now - e.observedAt <= 9e5).sort((a, b) => a.observedAt - b.observedAt);
|
|
12482
12939
|
}
|
|
@@ -12688,8 +13145,15 @@ const requestAreas = /* @__PURE__ */ new Set([
|
|
|
12688
13145
|
"image",
|
|
12689
13146
|
"voice"
|
|
12690
13147
|
]);
|
|
12691
|
-
const statuses =
|
|
12692
|
-
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
|
+
]);
|
|
12693
13157
|
const codes = /* @__PURE__ */ new Set([
|
|
12694
13158
|
"timeout",
|
|
12695
13159
|
"dns",
|
|
@@ -12702,7 +13166,9 @@ const routes = /* @__PURE__ */ new Set([
|
|
|
12702
13166
|
"direct",
|
|
12703
13167
|
"environment",
|
|
12704
13168
|
"system",
|
|
12705
|
-
"bypass"
|
|
13169
|
+
"bypass",
|
|
13170
|
+
"proxy",
|
|
13171
|
+
"unknown"
|
|
12706
13172
|
]);
|
|
12707
13173
|
const elapsedBuckets = /* @__PURE__ */ new Set([
|
|
12708
13174
|
"under-1s",
|
|
@@ -12719,6 +13185,7 @@ function safeHistory(raw) {
|
|
|
12719
13185
|
status: value.status,
|
|
12720
13186
|
sequence: value.sequence,
|
|
12721
13187
|
observedAt: value.observedAt,
|
|
13188
|
+
...safeAttempt(value),
|
|
12722
13189
|
...codes.has(value.code) ? { code: value.code } : {},
|
|
12723
13190
|
...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {}
|
|
12724
13191
|
}];
|
|
@@ -12738,6 +13205,7 @@ function safeRequests(network) {
|
|
|
12738
13205
|
if (!statuses.has(value.status) || !routes.has(value.route) || !elapsedBuckets.has(value.elapsed)) continue;
|
|
12739
13206
|
result[area] = {
|
|
12740
13207
|
status: value.status,
|
|
13208
|
+
...safeAttempt(value),
|
|
12741
13209
|
...stages.has(value.stage) ? { stage: value.stage } : {},
|
|
12742
13210
|
...codes.has(value.code) ? { code: value.code } : {},
|
|
12743
13211
|
...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {},
|
|
@@ -12799,9 +13267,40 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
|
|
|
12799
13267
|
"connectionsReused",
|
|
12800
13268
|
"deltaRequests",
|
|
12801
13269
|
"websocketFailures",
|
|
12802
|
-
"sseFallbacks"
|
|
13270
|
+
"sseFallbacks",
|
|
13271
|
+
"recoveryAttempts",
|
|
13272
|
+
"recoverySuccesses",
|
|
13273
|
+
"recoveryDeferrals",
|
|
13274
|
+
"cooldownRequests"
|
|
12803
13275
|
]) : void 0
|
|
12804
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
|
+
],
|
|
12805
13304
|
[
|
|
12806
13305
|
"compaction",
|
|
12807
13306
|
"compaction",
|
|
@@ -12829,6 +13328,7 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
|
|
|
12829
13328
|
if (!Number.isSafeInteger(value?.count)) return void 0;
|
|
12830
13329
|
return {
|
|
12831
13330
|
count: value.count,
|
|
13331
|
+
...typeof value.attemptId === "string" && /^[a-f0-9-]{36}$/.test(value.attemptId) ? { attemptId: value.attemptId } : {},
|
|
12832
13332
|
...[
|
|
12833
13333
|
"prepare",
|
|
12834
13334
|
"request",
|
|
@@ -12949,6 +13449,7 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
|
|
|
12949
13449
|
...collected.history ? { requestHistory: collected.history } : {},
|
|
12950
13450
|
...collected.operations ? { operations: collected.operations } : {},
|
|
12951
13451
|
...collected.websocket ? { websocket: collected.websocket } : {},
|
|
13452
|
+
...collected.transportRecovery ? { transportRecovery: collected.transportRecovery } : {},
|
|
12952
13453
|
...collected.compaction ? { compaction: collected.compaction } : {},
|
|
12953
13454
|
...collected.review ? { review: collected.review } : {},
|
|
12954
13455
|
...collected.streamFailure ? { streamFailure: collected.streamFailure } : {},
|
|
@@ -16129,7 +16630,7 @@ function createNativeVoiceHost({ desktopVoice, spawn: spawn$1 = spawn, platform
|
|
|
16129
16630
|
if (call.state === "connected") gate.sample({
|
|
16130
16631
|
mic: call.levels.mic,
|
|
16131
16632
|
output: call.levels.assistant,
|
|
16132
|
-
now: performance.now()
|
|
16633
|
+
now: performance$1.now()
|
|
16133
16634
|
});
|
|
16134
16635
|
}, (error) => {
|
|
16135
16636
|
closeCall(call, error.code);
|
|
@@ -16188,13 +16689,13 @@ function createNativeVoiceHost({ desktopVoice, spawn: spawn$1 = spawn, platform
|
|
|
16188
16689
|
clearTimeout(readyTimer);
|
|
16189
16690
|
}
|
|
16190
16691
|
call.state = "connected";
|
|
16191
|
-
call.renewed = performance.now();
|
|
16692
|
+
call.renewed = performance$1.now();
|
|
16192
16693
|
info("native-connected");
|
|
16193
16694
|
clearTimeout(call.deadline);
|
|
16194
16695
|
call.removeAbort?.();
|
|
16195
16696
|
call.removeAbort = void 0;
|
|
16196
16697
|
call.heartbeat = setInterval(() => {
|
|
16197
|
-
if (performance.now() - call.renewed >= LEASE_TIMEOUT) {
|
|
16698
|
+
if (performance$1.now() - call.renewed >= LEASE_TIMEOUT) {
|
|
16198
16699
|
closeCall(call, "native-lease-expired");
|
|
16199
16700
|
return;
|
|
16200
16701
|
}
|
|
@@ -16221,7 +16722,7 @@ function createNativeVoiceHost({ desktopVoice, spawn: spawn$1 = spawn, platform
|
|
|
16221
16722
|
status(sessionId, leaseToken) {
|
|
16222
16723
|
if (!owns(current, sessionId, leaseToken) || current.ended) return inactive(owns(last, sessionId, leaseToken) ? last.code : "native-voice-owner");
|
|
16223
16724
|
const call = current;
|
|
16224
|
-
call.renewed = performance.now();
|
|
16725
|
+
call.renewed = performance$1.now();
|
|
16225
16726
|
let remote;
|
|
16226
16727
|
try {
|
|
16227
16728
|
remote = desktopVoice.status(sessionId);
|
|
@@ -16485,7 +16986,8 @@ function apply(ctx, config = {}) {
|
|
|
16485
16986
|
},
|
|
16486
16987
|
resolveReviewModel: () => settings.get().reviewModel,
|
|
16487
16988
|
catalog: modelCatalog,
|
|
16488
|
-
runNetwork: network.run
|
|
16989
|
+
runNetwork: network.run,
|
|
16990
|
+
beginModelAttempt: network.beginModelAttempt
|
|
16489
16991
|
});
|
|
16490
16992
|
let fetchRouted = false;
|
|
16491
16993
|
const preferences = {
|
|
@@ -16610,9 +17112,7 @@ function apply(ctx, config = {}) {
|
|
|
16610
17112
|
prepare: instance.prepare,
|
|
16611
17113
|
persist: (mode) => settings.update({ subagentBackend: mode })
|
|
16612
17114
|
});
|
|
16613
|
-
const unconfigure = scoped.on("internal/config",
|
|
16614
|
-
return switcher.configure(this, next());
|
|
16615
|
-
}, { global: true });
|
|
17115
|
+
const unconfigure = scoped.on("internal/config", subagentConfigListener(switcher), { global: true });
|
|
16616
17116
|
let requested = "dsh";
|
|
16617
17117
|
const select = async (mode) => {
|
|
16618
17118
|
requested = mode;
|