dsh-codex-subscription 3.1.5 → 3.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -20,6 +20,7 @@ import { lstat, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } fr
20
20
  import { defineTool } from "@deepseek-ai/dsh-tools";
21
21
  import * as dshCredentials from "@deepseek-ai/dsh-credentials";
22
22
  import { homedir, hostname } from "node:os";
23
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
23
24
  import { dshHomePath, resolveDshHome } from "@deepseek-ai/dsh-home-paths";
24
25
  import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
25
26
  import { WebError } from "@deepseek-ai/dsh-web";
@@ -402,6 +403,9 @@ const SEARCH_PROVIDER_FIELD = "searchProvider";
402
403
  const SEARCH_PROVIDER_AUTO = "auto";
403
404
  const SEARCH_PROVIDER_CODEX = "codex";
404
405
  const DEFAULT_SEARCH_PROVIDER = SEARCH_PROVIDER_AUTO;
406
+ const FETCH_PROVIDER_FIELD = "fetchProvider";
407
+ const FETCH_PROVIDER_CODEX = "codex";
408
+ const normalizeFetchProvider = (value) => value === "codex" ? FETCH_PROVIDER_CODEX : "dsh";
405
409
  const SPEED_MODE_FIELD = "speedMode";
406
410
  const SPEED_MODE_STANDARD = "standard";
407
411
  const SPEED_MODE_FAST = "fast";
@@ -659,6 +663,11 @@ const PREFERENCE_FIELDS = Object.freeze({
659
663
  default: DEFAULT_SEARCH_PROVIDER,
660
664
  error: "Invalid search provider preference"
661
665
  },
666
+ [FETCH_PROVIDER_FIELD]: {
667
+ choices: ["dsh", FETCH_PROVIDER_CODEX],
668
+ default: "dsh",
669
+ error: "Invalid fetch provider preference"
670
+ },
662
671
  [SPEED_MODE_FIELD]: {
663
672
  choices: [
664
673
  SPEED_MODE_STANDARD,
@@ -738,7 +747,8 @@ const areas$1 = /* @__PURE__ */ new Set([
738
747
  "quota",
739
748
  "quota-reset",
740
749
  "search",
741
- "image"
750
+ "image",
751
+ "voice"
742
752
  ]);
743
753
  const codes$1 = /* @__PURE__ */ new Set([
744
754
  "timeout",
@@ -792,8 +802,8 @@ const LEVELS$1 = [
792
802
  "warn",
793
803
  "error"
794
804
  ];
795
- const MAX_ENTRIES$1 = 400;
796
- const FILE_LIMIT = 256 * 1024;
805
+ const MAX_ENTRIES$1 = 1e3;
806
+ const FILE_LIMIT = 1024 * 1024;
797
807
  function createDiagnosticLog({ now = Date.now, limit = MAX_ENTRIES$1 } = {}) {
798
808
  let entries = [];
799
809
  let dropped = 0;
@@ -1023,7 +1033,7 @@ function fetchThroughProxy(input, init, proxyUrl) {
1023
1033
  const request$1 = request(target, {
1024
1034
  method: init?.method ?? "GET",
1025
1035
  headers: Object.fromEntries(headers.entries()),
1026
- agent: new HttpsProxyAgent(proxyUrl),
1036
+ agent: proxyUrl ? new HttpsProxyAgent(proxyUrl) : void 0,
1027
1037
  signal: init?.signal
1028
1038
  }, (response) => {
1029
1039
  const responseHeaders = new Headers();
@@ -1083,7 +1093,7 @@ async function withCodexNetwork(run, options = {}) {
1083
1093
  }
1084
1094
  const route = await proxy;
1085
1095
  scopedOptions.onRoute?.(route.source);
1086
- const response = await (route.url === void 0 ? fetchBeforeScope(input, init) : proxyFetch(input, init, route.url));
1096
+ const response = await (route.url === void 0 && !scopedOptions.standardHttps ? fetchBeforeScope(input, init) : proxyFetch(input, init, route.url));
1087
1097
  return scopedOptions.transformResponse?.(response, target) ?? response;
1088
1098
  };
1089
1099
  globalThis.fetch = scopedFetch;
@@ -1174,7 +1184,7 @@ function createCodexNetworkTransport(options = {}) {
1174
1184
  return Object.freeze({
1175
1185
  run,
1176
1186
  history: evidence.snapshot,
1177
- fetch: (area, input, init) => run(area, () => globalThis.fetch(input, init)),
1187
+ fetch: (area, input, init, connection) => run(area, () => globalThis.fetch(input, init), connection),
1178
1188
  snapshot: () => Object.fromEntries([...attempts].map(([area, value]) => [area, { ...value }]))
1179
1189
  });
1180
1190
  }
@@ -1250,9 +1260,9 @@ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy
1250
1260
  //#region src/subscription-compaction.js
1251
1261
  /** Experimental SSE bridge; callers must explicitly opt in. */
1252
1262
  const clone$2 = (value) => JSON.parse(JSON.stringify(value));
1253
- const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
1263
+ const hash$1 = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
1254
1264
  const key = "codexCompactionV1";
1255
- const historyHash = (messages) => hash(messages.map(({ source, ...message }) => ({
1265
+ const historyHash = (messages) => hash$1(messages.map(({ source, ...message }) => ({
1256
1266
  ...message,
1257
1267
  source: source && {
1258
1268
  kind: source.kind,
@@ -1260,8 +1270,8 @@ const historyHash = (messages) => hash(messages.map(({ source, ...message }) =>
1260
1270
  model: source.model
1261
1271
  }
1262
1272
  })));
1263
- const MAX_BYTES = 2 * 1024 * 1024;
1264
- const MAX_AGE_MS = 10080 * 60 * 1e3;
1273
+ const MAX_BYTES$1 = 2 * 1024 * 1024;
1274
+ const MAX_AGE_MS$1 = 10080 * 60 * 1e3;
1265
1275
  function createCompactionBridge({ enabled = () => false, threshold, accountScope, diagnostic = () => {}, now = Date.now }) {
1266
1276
  const scope = new AsyncLocalStorage();
1267
1277
  const stats = {
@@ -1277,7 +1287,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1277
1287
  const identity = await accountScope(options);
1278
1288
  if (!identity) throw new Error("Compaction requires a stable account identity");
1279
1289
  const state = {
1280
- identity: hash([identity, options.model]),
1290
+ identity: hash$1([identity, options.model]),
1281
1291
  original: options.messages,
1282
1292
  blocks: [],
1283
1293
  suffix: void 0,
@@ -1287,7 +1297,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1287
1297
  for (let i = messages.length - 1; i >= 0; i--) {
1288
1298
  const candidate = messages[i].source?.replayState?.response?.[key];
1289
1299
  if (!candidate) continue;
1290
- if (Number.isFinite(candidate.createdAt) && candidate.createdAt <= now() && now() - candidate.createdAt <= MAX_AGE_MS && candidate.scope === state.identity && candidate.prefix === historyHash(messages.slice(0, i)) && candidate.content === hash(messages[i].content) && Array.isArray(candidate.items) && candidate.items[0]?.type === "compaction" && typeof candidate.items[0].encrypted_content === "string" && candidate.digest === hash(candidate.items) && JSON.stringify(candidate.items).length <= MAX_BYTES) {
1300
+ if (Number.isFinite(candidate.createdAt) && candidate.createdAt <= now() && now() - candidate.createdAt <= MAX_AGE_MS$1 && candidate.scope === state.identity && candidate.prefix === historyHash(messages.slice(0, i)) && candidate.content === hash$1(messages[i].content) && Array.isArray(candidate.items) && candidate.items[0]?.type === "compaction" && typeof candidate.items[0].encrypted_content === "string" && candidate.digest === hash$1(candidate.items) && JSON.stringify(candidate.items).length <= MAX_BYTES$1) {
1291
1301
  state.suffix = clone$2(candidate.items);
1292
1302
  messages = [...messages.slice(0, i + 1).filter((m) => m.role === "system"), ...messages.slice(i + 1)];
1293
1303
  }
@@ -1314,9 +1324,9 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1314
1324
  createdAt: now(),
1315
1325
  scope: state.identity,
1316
1326
  prefix: historyHash(state.original),
1317
- content: hash(state.blocks.filter(Boolean)),
1327
+ content: hash$1(state.blocks.filter(Boolean)),
1318
1328
  items,
1319
- digest: hash(items)
1329
+ digest: hash$1(items)
1320
1330
  };
1321
1331
  event = {
1322
1332
  ...event,
@@ -1406,7 +1416,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1406
1416
  if (event.type === "response.output_item.done") {
1407
1417
  if (event.item?.type === "compaction") state.captured = [clone$2(event.item)];
1408
1418
  else if (state.captured) state.captured.push(clone$2(event.item));
1409
- if (state.captured && JSON.stringify(state.captured).length > MAX_BYTES) {
1419
+ if (state.captured && JSON.stringify(state.captured).length > MAX_BYTES$1) {
1410
1420
  state.captured = void 0;
1411
1421
  oversized = true;
1412
1422
  }
@@ -1423,7 +1433,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
1423
1433
  observe(buffer.slice(0, index).trimEnd());
1424
1434
  buffer = buffer.slice(index + 1);
1425
1435
  }
1426
- if (buffer.length > MAX_BYTES) {
1436
+ if (buffer.length > MAX_BYTES$1) {
1427
1437
  buffer = "";
1428
1438
  oversized = true;
1429
1439
  state.captured = void 0;
@@ -1633,6 +1643,103 @@ function normalizeTransportEvent(event, signal) {
1633
1643
  };
1634
1644
  }
1635
1645
  //#endregion
1646
+ //#region src/model-retry-hint.js
1647
+ /** Keep the provider's wait as a fact; only DSH decides whether and when to retry. */
1648
+ function providerRetryAfterMs(headers, at = Date.now()) {
1649
+ const read = (key) => typeof headers?.get === "function" ? headers.get(key) : headers?.[key];
1650
+ const millis = read("retry-after-ms");
1651
+ if (millis !== void 0 && millis !== null) {
1652
+ const value = Number(millis);
1653
+ if (Number.isFinite(value)) return value > 0 ? Math.min(value, Number.MAX_SAFE_INTEGER) : void 0;
1654
+ }
1655
+ const raw = read("retry-after");
1656
+ if (typeof raw !== "string" || !raw.trim()) return void 0;
1657
+ const seconds = Number(raw), value = Number.isFinite(seconds) ? seconds * 1e3 : Date.parse(raw) - at;
1658
+ return Number.isFinite(value) && value > 0 ? Math.min(value, Number.MAX_SAFE_INTEGER) : void 0;
1659
+ }
1660
+ function createModelRetryHint({ now = Date.now, ErrorClass = dshLlm.LlmError } = {}) {
1661
+ let response, outputStarted = false;
1662
+ return {
1663
+ onResponse(info) {
1664
+ response = [429, 503].includes(info?.status) ? {
1665
+ status: info.status,
1666
+ delay: providerRetryAfterMs(info.headers, now())
1667
+ } : void 0;
1668
+ },
1669
+ observe(event) {
1670
+ if (event && ![
1671
+ "start",
1672
+ "done",
1673
+ "error"
1674
+ ].includes(event.type)) outputStarted = true;
1675
+ },
1676
+ failure(original, signal) {
1677
+ if (signal?.aborted || outputStarted || !response || !original || typeof original.message !== "string" || [
1678
+ "ABORTED",
1679
+ "QUOTA",
1680
+ "ACCOUNT_QUOTA",
1681
+ "QUOTA_EXCEEDED"
1682
+ ].includes(original.code) || typeof dshLlm.isQuotaExceededError === "function" && dshLlm.isQuotaExceededError(original.message)) return original;
1683
+ if (/You have hit your ChatGPT usage limit/iu.test(original.message) || response.status === 429 && original.code !== "RATE_LIMIT") return original;
1684
+ let error;
1685
+ try {
1686
+ error = new ErrorClass(original.message, response.status === 429 ? "RATE_LIMIT" : "SERVER", {
1687
+ status: response.status,
1688
+ ...response.delay === void 0 ? {} : { providerRetryAfterMs: response.delay }
1689
+ });
1690
+ } catch {
1691
+ return original;
1692
+ }
1693
+ return error.failure?.status === response.status && (response.delay === void 0 || error.failure.providerRetryAfterMs === response.delay) ? {
1694
+ ...original,
1695
+ ...error.failure
1696
+ } : original;
1697
+ }
1698
+ };
1699
+ }
1700
+ /** One request-local scope spanning the provider and DSH adapter; no timers or replay. */
1701
+ function createModelRetryBridge() {
1702
+ const scope = new AsyncLocalStorage();
1703
+ const wrapStream = (factory, options) => (async function* () {
1704
+ const hint = createModelRetryHint();
1705
+ const iterator = scope.run(hint, () => factory(options)[Symbol.asyncIterator]());
1706
+ try {
1707
+ while (true) {
1708
+ const result = await scope.run(hint, () => iterator.next());
1709
+ if (result.done) return;
1710
+ const event = result.value;
1711
+ if (event.type === "finish" && event.reason?.kind === "error") yield {
1712
+ ...event,
1713
+ reason: {
1714
+ ...event.reason,
1715
+ failure: hint.failure(event.reason.failure, options.signal)
1716
+ }
1717
+ };
1718
+ else yield event;
1719
+ }
1720
+ } finally {
1721
+ await scope.run(hint, () => iterator.return?.());
1722
+ }
1723
+ })();
1724
+ return {
1725
+ current: () => scope.getStore(),
1726
+ wrapAdapter(adapter) {
1727
+ return new Proxy(adapter, { get(target, property) {
1728
+ if (property === "stream") return (options) => wrapStream((o) => target.stream(o), options);
1729
+ if (property === "prepareCall" && typeof target.prepareCall === "function") return async (...args) => {
1730
+ const call = await target.prepareCall(...args);
1731
+ return {
1732
+ ...call,
1733
+ stream: (options) => wrapStream((o) => call.stream(o), options)
1734
+ };
1735
+ };
1736
+ const value = Reflect.get(target, property, target);
1737
+ return typeof value === "function" ? value.bind(target) : value;
1738
+ } });
1739
+ }
1740
+ };
1741
+ }
1742
+ //#endregion
1636
1743
  //#region src/pi-ai-runtime.js
1637
1744
  const FAST_SERVICE_TIER = "priority";
1638
1745
  const ULTRAFAST_SERVICE_TIER = "ultrafast";
@@ -1704,6 +1811,7 @@ function isDshAutoReview(context) {
1704
1811
  */
1705
1812
  function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, resolveOutputVerbosity = () => OUTPUT_VERBOSITY_DEFAULT, resolveInputImageDetail = () => void 0, resolveReasoningSummary = () => void 0, resolveContextMode = () => void 0, resolveCustomContextWindow = () => void 0, resolveReviewModel = () => REVIEW_MODEL_SESSION, catalog, connection, compaction, reasoning, runNetwork = (_area, operation) => operation() } = {}) {
1706
1813
  const provider = createOpenAICodexProvider();
1814
+ const retryBridge = createModelRetryBridge();
1707
1815
  const requestToken = Object.freeze({
1708
1816
  name: "DSH-managed Codex OAuth request token",
1709
1817
  async resolve({ credential }) {
@@ -1868,6 +1976,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1868
1976
  let iterator;
1869
1977
  let prepared;
1870
1978
  let stage = "prepare";
1979
+ const retryHint = direct ? void 0 : retryBridge.current();
1871
1980
  const step = async (method, value) => {
1872
1981
  try {
1873
1982
  const request = await (prepared ??= (direct ? void 0 : connection?.prepare(options)) ?? Promise.resolve({ options }));
@@ -1876,6 +1985,10 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1876
1985
  const next = direct ? request.options : compaction?.requestOptions(request.options) ?? request.options;
1877
1986
  iterator ??= factory({
1878
1987
  ...next,
1988
+ async onResponse(info, requestModel) {
1989
+ retryHint?.onResponse(info);
1990
+ return next.onResponse?.(info, requestModel);
1991
+ },
1879
1992
  async onPayload(payload, requestModel) {
1880
1993
  stage = "payload";
1881
1994
  return next.onPayload?.(payload, requestModel);
@@ -1887,6 +2000,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1887
2000
  }));
1888
2001
  }, direct ? request.network : compaction?.networkOptions(request.network) ?? request.network);
1889
2002
  if (!result.done) {
2003
+ retryHint?.observe(result.value, request.options?.signal);
1890
2004
  if (result.value?.type === "error" && !request.options?.signal?.aborted) noteStreamFailure(stage, void 0, source);
1891
2005
  else if (stage === "payload") stage = "stream";
1892
2006
  }
@@ -1934,7 +2048,8 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1934
2048
  streamSimple: (model, context, options) => routed("streamSimple", model, context, options),
1935
2049
  reviewCounters: () => ({ ...review }),
1936
2050
  streamFailure: () => ({ ...streamFailure }),
1937
- noteAdapterFailure
2051
+ noteAdapterFailure,
2052
+ wrapRetryAdapter: (adapter) => retryBridge.wrapAdapter(adapter)
1938
2053
  });
1939
2054
  }
1940
2055
  Object.freeze([
@@ -2021,7 +2136,7 @@ const REASONING_LIMITS = Object.freeze({
2021
2136
  bytes: 16 * 1024 * 1024,
2022
2137
  updates: 128
2023
2138
  });
2024
- const record$9 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2139
+ const record$8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2025
2140
  const efforts = /* @__PURE__ */ new Set([
2026
2141
  "low",
2027
2142
  "medium",
@@ -2035,13 +2150,13 @@ const reasoningDigest = (value) => {
2035
2150
  const text = boundedStringify(value, REASONING_LIMITS.bytes);
2036
2151
  return text === void 0 ? void 0 : reasoningHash(text);
2037
2152
  };
2038
- const boundary = (value, update = false) => record$9(value) && Object.keys(value).every((key) => [
2153
+ const boundary = (value, update = false) => record$8(value) && Object.keys(value).every((key) => [
2039
2154
  "offset",
2040
2155
  "hash",
2041
2156
  ...update ? ["effort"] : []
2042
2157
  ].includes(key)) && Number.isInteger(value.offset) && value.offset >= 0 && value.offset <= REASONING_LIMITS.items && isHash(value.hash);
2043
2158
  function isReasoningState(value) {
2044
- if (!record$9(value) || value.version !== 1 || !isHash(value.scope) || !isHash(value.envelope) || !efforts.has(value.baseline) || !boundary(value.last) || !Array.isArray(value.updates) || value.updates.length > REASONING_LIMITS.updates || Object.keys(value).some((key) => ![
2159
+ if (!record$8(value) || value.version !== 1 || !isHash(value.scope) || !isHash(value.envelope) || !efforts.has(value.baseline) || !boundary(value.last) || !Array.isArray(value.updates) || value.updates.length > REASONING_LIMITS.updates || Object.keys(value).some((key) => ![
2045
2160
  "version",
2046
2161
  "scope",
2047
2162
  "envelope",
@@ -2075,7 +2190,7 @@ function rewriteReasoning(payload, { model, scope, previous, fresh = false }) {
2075
2190
  payload,
2076
2191
  reason
2077
2192
  });
2078
- if (!supportsReasoningUpdates(model) || !record$9(payload) || payload.model !== model.id || !Array.isArray(payload.input) || !record$9(payload.reasoning) || !efforts.has(payload.reasoning.effort)) return skip("unsupported-request");
2193
+ if (!supportsReasoningUpdates(model) || !record$8(payload) || payload.model !== model.id || !Array.isArray(payload.input) || !record$8(payload.reasoning) || !efforts.has(payload.reasoning.effort)) return skip("unsupported-request");
2079
2194
  if (payload.context_management !== void 0) return skip("cloud-compaction");
2080
2195
  if (payload.multi_agent !== void 0 || payload.reasoning.mode !== void 0 && payload.reasoning.mode !== "standard" || payload.previous_response_id !== void 0 || payload.conversation !== void 0 || payload.background === true || payload.truncation !== void 0 && payload.truncation !== "disabled" || payload.input.some((item) => [
2081
2196
  "configuration_update",
@@ -2183,7 +2298,7 @@ function createReasoningBridge({ enabled = () => false, cloud = () => false, unl
2183
2298
  };
2184
2299
  };
2185
2300
  const wrapStream = (factory, options) => (async function* () {
2186
- if (isDshAutoReview(options)) {
2301
+ if (isDshAutoReview(options) || options.purpose === "session-title") {
2187
2302
  yield* unscoped(factory, options);
2188
2303
  return;
2189
2304
  }
@@ -3391,7 +3506,7 @@ function inheritedOriginalImageRef(session, assetId) {
3391
3506
  }
3392
3507
  //#endregion
3393
3508
  //#region src/version.js
3394
- const PACKAGE_VERSION = "3.1.5";
3509
+ const PACKAGE_VERSION = "3.1.7";
3395
3510
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
3396
3511
  //#endregion
3397
3512
  //#region src/codex-images.js
@@ -3419,7 +3534,7 @@ const FULL_ATTACHMENT_ID = /^sha256:[0-9a-f]{64}$/u;
3419
3534
  const BARE_ATTACHMENT_DIGEST = /^[0-9a-f]{64}$/iu;
3420
3535
  const PATH_LIKE_ATTACHMENT_ID = /[\\/]/u;
3421
3536
  const FILE_NAME_ATTACHMENT_ID = /\.[A-Za-z0-9]{1,16}$/u;
3422
- const record$8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3537
+ const record$7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3423
3538
  const nonEmpty$2 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
3424
3539
  const NETWORK_REASONS = {
3425
3540
  UND_ERR_HEADERS_TIMEOUT: "the image service sent no response within 5 minutes",
@@ -3505,7 +3620,7 @@ function decodeCodexPng(value, maximumBytes) {
3505
3620
  return new Uint8Array(data);
3506
3621
  }
3507
3622
  function imageReference(value) {
3508
- const originalDimensions = record$8(value.originalDimensions) ? {
3623
+ const originalDimensions = record$7(value.originalDimensions) ? {
3509
3624
  width: value.originalDimensions.width,
3510
3625
  height: value.originalDimensions.height
3511
3626
  } : void 0;
@@ -3533,7 +3648,7 @@ function invalidAttachmentId(value) {
3533
3648
  function referenceOf(value, attachments) {
3534
3649
  const attachmentId = normalizeAttachmentId(value?.attachmentId);
3535
3650
  if (attachmentId === void 0) invalidAttachmentId(value);
3536
- if (!record$8(value) || !attachments.imageLimits.mediaTypes.includes(value.mediaType) || !Number.isSafeInteger(value.bytes) || value.bytes <= 0 || !Number.isSafeInteger(value.width) || value.width <= 0 || !Number.isSafeInteger(value.height) || value.height <= 0 || value.name !== void 0 && (typeof value.name !== "string" || value.name.length > 256) || value.originalDimensions !== void 0 && (!record$8(value.originalDimensions) || !Number.isSafeInteger(value.originalDimensions.width) || value.originalDimensions.width <= 0 || !Number.isSafeInteger(value.originalDimensions.height) || value.originalDimensions.height <= 0)) throw new Error("referenceImages contains an invalid image reference");
3651
+ if (!record$7(value) || !attachments.imageLimits.mediaTypes.includes(value.mediaType) || !Number.isSafeInteger(value.bytes) || value.bytes <= 0 || !Number.isSafeInteger(value.width) || value.width <= 0 || !Number.isSafeInteger(value.height) || value.height <= 0 || value.name !== void 0 && (typeof value.name !== "string" || value.name.length > 256) || value.originalDimensions !== void 0 && (!record$7(value.originalDimensions) || !Number.isSafeInteger(value.originalDimensions.width) || value.originalDimensions.width <= 0 || !Number.isSafeInteger(value.originalDimensions.height) || value.originalDimensions.height <= 0)) throw new Error("referenceImages contains an invalid image reference");
3537
3652
  return imageReference({
3538
3653
  ...value,
3539
3654
  attachmentId
@@ -3543,7 +3658,7 @@ function sessionImageReferences(messages) {
3543
3658
  const references = /* @__PURE__ */ new Map();
3544
3659
  const visit = (content) => {
3545
3660
  if (!Array.isArray(content)) return;
3546
- for (const block of content) if (block?.type === "image" && record$8(block.attachment)) {
3661
+ for (const block of content) if (block?.type === "image" && record$7(block.attachment)) {
3547
3662
  const id = normalizeAttachmentId(block.attachment.attachmentId);
3548
3663
  if (id !== void 0) references.set(id, block.attachment);
3549
3664
  } else if (block?.type === "tool-result") visit(block.content);
@@ -3708,7 +3823,7 @@ async function limitMessage(response, now = Date.now()) {
3708
3823
  } catch {
3709
3824
  return fallback;
3710
3825
  }
3711
- if (!record$8(error)) return fallback;
3826
+ if (!record$7(error)) return fallback;
3712
3827
  const at = Number.isSafeInteger(error.resets_at) && error.resets_at > 0 ? error.resets_at * 1e3 : Number.isSafeInteger(error.resets_in_seconds) && error.resets_in_seconds > 0 ? now + error.resets_in_seconds * 1e3 : void 0;
3713
3828
  if (at === void 0) return fallback;
3714
3829
  const minutes = Math.max(1, Math.ceil((at - now) / 6e4));
@@ -3720,7 +3835,7 @@ async function refusalMessage(response, editing) {
3720
3835
  let reason;
3721
3836
  try {
3722
3837
  const value = JSON.parse(await readTextWithin(response, 16 * 1024));
3723
- const error = record$8(value?.error) ? value.error : void 0;
3838
+ const error = record$7(value?.error) ? value.error : void 0;
3724
3839
  reason = [
3725
3840
  error?.message,
3726
3841
  value?.detail,
@@ -3745,7 +3860,7 @@ async function readTextWithin(response, maximumBytes) {
3745
3860
  }
3746
3861
  function responseMetadata(value) {
3747
3862
  const data = Array.isArray(value?.data) ? value.data[0] : void 0;
3748
- const encoded = record$8(data) ? data.b64_json : void 0;
3863
+ const encoded = record$7(data) ? data.b64_json : void 0;
3749
3864
  if (typeof encoded !== "string") throw new Error("Codex returned no image data");
3750
3865
  return {
3751
3866
  encoded,
@@ -4198,6 +4313,48 @@ function createSketchAgentTool(bridge, attachments, getSessionMessages = () => [
4198
4313
  });
4199
4314
  }
4200
4315
  //#endregion
4316
+ //#region src/remote-control-log.js
4317
+ const IDS = /* @__PURE__ */ new Set([
4318
+ "requestId",
4319
+ "clientId",
4320
+ "threadId",
4321
+ "turnId",
4322
+ "itemId",
4323
+ "attachmentId"
4324
+ ]);
4325
+ const FIELDS = /* @__PURE__ */ new Set([
4326
+ "method",
4327
+ "status",
4328
+ "type",
4329
+ "code",
4330
+ "ms",
4331
+ "bytes",
4332
+ "items",
4333
+ "turns",
4334
+ "images",
4335
+ "segments",
4336
+ "sequence",
4337
+ "chunks",
4338
+ "hasClientId",
4339
+ "matched",
4340
+ "pending",
4341
+ "event",
4342
+ "error"
4343
+ ]);
4344
+ function phoneLog(event, details = {}, level = "info") {
4345
+ const fields = {};
4346
+ for (const [name, value] of Object.entries(details)) {
4347
+ if (value === void 0 || value === null) continue;
4348
+ if (IDS.has(name)) fields[name] = createHash("sha256").update(String(value)).digest("hex").slice(0, 12);
4349
+ else if (FIELDS.has(name) && [
4350
+ "string",
4351
+ "number",
4352
+ "boolean"
4353
+ ].includes(typeof value)) fields[name] = value;
4354
+ }
4355
+ diagnosticLog.log(level, "phone", event, JSON.stringify(fields));
4356
+ }
4357
+ //#endregion
4201
4358
  //#region src/remote-control-host.js
4202
4359
  const METHOD_NOT_FOUND = -32601;
4203
4360
  const INVALID_PARAMS = -32602;
@@ -4231,7 +4388,7 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
4231
4388
  if (!debug) return;
4232
4389
  const value = {
4233
4390
  at: Date.now(),
4234
- ...entry
4391
+ ...Object.fromEntries(Object.entries(entry).map(([key, value]) => [key, typeof value === "string" ? value.replace(/https?:\/\/[^\s"'<>]+/gu, (url) => url.split(/[?#]/u)[0]) : value]))
4235
4392
  };
4236
4393
  trace.push(value);
4237
4394
  if (trace.length > 60) trace.shift();
@@ -4266,10 +4423,28 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
4266
4423
  message: params?.message
4267
4424
  })
4268
4425
  });
4269
- await client.send(params === void 0 ? { method } : {
4270
- method,
4271
- params
4272
- });
4426
+ try {
4427
+ await client.send(params === void 0 ? { method } : {
4428
+ method,
4429
+ params
4430
+ });
4431
+ if (!STREAMING.test(method)) phoneLog("notification sent", {
4432
+ method,
4433
+ clientId: client.id,
4434
+ threadId: params?.threadId,
4435
+ turnId: params?.turnId,
4436
+ itemId: params?.item?.id,
4437
+ type: params?.item?.type
4438
+ });
4439
+ } catch (error) {
4440
+ phoneLog("notification failed", {
4441
+ method,
4442
+ clientId: client.id,
4443
+ threadId: params?.threadId,
4444
+ error: error?.message
4445
+ }, "error");
4446
+ throw error;
4447
+ }
4273
4448
  };
4274
4449
  /** Ask the phone something (approvals); settles with its result or rejects. */
4275
4450
  const ask = (method, params, signal) => new Promise((resolve, reject) => {
@@ -4359,6 +4534,17 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
4359
4534
  return;
4360
4535
  }
4361
4536
  note("request", method);
4537
+ const started = Date.now();
4538
+ const logged = {
4539
+ method,
4540
+ requestId: id,
4541
+ clientId: client.id,
4542
+ threadId: params?.threadId
4543
+ };
4544
+ phoneLog("request received", {
4545
+ ...logged,
4546
+ hasClientId: typeof params?.clientUserMessageId === "string"
4547
+ });
4362
4548
  if (!active && method !== "initialize") {
4363
4549
  active = true;
4364
4550
  onActive?.(client, notify);
@@ -4369,6 +4555,10 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
4369
4555
  });
4370
4556
  const handler = methods[method];
4371
4557
  if (!handler) {
4558
+ phoneLog("method unavailable", {
4559
+ ...logged,
4560
+ code: METHOD_NOT_FOUND
4561
+ }, "warn");
4372
4562
  record({
4373
4563
  method,
4374
4564
  missing: true,
@@ -4383,16 +4573,40 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
4383
4573
  Promise.resolve().then(() => handler(params, {
4384
4574
  ...context,
4385
4575
  signal: controller.signal
4386
- })).then((result) => reply(id, result ?? {}), (error) => {
4576
+ })).then(async (result) => {
4577
+ await reply(id, result ?? {});
4578
+ phoneLog("request completed", {
4579
+ ...logged,
4580
+ ms: Date.now() - started,
4581
+ bytes: Buffer.byteLength(JSON.stringify(result ?? {})),
4582
+ turns: result?.thread?.turns?.length
4583
+ });
4584
+ }, (error) => {
4585
+ phoneLog("request failed", {
4586
+ ...logged,
4587
+ ms: Date.now() - started,
4588
+ code: error?.code,
4589
+ error: error?.message
4590
+ }, "error");
4387
4591
  if (!QUIET$1.has(method)) record({
4388
4592
  method,
4389
4593
  error: String(error?.message ?? error).slice(0, 300),
4390
4594
  params: JSON.stringify(params ?? null).slice(0, 600)
4391
4595
  });
4392
4596
  return fail(id, error);
4393
- }).catch(() => {}).finally(() => aborts.delete(controller));
4597
+ }).catch((error) => {
4598
+ phoneLog("response failed", {
4599
+ ...logged,
4600
+ ms: Date.now() - started,
4601
+ error: error?.message
4602
+ }, "error");
4603
+ }).finally(() => aborts.delete(controller));
4394
4604
  },
4395
4605
  close() {
4606
+ phoneLog("client disconnected", {
4607
+ clientId: client.id,
4608
+ pending: aborts.size
4609
+ });
4396
4610
  for (const waiting of [...pending.values()]) waiting.reject(new RpcError(-32800, "Client disconnected"));
4397
4611
  for (const controller of aborts) controller.abort();
4398
4612
  aborts.clear();
@@ -4678,6 +4892,15 @@ function createRemoteControlRelay(options) {
4678
4892
  if (bytes.byteLength > MAX_MESSAGE_BYTES) throw new RemoteControlError("too-large", "Remote Control message is too large");
4679
4893
  const chunks = [];
4680
4894
  for (let offset = 0; offset < bytes.byteLength; offset += TARGET_SEGMENT_BYTES) chunks.push(bytes.subarray(offset, offset + TARGET_SEGMENT_BYTES).toString("base64"));
4895
+ const started = now();
4896
+ phoneLog("chunked send started", {
4897
+ clientId,
4898
+ method: message.method,
4899
+ requestId: message.id,
4900
+ bytes: bytes.byteLength,
4901
+ segments: chunks.length,
4902
+ sequence
4903
+ });
4681
4904
  for (const [segmentId, chunk] of chunks.entries()) {
4682
4905
  const text = JSON.stringify({
4683
4906
  client_id: clientId,
@@ -4695,6 +4918,13 @@ function createRemoteControlRelay(options) {
4695
4918
  if (socket?.readyState === 1) await new Promise((resolve) => socket.send(text, () => resolve()));
4696
4919
  }
4697
4920
  }
4921
+ phoneLog("chunked send completed", {
4922
+ clientId,
4923
+ bytes: bytes.byteLength,
4924
+ segments: chunks.length,
4925
+ sequence,
4926
+ ms: now() - started
4927
+ });
4698
4928
  };
4699
4929
  const closeClient = (clientId, streamId) => {
4700
4930
  for (const [key, client] of clients) if (key.startsWith(`${clientId}\u0000`) && (streamId === void 0 || key === `${clientId}\u0000${streamId}`)) {
@@ -4729,12 +4959,18 @@ function createRemoteControlRelay(options) {
4729
4959
  if (!client && !starts) return;
4730
4960
  if (!client) {
4731
4961
  let closed = false;
4962
+ let sending = Promise.resolve();
4732
4963
  const connection = options.serve({
4733
4964
  id: `${envelope.client_id}/${streamId}`,
4734
4965
  clientId: envelope.client_id,
4735
4966
  streamId,
4736
- send: async (message) => {
4737
- if (!closed) await sendServerMessage(envelope.client_id, streamId, message);
4967
+ send: (message) => {
4968
+ const snapshot = structuredClone(message);
4969
+ const next = sending.then(() => {
4970
+ if (!closed) return sendServerMessage(envelope.client_id, streamId, snapshot);
4971
+ });
4972
+ sending = next.catch(() => {});
4973
+ return next;
4738
4974
  },
4739
4975
  close: () => {
4740
4976
  closed = true;
@@ -4749,6 +4985,7 @@ function createRemoteControlRelay(options) {
4749
4985
  }
4750
4986
  };
4751
4987
  clients.set(key, client);
4988
+ phoneLog("client stream opened", { clientId: envelope.client_id });
4752
4989
  }
4753
4990
  if (!(!starts && Number.isInteger(envelope.seq_id) && (lastInbound.get(key) ?? -1) >= envelope.seq_id)) {
4754
4991
  if (Number.isInteger(envelope.seq_id)) lastInbound.set(key, envelope.seq_id);
@@ -4879,6 +5116,10 @@ function createRemoteControlRelay(options) {
4879
5116
  ws.on("message", (data) => {
4880
5117
  queue = queue.then(() => receive(String(data))).catch((error) => {
4881
5118
  state.lastError = error?.code ?? "protocol";
5119
+ phoneLog("relay message failed", {
5120
+ code: error?.code,
5121
+ error: error?.message
5122
+ }, "error");
4882
5123
  });
4883
5124
  });
4884
5125
  ws.on("error", (error) => {
@@ -5874,8 +6115,9 @@ function parseEvent(payload) {
5874
6115
  * Ask the ChatGPT backend for a voice call: the browser's WebRTC offer goes in with the session settings, the answer
5875
6116
  * comes back as plain SDP and the call id in the Location header. The same request the phone makes for its own call.
5876
6117
  */
5877
- async function createVoiceCall({ fetch, credentials, userAgent, sdp, session, base = "https://chatgpt.com/backend-api", threadId }) {
5878
- const { access, accountId } = await credentials();
6118
+ async function createVoiceCall({ fetch, credentials, userAgent, sdp, session, base = "https://chatgpt.com/backend-api", threadId, signal }) {
6119
+ signal?.throwIfAborted();
6120
+ const { access, accountId } = await credentials(signal);
5879
6121
  const response = await fetch(`${base}/wham/realtime/calls?intent=quicksilver&architecture=avas`, {
5880
6122
  method: "POST",
5881
6123
  headers: {
@@ -5892,7 +6134,7 @@ async function createVoiceCall({ fetch, credentials, userAgent, sdp, session, ba
5892
6134
  sdp,
5893
6135
  session
5894
6136
  }),
5895
- signal: AbortSignal.timeout(2e4)
6137
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(2e4)]) : AbortSignal.timeout(2e4)
5896
6138
  });
5897
6139
  const answer = await response.text();
5898
6140
  if (!response.ok) throw new Error(`the voice backend refused the call (HTTP ${response.status}): ${answer.slice(0, 200)}${response.status === 403 ? " (if your ChatGPT account has no two-step verification, turn it on in ChatGPT security settings and try again)" : ""}`);
@@ -5935,19 +6177,29 @@ function createRealtimeVoice(options) {
5935
6177
  error() {}
5936
6178
  };
5937
6179
  const sessions = /* @__PURE__ */ new Map();
5938
- const connect = (base, callId, headers) => new Promise((resolve, reject) => {
6180
+ const starts = /* @__PURE__ */ new Map();
6181
+ const connect = (base, callId, headers, signal) => new Promise((resolve, reject) => {
6182
+ signal?.throwIfAborted();
5939
6183
  const url = `${base.replace(/\/$/, "")}/${encodeURIComponent(callId)}`;
5940
6184
  const ws = new options.WebSocket(url, { headers });
5941
6185
  let settled = false;
6186
+ const abort = () => {
6187
+ fail(/* @__PURE__ */ new Error("Voice start cancelled"));
6188
+ try {
6189
+ ws.close();
6190
+ } catch {}
6191
+ };
5942
6192
  const fail = (error) => {
5943
6193
  if (!settled) {
5944
6194
  settled = true;
6195
+ signal?.removeEventListener("abort", abort);
5945
6196
  reject(error);
5946
6197
  }
5947
6198
  };
5948
6199
  ws.on("open", () => {
5949
6200
  if (!settled) {
5950
6201
  settled = true;
6202
+ signal?.removeEventListener("abort", abort);
5951
6203
  resolve(ws);
5952
6204
  }
5953
6205
  });
@@ -5961,16 +6213,19 @@ function createRealtimeVoice(options) {
5961
6213
  });
5962
6214
  ws.on("error", (error) => fail(error));
5963
6215
  ws.on("close", () => fail(/* @__PURE__ */ new Error("closed before it opened")));
6216
+ signal?.addEventListener("abort", abort, { once: true });
5964
6217
  });
5965
- async function join(callId, headers) {
6218
+ async function join(callId, headers, signal) {
5966
6219
  let last;
5967
6220
  for (const base of bases) {
5968
6221
  const host = new URL(base).host;
5969
6222
  for (let attempt = 0; attempt <= ACTIVATION_RETRY_MS.length; attempt++) try {
5970
- const ws = await connect(base, callId, headers);
6223
+ signal?.throwIfAborted();
6224
+ const ws = await connect(base, callId, headers, signal);
5971
6225
  log.info("voice", `joined the voice call on ${host}`);
5972
6226
  return ws;
5973
6227
  } catch (error) {
6228
+ signal?.throwIfAborted();
5974
6229
  last = error;
5975
6230
  if (error?.status === 404 && attempt < ACTIVATION_RETRY_MS.length) {
5976
6231
  await new Promise((resolve) => setTimeout(resolve, ACTIVATION_RETRY_MS[attempt]));
@@ -5989,8 +6244,11 @@ function createRealtimeVoice(options) {
5989
6244
  session.chain = session.chain.then(save).catch((error) => log.warn("voice", "could not save the voice transcript to the conversation", String(error?.message ?? error)));
5990
6245
  };
5991
6246
  const stop = (threadId, reason = "requested") => {
6247
+ const pending = starts.get(threadId);
6248
+ starts.delete(threadId);
6249
+ pending?.abort();
5992
6250
  const session = sessions.get(threadId);
5993
- if (!session) return false;
6251
+ if (!session) return pending !== void 0;
5994
6252
  sessions.delete(threadId);
5995
6253
  session.ended = true;
5996
6254
  log.info("voice", "the voice call ended", reason);
@@ -6011,21 +6269,48 @@ function createRealtimeVoice(options) {
6011
6269
  }).catch(() => {});
6012
6270
  return true;
6013
6271
  };
6014
- async function start(params, notify) {
6272
+ async function start(params, notify, { signal } = {}) {
6015
6273
  const threadId = typeof params?.threadId === "string" ? params.threadId : "";
6016
6274
  const callId = params?.transport?.type === "existingCall" ? params.transport.callId : void 0;
6017
6275
  if (threadId === "") throw new Error("The voice start has no thread");
6018
6276
  if (typeof callId !== "string" || callId === "") throw new Error("Live voice needs a call the phone has already set up");
6019
6277
  stop(threadId, "replaced");
6020
- const { access, accountId } = await options.credentials();
6021
- const ws = await join(callId, {
6278
+ const pending = new AbortController();
6279
+ starts.set(threadId, pending);
6280
+ const lifetime = signal ? AbortSignal.any([signal, pending.signal]) : pending.signal;
6281
+ let credential, ws;
6282
+ try {
6283
+ lifetime.throwIfAborted();
6284
+ credential = await options.credentials(lifetime);
6285
+ lifetime.throwIfAborted();
6286
+ } catch (error) {
6287
+ if (starts.get(threadId) === pending) starts.delete(threadId);
6288
+ throw error;
6289
+ }
6290
+ const { access, accountId } = credential;
6291
+ const headers = {
6022
6292
  authorization: `Bearer ${access}`,
6023
6293
  "chatgpt-account-id": accountId,
6024
6294
  "openai-alpha": "quicksilver=v2",
6025
6295
  "user-agent": options.userAgent,
6026
6296
  ...typeof params.realtimeSessionId === "string" ? { "x-session-id": params.realtimeSessionId } : {},
6027
6297
  ...typeof params.voiceSessionId === "string" ? { "voice-session-id": params.voiceSessionId } : {}
6028
- });
6298
+ };
6299
+ try {
6300
+ ws = await join(callId, headers, lifetime);
6301
+ lifetime.throwIfAborted();
6302
+ } catch (error) {
6303
+ if (starts.get(threadId) === pending) starts.delete(threadId);
6304
+ try {
6305
+ ws?.close();
6306
+ } catch {}
6307
+ throw error;
6308
+ }
6309
+ if (starts.get(threadId) !== pending) {
6310
+ ws.close();
6311
+ throw new Error("Voice start replaced");
6312
+ }
6313
+ starts.delete(threadId);
6029
6314
  const session = {
6030
6315
  ws,
6031
6316
  notify,
@@ -6250,8 +6535,83 @@ function createRealtimeVoice(options) {
6250
6535
  };
6251
6536
  },
6252
6537
  closeAll: () => {
6253
- for (const threadId of [...sessions.keys()]) stop(threadId, "shutdown");
6538
+ for (const threadId of /* @__PURE__ */ new Set([...sessions.keys(), ...starts.keys()])) stop(threadId, "shutdown");
6539
+ }
6540
+ };
6541
+ }
6542
+ //#endregion
6543
+ //#region src/remote-control-image-output.js
6544
+ const images = /* @__PURE__ */ new WeakMap();
6545
+ const renderedSources = /* @__PURE__ */ new WeakMap();
6546
+ const metadata = (message) => {
6547
+ for (const block of message.content ?? []) if (block.type === "text") try {
6548
+ const value = JSON.parse(block.text);
6549
+ if (value && typeof value === "object") return value;
6550
+ } catch {}
6551
+ };
6552
+ function rememberRemoteImage(item, message, assets) {
6553
+ const image = (message.content ?? []).find((block) => block.type === "image" && assets.has(block.attachment?.attachmentId));
6554
+ images.set(item, {
6555
+ asset: image ? assets.get(image.attachment.attachmentId) : void 0,
6556
+ state: metadata(message)
6557
+ });
6558
+ }
6559
+ const pathKey = (value) => typeof value === "string" ? value.replaceAll("\\", "/").replace(/^\.\//u, "") : "";
6560
+ const filename = (value) => pathKey(value).split("/").at(-1);
6561
+ const matchesPresentedPath = (path, ref) => {
6562
+ const normal = (value) => /^[A-Za-z]:\//u.test(pathKey(path)) ? pathKey(value).toLowerCase() : pathKey(value);
6563
+ return normal(path) === normal(ref) || !/[\\/]/u.test(ref) && normal(filename(path)) === normal(filename(ref));
6564
+ };
6565
+ const fullPreview = (item) => item.arguments?.action === "preview" && !item.arguments?.box && (!item.arguments?.mode || item.arguments.mode === "full");
6566
+ /** A native image or the exact full preview of a successfully finished sketch. */
6567
+ function withRemoteImageOutput(turn) {
6568
+ const previews = /* @__PURE__ */ new Map(), outputs = [], sketchOutputs = /* @__PURE__ */ new Set();
6569
+ let lastOutput = -1;
6570
+ for (const [index, item] of turn.items.entries()) {
6571
+ const record = images.get(item);
6572
+ if (item.status !== "completed" || !record) continue;
6573
+ let asset;
6574
+ if (item.type === "imageGeneration") asset = record.asset;
6575
+ else if (item.type === "dynamicToolCall" && item.tool === "codex_sketch" && item.success) {
6576
+ const state = record.state;
6577
+ const key = typeof state?.documentId === "string" && Number.isSafeInteger(state.revision) ? `${state.documentId}:${state.revision}` : null;
6578
+ if (key && fullPreview(item) && record.asset) previews.set(key, record.asset);
6579
+ if (item.arguments?.action === "finish") {
6580
+ asset = record.asset ?? (key ? previews.get(key) : void 0);
6581
+ if (asset) sketchOutputs.add(asset.fileId);
6582
+ }
6583
+ }
6584
+ if (asset) {
6585
+ if (!outputs.some((output) => output.fileId === asset.fileId)) outputs.push(asset);
6586
+ lastOutput = index;
6254
6587
  }
6588
+ }
6589
+ if (outputs.length === 0) return turn;
6590
+ const answer = turn.items.findLastIndex((item, index) => index > lastOutput && item.type === "agentMessage");
6591
+ if (answer < 0) return turn;
6592
+ const item = turn.items[answer];
6593
+ let text = item.text;
6594
+ for (const [fileId, previousUrl] of renderedSources.get(item) ?? []) {
6595
+ const current = outputs.find((output) => output.fileId === fileId);
6596
+ if (current && current.downloadUrl !== previousUrl) text = text.replaceAll(previousUrl, current.downloadUrl);
6597
+ }
6598
+ const presented = turn.items.filter((item) => item.type === "dynamicToolCall" && item.tool === "present").flatMap((item) => item.arguments?.files ?? []).map((file) => file.path).filter((path) => typeof path === "string");
6599
+ if (outputs.length === 1 && sketchOutputs.has(outputs[0].fileId)) text = text.replace(/!\[([^\]]*)\]\(([^)]+)\)/gu, (whole, alt, source) => {
6600
+ const ref = source.trim().replace(/^<|>$/gu, "");
6601
+ return presented.some((path) => matchesPresentedPath(path, ref)) ? `![${alt}](${outputs[0].downloadUrl})` : whole;
6602
+ });
6603
+ for (const asset of outputs) if (!text.includes(asset.downloadUrl)) text += `\n\n![Image](${asset.downloadUrl})`;
6604
+ const sources = new Map(outputs.map((asset) => [asset.fileId, asset.downloadUrl]));
6605
+ renderedSources.set(item, sources);
6606
+ if (text === item.text) return turn;
6607
+ const rendered = {
6608
+ ...item,
6609
+ text
6610
+ };
6611
+ renderedSources.set(rendered, sources);
6612
+ return {
6613
+ ...turn,
6614
+ items: turn.items.map((entry, index) => index === answer ? rendered : entry)
6255
6615
  };
6256
6616
  }
6257
6617
  //#endregion
@@ -6512,7 +6872,7 @@ function toolItem(block, cwd) {
6512
6872
  };
6513
6873
  }
6514
6874
  /** Record a tool's result on the item that showed the call. */
6515
- function finishTool(item, message, imageUrls) {
6875
+ function finishTool(item, message, imageUrls, imageAssets = /* @__PURE__ */ new Map()) {
6516
6876
  const failed = Boolean(message.isError);
6517
6877
  item.status = failed ? "failed" : "completed";
6518
6878
  if (item.type === "commandExecution") {
@@ -6521,9 +6881,11 @@ function finishTool(item, message, imageUrls) {
6521
6881
  } else if (item.type === "imageGeneration") {
6522
6882
  const url = imageBlocks(message).map((block) => imageUrls.get(block.attachment.attachmentId)).find(Boolean);
6523
6883
  item.result = url ? url.slice(url.indexOf(",") + 1) : "";
6884
+ const asset = imageBlocks(message).map((block) => imageAssets.get(block.attachment.attachmentId)).find(Boolean);
6885
+ if (asset) item.fileId = asset.fileId;
6524
6886
  if (!url) item.status = "failed";
6525
6887
  } else if (item.type === "dynamicToolCall") {
6526
- item.contentItems = toolOutput(message, imageUrls);
6888
+ item.contentItems = toolOutput(message, imageUrls, imageAssets);
6527
6889
  item.success = !failed;
6528
6890
  } else if (item.type === "mcpToolCall") {
6529
6891
  const text = textOf(message.content);
@@ -6536,12 +6898,13 @@ function finishTool(item, message, imageUrls) {
6536
6898
  structuredContent: null
6537
6899
  };
6538
6900
  }
6901
+ rememberRemoteImage(item, message, imageAssets);
6539
6902
  }
6540
6903
  const imageBlocks = (message) => (message.content ?? []).filter((block) => block?.type === "image" && block.attachment);
6541
- const toolOutput = (message, imageUrls) => [{
6904
+ const toolOutput = (message, imageUrls, imageAssets) => [{
6542
6905
  type: "inputText",
6543
6906
  text: textOf(message.content)
6544
- }, ...imageBlocks(message).map((block) => imageUrls.get(block.attachment.attachmentId)).filter(Boolean).map((imageUrl) => ({
6907
+ }, ...imageBlocks(message).map((block) => imageAssets.get(block.attachment.attachmentId)?.downloadUrl ?? imageUrls.get(block.attachment.attachmentId)).filter(Boolean).map((imageUrl) => ({
6545
6908
  type: "inputImage",
6546
6909
  imageUrl
6547
6910
  }))];
@@ -6549,7 +6912,7 @@ const toolOutput = (message, imageUrls) => [{
6549
6912
  /** Images the person attached to a message of their own. */
6550
6913
  const typedImages = (message) => message.role === "user" && (message.source === void 0 || message.source?.kind === "user") ? (message.content ?? []).filter((block) => block?.type === "image" && block.attachment) : [];
6551
6914
  /** `imageUrls` maps an attachment id to a data URL the phone can show; images without one are left out. */
6552
- function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new Map(), cwd = void 0) {
6915
+ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new Map(), cwd = void 0, imageAssets = /* @__PURE__ */ new Map()) {
6553
6916
  const turns = [];
6554
6917
  let turn;
6555
6918
  const calls = /* @__PURE__ */ new Map();
@@ -6563,7 +6926,7 @@ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new
6563
6926
  };
6564
6927
  for (const message of messages) if (message.role === "user") {
6565
6928
  const text = typedText(message);
6566
- const pictures = typedImages(message).map((block) => imageUrls.get(block.attachment.attachmentId)).filter(Boolean);
6929
+ const pictures = typedImages(message).map((block) => imageAssets.get(block.attachment.attachmentId)?.downloadUrl ?? imageUrls.get(block.attachment.attachmentId)).filter(Boolean);
6567
6930
  if (text === "" && pictures.length === 0) continue;
6568
6931
  close();
6569
6932
  turn = {
@@ -6613,10 +6976,10 @@ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new
6613
6976
  }
6614
6977
  } else if (message.role === "tool") {
6615
6978
  const item = calls.get(message.toolCallId);
6616
- if (item) finishTool(item, message, imageUrls);
6979
+ if (item) finishTool(item, message, imageUrls, imageAssets);
6617
6980
  }
6618
6981
  close();
6619
- return turns;
6982
+ return turns.map(withRemoteImageOutput);
6620
6983
  }
6621
6984
  function thread({ id, title, preview, cwd, createdAt, updatedAt, running, turns = [], projectId = null, threadSource = "dsh" }) {
6622
6985
  return {
@@ -6742,11 +7105,12 @@ function createPhoneConfig(file) {
6742
7105
  }
6743
7106
  };
6744
7107
  }
6745
- function createDshRemoteControl({ controller, agents, permissions = () => void 0, workspaces = () => void 0, attachments = () => void 0, usage = () => void 0, usageProfile = () => void 0, projections = () => void 0, skills = () => void 0, commands = () => void 0, llm = () => void 0, speed = void 0, trace = () => {}, phoneReturnMs = PHONE_RETURN_MS, userAgent, appServerUserAgent = userAgent, configFile = void 0, voice = void 0 }) {
7108
+ function createDshRemoteControl({ controller, agents, permissions = () => void 0, workspaces = () => void 0, attachments = () => void 0, remoteImages = void 0, imagePublishMs = 2e4, usage = () => void 0, usageProfile = () => void 0, projections = () => void 0, skills = () => void 0, commands = () => void 0, llm = () => void 0, speed = void 0, trace = () => {}, phoneReturnMs = PHONE_RETURN_MS, userAgent, appServerUserAgent = userAgent, configFile = void 0, voice = void 0 }) {
6746
7109
  const subscribers = /* @__PURE__ */ new Map();
6747
7110
  const threadSources = /* @__PURE__ */ new Map();
6748
7111
  const active = /* @__PURE__ */ new Map();
6749
7112
  const queues = /* @__PURE__ */ new Map();
7113
+ const starting = /* @__PURE__ */ new Map();
6750
7114
  let catalog;
6751
7115
  const service = () => {
6752
7116
  const value = controller();
@@ -6787,7 +7151,13 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6787
7151
  signal?.addEventListener("abort", stop, { once: true });
6788
7152
  });
6789
7153
  const emit = (threadId, method, params) => {
6790
- for (const notify of subscribers.get(threadId) ?? []) notify(method, params).catch(() => {});
7154
+ for (const notify of subscribers.get(threadId) ?? []) notify(method, params).catch((error) => {
7155
+ phoneLog("thread notification failed", {
7156
+ method,
7157
+ threadId,
7158
+ error: error?.message
7159
+ }, "error");
7160
+ });
6791
7161
  };
6792
7162
  const agentFor = async (id) => {
6793
7163
  const result = await service().resolveAgent(id);
@@ -6868,18 +7238,18 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6868
7238
  const values = projections()?.snapshot?.(session, ["tokenUsage", "contextPressure"])?.values;
6869
7239
  const used = values?.tokenUsage;
6870
7240
  if (!used) return void 0;
6871
- const breakdown = (total, input, cached, output) => ({
7241
+ const breakdown = (total, input, cached, output, written = 0) => ({
6872
7242
  totalTokens: total,
6873
7243
  inputTokens: input,
6874
7244
  cachedInputTokens: cached,
6875
- cacheWriteInputTokens: 0,
7245
+ cacheWriteInputTokens: written,
6876
7246
  outputTokens: output,
6877
7247
  reasoningOutputTokens: 0
6878
7248
  });
6879
7249
  const input = (used.uncachedInputTokens ?? 0) + (used.cacheReadTokens ?? 0) + (used.cacheWriteTokens ?? 0);
6880
7250
  const pressure = values.contextPressure?.pressureTokens ?? 0;
6881
7251
  return {
6882
- total: breakdown(input + (used.outputTokens ?? 0), input, used.cacheReadTokens ?? 0, used.outputTokens ?? 0),
7252
+ total: breakdown(input + (used.outputTokens ?? 0), input, used.cacheReadTokens ?? 0, used.outputTokens ?? 0, used.cacheWriteTokens ?? 0),
6883
7253
  last: breakdown(pressure, pressure, 0, 0),
6884
7254
  modelContextWindow: values.contextPressure?.contextWindow ?? null
6885
7255
  };
@@ -6906,31 +7276,104 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6906
7276
  recencyAt: entry.sessionIds?.length ? seconds(entry.updatedAt) : null
6907
7277
  });
6908
7278
  /** Data URLs for the images in a conversation (newest first, bounded), so the phone can show them. */
6909
- const imageUrlsOf = async (messages) => {
6910
- const urls = /* @__PURE__ */ new Map();
7279
+ const imageUrlsOf = async (messages, parentSignal) => {
7280
+ const urls = /* @__PURE__ */ new Map(), assets = /* @__PURE__ */ new Map();
6911
7281
  const store = attachments();
6912
- if (!store) return urls;
6913
- const wanted = messages.flatMap((message) => message.role === "tool" || typedImages(message).length > 0 ? imageBlocks(message) : []).toReversed().slice(0, 12);
7282
+ if (!store) {
7283
+ if (messages.some((message) => imageBlocks(message).length)) phoneLog("image store unavailable", { images: messages.flatMap(imageBlocks).length }, "warn");
7284
+ return {
7285
+ urls,
7286
+ assets
7287
+ };
7288
+ }
7289
+ const recentUnique = (blocks) => [...new Map(blocks.toReversed().map((block) => [block.attachment.attachmentId, block])).values()].slice(0, 12);
7290
+ const userImages = recentUnique(messages.flatMap(typedImages));
7291
+ const toolImages = recentUnique(messages.filter((message) => message.role === "tool").flatMap(imageBlocks));
7292
+ const balanced = [
7293
+ ...userImages.slice(0, 6),
7294
+ ...toolImages.slice(0, 6),
7295
+ ...userImages.slice(6),
7296
+ ...toolImages.slice(6)
7297
+ ];
7298
+ const wanted = [...new Map(balanced.map((block) => [block.attachment.attachmentId, block])).values()].slice(0, 12);
6914
7299
  await Promise.all(wanted.map(async (block) => {
7300
+ const started = Date.now();
6915
7301
  try {
6916
7302
  const stored = await store.readImage(block.attachment, AbortSignal.timeout(1e4));
6917
7303
  urls.set(block.attachment.attachmentId, `data:${stored.ref.mediaType};base64,${Buffer.from(stored.data).toString("base64")}`);
6918
- } catch {}
7304
+ phoneLog("image read completed", {
7305
+ attachmentId: block.attachment.attachmentId,
7306
+ bytes: stored.data.byteLength,
7307
+ ms: Date.now() - started
7308
+ });
7309
+ if (remoteImages) {
7310
+ const signal = AbortSignal.any([AbortSignal.timeout(imagePublishMs), ...parentSignal ? [parentSignal] : []]);
7311
+ try {
7312
+ const asset = await remoteImages.publish({
7313
+ data: stored.data,
7314
+ mediaType: stored.ref.mediaType
7315
+ }, signal);
7316
+ signal.throwIfAborted();
7317
+ assets.set(block.attachment.attachmentId, asset);
7318
+ phoneLog("image publication completed", {
7319
+ attachmentId: block.attachment.attachmentId,
7320
+ bytes: stored.data.byteLength
7321
+ });
7322
+ } catch {
7323
+ phoneLog("image publication unavailable", {
7324
+ attachmentId: block.attachment.attachmentId,
7325
+ code: parentSignal?.aborted ? "cancelled" : signal.aborted ? "timeout" : "publish-failed"
7326
+ }, "warn");
7327
+ }
7328
+ }
7329
+ } catch (error) {
7330
+ phoneLog("image read failed", {
7331
+ attachmentId: block.attachment.attachmentId,
7332
+ ms: Date.now() - started,
7333
+ error: error?.message
7334
+ }, "warn");
7335
+ }
6919
7336
  }));
6920
- return urls;
7337
+ return {
7338
+ urls,
7339
+ assets
7340
+ };
6921
7341
  };
6922
7342
  /** The turn DSH is running, as the phone should see it now: what is committed, plus the reply still being written. */
6923
7343
  const aliases = /* @__PURE__ */ new Map();
7344
+ const turnAliases = /* @__PURE__ */ new Map();
7345
+ const clientAliases = /* @__PURE__ */ new Map();
6924
7346
  const keepShownId = (threadId, committed, shown) => {
6925
7347
  if (committed === shown) return;
6926
7348
  aliases.set(`${threadId}\0${committed}`, shown);
6927
7349
  if (aliases.size > 2e3) aliases.delete(aliases.keys().next().value);
6928
7350
  };
6929
- const withShownIds = (id, turns) => aliases.size === 0 ? turns : turns.map((turn) => ({
7351
+ const reconcileUser = (id, live, message) => {
7352
+ if (!message || live.committedUserId || live.priorMessageIds.has(message.id)) return;
7353
+ const text = visibleText(live.userItem.content.filter((part) => part.type === "text"));
7354
+ if (message.role !== "user" || typedText(message) !== text || typedImages(message).length !== live.userItem.content.filter((part) => part.type === "image").length) return;
7355
+ live.committedUserId = message.id;
7356
+ keepShownId(id, message.id, live.userItem.id);
7357
+ turnAliases.set(`${id}\0${message.id}`, live.turn.id);
7358
+ if (turnAliases.size > 2e3) turnAliases.delete(turnAliases.keys().next().value);
7359
+ if (live.userItem.clientId !== null) {
7360
+ clientAliases.set(`${id}\0${message.id}`, live.userItem.clientId);
7361
+ if (clientAliases.size > 2e3) clientAliases.delete(clientAliases.keys().next().value);
7362
+ }
7363
+ phoneLog("user message reconciled", {
7364
+ threadId: id,
7365
+ turnId: live.turn.id,
7366
+ itemId: live.userItem.id,
7367
+ matched: true
7368
+ });
7369
+ };
7370
+ const withShownIds = (id, turns) => turns.map((turn) => ({
6930
7371
  ...turn,
7372
+ id: turnAliases.get(`${id}\0${turn.id}`) ?? turn.id,
6931
7373
  items: turn.items.map((item) => aliases.has(`${id}\0${item.id}`) ? {
6932
7374
  ...item,
6933
- id: aliases.get(`${id}\0${item.id}`)
7375
+ id: aliases.get(`${id}\0${item.id}`),
7376
+ ...item.type === "userMessage" ? { clientId: clientAliases.get(`${id}\0${item.id}`) ?? null } : {}
6934
7377
  } : item)
6935
7378
  }));
6936
7379
  const withLiveTurn = (id, shownTurns) => {
@@ -6944,7 +7387,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6944
7387
  text: writing.text
6945
7388
  }] : [];
6946
7389
  const last = turns.at(-1);
6947
- const ours = last?.items[0]?.type === "userMessage" && typed(last.items[0]) === typed(live.userItem);
7390
+ const ours = last?.items[0]?.type === "userMessage" && (last.items[0].id === live.userItem.id || !live.priorMessageIds.has(last.items[0].id) && typed(last.items[0]) === typed(live.userItem));
6948
7391
  const items = ours ? [
6949
7392
  live.userItem,
6950
7393
  ...last.items.slice(1),
@@ -6959,16 +7402,20 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6959
7402
  durationMs: null
6960
7403
  }];
6961
7404
  };
6962
- const openThread = async (id, notify) => {
7405
+ const openThread = async (id, notify, signal) => {
7406
+ const started = Date.now();
7407
+ phoneLog("history restore started", { threadId: id });
6963
7408
  const agent = await agentFor(id);
6964
7409
  if (notify) subscribe(id, notify);
6965
7410
  await (catalog ? void 0 : loadCatalog().catch(() => void 0));
6966
7411
  const session = agent.session;
6967
7412
  const messages = session.deriveMessages();
7413
+ const live = active.get(id);
7414
+ if (live?.userItem) for (const message of messages) reconcileUser(id, live, message);
6968
7415
  const first = messages.find((message) => typedText(message) !== "");
6969
- const imageUrls = await imageUrlsOf(messages);
7416
+ const { urls: imageUrls, assets: imageAssets } = await imageUrlsOf(messages, signal);
6970
7417
  const cwd = directoryOf(session);
6971
- return {
7418
+ const result = {
6972
7419
  agent,
6973
7420
  thread: thread({
6974
7421
  id,
@@ -6978,9 +7425,17 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
6978
7425
  projectId: projectIdOf(id),
6979
7426
  threadSource: threadSources.get(id),
6980
7427
  preview: first ? visibleText(first.content).slice(0, 200) : "",
6981
- turns: withLiveTurn(id, projectTurns(messages, session.meta?.createdAt, imageUrls, cwd))
7428
+ turns: withLiveTurn(id, projectTurns(messages, session.meta?.createdAt, imageUrls, cwd, imageAssets))
6982
7429
  })
6983
7430
  };
7431
+ phoneLog("history restore completed", {
7432
+ threadId: id,
7433
+ ms: Date.now() - started,
7434
+ items: messages.length,
7435
+ turns: result.thread.turns.length,
7436
+ images: imageUrls.size
7437
+ });
7438
+ return result;
6984
7439
  };
6985
7440
  /** Apply a model or effort the phone picked; DSH validates it against its own catalog. */
6986
7441
  const TIER_OF = {
@@ -7145,7 +7600,35 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7145
7600
  }], ...images]
7146
7601
  };
7147
7602
  };
7148
- async function startTurn(params, notify) {
7603
+ async function startTurn(params, notify, queued) {
7604
+ const id = params?.threadId;
7605
+ if (active.has(id) || starting.has(id)) throw invalidParams("A turn is already running in this conversation");
7606
+ const launch = {
7607
+ queued,
7608
+ submitted: false,
7609
+ abort: new AbortController()
7610
+ };
7611
+ starting.set(id, launch);
7612
+ try {
7613
+ return await acceptTurn(params, notify, launch);
7614
+ } catch (error) {
7615
+ if (launch.abort.signal.aborted && error?.name === "AbortError") throw new RpcError(-32800, "Turn start cancelled");
7616
+ throw error;
7617
+ } finally {
7618
+ if (starting.get(id) === launch) starting.delete(id);
7619
+ }
7620
+ }
7621
+ async function startQueuedTurn(id, notify, queuedId, selection = {}) {
7622
+ const queued = (queues.get(id) ?? []).find((entry) => queuedId == null || entry.id === queuedId);
7623
+ if (!queued) throw invalidParams("Nothing queued");
7624
+ return startTurn({
7625
+ ...selection,
7626
+ threadId: id,
7627
+ input: queued.input,
7628
+ clientUserMessageId: queued.clientUserMessageId
7629
+ }, notify, queued);
7630
+ }
7631
+ async function acceptTurn(params, notify, launch) {
7149
7632
  const { text, pictures, content } = contentOf(params?.input);
7150
7633
  lastPrompt.text = text;
7151
7634
  const id = params?.threadId;
@@ -7156,11 +7639,22 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7156
7639
  applyPermissions(agent, params);
7157
7640
  const speedBefore = speed?.current?.();
7158
7641
  const speedForTurn = typeof params?.serviceTierForTurn === "string" ? params.serviceTierForTurn : void 0;
7159
- await applySpeed(speedForTurn ?? (Object.hasOwn(params ?? {}, "serviceTier") ? params.serviceTier : void 0));
7642
+ const restoreSpeed = async () => {
7643
+ if (speedForTurn !== void 0 && speedBefore !== void 0 && speed?.current?.() !== speedBefore) await Promise.resolve(speed.set?.(speedBefore)).catch(() => {});
7644
+ };
7645
+ try {
7646
+ await applySpeed(speedForTurn ?? (Object.hasOwn(params ?? {}, "serviceTier") ? params.serviceTier : void 0));
7647
+ launch.abort.signal.throwIfAborted();
7648
+ if (active.has(id)) throw invalidParams("A turn is already running in this conversation");
7649
+ if (launch.queued && !(queues.get(id) ?? []).includes(launch.queued)) throw invalidParams("Queued submission was deleted before starting");
7650
+ } catch (error) {
7651
+ await restoreSpeed();
7652
+ throw error;
7653
+ }
7160
7654
  const turn = emptyTurn();
7161
7655
  const userItem = {
7162
7656
  type: "userMessage",
7163
- id: params.clientUserMessageId ?? randomUUID(),
7657
+ id: randomUUID(),
7164
7658
  clientId: params.clientUserMessageId ?? null,
7165
7659
  content: [...text === "" ? [] : [{
7166
7660
  type: "text",
@@ -7171,10 +7665,22 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7171
7665
  url: picture.url
7172
7666
  }))]
7173
7667
  };
7174
- active.set(id, {
7668
+ const running = {
7175
7669
  turn,
7176
7670
  ended: void 0,
7177
- userItem
7671
+ userItem,
7672
+ priorMessageIds: new Set(agent.session.deriveMessages().map((message) => message.id)),
7673
+ pendingImages: /* @__PURE__ */ new Set(),
7674
+ pendingSteers: /* @__PURE__ */ new Set(),
7675
+ abort: launch.abort
7676
+ };
7677
+ active.set(id, running);
7678
+ phoneLog("turn accepted", {
7679
+ threadId: id,
7680
+ turnId: turn.id,
7681
+ itemId: userItem.id,
7682
+ hasClientId: userItem.clientId !== null,
7683
+ images: pictures.length
7178
7684
  });
7179
7685
  emit(id, "turn/started", {
7180
7686
  threadId: id,
@@ -7201,18 +7707,61 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7201
7707
  completedAtMs: Date.now()
7202
7708
  });
7203
7709
  try {
7204
- await service().prompt({
7205
- requestId: randomUUID(),
7710
+ launch.submitted = true;
7711
+ if ((await service().prompt({
7712
+ requestId: launch.queued?.id ?? randomUUID(),
7206
7713
  sessionId: id,
7207
7714
  mode: "queue",
7208
7715
  content
7209
- }, AbortSignal.timeout(3e4));
7716
+ }, AbortSignal.any([running.abort.signal, AbortSignal.timeout(3e4)])))?.accepted === false) throw new Error("DSH rejected the message");
7210
7717
  } catch (error) {
7211
- active.delete(id);
7718
+ if (active.get(id) === running) active.delete(id);
7719
+ const cancelled = running.abort.signal.aborted;
7720
+ turn.status = cancelled ? "interrupted" : "failed";
7721
+ turn.completedAt = seconds(Date.now());
7722
+ turn.error = cancelled ? null : {
7723
+ message: "DSH did not accept the message",
7724
+ codexErrorInfo: null,
7725
+ additionalDetails: null
7726
+ };
7727
+ running.abort.abort();
7728
+ emit(id, "turn/completed", {
7729
+ threadId: id,
7730
+ turn
7731
+ });
7732
+ emit(id, "thread/status/changed", {
7733
+ threadId: id,
7734
+ status: { type: "idle" }
7735
+ });
7736
+ await restoreSpeed();
7737
+ if (cancelled) throw new RpcError(-32800, "Turn start cancelled");
7212
7738
  throw new RpcError(-32603, error?.message ? `DSH did not accept the message: ${String(error.message).slice(0, 200)}` : "DSH did not accept the message");
7213
7739
  }
7214
- Promise.resolve(agent.whenIdle?.()).catch(() => {}).then(() => {
7215
- const reason = active.get(id)?.ended;
7740
+ if (launch.queued) {
7741
+ queues.set(id, (queues.get(id) ?? []).filter((entry) => entry.id !== launch.queued.id));
7742
+ emit(id, "thread/queue/changed", { threadId: id });
7743
+ }
7744
+ if (running.abort.signal.aborted) {
7745
+ running.ended ??= { kind: "aborted" };
7746
+ await Promise.resolve(service().cancel({ sessionId: id })).catch(() => {});
7747
+ }
7748
+ if (starting.get(id) === launch) starting.delete(id);
7749
+ Promise.resolve(agent.whenIdle?.()).catch(() => {}).then(async () => {
7750
+ running.finishing = true;
7751
+ const pendingSteers = [...running.pendingSteers];
7752
+ if (pendingSteers.length) {
7753
+ await Promise.allSettled(pendingSteers);
7754
+ await Promise.resolve(agent.whenIdle?.()).catch(() => {});
7755
+ }
7756
+ if (running.pendingImages.size) phoneLog("waiting for tool images", {
7757
+ threadId: id,
7758
+ turnId: turn.id,
7759
+ pending: running.pendingImages.size
7760
+ });
7761
+ await Promise.allSettled([...running.pendingImages]);
7762
+ if (active.get(id) !== running) return;
7763
+ turn.items = withRemoteImageOutput(turn).items;
7764
+ const reason = running.ended;
7216
7765
  turn.status = reason?.kind === "error" ? "failed" : reason?.kind === "aborted" || reason?.kind === "interrupted" ? "interrupted" : "completed";
7217
7766
  if (reason?.kind === "error") {
7218
7767
  const message = String(reason.error?.message ?? reason.error?.code ?? "The model request failed").slice(0, 500);
@@ -7230,12 +7779,11 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7230
7779
  }
7231
7780
  turn.completedAt = seconds(Date.now());
7232
7781
  if (speedForTurn !== void 0 && speedBefore !== void 0 && speed?.current?.() !== speedBefore) Promise.resolve(speed.set?.(speedBefore)).catch(() => {});
7233
- const sentText = visibleText(userItem.content.filter((part) => part.type === "text"));
7234
7782
  try {
7235
- const committedUser = agent.session.deriveMessages().findLast((message) => typedText(message) !== "" && typedText(message) === sentText);
7236
- if (committedUser) keepShownId(id, committedUser.id, userItem.id);
7783
+ for (const message of agent.session.deriveMessages()) reconcileUser(id, running, message);
7237
7784
  } catch {}
7238
7785
  active.delete(id);
7786
+ running.abort.abort();
7239
7787
  compactions.delete(id);
7240
7788
  const usageNow = tokenUsage(agent.session);
7241
7789
  if (usageNow) emit(id, "thread/tokenUsage/updated", {
@@ -7247,22 +7795,25 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7247
7795
  threadId: id,
7248
7796
  turn
7249
7797
  });
7798
+ phoneLog("turn completed", {
7799
+ threadId: id,
7800
+ turnId: turn.id,
7801
+ status: turn.status,
7802
+ items: turn.items.length
7803
+ });
7250
7804
  emit(id, "thread/status/changed", {
7251
7805
  threadId: id,
7252
7806
  status: { type: "idle" }
7253
7807
  });
7254
- const [next, ...rest] = queues.get(id) ?? [];
7255
- if (next) {
7256
- queues.set(id, rest);
7257
- emit(id, "thread/queue/changed", { threadId: id });
7258
- startTurn({
7259
- threadId: id,
7260
- input: next.input,
7261
- clientUserMessageId: next.clientUserMessageId
7262
- }, notify).catch(() => {});
7263
- }
7808
+ if (queues.get(id)?.length) startQueuedTurn(id, notify).catch((error) => phoneLog("queued turn not accepted", {
7809
+ threadId: id,
7810
+ code: error?.code
7811
+ }, "warn"));
7264
7812
  });
7265
- return { turn };
7813
+ return { turn: {
7814
+ ...turn,
7815
+ items: []
7816
+ } };
7266
7817
  }
7267
7818
  /** Conversations the phone may see, filtered the way it asks, plus the passages DSH found for a search term. */
7268
7819
  const listed = async (params, signal) => {
@@ -7443,6 +7994,13 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7443
7994
  };
7444
7995
  },
7445
7996
  "command/exec": async (params, { notify, signal }) => {
7997
+ const command = Array.isArray(params?.command) ? params.command.filter((part) => typeof part === "string") : [];
7998
+ const executable = command[0]?.replaceAll("\\", "/").split("/").at(-1) ?? "";
7999
+ phoneLog("command request classified", {
8000
+ type: /^(?:git|powershell|pwsh|bash|sh)(?:\.exe)?$/iu.test(executable) ? executable.toLowerCase().replace(/\.exe$/u, "") : "other",
8001
+ items: command.length,
8002
+ images: command.some((part) => /ReadAllBytes|ToBase64String|\bbase64\b/iu.test(part)) ? 1 : 0
8003
+ });
7446
8004
  const home = homeFolderAnswer(params?.command);
7447
8005
  if (home !== void 0) return home;
7448
8006
  const folders = await conversationFolders();
@@ -7453,6 +8011,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7453
8011
  signal
7454
8012
  }) : await runGit(params, { folders });
7455
8013
  } catch (error) {
8014
+ phoneLog("command request refused", { code: error?.code ?? error?.name }, "warn");
7456
8015
  trace({
7457
8016
  method: "command/exec:refused",
7458
8017
  reason: String(error?.message).slice(0, 80),
@@ -7705,9 +8264,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7705
8264
  await registry.unarchiveSession(params?.threadId);
7706
8265
  return { thread: (await openThread(params?.threadId)).thread };
7707
8266
  },
7708
- "thread/read": async (params) => ({ thread: (await openThread(params?.threadId)).thread }),
7709
- "thread/resume": async (params, { notify }) => {
7710
- const { agent, thread: value } = await openThread(params?.threadId, notify);
8267
+ "thread/read": async (params, { signal } = {}) => ({ thread: (await openThread(params?.threadId, void 0, signal)).thread }),
8268
+ "thread/resume": async (params, { notify, signal }) => {
8269
+ const { agent, thread: value } = await openThread(params?.threadId, notify, signal);
7711
8270
  return {
7712
8271
  ...settings(agent, value.cwd),
7713
8272
  thread: value
@@ -7744,8 +8303,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7744
8303
  },
7745
8304
  "turn/start": (params, { notify }) => titles.has(params?.threadId) ? titleTurn(params, notify) : startTurn(params, notify),
7746
8305
  "turn/interrupt": (params) => {
7747
- service().cancel({ sessionId: params?.threadId });
7748
8306
  active.get(params?.threadId)?.abort?.abort();
8307
+ starting.get(params?.threadId)?.abort.abort();
8308
+ service().cancel({ sessionId: params?.threadId });
7749
8309
  return {};
7750
8310
  },
7751
8311
  "thread/compact/start": async (params, { notify }) => {
@@ -7753,7 +8313,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7753
8313
  const registry = commands();
7754
8314
  const agent = await agentFor(id);
7755
8315
  if (typeof registry?.execute !== "function" || registry.find?.(agent, "compact") === void 0) throw new RpcError(-32601, "This DSH version cannot compact a conversation on request");
7756
- if (active.has(id)) throw new RpcError(-32602, "A turn is already running in this conversation");
8316
+ if (active.has(id) || starting.has(id)) throw new RpcError(-32602, "A turn is already running in this conversation");
7757
8317
  subscribe(id, notify);
7758
8318
  const turn = emptyTurn();
7759
8319
  const abort = new AbortController();
@@ -7833,15 +8393,34 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7833
8393
  })();
7834
8394
  return {};
7835
8395
  },
7836
- "turn/steer": async (params) => {
8396
+ "turn/steer": async (params, { signal } = {}) => {
8397
+ const running = active.get(params?.threadId);
8398
+ const current = () => running && active.get(params?.threadId) === running && running.userItem && !running.finishing && !running.ended && !running.abort.signal.aborted && !starting.has(params?.threadId) && params?.expectedTurnId === running.turn.id;
8399
+ signal?.throwIfAborted();
8400
+ if (!current()) throw invalidParams("The expected turn is not active");
7837
8401
  const { content } = contentOf(params?.input);
7838
- await service().prompt({
7839
- requestId: randomUUID(),
7840
- sessionId: params?.threadId,
7841
- mode: "steer",
7842
- content
7843
- }, AbortSignal.timeout(3e4));
7844
- return { turnId: params?.expectedTurnId ?? active.get(params?.threadId)?.turn.id ?? "" };
8402
+ const operation = (async () => {
8403
+ if ((await service().prompt({
8404
+ requestId: randomUUID(),
8405
+ sessionId: params.threadId,
8406
+ mode: "steer",
8407
+ content
8408
+ }, AbortSignal.any([
8409
+ running.abort.signal,
8410
+ AbortSignal.timeout(3e4),
8411
+ ...signal ? [signal] : []
8412
+ ])))?.accepted === false) throw invalidParams("DSH rejected the steering message");
8413
+ if (!current()) {
8414
+ if (active.get(params.threadId) === running) await Promise.resolve(service().cancel({ sessionId: params.threadId })).catch(() => {});
8415
+ }
8416
+ return { turnId: running.turn.id };
8417
+ })();
8418
+ running.pendingSteers.add(operation);
8419
+ try {
8420
+ return await operation;
8421
+ } finally {
8422
+ running.pendingSteers.delete(operation);
8423
+ }
7845
8424
  },
7846
8425
  "thread/name/set": async (params) => {
7847
8426
  await service().rename({
@@ -7860,6 +8439,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7860
8439
  }),
7861
8440
  "thread/queue/add": async (params, { notify }) => {
7862
8441
  if (!Array.isArray(params?.input)) throw invalidParams("input is required");
8442
+ contentOf(params.input);
7863
8443
  const id = params?.threadId;
7864
8444
  const queued = {
7865
8445
  id: randomUUID(),
@@ -7867,20 +8447,17 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7867
8447
  input: params.input
7868
8448
  };
7869
8449
  subscribe(id, notify);
7870
- if (!active.has(id)) await startTurn({
7871
- threadId: id,
7872
- input: queued.input,
7873
- clientUserMessageId: queued.clientUserMessageId,
8450
+ queues.set(id, [...queues.get(id) ?? [], queued]);
8451
+ emit(id, "thread/queue/changed", { threadId: id });
8452
+ if (!active.has(id) && !starting.has(id)) await startQueuedTurn(id, notify, queued.id, {
7874
8453
  model: params.model,
7875
8454
  effort: params.effort
7876
- }, notify);
7877
- else {
7878
- queues.set(id, [...queues.get(id) ?? [], queued]);
7879
- emit(id, "thread/queue/changed", { threadId: id });
7880
- }
8455
+ });
7881
8456
  return { queuedSubmission: queued };
7882
8457
  },
7883
8458
  "thread/queue/delete": (params) => {
8459
+ const launch = starting.get(params?.threadId);
8460
+ if (launch?.submitted && launch.queued?.id === params?.queuedSubmissionId) throw invalidParams("Queued submission is being accepted");
7884
8461
  const list = queues.get(params?.threadId) ?? [];
7885
8462
  const next = list.filter((entry) => entry.id !== params?.queuedSubmissionId);
7886
8463
  queues.set(params?.threadId, next);
@@ -7888,24 +8465,13 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7888
8465
  return { deleted: next.length !== list.length };
7889
8466
  },
7890
8467
  "thread/queue/reorder": (params) => {
7891
- const order = Array.isArray(params?.queuedSubmissionIds) ? params.queuedSubmissionIds : [];
8468
+ const order = Array.isArray(params?.queuedSubmissionIds) ? [...new Set(params.queuedSubmissionIds)] : [];
7892
8469
  const list = queues.get(params?.threadId) ?? [];
7893
8470
  queues.set(params?.threadId, [...order.map((id) => list.find((entry) => entry.id === id)).filter(Boolean), ...list.filter((entry) => !order.includes(entry.id))]);
7894
8471
  emit(params?.threadId, "thread/queue/changed", { threadId: params?.threadId });
7895
8472
  return {};
7896
8473
  },
7897
- "thread/queue/start": async (params, { notify }) => {
7898
- const list = queues.get(params?.threadId) ?? [];
7899
- const queued = list.find((entry) => params?.queuedSubmissionId == null || entry.id === params.queuedSubmissionId);
7900
- if (!queued) throw invalidParams("Nothing queued");
7901
- queues.set(params.threadId, list.filter((entry) => entry !== queued));
7902
- emit(params.threadId, "thread/queue/changed", { threadId: params.threadId });
7903
- return startTurn({
7904
- threadId: params.threadId,
7905
- input: queued.input,
7906
- clientUserMessageId: queued.clientUserMessageId
7907
- }, notify);
7908
- }
8474
+ "thread/queue/start": (params, { notify }) => startQueuedTurn(params?.threadId, notify, params?.queuedSubmissionId)
7909
8475
  };
7910
8476
  const callOf = (session, callId) => {
7911
8477
  for (const message of session.deriveMessages().toReversed()) {
@@ -8065,10 +8631,21 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8065
8631
  const id = session.id;
8066
8632
  if (frame.type === "start") {
8067
8633
  streams.delete(id);
8634
+ phoneLog("assistant stream started", {
8635
+ threadId: id,
8636
+ turnId: running.turn.id
8637
+ });
8068
8638
  return;
8069
8639
  }
8070
8640
  if (frame.type === "end") {
8071
8641
  const stream = streams.get(id);
8642
+ phoneLog("assistant stream ended", {
8643
+ threadId: id,
8644
+ turnId: running.turn.id,
8645
+ chunks: stream?.chunks ?? 0,
8646
+ bytes: Buffer.byteLength(stream?.text ?? ""),
8647
+ status: frame.outcome?.kind
8648
+ });
8072
8649
  if (stream && frame.outcome?.eventType !== "assistant/message") {
8073
8650
  streams.delete(id);
8074
8651
  stream.item.text = stream.text;
@@ -8094,7 +8671,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8094
8671
  memoryCitation: null,
8095
8672
  delivery: null
8096
8673
  },
8097
- text: ""
8674
+ text: "",
8675
+ chunks: 0
8098
8676
  };
8099
8677
  streams.set(id, stream);
8100
8678
  running.turn.items.push(stream.item);
@@ -8106,6 +8684,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8106
8684
  });
8107
8685
  }
8108
8686
  stream.text += chunk.text;
8687
+ stream.chunks++;
8109
8688
  emit(id, "item/agentMessage/delta", {
8110
8689
  threadId: id,
8111
8690
  turnId: running.turn.id,
@@ -8121,6 +8700,13 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8121
8700
  });
8122
8701
  const running = active.get(session.id);
8123
8702
  if (!running || !subscribers.has(session.id)) return;
8703
+ if (event.type === "user/message" && running.userItem) {
8704
+ reconcileUser(session.id, running, {
8705
+ role: "user",
8706
+ ...event.data
8707
+ });
8708
+ return;
8709
+ }
8124
8710
  if (event.type === "turn/end") {
8125
8711
  running.ended = event.data?.reason;
8126
8712
  return;
@@ -8152,12 +8738,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8152
8738
  return;
8153
8739
  }
8154
8740
  if (event.type !== "assistant/message" && event.type !== "tool/result") return;
8155
- const message = session.deriveMessages().at(-1);
8741
+ const message = event.data?.message ?? session.deriveMessages().at(-1);
8156
8742
  if (message?.role === "tool") {
8157
8743
  const item = running.turn.items.find((entry) => entry.id === message.toolCallId && entry.type !== "agentMessage");
8158
8744
  if (item) {
8159
- const finish = (imageUrls) => {
8160
- finishTool(item, message, imageUrls);
8745
+ const finish = ({ urls, assets }) => {
8746
+ finishTool(item, message, urls, assets);
8161
8747
  emit(session.id, "item/completed", {
8162
8748
  threadId: session.id,
8163
8749
  turnId: running.turn.id,
@@ -8165,8 +8751,25 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8165
8751
  completedAtMs: Date.now()
8166
8752
  });
8167
8753
  };
8168
- if (imageBlocks(message).length > 0) imageUrlsOf([message]).then(finish, () => finish(/* @__PURE__ */ new Map()));
8169
- else finish(/* @__PURE__ */ new Map());
8754
+ if (imageBlocks(message).length > 0) {
8755
+ const pending = imageUrlsOf([message], running.abort.signal).then(finish, () => finish({
8756
+ urls: /* @__PURE__ */ new Map(),
8757
+ assets: /* @__PURE__ */ new Map()
8758
+ }));
8759
+ running.pendingImages ??= /* @__PURE__ */ new Set();
8760
+ running.pendingImages.add(pending);
8761
+ pending.then(() => running.pendingImages.delete(pending), (error) => {
8762
+ running.pendingImages.delete(pending);
8763
+ phoneLog("tool image delivery failed", {
8764
+ threadId: session.id,
8765
+ itemId: item.id,
8766
+ error: error?.message
8767
+ }, "error");
8768
+ });
8769
+ } else finish({
8770
+ urls: /* @__PURE__ */ new Map(),
8771
+ assets: /* @__PURE__ */ new Map()
8772
+ });
8170
8773
  }
8171
8774
  return;
8172
8775
  }
@@ -8179,6 +8782,27 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8179
8782
  text: "x"
8180
8783
  }]
8181
8784
  }, message], void 0, void 0, directoryOf(session)).flatMap((turn) => turn.items.slice(1));
8785
+ const toolIds = new Set(message.content.filter((block) => block.type === "tool-call").map((block) => block.id));
8786
+ const completeText = (item) => {
8787
+ const finish = () => {
8788
+ const projected = withRemoteImageOutput(running.turn).items.find((entry) => entry.id === item.id);
8789
+ if (projected) item.text = projected.text;
8790
+ emit(session.id, "item/completed", {
8791
+ threadId: session.id,
8792
+ turnId: running.turn.id,
8793
+ item,
8794
+ completedAtMs: Date.now()
8795
+ });
8796
+ };
8797
+ const pending = toolIds.size === 0 ? [...running.pendingImages ?? []] : [];
8798
+ if (pending.length === 0) {
8799
+ finish();
8800
+ return;
8801
+ }
8802
+ const job = Promise.allSettled(pending).then(finish);
8803
+ running.pendingImages.add(job);
8804
+ job.then(() => running.pendingImages.delete(job), () => running.pendingImages.delete(job));
8805
+ };
8182
8806
  const stream = streams.get(session.id);
8183
8807
  streams.delete(session.id);
8184
8808
  let reuse = stream?.item;
@@ -8207,12 +8831,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8207
8831
  reuse = void 0;
8208
8832
  keepShownId(session.id, item.id, shown.id);
8209
8833
  shown.text = item.text;
8210
- emit(session.id, "item/completed", {
8211
- threadId: session.id,
8212
- turnId: running.turn.id,
8213
- item: shown,
8214
- completedAtMs: Date.now()
8215
- });
8834
+ completeText(shown);
8216
8835
  continue;
8217
8836
  }
8218
8837
  running.turn.items.push(item);
@@ -8222,7 +8841,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8222
8841
  item,
8223
8842
  startedAtMs: Date.now()
8224
8843
  });
8225
- emit(session.id, "item/completed", {
8844
+ if (item.type === "agentMessage") completeText(item);
8845
+ else if (!toolIds.has(item.id)) emit(session.id, "item/completed", {
8226
8846
  threadId: session.id,
8227
8847
  turnId: running.turn.id,
8228
8848
  item,
@@ -8249,40 +8869,43 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8249
8869
  if (!set.has(notify)) subscribe(threadId, notify);
8250
8870
  }
8251
8871
  };
8872
+ const startDesktopVoice = async ({ sessionId, sdp, voice: voiceName, language, signal }) => {
8873
+ if (typeof sdp !== "string" || !sdp.startsWith("v=0") || sdp.length > 64 * 1024) throw new RpcError(-32602, "Invalid voice offer");
8874
+ const agent = await agentFor(sessionId);
8875
+ diagnosticLog.info("voice", "the conversation can take a context note", String(typeof agent.inject === "function"));
8876
+ const session = {
8877
+ audio: { output: { voice: typeof voiceName === "string" && /^[a-z]{2,16}$/u.test(voiceName) ? voiceName : "cove" } },
8878
+ delegation: { type: "client" },
8879
+ instructions: desktopInstructions(language),
8880
+ model: "gpt-live-1.1-codex"
8881
+ };
8882
+ const { callId, answer } = await createVoiceCall({
8883
+ fetch: voice.fetch,
8884
+ credentials: voice.credentials,
8885
+ userAgent,
8886
+ sdp,
8887
+ session,
8888
+ threadId: sessionId,
8889
+ signal
8890
+ });
8891
+ signal?.throwIfAborted();
8892
+ await realtimeVoice.start({
8893
+ threadId: sessionId,
8894
+ transport: {
8895
+ type: "existingCall",
8896
+ callId
8897
+ },
8898
+ flushTranscriptTailOnSessionEnd: true,
8899
+ silentTailRecord: true,
8900
+ hangUpOnGoodbye: true,
8901
+ version: "v3"
8902
+ }, async () => {}, { signal });
8903
+ return { answer };
8904
+ };
8252
8905
  return {
8253
8906
  methods,
8254
8907
  desktopVoice: realtimeVoice === void 0 ? void 0 : Object.freeze({
8255
- async start({ sessionId, sdp, voice: voiceName, language }) {
8256
- if (typeof sdp !== "string" || !sdp.startsWith("v=0") || sdp.length > 64 * 1024) throw new RpcError(-32602, "Invalid voice offer");
8257
- const agent = await agentFor(sessionId);
8258
- diagnosticLog.info("voice", "the conversation can take a context note", String(typeof agent.inject === "function"));
8259
- const session = {
8260
- audio: { output: { voice: typeof voiceName === "string" && /^[a-z]{2,16}$/u.test(voiceName) ? voiceName : "cove" } },
8261
- delegation: { type: "client" },
8262
- instructions: desktopInstructions(language),
8263
- model: "gpt-live-1.1-codex"
8264
- };
8265
- const { callId, answer } = await createVoiceCall({
8266
- fetch: voice.fetch,
8267
- credentials: voice.credentials,
8268
- userAgent,
8269
- sdp,
8270
- session,
8271
- threadId: sessionId
8272
- });
8273
- await realtimeVoice.start({
8274
- threadId: sessionId,
8275
- transport: {
8276
- type: "existingCall",
8277
- callId
8278
- },
8279
- flushTranscriptTailOnSessionEnd: true,
8280
- silentTailRecord: true,
8281
- hangUpOnGoodbye: true,
8282
- version: "v3"
8283
- }, async () => {});
8284
- return { answer };
8285
- },
8908
+ start: startDesktopVoice,
8286
8909
  stop: (sessionId) => realtimeVoice.stop(sessionId),
8287
8910
  interrupt: (sessionId) => realtimeVoice.interrupt(sessionId),
8288
8911
  end: (sessionId) => realtimeVoice.requestClose(sessionId),
@@ -8293,28 +8916,278 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8293
8916
  onApproval,
8294
8917
  onQuestion,
8295
8918
  adopt,
8919
+ close() {
8920
+ realtimeVoice?.closeAll();
8921
+ },
8296
8922
  forget: (notify) => {
8297
8923
  for (const set of subscribers.values()) set.delete(notify);
8298
8924
  }
8299
8925
  };
8300
8926
  }
8301
8927
  //#endregion
8302
- //#region src/retry-policy.js
8303
- /** @param {string} choice a RETRY_POLICIES value @param {Function | undefined} resolve DSH's resolveRetryPolicy */
8304
- function retryPolicyFor(choice, resolve) {
8305
- if (choice === "default" || typeof resolve !== "function") return void 0;
8928
+ //#region src/remote-image-assets.js
8929
+ const BASE$1 = "https://chatgpt.com/backend-api/";
8930
+ const FILE_ID = /^file[-_][A-Za-z0-9_-]{1,200}$/u;
8931
+ const HASH = /^[a-f0-9]{64}$/u;
8932
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
8933
+ function imageBytes({ data, mediaType } = {}) {
8934
+ if (!(data instanceof Uint8Array) || data.byteLength === 0 || data.byteLength > 8 * 1024 * 1024) throw new Error("Invalid remote image size");
8935
+ const bytes = Buffer.from(data);
8936
+ const png = bytes.length >= 24 && bytes.subarray(0, 8).toString("hex") === "89504e470d0a1a0a" && bytes.toString("ascii", 12, 16) === "IHDR" && bytes.readUInt32BE(16) > 0 && bytes.readUInt32BE(20) > 0;
8937
+ const jpeg = bytes.length >= 4 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 && bytes.at(-2) === 255 && bytes.at(-1) === 217;
8938
+ if (!(mediaType === "image/png" && png || mediaType === "image/jpeg" && jpeg)) throw new Error("Remote image type does not match image bytes");
8939
+ return bytes;
8940
+ }
8941
+ function signedUrl(value) {
8942
+ let url;
8306
8943
  try {
8307
- if (choice === "unlimited") return resolve({ mode: "always" }, "codex-subscription retryPolicy");
8308
- return resolve({
8309
- mode: "normal",
8310
- maxRetries: choice === "off" ? 0 : Number(choice)
8311
- }, "codex-subscription retryPolicy");
8944
+ url = new URL(value);
8312
8945
  } catch {
8313
- return;
8946
+ throw new Error("Invalid signed image destination");
8314
8947
  }
8948
+ if (url.protocol !== "https:" || url.username || url.password || url.port && url.port !== "443" || !/(?:\.blob\.core\.windows\.net|\.oaiusercontent\.com|\.openai\.com)$/u.test(url.hostname)) throw new Error("Untrusted signed image destination");
8949
+ return url.href;
8315
8950
  }
8316
- //#endregion
8317
- //#region src/account-vault.js
8951
+ function cachedEntry(value) {
8952
+ return value && HASH.test(value.hash) && FILE_ID.test(value.fileId) && Number.isSafeInteger(value.bytes) && value.bytes > 0 && value.bytes <= 8 * 1024 * 1024 && ["image/png", "image/jpeg"].includes(value.mediaType);
8953
+ }
8954
+ /** Private, account-scoped image upload cache. Persist only IDs and image metadata. */
8955
+ function createRemoteImageAssets({ credentials, fetch: request = globalThis.fetch, stateFile, timeoutMs = 3e4 } = {}) {
8956
+ const accounts = /* @__PURE__ */ new Map(), flights = /* @__PURE__ */ new Map();
8957
+ let writes = Promise.resolve();
8958
+ let ready;
8959
+ const load = () => ready ??= (async () => {
8960
+ if (!stateFile) return;
8961
+ let state;
8962
+ try {
8963
+ state = JSON.parse(await readFile(stateFile, "utf8"));
8964
+ } catch (error) {
8965
+ if (error.code === "ENOENT" || error instanceof SyntaxError) return;
8966
+ throw error;
8967
+ }
8968
+ if (state?.version !== 1 || !Array.isArray(state.accounts)) return;
8969
+ for (const account of state.accounts) {
8970
+ if (!HASH.test(account?.account)) continue;
8971
+ const entries = /* @__PURE__ */ new Map();
8972
+ for (const entry of (Array.isArray(account.images) ? account.images : []).slice(-128)) if (cachedEntry(entry)) entries.set(entry.hash, {
8973
+ hash: entry.hash,
8974
+ fileId: entry.fileId,
8975
+ bytes: entry.bytes,
8976
+ mediaType: entry.mediaType
8977
+ });
8978
+ accounts.set(account.account, entries);
8979
+ }
8980
+ })();
8981
+ const persist = () => {
8982
+ if (!stateFile) return Promise.resolve();
8983
+ const next = writes.catch(() => {}).then(async () => {
8984
+ const temporary = `${stateFile}.${randomUUID()}.tmp`;
8985
+ await mkdir(dirname(stateFile), {
8986
+ recursive: true,
8987
+ mode: 448
8988
+ });
8989
+ try {
8990
+ await writeFile(temporary, JSON.stringify({
8991
+ version: 1,
8992
+ accounts: [...accounts].map(([account, images]) => ({
8993
+ account,
8994
+ images: [...images.values()]
8995
+ }))
8996
+ }), {
8997
+ mode: 384,
8998
+ flag: "wx"
8999
+ });
9000
+ await rename(temporary, stateFile);
9001
+ } finally {
9002
+ await rm(temporary, { force: true });
9003
+ }
9004
+ });
9005
+ writes = next;
9006
+ return next;
9007
+ };
9008
+ const send = async (url, init) => {
9009
+ try {
9010
+ return await request(url, init);
9011
+ } catch {
9012
+ init.signal?.throwIfAborted();
9013
+ throw new Error("Remote image request failed");
9014
+ }
9015
+ };
9016
+ async function upload(bytes, mediaType, auth, owner, key, signal) {
9017
+ const api = async (method, path, body) => {
9018
+ signal.throwIfAborted();
9019
+ const response = await send(BASE$1 + path, {
9020
+ method,
9021
+ redirect: "error",
9022
+ signal: AbortSignal.any([signal, AbortSignal.timeout(6e4)]),
9023
+ headers: {
9024
+ authorization: `Bearer ${auth.access}`,
9025
+ "ChatGPT-Account-ID": auth.accountId,
9026
+ "content-type": "application/json"
9027
+ },
9028
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
9029
+ });
9030
+ if (!response.ok) {
9031
+ const error = /* @__PURE__ */ new Error(`Remote image ${method} failed (HTTP ${response.status})`);
9032
+ error.status = response.status;
9033
+ throw error;
9034
+ }
9035
+ try {
9036
+ return await response.json();
9037
+ } catch {
9038
+ throw new Error("Invalid remote image response");
9039
+ }
9040
+ };
9041
+ const finalize = async (fileId) => {
9042
+ for (let attempt = 0; attempt < 8; attempt++) {
9043
+ const completed = await api("POST", `files/${encodeURIComponent(fileId)}/uploaded`, {});
9044
+ if (completed.status === "success") return signedUrl(completed.download_url);
9045
+ if (completed.status !== "retry") throw new Error("Remote image finalization failed");
9046
+ if (attempt < 7) await setTimeout$1(250, void 0, { signal });
9047
+ }
9048
+ throw new Error("Remote image finalization did not complete");
9049
+ };
9050
+ let entries = accounts.get(owner);
9051
+ if (!entries) {
9052
+ entries = /* @__PURE__ */ new Map();
9053
+ accounts.set(owner, entries);
9054
+ }
9055
+ const saved = entries.get(key);
9056
+ if (saved) {
9057
+ try {
9058
+ return {
9059
+ fileId: saved.fileId,
9060
+ downloadUrl: await finalize(saved.fileId)
9061
+ };
9062
+ } catch (error) {
9063
+ if (error.status !== 404 && error.status !== 410) throw error;
9064
+ }
9065
+ entries.delete(key);
9066
+ }
9067
+ const created = await api("POST", "files", {
9068
+ file_name: `dsh-image-${key.slice(0, 16)}.${mediaType === "image/png" ? "png" : "jpg"}`,
9069
+ file_size: bytes.length,
9070
+ use_case: "codex"
9071
+ });
9072
+ if (!FILE_ID.test(created.file_id)) throw new Error("Invalid remote image file identity");
9073
+ const destination = signedUrl(created.upload_url);
9074
+ const put = await send(destination, {
9075
+ method: "PUT",
9076
+ redirect: "error",
9077
+ signal: AbortSignal.any([signal, AbortSignal.timeout(6e4)]),
9078
+ headers: {
9079
+ "x-ms-blob-type": "BlockBlob",
9080
+ "content-length": String(bytes.length),
9081
+ "content-type": mediaType
9082
+ },
9083
+ body: bytes
9084
+ });
9085
+ if (!put.ok) throw new Error(`Remote image upload failed (HTTP ${put.status})`);
9086
+ const downloadUrl = await finalize(created.file_id);
9087
+ signal.throwIfAborted();
9088
+ entries.set(key, {
9089
+ hash: key,
9090
+ fileId: created.file_id,
9091
+ bytes: bytes.length,
9092
+ mediaType
9093
+ });
9094
+ while (entries.size > 128) entries.delete(entries.keys().next().value);
9095
+ try {
9096
+ await persist();
9097
+ } catch (error) {
9098
+ entries.delete(key);
9099
+ throw error;
9100
+ }
9101
+ return {
9102
+ fileId: created.file_id,
9103
+ downloadUrl
9104
+ };
9105
+ }
9106
+ const publish = async (image, signal) => {
9107
+ signal?.throwIfAborted();
9108
+ const bytes = imageBytes(image);
9109
+ const credential = await credentials({ signal });
9110
+ const auth = {
9111
+ access: credential?.access,
9112
+ accountId: credential?.accountId
9113
+ };
9114
+ signal?.throwIfAborted();
9115
+ if (!auth?.access || typeof auth.access !== "string" || !auth.accountId || typeof auth.accountId !== "string") throw new Error("Remote image upload requires a signed-in account");
9116
+ await load();
9117
+ signal?.throwIfAborted();
9118
+ const owner = hash(auth.accountId), key = hash(bytes), flightKey = `${owner}:${key}`;
9119
+ let flight = flights.get(flightKey);
9120
+ if (!flight) {
9121
+ const controller = new AbortController();
9122
+ flight = {
9123
+ controller,
9124
+ waiters: 0,
9125
+ settled: false
9126
+ };
9127
+ flight.promise = Promise.resolve().then(() => upload(bytes, image.mediaType, auth, owner, key, controller.signal)).finally(() => {
9128
+ flight.settled = true;
9129
+ if (flights.get(flightKey) === flight) flights.delete(flightKey);
9130
+ });
9131
+ flights.set(flightKey, flight);
9132
+ }
9133
+ flight.waiters++;
9134
+ return new Promise((resolve, reject) => {
9135
+ let done = false;
9136
+ const finish = (error, value) => {
9137
+ if (done) return;
9138
+ done = true;
9139
+ signal?.removeEventListener("abort", abort);
9140
+ if (--flight.waiters === 0 && !flight.settled) {
9141
+ if (flights.get(flightKey) === flight) flights.delete(flightKey);
9142
+ flight.controller.abort();
9143
+ }
9144
+ if (error) reject(error);
9145
+ else resolve(value);
9146
+ };
9147
+ const abort = () => finish(signal.reason ?? /* @__PURE__ */ new Error("Remote image upload aborted"));
9148
+ signal?.addEventListener("abort", abort, { once: true });
9149
+ if (signal?.aborted) abort();
9150
+ flight.promise.then((value) => finish(void 0, value), (error) => finish(error));
9151
+ });
9152
+ };
9153
+ return Object.freeze({ publish(image, callerSignal) {
9154
+ const deadline = AbortSignal.timeout(timeoutMs);
9155
+ const signal = callerSignal ? AbortSignal.any([callerSignal, deadline]) : deadline;
9156
+ const operation = publish(image, signal);
9157
+ return new Promise((resolve, reject) => {
9158
+ const abort = () => {
9159
+ signal.removeEventListener("abort", abort);
9160
+ reject(signal.reason);
9161
+ };
9162
+ signal.addEventListener("abort", abort, { once: true });
9163
+ if (signal.aborted) abort();
9164
+ operation.then((value) => {
9165
+ signal.removeEventListener("abort", abort);
9166
+ resolve(value);
9167
+ }, (error) => {
9168
+ signal.removeEventListener("abort", abort);
9169
+ reject(error);
9170
+ });
9171
+ });
9172
+ } });
9173
+ }
9174
+ //#endregion
9175
+ //#region src/retry-policy.js
9176
+ /** @param {string} choice a RETRY_POLICIES value @param {Function | undefined} resolve DSH's resolveRetryPolicy */
9177
+ function retryPolicyFor(choice, resolve) {
9178
+ if (choice === "default" || typeof resolve !== "function") return void 0;
9179
+ try {
9180
+ if (choice === "unlimited") return resolve({ mode: "always" }, "codex-subscription retryPolicy");
9181
+ return resolve({
9182
+ mode: "normal",
9183
+ maxRetries: choice === "off" ? 0 : Number(choice)
9184
+ }, "codex-subscription retryPolicy");
9185
+ } catch {
9186
+ return;
9187
+ }
9188
+ }
9189
+ //#endregion
9190
+ //#region src/account-vault.js
8318
9191
  const VERSION = 1;
8319
9192
  const DEFAULT_LABEL = "Account 1";
8320
9193
  const clone$1 = (value) => value === void 0 ? void 0 : structuredClone(value);
@@ -9225,6 +10098,110 @@ function createCodexRpcHandler(coordinator, options = {}) {
9225
10098
  };
9226
10099
  }
9227
10100
  //#endregion
10101
+ //#region src/model-catalog-cache.js
10102
+ const SCHEMA_VERSION = 1;
10103
+ const MAX_AGE_MS = 1440 * 60 * 1e3;
10104
+ const MAX_BYTES = 4 * 1024 * 1024;
10105
+ /**
10106
+ * 按账号身份读取并校验本地模型目录缓存。
10107
+ * @param {string} accountId - 当前 OAuth 账号标识
10108
+ * @param {{ directory?: string, now?: number, parseCatalog: Function }} options - 缓存目录与目录校验方法
10109
+ * @returns {Promise<{ rawCatalog: object, etag?: string } | undefined>} 有效目录缓存;缺失或无效时返回 undefined
10110
+ */
10111
+ async function loadModelCatalogCache(accountId, options) {
10112
+ const { accountKey, filename } = cacheLocation(accountId, options.directory);
10113
+ let entry;
10114
+ try {
10115
+ options.signal?.throwIfAborted();
10116
+ if ((await stat(filename)).size > MAX_BYTES) return void 0;
10117
+ entry = JSON.parse(await readFile(filename, {
10118
+ encoding: "utf8",
10119
+ signal: options.signal
10120
+ }));
10121
+ } catch (error) {
10122
+ if (error?.code === "ENOENT" || error instanceof SyntaxError) return void 0;
10123
+ throw error;
10124
+ }
10125
+ const now = options.now ?? Date.now();
10126
+ if (!Number.isSafeInteger(now) || now <= 0 || !isRecord(entry) || entry.schemaVersion !== SCHEMA_VERSION || entry.accountKey !== accountKey || !Number.isSafeInteger(entry.savedAt) || entry.savedAt <= 0 || entry.savedAt > now || now - entry.savedAt > MAX_AGE_MS || entry.etag !== void 0 && typeof entry.etag !== "string") return void 0;
10127
+ try {
10128
+ const parsed = options.parseCatalog(entry.rawCatalog, now);
10129
+ if (!Array.isArray(parsed) || parsed.length === 0) return void 0;
10130
+ } catch {
10131
+ return;
10132
+ }
10133
+ return {
10134
+ rawCatalog: entry.rawCatalog,
10135
+ ...entry.etag === void 0 ? {} : { etag: entry.etag }
10136
+ };
10137
+ }
10138
+ /**
10139
+ * 将经过目录校验的原始账号目录以原子替换方式保存。
10140
+ * @param {string} accountId - 当前 OAuth 账号标识
10141
+ * @param {{ rawCatalog: object, etag?: string }} catalog - 远端返回的完整目录和 ETag
10142
+ * @param {{ directory?: string, now?: number, parseCatalog: Function, isCurrent?: () => boolean }} options - 缓存目录、目录校验方法和写入状态检查
10143
+ * @returns {Promise<void>} 缓存写入完成
10144
+ */
10145
+ async function saveModelCatalogCache(accountId, catalog, options) {
10146
+ options.signal?.throwIfAborted();
10147
+ const { accountKey, filename } = cacheLocation(accountId, options.directory);
10148
+ const now = options.now ?? Date.now();
10149
+ if (!isRecord(catalog) || !isRecord(catalog.rawCatalog) || !Number.isSafeInteger(now) || now <= 0 || catalog.etag !== void 0 && typeof catalog.etag !== "string") throw new Error("Refusing to persist malformed model catalog cache");
10150
+ const parsed = options.parseCatalog(catalog.rawCatalog, now);
10151
+ if (!Array.isArray(parsed) || parsed.length === 0) throw new Error("Refusing to persist an empty model catalog cache");
10152
+ const data = `${JSON.stringify({
10153
+ schemaVersion: SCHEMA_VERSION,
10154
+ accountKey,
10155
+ savedAt: now,
10156
+ ...catalog.etag === void 0 ? {} : { etag: catalog.etag },
10157
+ rawCatalog: catalog.rawCatalog
10158
+ })}\n`;
10159
+ if (Buffer.byteLength(data) > MAX_BYTES) throw new Error("Model catalog cache exceeds its size limit");
10160
+ if (options.isCurrent?.() === false) return;
10161
+ await mkdir(dirname(filename), {
10162
+ recursive: true,
10163
+ mode: 448
10164
+ });
10165
+ const temporary = `${filename}.${process.pid}.${randomUUID()}.tmp`;
10166
+ let handle;
10167
+ try {
10168
+ handle = await open(temporary, "wx", 384);
10169
+ options.signal?.throwIfAborted();
10170
+ await handle.writeFile(data, { signal: options.signal });
10171
+ await handle.sync();
10172
+ await handle.close();
10173
+ handle = void 0;
10174
+ options.signal?.throwIfAborted();
10175
+ if (options.isCurrent !== void 0 && !options.isCurrent()) return;
10176
+ await rename(temporary, filename);
10177
+ } finally {
10178
+ await handle?.close().catch(() => void 0);
10179
+ await rm(temporary, { force: true }).catch(() => void 0);
10180
+ }
10181
+ }
10182
+ /**
10183
+ * 根据账号标识生成只含摘要的缓存路径。
10184
+ * @param {string} accountId - OAuth 账号标识
10185
+ * @param {string | undefined} directory - 可选缓存目录
10186
+ * @returns {{ accountKey: string, filename: string }} 账号摘要和缓存文件路径
10187
+ */
10188
+ function cacheLocation(accountId, directory) {
10189
+ if (typeof accountId !== "string" || accountId.length === 0) throw new Error("A current account is required for the model catalog cache");
10190
+ const accountKey = createHash("sha256").update(accountId).digest("hex");
10191
+ return {
10192
+ accountKey,
10193
+ filename: join(directory ?? dshHomePath("state", "codex-subscription", "model-catalog"), `${accountKey}.json`)
10194
+ };
10195
+ }
10196
+ /**
10197
+ * 判断值是否为普通记录。
10198
+ * @param {unknown} value - 待检查的值
10199
+ * @returns {boolean} 值是否为普通记录
10200
+ */
10201
+ function isRecord(value) {
10202
+ return value !== null && typeof value === "object" && !Array.isArray(value);
10203
+ }
10204
+ //#endregion
9228
10205
  //#region src/model-catalog.js
9229
10206
  const CODEX_MODELS_URL = `https://chatgpt.com/backend-api/codex/models?client_version=${encodeURIComponent(PACKAGE_VERSION)}`;
9230
10207
  const LEVELS = [
@@ -9237,11 +10214,11 @@ const LEVELS = [
9237
10214
  "max"
9238
10215
  ];
9239
10216
  const DEFAULT_REFRESH_TIMEOUT_MS = 1e4;
9240
- const record$7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
10217
+ const record$6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
9241
10218
  const nonEmpty$1 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
9242
10219
  const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0 ? value : void 0;
9243
10220
  function upgradeModelId(value) {
9244
- return (typeof value.upgrade === "string" ? nonEmpty$1(value.upgrade) : record$7(value.upgrade) ? nonEmpty$1(value.upgrade.model) : void 0) ?? (record$7(value.upgrade_info) ? nonEmpty$1(value.upgrade_info.model) : void 0) ?? (record$7(value.upgradeInfo) ? nonEmpty$1(value.upgradeInfo.model) : void 0);
10221
+ return (typeof value.upgrade === "string" ? nonEmpty$1(value.upgrade) : record$6(value.upgrade) ? nonEmpty$1(value.upgrade.model) : void 0) ?? (record$6(value.upgrade_info) ? nonEmpty$1(value.upgrade_info.model) : void 0) ?? (record$6(value.upgradeInfo) ? nonEmpty$1(value.upgradeInfo.model) : void 0);
9245
10222
  }
9246
10223
  function retirementMillis(value) {
9247
10224
  for (const source of [
@@ -9250,7 +10227,7 @@ function retirementMillis(value) {
9250
10227
  value.upgrade_info,
9251
10228
  value.upgradeInfo
9252
10229
  ]) {
9253
- if (!record$7(source)) continue;
10230
+ if (!record$6(source)) continue;
9254
10231
  for (const raw of [source.retirement_at, source.retirementAt]) {
9255
10232
  const seconds = positiveInteger(raw);
9256
10233
  if (seconds !== void 0 && Number.isSafeInteger(seconds * 1e3)) return seconds * 1e3;
@@ -9262,7 +10239,7 @@ function retirementMillis(value) {
9262
10239
  }
9263
10240
  }
9264
10241
  function retirementNotice(value, now = Date.now(), targetDisplayName) {
9265
- if (!record$7(value) || !Number.isFinite(now)) return void 0;
10242
+ if (!record$6(value) || !Number.isFinite(now)) return void 0;
9266
10243
  const at = retirementMillis(value);
9267
10244
  if (at === void 0 || at <= now) return void 0;
9268
10245
  const date = new Date(at);
@@ -9278,7 +10255,7 @@ function retirementNotice(value, now = Date.now(), targetDisplayName) {
9278
10255
  };
9279
10256
  }
9280
10257
  function reasoningMap(levels) {
9281
- const supported = new Set((Array.isArray(levels) ? levels : []).map((level) => nonEmpty$1(record$7(level) ? level.effort : void 0)).filter(Boolean));
10258
+ const supported = new Set((Array.isArray(levels) ? levels : []).map((level) => nonEmpty$1(record$6(level) ? level.effort : void 0)).filter(Boolean));
9282
10259
  const map = Object.fromEntries(LEVELS.map((level) => [level, null]));
9283
10260
  if (supported.has("none")) map.off = "none";
9284
10261
  for (const level of LEVELS.slice(1)) if (supported.has(level)) map[level] = level;
@@ -9292,7 +10269,7 @@ const HONOURED_TIERS = /* @__PURE__ */ new Set([
9292
10269
  "ultrafast"
9293
10270
  ]);
9294
10271
  function serviceTierEntries(value) {
9295
- const found = (Array.isArray(value.service_tiers) ? value.service_tiers : []).flatMap((tier) => record$7(tier) && typeof tier.id === "string" && HONOURED_TIERS.has(tier.id) ? [{
10272
+ const found = (Array.isArray(value.service_tiers) ? value.service_tiers : []).flatMap((tier) => record$6(tier) && typeof tier.id === "string" && HONOURED_TIERS.has(tier.id) ? [{
9296
10273
  id: tier.id,
9297
10274
  name: nonEmpty$1(tier.name) ?? tier.id,
9298
10275
  description: nonEmpty$1(tier.description) ?? ""
@@ -9322,7 +10299,7 @@ function unsupportedCapabilities(value) {
9322
10299
  };
9323
10300
  }
9324
10301
  function visibleModel(value, displayNames, now) {
9325
- if (!record$7(value)) return void 0;
10302
+ if (!record$6(value)) return void 0;
9326
10303
  const id = nonEmpty$1(value.slug);
9327
10304
  const reserve = id === "gpt-reserve" && ["list", "hide"].includes(value.visibility);
9328
10305
  if (id === void 0 || value.visibility !== "list" && !reserve) return void 0;
@@ -9369,22 +10346,22 @@ function visibleModel(value, displayNames, now) {
9369
10346
  * visibility), with low reasoning when the reviewer supports it.
9370
10347
  */
9371
10348
  function officialReviewModel(value, parentId) {
9372
- if (!record$7(value) || !Array.isArray(value.models)) return void 0;
9373
- const parent = value.models.find((model) => record$7(model) && model.slug === parentId);
10349
+ if (!record$6(value) || !Array.isArray(value.models)) return void 0;
10350
+ const parent = value.models.find((model) => record$6(model) && model.slug === parentId);
9374
10351
  const id = nonEmpty$1(parent?.auto_review_model_override) ?? "codex-auto-review";
9375
- const preset = value.models.find((model) => record$7(model) && model.slug === id);
10352
+ const preset = value.models.find((model) => record$6(model) && model.slug === id);
9376
10353
  if (preset === void 0) return void 0;
9377
- const effort = (Array.isArray(preset.supported_reasoning_levels) ? preset.supported_reasoning_levels : []).some((level) => (record$7(level) ? level.effort : level) === "low") ? "low" : nonEmpty$1(preset.default_reasoning_level);
10354
+ const effort = (Array.isArray(preset.supported_reasoning_levels) ? preset.supported_reasoning_levels : []).some((level) => (record$6(level) ? level.effort : level) === "low") ? "low" : nonEmpty$1(preset.default_reasoning_level);
9378
10355
  return {
9379
10356
  id,
9380
10357
  ...effort === void 0 ? {} : { effort }
9381
10358
  };
9382
10359
  }
9383
10360
  function parseOfficialModelCatalog(value, now = Date.now()) {
9384
- if (!record$7(value) || !Array.isArray(value.models)) throw new Error("Codex returned a malformed model catalog");
10361
+ if (!record$6(value) || !Array.isArray(value.models)) throw new Error("Codex returned a malformed model catalog");
9385
10362
  const displayNames = /* @__PURE__ */ new Map();
9386
10363
  for (const model of value.models) {
9387
- if (!record$7(model)) continue;
10364
+ if (!record$6(model)) continue;
9388
10365
  const id = nonEmpty$1(model.slug);
9389
10366
  const name = nonEmpty$1(model.display_name);
9390
10367
  if (id !== void 0 && name !== void 0 && !displayNames.has(id)) displayNames.set(id, name);
@@ -9414,267 +10391,305 @@ function mergeModel(baseModels, remote) {
9414
10391
  } }
9415
10392
  };
9416
10393
  }
10394
+ /**
10395
+ * 创建带账号缓存、远端刷新和模型能力元数据的官方目录。
10396
+ * @param {object} options - 凭据、模型来源、网络和目录更新配置
10397
+ * @returns {object} 可初始化、刷新、查询和清除的模型目录
10398
+ */
9417
10399
  function createOfficialModelCatalog(options = {}) {
9418
10400
  const fetchCatalog = options.fetch ?? fetch;
9419
10401
  const getNow = options.now ?? Date.now;
9420
- const scheduleTimeout = options.setTimeout ?? setTimeout;
9421
- const cancelTimeout = options.clearTimeout ?? clearTimeout;
10402
+ const schedule = options.setTimeout ?? setTimeout;
10403
+ const cancelTimer = options.clearTimeout ?? clearTimeout;
9422
10404
  const timeoutMs = Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : DEFAULT_REFRESH_TIMEOUT_MS;
9423
- let models;
9424
- let metadata = /* @__PURE__ */ new Map();
9425
- let etag;
9426
- let rawCatalog;
9427
- let revision = 0;
9428
- let refreshing;
9429
- let generation = 0;
9430
- let refreshStatus = "idle";
9431
- const retryDelays = Array.isArray(options.retryDelaysMs) ? options.retryDelaysMs.filter((delay) => Number.isFinite(delay) && delay > 0) : [];
9432
- let retries = 0;
9433
- let retryTimer;
10405
+ const loadCache = options.loadCache ?? loadModelCatalogCache;
10406
+ const saveCache = options.saveCache ?? saveModelCatalogCache;
10407
+ const retryDelays = (options.retryDelaysMs ?? []).filter((delay) => Number.isFinite(delay) && delay > 0);
10408
+ let models, rawCatalog, etag, accountId, initializing, refreshing, retryTimer;
10409
+ let metadata = /* @__PURE__ */ new Map(), generation = 0, revision = 0, retries = 0, initialized = false;
10410
+ let source = "unavailable", refreshStatus = "idle", writeSequence = 0;
10411
+ const writes = /* @__PURE__ */ new Set();
10412
+ const notify = () => {
10413
+ try {
10414
+ options.onUpdated?.();
10415
+ } catch {}
10416
+ };
10417
+ const cacheError = (error) => {
10418
+ try {
10419
+ options.onCacheError?.(error);
10420
+ } catch {}
10421
+ };
9434
10422
  const stopRetry = () => {
9435
- if (retryTimer !== void 0) cancelTimeout(retryTimer);
10423
+ if (retryTimer !== void 0) cancelTimer(retryTimer);
9436
10424
  retryTimer = void 0;
9437
10425
  };
9438
- const scheduleRetry = (currentGeneration) => {
9439
- if (models !== void 0 || currentGeneration !== generation || retryTimer !== void 0 || retries >= retryDelays.length) return;
9440
- retryTimer = scheduleTimeout(() => {
10426
+ const cancelled = () => Object.assign(/* @__PURE__ */ new Error("Codex model catalog operation cancelled"), { name: "AbortError" });
10427
+ const current = (flight) => flight.generation === generation && !flight.controller.signal.aborted;
10428
+ const wait = (promise, signal) => {
10429
+ if (!signal) return promise;
10430
+ if (signal.aborted) return Promise.reject(signal.reason ?? cancelled());
10431
+ let abort;
10432
+ const interrupted = new Promise((_, reject) => {
10433
+ abort = () => reject(signal.reason ?? cancelled());
10434
+ signal.addEventListener("abort", abort, { once: true });
10435
+ });
10436
+ return Promise.race([promise, interrupted]).finally(() => signal.removeEventListener("abort", abort));
10437
+ };
10438
+ const bounded = (label, work, signal) => {
10439
+ const controller = new AbortController();
10440
+ const abort = () => controller.abort(signal?.reason ?? cancelled());
10441
+ signal?.addEventListener("abort", abort, { once: true });
10442
+ if (signal?.aborted) abort();
10443
+ const flight = {
10444
+ generation,
10445
+ controller
10446
+ };
10447
+ const timer = schedule(() => controller.abort(/* @__PURE__ */ new Error(`Codex model catalog ${label} timed out`)), timeoutMs);
10448
+ timer.unref?.();
10449
+ const task = Promise.resolve().then(() => {
10450
+ controller.signal.throwIfAborted();
10451
+ return work(flight, controller.signal);
10452
+ });
10453
+ flight.promise = wait(task, controller.signal).finally(() => {
10454
+ cancelTimer(timer);
10455
+ signal?.removeEventListener("abort", abort);
10456
+ });
10457
+ return flight;
10458
+ };
10459
+ const scheduleRetry = (expected) => {
10460
+ if (expected !== generation || retryTimer !== void 0 || retries >= retryDelays.length) return;
10461
+ retryTimer = schedule(() => {
9441
10462
  retryTimer = void 0;
9442
- if (models !== void 0 || currentGeneration !== generation) return;
9443
- refresh().catch(() => {});
10463
+ if (expected === generation) refresh().catch(() => {});
9444
10464
  }, retryDelays[retries++]);
9445
10465
  retryTimer.unref?.();
9446
10466
  };
10467
+ const restore = async (nextAccountId, flight, signal) => {
10468
+ if (!current(flight)) return false;
10469
+ if (accountId !== nextAccountId) {
10470
+ const hadModels = models !== void 0;
10471
+ accountId = nextAccountId;
10472
+ models = rawCatalog = etag = void 0;
10473
+ metadata = /* @__PURE__ */ new Map();
10474
+ source = "unavailable";
10475
+ if (hadModels) {
10476
+ revision += 1;
10477
+ notify();
10478
+ }
10479
+ }
10480
+ let cached;
10481
+ if (nextAccountId && options.cacheDirectory !== void 0) try {
10482
+ cached = await loadCache(nextAccountId, {
10483
+ directory: options.cacheDirectory,
10484
+ now: getNow(),
10485
+ parseCatalog: parseOfficialModelCatalog,
10486
+ signal
10487
+ });
10488
+ } catch (error) {
10489
+ if (!current(flight)) throw error;
10490
+ cacheError(error);
10491
+ }
10492
+ if (!current(flight) || accountId !== nextAccountId) return false;
10493
+ if (cached !== void 0) {
10494
+ const remote = parseOfficialModelCatalog(cached.rawCatalog, getNow());
10495
+ const next = remote.map((model) => mergeModel(options.baseModels(), model)).filter(Boolean);
10496
+ if (next.length) {
10497
+ models = next;
10498
+ rawCatalog = cached.rawCatalog;
10499
+ etag = cached.etag;
10500
+ metadata = new Map(remote.map((model) => [model.id, model]));
10501
+ source = "cached";
10502
+ revision += 1;
10503
+ notify();
10504
+ }
10505
+ }
10506
+ return true;
10507
+ };
10508
+ const initialize = ({ signal } = {}) => {
10509
+ if (signal?.aborted) return Promise.reject(signal.reason ?? cancelled());
10510
+ if (initializing) return wait(initializing.promise, signal);
10511
+ if (initialized) return Promise.resolve(accountId !== void 0);
10512
+ const flight = bounded("initialization", async (flight, requestSignal) => {
10513
+ const credential = await options.readCredential?.({ signal: requestSignal });
10514
+ if (!current(flight)) return false;
10515
+ const id = credential?.type === "oauth" ? nonEmpty$1(credential.accountId) : void 0;
10516
+ await restore(id, flight, requestSignal);
10517
+ if (!current(flight)) return false;
10518
+ initialized = true;
10519
+ return id !== void 0;
10520
+ }, signal);
10521
+ initializing = flight;
10522
+ flight.promise = flight.promise.finally(() => {
10523
+ if (initializing === flight) initializing = void 0;
10524
+ });
10525
+ return flight.promise;
10526
+ };
10527
+ const persist = (id, raw, nextEtag) => {
10528
+ if (options.cacheDirectory === void 0) return;
10529
+ const expected = generation, sequence = ++writeSequence;
10530
+ const flight = bounded("cache write", async (flight, signal) => {
10531
+ await saveCache(id, {
10532
+ rawCatalog: raw,
10533
+ etag: nextEtag
10534
+ }, {
10535
+ directory: options.cacheDirectory,
10536
+ now: getNow(),
10537
+ parseCatalog: parseOfficialModelCatalog,
10538
+ signal,
10539
+ isCurrent: () => current(flight) && accountId === id && writeSequence === sequence
10540
+ });
10541
+ });
10542
+ writes.add(flight);
10543
+ flight.promise.catch((error) => {
10544
+ if (expected === generation) cacheError(error);
10545
+ }).finally(() => writes.delete(flight));
10546
+ };
9447
10547
  const refresh = ({ signal } = {}) => {
9448
- if (signal?.aborted) return Promise.reject(signal.reason ?? /* @__PURE__ */ new Error("Codex model catalog refresh aborted"));
9449
- if (refreshing?.generation === generation) return refreshing.promise;
9450
- const currentGeneration = generation;
10548
+ if (signal?.aborted) return Promise.reject(signal.reason ?? cancelled());
10549
+ if (refreshing) return wait(refreshing.promise, signal);
9451
10550
  refreshStatus = "refreshing";
9452
- let outcome = "idle";
9453
- const controller = new AbortController();
9454
- const abort = () => {
9455
- if (!controller.signal.aborted) controller.abort(signal?.reason ?? /* @__PURE__ */ new Error("Codex model catalog refresh aborted"));
9456
- };
9457
- signal?.addEventListener("abort", abort, { once: true });
9458
- const requestSignal = controller.signal;
9459
- let timer;
9460
- const timeoutError = /* @__PURE__ */ new Error("Codex model catalog refresh timed out");
9461
- const work = (async () => {
9462
- const { access, accountId } = await readSubscriptionCredentials(options.getAuth, options.readCredential, requestSignal);
9463
- if (currentGeneration !== generation || requestSignal.aborted) return false;
9464
- if (typeof access !== "string" || access.length === 0 || typeof accountId !== "string" || accountId.length === 0) return false;
9465
- const headers = {
9466
- authorization: `Bearer ${access}`,
9467
- "chatgpt-account-id": accountId,
9468
- accept: "application/json",
9469
- originator: "pi",
9470
- "user-agent": USER_AGENT,
9471
- ...etag === void 0 ? {} : { "if-none-match": etag }
9472
- };
10551
+ const flight = bounded("refresh", async (flight, requestSignal) => {
10552
+ await initialize({ signal: requestSignal });
10553
+ if (!current(flight)) return false;
10554
+ const credentials = await readSubscriptionCredentials(options.getAuth, options.readCredential, requestSignal);
10555
+ if (!current(flight)) return false;
10556
+ if (!nonEmpty$1(credentials.access) || !nonEmpty$1(credentials.accountId)) {
10557
+ if (accountId !== void 0 || models !== void 0) throw new Error("Codex model catalog credentials are unavailable");
10558
+ refreshStatus = "idle";
10559
+ return false;
10560
+ }
10561
+ if (credentials.accountId !== accountId) {
10562
+ await restore(credentials.accountId, flight, requestSignal);
10563
+ if (!current(flight)) return false;
10564
+ initialized = true;
10565
+ }
10566
+ const id = credentials.accountId;
9473
10567
  const response = await fetchCatalog(CODEX_MODELS_URL, {
9474
10568
  method: "GET",
9475
10569
  redirect: "error",
9476
- headers,
9477
- signal: requestSignal
10570
+ signal: requestSignal,
10571
+ headers: {
10572
+ authorization: `Bearer ${credentials.access}`,
10573
+ "chatgpt-account-id": id,
10574
+ accept: "application/json",
10575
+ originator: "pi",
10576
+ "user-agent": USER_AGENT,
10577
+ ...etag === void 0 ? {} : { "if-none-match": etag }
10578
+ }
9478
10579
  });
9479
- if (currentGeneration !== generation || requestSignal.aborted) return false;
9480
- if (response.status === 304) {
9481
- outcome = "ok";
9482
- if (rawCatalog === void 0) return false;
9483
- const remote = parseOfficialModelCatalog(rawCatalog, getNow());
9484
- const next = remote.map((model) => mergeModel(options.baseModels(), model)).filter(Boolean);
9485
- if (next.length === 0 || JSON.stringify(next) === JSON.stringify(models)) return false;
9486
- models = next;
9487
- metadata = new Map(remote.map((model) => [model.id, model]));
9488
- revision += 1;
9489
- options.onUpdated?.();
9490
- return true;
9491
- }
9492
- if (!response.ok) throw new Error(`Codex model catalog failed (HTTP ${response.status})`);
9493
- const raw = await response.json();
10580
+ if (!current(flight) || accountId !== id) return false;
10581
+ if (response.status !== 304 && !response.ok) throw new Error(`Codex model catalog failed (HTTP ${response.status})`);
10582
+ const raw = response.status === 304 ? rawCatalog : await response.json();
10583
+ if (!current(flight) || accountId !== id) return false;
10584
+ if (raw === void 0) throw new Error("Codex returned HTTP 304 without a cached model catalog");
9494
10585
  const remote = parseOfficialModelCatalog(raw, getNow());
9495
- if (currentGeneration !== generation || requestSignal.aborted) return false;
9496
- if (remote.length === 0) throw new Error("Codex returned an empty model catalog");
9497
- const baseModels = options.baseModels();
9498
- const next = remote.map((model) => mergeModel(baseModels, model)).filter(Boolean);
9499
- if (next.length === 0) throw new Error("Codex model catalog has no compatible models");
9500
- if (currentGeneration !== generation || requestSignal.aborted) return false;
10586
+ const next = remote.map((model) => mergeModel(options.baseModels(), model)).filter(Boolean);
10587
+ if (!next.length) throw new Error("Codex returned an empty or incompatible model catalog");
10588
+ const changed = response.status !== 304 || JSON.stringify(next) !== JSON.stringify(models);
10589
+ const previousSource = source;
9501
10590
  models = next;
9502
10591
  rawCatalog = raw;
9503
10592
  metadata = new Map(remote.map((model) => [model.id, model]));
9504
10593
  etag = nonEmpty$1(response.headers.get("etag")) ?? etag;
9505
- revision += 1;
9506
- outcome = "ok";
9507
- options.onUpdated?.();
9508
- return true;
9509
- })();
9510
- let rejectAborted;
9511
- const abortPromise = new Promise((_, reject) => {
9512
- rejectAborted = () => reject(requestSignal.reason ?? /* @__PURE__ */ new Error("Codex model catalog refresh aborted"));
9513
- if (requestSignal.aborted) rejectAborted();
9514
- else requestSignal.addEventListener("abort", rejectAborted, { once: true });
9515
- });
9516
- timer = scheduleTimeout(() => controller.abort(timeoutError), timeoutMs);
9517
- timer.unref?.();
9518
- const promise = Promise.race([work, abortPromise]).catch((error) => {
9519
- outcome = "failed";
9520
- throw error;
9521
- }).finally(() => {
9522
- cancelTimeout(timer);
9523
- signal?.removeEventListener("abort", abort);
9524
- requestSignal.removeEventListener("abort", rejectAborted);
9525
- if (refreshing?.promise === promise) {
9526
- refreshing = void 0;
9527
- refreshStatus = outcome;
9528
- }
9529
- if (outcome === "ok") {
10594
+ source = "online";
10595
+ refreshStatus = "ok";
10596
+ if (changed) revision += 1;
10597
+ if (changed || previousSource !== "online") notify();
10598
+ if (current(flight) && accountId === id) persist(id, raw, etag);
10599
+ return changed;
10600
+ }, signal);
10601
+ refreshing = flight;
10602
+ flight.promise = flight.promise.then((value) => {
10603
+ if (current(flight)) {
9530
10604
  retries = 0;
9531
10605
  stopRetry();
9532
- } else if (outcome === "failed") scheduleRetry(currentGeneration);
10606
+ }
10607
+ return value;
10608
+ }, (error) => {
10609
+ if (flight.generation === generation) {
10610
+ refreshStatus = signal?.aborted ? "idle" : "failed";
10611
+ if (!signal?.aborted) scheduleRetry(flight.generation);
10612
+ }
10613
+ throw error;
10614
+ }).finally(() => {
10615
+ if (refreshing === flight) refreshing = void 0;
9533
10616
  });
9534
- refreshing = {
9535
- generation: currentGeneration,
9536
- promise,
9537
- cancel: () => controller.abort()
9538
- };
9539
- return promise;
10617
+ return flight.promise;
9540
10618
  };
9541
10619
  return Object.freeze({
10620
+ initialize,
9542
10621
  refresh,
9543
10622
  getModels: () => models ?? [],
9544
- metadata: (modelId) => metadata.get(modelId),
9545
- reviewModel: (parentId) => officialReviewModel(rawCatalog, parentId),
10623
+ metadata: (id) => metadata.get(id),
10624
+ reviewModel: (id) => officialReviewModel(rawCatalog, id),
9546
10625
  revision: () => revision,
9547
10626
  capabilityGaps: () => [...metadata.values()].filter((model) => model.unsupported && /^[a-z][a-z0-9._-]{0,79}$/u.test(model.id)).slice(0, 20).map((model) => ({
9548
10627
  model: model.id,
9549
10628
  ...structuredClone(model.unsupported)
9550
10629
  })),
9551
10630
  status: () => ({
9552
- source: models === void 0 ? "unavailable" : "online",
10631
+ source,
9553
10632
  refresh: refreshStatus
9554
10633
  }),
10634
+ flushCache: () => Promise.all([...writes].map((flight) => flight.promise.catch(() => {}))),
9555
10635
  clear() {
9556
10636
  generation += 1;
9557
- const flight = refreshing;
9558
- refreshing = void 0;
9559
- flight?.cancel();
10637
+ writeSequence += 1;
10638
+ initializing?.controller.abort(cancelled());
10639
+ refreshing?.controller.abort(cancelled());
10640
+ for (const flight of writes) flight.controller.abort(cancelled());
10641
+ initializing = refreshing = void 0;
9560
10642
  stopRetry();
9561
10643
  retries = 0;
9562
- models = void 0;
9563
- rawCatalog = void 0;
10644
+ initialized = false;
10645
+ models = rawCatalog = etag = accountId = void 0;
9564
10646
  metadata = /* @__PURE__ */ new Map();
9565
- etag = void 0;
10647
+ source = "unavailable";
9566
10648
  refreshStatus = "idle";
9567
10649
  revision += 1;
9568
- options.onUpdated?.();
10650
+ notify();
9569
10651
  }
9570
10652
  });
9571
10653
  }
9572
- //#endregion
9573
- //#region src/deepseek-account-search.js
9574
- const DSH_ACCOUNT_SEARCH_PROVIDER_ID = "codex-subscription-dsh";
9575
- const DEFAULT_BASE_URL = "https://api.deepseek.com/v1/tools";
9576
- const DEFAULT_COUNT = 10;
9577
- const MAX_QUESTION = 128;
9578
- const record$6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
9579
- const missing = (message) => new WebError(message, "WEB_PROVIDER_CREDENTIAL_MISSING");
9580
- function parseSources(value) {
9581
- if (!record$6(value) || !Array.isArray(value.results)) throw new WebError("DeepSeek returned an invalid search response", "WEB_PROVIDER_ERROR");
9582
- return {
9583
- sources: value.results.flatMap((item) => {
9584
- if (!record$6(item) || typeof item.url !== "string" || item.url.length === 0) return [];
9585
- return [{
9586
- url: item.url,
9587
- ...typeof item.title === "string" && item.title.length > 0 ? { title: item.title } : {},
9588
- ...typeof item.snippet === "string" && item.snippet.length > 0 ? { snippet: item.snippet } : {},
9589
- ...typeof item.date === "string" && item.date.length > 0 ? { publishedAt: item.date } : {}
9590
- }];
9591
- }),
9592
- truncated: false
10654
+ /** Gate actual asynchronous adapter entry points, while keeping the provider registered. */
10655
+ function withModelCatalogReady(adapter, catalog, { signal: lifetime } = {}) {
10656
+ const ready = async (signal) => {
10657
+ const active = lifetime && signal ? AbortSignal.any([lifetime, signal]) : lifetime ?? signal;
10658
+ active?.throwIfAborted();
10659
+ await catalog.initialize({ signal: active });
10660
+ if (catalog.getModels().length === 0) await catalog.refresh({ signal: active });
10661
+ active?.throwIfAborted();
9593
10662
  };
10663
+ return new Proxy(adapter, { get(target, property) {
10664
+ const value = Reflect.get(target, property, target);
10665
+ if (typeof value === "function" && [
10666
+ "resolveModel",
10667
+ "prepareCall",
10668
+ "listModels"
10669
+ ].includes(property)) return async (...args) => {
10670
+ await ready(args[2]);
10671
+ return value.apply(target, args);
10672
+ };
10673
+ if (property === "stream" && typeof value === "function") return async function* (options) {
10674
+ await ready(options?.signal);
10675
+ yield* value.call(target, options);
10676
+ };
10677
+ return typeof value === "function" ? value.bind(target) : value;
10678
+ } });
9594
10679
  }
9595
- /**
9596
- * Search through DeepSeek's Search API with the signed-in DeepSeek account, for conversations whose
9597
- * model is not a DeepSeek Account one (DSH itself only hands the account token to those).
9598
- */
9599
- async function searchWithDeepSeekAccount(options, request, signal) {
9600
- signal?.throwIfAborted();
9601
- const account = options.resolveAccount?.();
9602
- if (typeof account?.resolveToken !== "function") throw missing("DeepSeek account sign-in is not available");
9603
- const config = options.resolveConfig?.() ?? {};
9604
- const baseURL = typeof config.baseURL === "string" && config.baseURL.length > 0 ? config.baseURL : DEFAULT_BASE_URL;
9605
- const count = Number.isInteger(config.count) && config.count > 0 ? config.count : DEFAULT_COUNT;
9606
- let endpoint;
9607
- try {
9608
- endpoint = `${new URL(baseURL).href.replace(/\/+$/u, "")}/search`;
9609
- } catch {
9610
- throw new WebError("DeepSeek search base URL is invalid", "WEB_PROVIDER_ERROR");
9611
- }
9612
- let token;
9613
- try {
9614
- token = await account.resolveToken(endpoint);
9615
- } catch {
9616
- throw missing("DeepSeek account sign-in could not be read");
9617
- }
9618
- if (typeof token !== "string" || token.length === 0) throw missing("DeepSeek account is not signed in");
9619
- const question = config.sendOriginalQuestion === false ? void 0 : Array.from((options.resolveQuestion?.() ?? "").replace(/\s+/gu, " ").trim()).slice(0, MAX_QUESTION).join("");
9620
- let response;
9621
- try {
9622
- response = await (options.fetch ?? fetch)(endpoint, {
9623
- method: "POST",
9624
- redirect: "error",
9625
- headers: {
9626
- "x-dsh-auth-token": token,
9627
- "content-type": "application/json",
9628
- accept: "application/json",
9629
- "user-agent": USER_AGENT
9630
- },
9631
- body: JSON.stringify({
9632
- query: request.query,
9633
- count: Math.min(count, request.maxResults ?? count),
9634
- need_content: false,
9635
- ...question ? { ori_question: question } : {}
9636
- }),
9637
- signal
9638
- });
9639
- } catch (error) {
9640
- if (signal?.aborted || error?.name === "AbortError") throw new WebError("DeepSeek web request aborted", "WEB_ABORTED", { cause: error });
9641
- throw new WebError("DeepSeek web request failed", "WEB_PROVIDER_ERROR", { cause: error });
9642
- }
9643
- if (!response.ok) throw response.status === 401 ? new WebError("DeepSeek rejected the account sign-in used for web search; sign in to DeepSeek again", "WEB_PROVIDER_ERROR") : new WebError(`DeepSeek search request failed (HTTP ${response.status})`, "WEB_PROVIDER_ERROR");
9644
- let body;
9645
- try {
9646
- body = await response.json();
9647
- } catch (error) {
9648
- throw new WebError("DeepSeek returned an unreadable search response", "WEB_PROVIDER_ERROR", { cause: error });
9649
- }
9650
- return parseSources(body);
9651
- }
9652
- /**
9653
- * The DSH search source with the account fallback: DSH's own provider goes first, and only when it
9654
- * reports a missing credential (no API key, model not a DeepSeek Account one) the account token is used.
9655
- */
9656
- function createDshAccountSearchProvider(options) {
10680
+ //#endregion
10681
+ //#region src/dsh-search.js
10682
+ const DSH_SEARCH_PROVIDER_ID = "codex-subscription-dsh";
10683
+ function createDshSearchProvider({ resolveDshProvider, report }) {
9657
10684
  return Object.freeze({
9658
- id: DSH_ACCOUNT_SEARCH_PROVIDER_ID,
10685
+ id: DSH_SEARCH_PROVIDER_ID,
9659
10686
  available: () => true,
9660
10687
  async search(request, signal) {
9661
- const provider = options.resolveDshProvider?.();
9662
- if (provider === void 0 || provider.id === "codex-subscription-dsh" || provider.available() !== true) throw new WebError("DSH default search is unavailable", "WEB_PROVIDER_UNAVAILABLE");
9663
- try {
9664
- const result = await provider.search(request, signal);
9665
- options.report?.(`answered by DSH provider ${provider.id}`);
9666
- return result;
9667
- } catch (error) {
9668
- if (error?.code !== "WEB_PROVIDER_CREDENTIAL_MISSING" || signal?.aborted) throw error;
9669
- try {
9670
- const result = await searchWithDeepSeekAccount(options, request, signal);
9671
- options.report?.("answered by DeepSeek account fallback");
9672
- return result;
9673
- } catch (fallback) {
9674
- options.report?.(`DeepSeek account fallback failed: ${fallback?.message}`);
9675
- throw fallback?.code === "WEB_PROVIDER_CREDENTIAL_MISSING" ? error : fallback;
9676
- }
9677
- }
10688
+ const provider = resolveDshProvider?.();
10689
+ if (!provider || provider.id === "codex-subscription-dsh" || provider.available() !== true) throw new WebError("DSH default search is unavailable", "WEB_PROVIDER_UNAVAILABLE");
10690
+ const result = await provider.search(request, signal);
10691
+ report?.(`answered by DSH provider ${provider.id}`);
10692
+ return result;
9678
10693
  }
9679
10694
  });
9680
10695
  }
@@ -9849,15 +10864,37 @@ function createCodexAutoSearchProvider(options) {
9849
10864
  const OWN_IDS = /* @__PURE__ */ new Set([
9850
10865
  CODEX_SEARCH_PROVIDER_ID,
9851
10866
  CODEX_AUTO_SEARCH_PROVIDER_ID,
9852
- DSH_ACCOUNT_SEARCH_PROVIDER_ID
10867
+ DSH_SEARCH_PROVIDER_ID
9853
10868
  ]);
10869
+ /** Guard the provider itself, including direct/cached handles and hosts without the registry proxy. */
10870
+ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
10871
+ const selected = () => {
10872
+ if (allowed()) return provider;
10873
+ const dsh = resolveDshProvider();
10874
+ if (!dsh || OWN_IDS.has(dsh.id) || dsh.available() !== true) throw new WebError("DSH default search is unavailable", "WEB_PROVIDER_UNAVAILABLE");
10875
+ return dsh;
10876
+ };
10877
+ return Object.freeze({
10878
+ id: provider.id,
10879
+ available: () => {
10880
+ try {
10881
+ return selected().available();
10882
+ } catch {
10883
+ return false;
10884
+ }
10885
+ },
10886
+ async search(request, signal) {
10887
+ return selected().search(request, signal);
10888
+ }
10889
+ });
10890
+ }
9854
10891
  /**
9855
10892
  * Routes web search by the plugin's "search source" setting without touching which provider DSH has configured.
9856
10893
  *
9857
10894
  * The provider the user (or DSH's own settings page) picked stays the configured one, so DSH's settings keep showing
9858
10895
  * and saving what the user chose (for example the new Search API switch). Only the lookup of that one provider at
9859
10896
  * search time answers with a small router that sends the search to the Codex subscription, to the configured provider
9860
- * (with the DeepSeek account fallback), or by the conversation's model.
10897
+ * without an extra account fallback, or by the conversation's model.
9861
10898
  *
9862
10899
  * @returns {Map|undefined} a stand-in for the web registry, or undefined when the registry is not a Map.
9863
10900
  */
@@ -9888,9 +10925,134 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
9888
10925
  return typeof value === "function" ? value.bind(target) : value;
9889
10926
  } });
9890
10927
  }
9891
- /** With subscription features switched off for other models, an explicit Codex choice becomes automatic: Codex models still use Codex search, every other model uses DSH search. */
9892
- function effectiveSearchMode(mode, otherModels) {
9893
- return mode === "codex" && otherModels === "off" ? "auto" : mode;
10928
+ //#endregion
10929
+ //#region src/codex-fetch.js
10930
+ const CODEX_FETCH_PROVIDER_ID = "codex-subscription-fetch";
10931
+ const MAX_CONTENT = 64e3;
10932
+ const httpUrl = (value) => {
10933
+ try {
10934
+ const url = new URL(value);
10935
+ return ["http:", "https:"].includes(url.protocol) && !url.username && !url.password ? url.href : void 0;
10936
+ } catch {
10937
+ return;
10938
+ }
10939
+ };
10940
+ /** Read public page text through Codex commands.open; never call another provider. */
10941
+ function createCodexFetchProvider(options) {
10942
+ const fetchPage = options.fetch ?? fetch;
10943
+ return Object.freeze({
10944
+ id: CODEX_FETCH_PROVIDER_ID,
10945
+ available: () => true,
10946
+ async fetch(request, signal) {
10947
+ signal?.throwIfAborted();
10948
+ if (options.allowed?.() === false) throw new WebError("Codex webpage reading is disabled for this model", "WEB_PROVIDER_UNAVAILABLE");
10949
+ const url = typeof request?.url === "string" && request.url.length <= 8192 ? httpUrl(request.url) : void 0;
10950
+ if (url === void 0) throw new WebError("Codex webpage reading requires an HTTP or HTTPS URL without credentials", "WEB_INVALID_URL");
10951
+ let credentials;
10952
+ try {
10953
+ credentials = await readSubscriptionCredentials(options.getAuth, options.readCredential, signal);
10954
+ } catch {
10955
+ if (signal?.aborted) throw new WebError("Codex webpage request aborted", "WEB_ABORTED");
10956
+ throw new WebError("Could not read ChatGPT subscription sign-in", "WEB_PROVIDER_CREDENTIAL_MISSING");
10957
+ }
10958
+ const { access, accountId } = credentials;
10959
+ if (typeof access !== "string" || !access || typeof accountId !== "string" || !accountId) throw new WebError("ChatGPT subscription is not signed in", "WEB_PROVIDER_CREDENTIAL_MISSING");
10960
+ const timeout = AbortSignal.timeout(options.timeoutMs ?? 3e4);
10961
+ const activeSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
10962
+ try {
10963
+ const response = await fetchPage(CODEX_SEARCH_URL, {
10964
+ method: "POST",
10965
+ redirect: "error",
10966
+ headers: {
10967
+ authorization: `Bearer ${access}`,
10968
+ "chatgpt-account-id": accountId,
10969
+ accept: "application/json",
10970
+ "content-type": "application/json",
10971
+ originator: "pi",
10972
+ "user-agent": USER_AGENT
10973
+ },
10974
+ body: JSON.stringify({
10975
+ id: options.resolveSessionId?.() || randomUUID(),
10976
+ model: options.resolveModel?.() || "gpt-5.6-luna",
10977
+ input: url,
10978
+ commands: {
10979
+ open: [{ ref_id: url }],
10980
+ response_length: "long"
10981
+ },
10982
+ settings: {
10983
+ allowed_callers: ["direct"],
10984
+ external_web_access: true
10985
+ },
10986
+ max_output_tokens: 4096
10987
+ }),
10988
+ signal: activeSignal
10989
+ });
10990
+ activeSignal.throwIfAborted();
10991
+ if (!response.ok) {
10992
+ const authFailure = await authFailureMessage(response);
10993
+ throw new WebError(authFailure ?? `Codex webpage request failed (HTTP ${response.status})`, authFailure === "ChatGPT sign-in needs to be renewed" ? "WEB_PROVIDER_CREDENTIAL_MISSING" : "WEB_PROVIDER_ERROR");
10994
+ }
10995
+ const value = await response.json();
10996
+ activeSignal.throwIfAborted();
10997
+ const source = Array.isArray(value?.results) ? value.results.find((item) => httpUrl(item?.url) !== void 0 && item?.type !== "error" && item?.title !== "Internal Error") : void 0;
10998
+ const output = typeof value?.output === "string" ? value.output : "";
10999
+ const heading = output.split(/\r?\n/u, 1)[0].trim();
11000
+ const headingUrl = heading.endsWith(")") ? httpUrl(heading.slice(heading.lastIndexOf(" (") + 2, -1)) : void 0;
11001
+ const metadata = output.slice(0, 1024);
11002
+ const pageUrl = source ? httpUrl(source.url) : headingUrl && /Content type:/u.test(metadata) && /Source: open\(/u.test(metadata) ? headingUrl : void 0;
11003
+ if (!pageUrl || output.trim() === "" || /^Internal Error(?:\s|\()/iu.test(heading)) throw new WebError("Codex could not read this webpage", "WEB_PROVIDER_ERROR");
11004
+ const lineCount = Number(metadata.match(/Total lines: (\d+)/u)?.[1]);
11005
+ const shownLines = new Set([...output.matchAll(/^L(\d+):/gmu)].map((match) => Number(match[1]))).size;
11006
+ const partialPage = Number.isSafeInteger(lineCount) && lineCount > 0 && shownLines > 0 && shownLines < lineCount;
11007
+ return {
11008
+ url: pageUrl,
11009
+ statusCode: 200,
11010
+ body: {
11011
+ kind: "text",
11012
+ content: output.slice(0, MAX_CONTENT)
11013
+ },
11014
+ truncated: output.length > MAX_CONTENT || partialPage
11015
+ };
11016
+ } catch (error) {
11017
+ if (signal?.aborted || error?.name === "AbortError") throw new WebError("Codex webpage request aborted", "WEB_ABORTED");
11018
+ if (activeSignal.aborted) throw new WebError("Codex webpage request timed out", "WEB_FETCH_TIMEOUT");
11019
+ if (error instanceof WebError) throw error;
11020
+ throw new WebError("Codex webpage request failed", "WEB_PROVIDER_ERROR");
11021
+ }
11022
+ }
11023
+ });
11024
+ }
11025
+ /** Preserve DSH's configured fetch provider; only an explicit plugin choice changes dispatch. */
11026
+ function createCodexFetchRouter({ registry, configuredId, mode, codex }) {
11027
+ if (!(registry instanceof Map)) return void 0;
11028
+ const wrappers = /* @__PURE__ */ new Map();
11029
+ const wrapper = (id) => {
11030
+ if (!wrappers.has(id)) wrappers.set(id, Object.freeze({
11031
+ id,
11032
+ available: () => mode() === "codex",
11033
+ fetch(request, signal) {
11034
+ if (mode() !== "codex") throw new WebError("Codex webpage reading is no longer selected", "WEB_PROVIDER_UNAVAILABLE");
11035
+ return codex.fetch(request, signal);
11036
+ }
11037
+ }));
11038
+ return wrappers.get(id);
11039
+ };
11040
+ return new Proxy(registry, { get(target, property) {
11041
+ if (property === "get") return (id) => mode() === "codex" && id === configuredId() ? wrapper(id) : target.get(id);
11042
+ if (property === "values" && mode() === "codex" && configuredId() === void 0) return () => [wrapper(CODEX_FETCH_PROVIDER_ID)].values();
11043
+ const value = Reflect.get(target, property, target);
11044
+ return typeof value === "function" ? value.bind(target) : value;
11045
+ } });
11046
+ }
11047
+ /** Match the runtime's live volatile selection and constructor-time env snapshot. */
11048
+ function configuredFetchProviderId(web, entries = [], ambient = process.env.DSH_WEB_FETCH_PROVIDER) {
11049
+ if ("fetchProviderId" in web) return web.fetchProviderId;
11050
+ const environment = "fetchProviderEnv" in web ? web.fetchProviderEnv : ambient;
11051
+ if (typeof web.config?.fetchProvider?.get === "function") return web.config.fetchProvider.get() ?? environment;
11052
+ const entry = [...entries].find((item) => item.options?.id === "web");
11053
+ const value = entry?.fiber?.config?.fetchProvider;
11054
+ if (typeof value?.get === "function") return value.get() ?? environment;
11055
+ return value ?? entry?.options?.config?.fetchProvider ?? environment;
9894
11056
  }
9895
11057
  //#endregion
9896
11058
  //#region src/image-tool-registration.js
@@ -10133,6 +11295,7 @@ const areas = {
10133
11295
  search: "search",
10134
11296
  image: "images",
10135
11297
  model: "transport",
11298
+ voice: "transport",
10136
11299
  login: "account",
10137
11300
  "quota-reset": "quota"
10138
11301
  };
@@ -10199,8 +11362,8 @@ function capabilityCoverage({ account, preference, runtime, catalog, tools, stor
10199
11362
  readiness = runtime.installed && !runtime.restartRequired ? "pass" : "warn";
10200
11363
  reason = runtime.restartRequired ? "restart-required" : runtime.installed ? "runtime-present" : "runtime-missing";
10201
11364
  } else if (id === "models" && catalog) {
10202
- readiness = catalog.source === "online" ? "pass" : "warn";
10203
- reason = catalog.source === "online" ? "catalog-online" : "catalog-unavailable";
11365
+ readiness = catalog.source === "online" || catalog.source === "cached" ? "pass" : "warn";
11366
+ reason = catalog.source === "online" ? "catalog-online" : catalog.source === "cached" ? "catalog-cached" : "catalog-unavailable";
10204
11367
  } else if (id === "storage" && storage?.readable) {
10205
11368
  readiness = "pass";
10206
11369
  reason = "storage-readable";
@@ -10345,7 +11508,8 @@ const requestAreas = /* @__PURE__ */ new Set([
10345
11508
  "quota",
10346
11509
  "quota-reset",
10347
11510
  "search",
10348
- "image"
11511
+ "image",
11512
+ "voice"
10349
11513
  ]);
10350
11514
  const statuses = /* @__PURE__ */ new Set(["ok", "failed"]);
10351
11515
  const stages = /* @__PURE__ */ new Set(["transport", "http"]);
@@ -10606,7 +11770,11 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
10606
11770
  ...collected.compaction ? { compaction: collected.compaction } : {},
10607
11771
  ...collected.review ? { review: collected.review } : {},
10608
11772
  ...collected.streamFailure ? { streamFailure: collected.streamFailure } : {},
10609
- ...catalog && ["unavailable", "online"].includes(catalog.source) && [
11773
+ ...catalog && [
11774
+ "unavailable",
11775
+ "cached",
11776
+ "online"
11777
+ ].includes(catalog.source) && [
10610
11778
  "idle",
10611
11779
  "refreshing",
10612
11780
  "ok",
@@ -11042,7 +12210,7 @@ const timestamp = (value) => {
11042
12210
  const parsed = typeof value === "string" ? Date.parse(value) : NaN;
11043
12211
  return Number.isFinite(parsed) ? parsed : void 0;
11044
12212
  };
11045
- const percent = (basisPoints) => Number.isFinite(basisPoints) && basisPoints >= 0 ? Math.round(basisPoints) / 100 : void 0;
12213
+ const percent = (basisPoints) => Number.isFinite(basisPoints) && basisPoints >= 0 ? basisPoints / 100 : void 0;
11046
12214
  /** Reduce the provider payload to a browser-safe projection; anything malformed is dropped, never an error. */
11047
12215
  function parsePlanHistory(value) {
11048
12216
  if (!record$3(value) || !Array.isArray(value.periods)) throw new Error("Codex returned a malformed usage history");
@@ -11768,12 +12936,19 @@ function refineQuotaRate(samples, conservative) {
11768
12936
  }
11769
12937
  if (crossings < 3) return conservative;
11770
12938
  const candidate = quotaSharedOffsetInterval(samples);
11771
- if (!candidate.feasible || candidate.min <= 0) return conservative;
11772
- if (candidate.max - candidate.min >= conservative.max - conservative.min) return conservative;
12939
+ if (!candidate.feasible) return {
12940
+ ...conservative,
12941
+ steadyHypothesisFailed: true
12942
+ };
12943
+ if (candidate.min <= 0 || candidate.max - candidate.min >= conservative.max - conservative.min) return {
12944
+ ...conservative,
12945
+ steadyHypothesisFailed: false
12946
+ };
11773
12947
  return {
11774
12948
  ...candidate,
11775
12949
  method: "shared-offset",
11776
- maxLagMs: 12e4
12950
+ maxLagMs: 12e4,
12951
+ steadyHypothesisFailed: false
11777
12952
  };
11778
12953
  }
11779
12954
  //#endregion
@@ -11840,14 +13015,15 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
11840
13015
  status: "calibrating",
11841
13016
  reason: "stale"
11842
13017
  };
11843
- let bounds = quotaRateInterval(samples);
13018
+ const rateBounds = (readings) => refineQuotaRate(readings, quotaRateInterval(readings));
13019
+ const contradicted = (range) => !range.feasible || range.steadyHypothesisFailed === true || range.min > 1e-9 && range.max - range.min <= 1e-9;
13020
+ let bounds = rateBounds(samples);
11844
13021
  let changedIntensity = false;
11845
- while (!bounds.feasible && samples.length > 3) {
13022
+ while (contradicted(bounds) && samples.length > 3) {
11846
13023
  samples = samples.slice(1);
11847
- bounds = quotaRateInterval(samples);
13024
+ bounds = rateBounds(samples);
11848
13025
  changedIntensity = true;
11849
13026
  }
11850
- bounds = refineQuotaRate(samples, bounds);
11851
13027
  const spanMs = samples.at(-1).at - samples[0].at;
11852
13028
  const common = {
11853
13029
  sampleCount: samples.length,
@@ -11858,7 +13034,8 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
11858
13034
  changedIntensity,
11859
13035
  rateMethod: bounds.method ?? "conservative"
11860
13036
  };
11861
- if (!bounds.feasible) return {
13037
+ const integerReports = samples.every((sample) => Number.isInteger(sample.remainingPercent));
13038
+ if (contradicted(bounds) || changedIntensity && (samples.length < 4 || spanMs < 20 * 6e4 || integerReports && bounds.steadyHypothesisFailed !== false)) return {
11862
13039
  ...common,
11863
13040
  status: "calibrating",
11864
13041
  reason: "changing-pace"
@@ -11868,17 +13045,16 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
11868
13045
  status: "calibrating",
11869
13046
  reason: "stale"
11870
13047
  };
11871
- if (spanMs >= 5 * 6e4 && samples.length >= 3 && bounds.min <= 1e-9 && common.consumedPercent >= 1) {
13048
+ if (spanMs >= 5 * 6e4 && samples.length >= 3 && (changedIntensity || bounds.min <= 1e-9) && common.consumedPercent >= 1) {
11872
13049
  const pacePerHour = common.consumedPercent / (spanMs / HOUR_MS);
11873
13050
  const runwaySeconds = clampPercent(window.remainingPercent) / pacePerHour * 3600;
11874
- const untilReset = resetsAt === null ? null : resetsAt - now / 1e3;
11875
13051
  return {
11876
13052
  ...common,
11877
13053
  status: "ready",
11878
13054
  provisional: true,
11879
13055
  pacePerHour,
11880
13056
  runwaySeconds,
11881
- survivesReset: untilReset !== null && runwaySeconds >= untilReset
13057
+ survivesReset: false
11882
13058
  };
11883
13059
  }
11884
13060
  if (spanMs < 6e4 || bounds.min <= 1e-9) return {
@@ -12471,7 +13647,8 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
12471
13647
  sessionId: payload.sessionId,
12472
13648
  sdp: payload.sdp,
12473
13649
  voice: current.voiceVoice,
12474
- language: current.voiceLanguage
13650
+ language: current.voiceLanguage,
13651
+ signal
12475
13652
  })
12476
13653
  };
12477
13654
  } catch (error) {
@@ -12483,16 +13660,20 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
12483
13660
  if (!voicePreview) return publicError("unavailable", "Voice preview is unavailable");
12484
13661
  if (endpoint === "voice/catalog") return {
12485
13662
  ok: true,
12486
- value: { voices: await voicePreview.available(payload?.language) }
13663
+ value: { voices: await voicePreview.available(payload?.language, signal) }
12487
13664
  };
12488
- const value = await voicePreview.preview(payload?.voice, payload?.language);
13665
+ const value = await voicePreview.preview(payload?.voice, payload?.language, signal);
12489
13666
  return value === void 0 ? publicError("not-found", "No sample for this voice") : {
12490
13667
  ok: true,
12491
13668
  value
12492
13669
  };
12493
13670
  } catch (error) {
12494
13671
  if (signal.aborted) throw error;
12495
- return publicError("operation-error", "Could not load the voice sample");
13672
+ return publicError([
13673
+ "voice-auth",
13674
+ "voice-catalog",
13675
+ "voice-download"
13676
+ ].includes(error?.code) ? error.code : "operation-error", "Could not load the voice sample");
12496
13677
  }
12497
13678
  if ([
12498
13679
  "remote/status",
@@ -12750,7 +13931,9 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
12750
13931
  ];
12751
13932
  if (endpoint === "logout") tasks.push(() => usageReader.clear(), () => accountUsageReader?.clear());
12752
13933
  if (endpoint === "account/remove" && typeof payload?.id === "string") tasks.push(() => usageReader.clearScope(payload.id));
12753
- if ((await Promise.allSettled(tasks.map((task) => Promise.resolve().then(task)))).some((value) => value.status === "rejected")) try {
13934
+ const outcomes = await Promise.allSettled(tasks.map((task) => Promise.resolve().then(task)));
13935
+ const catalogOutcomes = endpoint === "logout" ? [] : await Promise.allSettled([Promise.resolve().then(() => modelCatalog?.initialize())]);
13936
+ if ([...outcomes, ...catalogOutcomes].some((value) => value.status === "rejected")) try {
12754
13937
  onCleanupFailure?.();
12755
13938
  } catch {}
12756
13939
  if (endpoint !== "logout") Promise.resolve().then(() => modelCatalog?.refresh({ signal: void 0 })).catch(() => {});
@@ -12764,6 +13947,7 @@ const BASE = "https://chatgpt.com/backend-api";
12764
13947
  const CATALOG_TTL_MS = 10 * 6e4;
12765
13948
  const MAX_CLIP_BYTES = 2 * 1024 * 1024;
12766
13949
  const PREVIEW_HOSTS = /^https:\/\/[a-z0-9.-]*oaistatic\.com\//u;
13950
+ const failure = (code, message) => Object.assign(new Error(message), { code });
12767
13951
  function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, base = BASE }) {
12768
13952
  const catalogs = /* @__PURE__ */ new Map();
12769
13953
  const clips = /* @__PURE__ */ new Map();
@@ -12771,21 +13955,33 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
12771
13955
  const language = normalizeVoiceLanguage(value);
12772
13956
  return language === "auto" ? "en" : language;
12773
13957
  };
12774
- const readCatalog = async (language) => {
13958
+ const readCatalog = async (language, signal) => {
13959
+ signal?.throwIfAborted();
12775
13960
  const catalog = catalogs.get(language);
12776
13961
  if (catalog && now() - catalog.at < CATALOG_TTL_MS) return catalog.voices;
12777
- const { access, accountId } = await credentials();
12778
- const response = await fetch(`${base}/settings/voices?spoken_language=${language}`, {
12779
- headers: {
12780
- authorization: `Bearer ${access}`,
12781
- "chatgpt-account-id": accountId,
12782
- accept: "application/json",
12783
- "user-agent": userAgent
12784
- },
12785
- signal: AbortSignal.timeout(15e3)
12786
- });
12787
- if (!response.ok) throw new Error(`voice catalog HTTP ${response.status}`);
12788
- const value = await response.json();
13962
+ let value;
13963
+ try {
13964
+ const { access, accountId } = await credentials(signal);
13965
+ if (!access || !accountId) throw failure("voice-auth", "ChatGPT sign-in is required");
13966
+ const response = await fetch(`${base}/settings/voices?spoken_language=${language}`, {
13967
+ headers: {
13968
+ authorization: `Bearer ${access}`,
13969
+ "chatgpt-account-id": accountId,
13970
+ accept: "application/json",
13971
+ "user-agent": userAgent
13972
+ },
13973
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3)
13974
+ });
13975
+ if (response.status === 401) throw failure("voice-auth", "ChatGPT sign-in needs renewal");
13976
+ if (!response.ok) throw failure("voice-catalog", `voice catalog HTTP ${response.status}`);
13977
+ value = await response.json();
13978
+ if (!Array.isArray(value?.voices)) throw failure("voice-catalog", "Invalid voice catalog");
13979
+ signal?.throwIfAborted();
13980
+ } catch (error) {
13981
+ signal?.throwIfAborted();
13982
+ if (error?.code === "voice-auth" || error?.code === "voice-catalog") throw error;
13983
+ throw failure("voice-catalog", "Could not load the voice catalog");
13984
+ }
12789
13985
  const voices = (Array.isArray(value?.voices) ? value.voices : []).filter((entry) => typeof entry?.name === "string" && typeof entry?.preview_url === "string" && PREVIEW_HOSTS.test(entry.preview_url));
12790
13986
  catalogs.set(language, {
12791
13987
  at: now(),
@@ -12795,21 +13991,29 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
12795
13991
  };
12796
13992
  return {
12797
13993
  /** Which voices ChatGPT's own catalog offers right now (lower-case names), so the settings can mark the others unavailable. */
12798
- async available(language) {
12799
- return (await readCatalog(languageOf(language))).map((entry) => entry.name.toLowerCase());
13994
+ async available(language, signal) {
13995
+ return (await readCatalog(languageOf(language), signal)).map((entry) => entry.name.toLowerCase());
12800
13996
  },
12801
13997
  /** The clip of one voice (by its Codex name, e.g. "spruce") as a data URL, with the catalog's description. */
12802
- async preview(voice, selectedLanguage) {
13998
+ async preview(voice, selectedLanguage, signal) {
13999
+ signal?.throwIfAborted();
12803
14000
  if (typeof voice !== "string" || !/^[a-z]{2,16}$/u.test(voice)) return void 0;
12804
14001
  const language = languageOf(selectedLanguage);
12805
14002
  const key = `${language}:${voice}`;
12806
14003
  if (clips.has(key)) return clips.get(key);
12807
- const entry = (await readCatalog(language)).find((item) => item.name.toLowerCase() === voice || item.voice === voice);
14004
+ const entry = (await readCatalog(language, signal)).find((item) => item.name.toLowerCase() === voice || item.voice === voice);
12808
14005
  if (!entry) return void 0;
12809
- const response = await fetch(entry.preview_url, { signal: AbortSignal.timeout(15e3) });
12810
- if (!response.ok) throw new Error(`voice sample HTTP ${response.status}`);
12811
- const bytes = Buffer.from(await response.arrayBuffer());
12812
- if (bytes.byteLength === 0 || bytes.byteLength > MAX_CLIP_BYTES) throw new Error("voice sample has an unexpected size");
14006
+ let bytes;
14007
+ try {
14008
+ const response = await fetch(entry.preview_url, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3) });
14009
+ if (!response.ok) throw failure("voice-download", `voice sample HTTP ${response.status}`);
14010
+ bytes = Buffer.from(await response.arrayBuffer());
14011
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_CLIP_BYTES) throw failure("voice-download", "voice sample has an unexpected size");
14012
+ signal?.throwIfAborted();
14013
+ } catch {
14014
+ signal?.throwIfAborted();
14015
+ throw failure("voice-download", "Could not download the voice sample");
14016
+ }
12813
14017
  const type = /\.mp3(?:$|\?)/u.test(entry.preview_url) ? "audio/mpeg" : "audio/mp4";
12814
14018
  const result = {
12815
14019
  name: entry.name,
@@ -12913,7 +14117,7 @@ const DSH_SEARCH_PROVIDER_FALLBACK = "deepseek-official";
12913
14117
  const SUBSCRIPTION_SEARCH_PROVIDER_IDS = /* @__PURE__ */ new Set([
12914
14118
  CODEX_SEARCH_PROVIDER_ID,
12915
14119
  CODEX_AUTO_SEARCH_PROVIDER_ID,
12916
- DSH_ACCOUNT_SEARCH_PROVIDER_ID
14120
+ DSH_SEARCH_PROVIDER_ID
12917
14121
  ]);
12918
14122
  const MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
12919
14123
  const REQUEST_IMAGE_PIXEL_BUDGET = 2048 * 2048;
@@ -12938,7 +14142,7 @@ function createSearchProviderSwitcher(loader) {
12938
14142
  searchProvider: provider
12939
14143
  }, true);
12940
14144
  };
12941
- const select = (selection) => writeProvider(selection === "codex" ? CODEX_SEARCH_PROVIDER_ID : selection === "auto" ? CODEX_AUTO_SEARCH_PROVIDER_ID : DSH_ACCOUNT_SEARCH_PROVIDER_ID);
14145
+ const select = (selection) => writeProvider(selection === "codex" ? CODEX_SEARCH_PROVIDER_ID : selection === "auto" ? CODEX_AUTO_SEARCH_PROVIDER_ID : DSH_SEARCH_PROVIDER_ID);
12942
14146
  return Object.freeze({
12943
14147
  dshProviderId,
12944
14148
  current,
@@ -13003,6 +14207,8 @@ function apply(ctx, config = {}) {
13003
14207
  ctx.effect(() => ctx.on?.("plugin-manager/install-state", (value) => runtimeManagement.progress(value)));
13004
14208
  const modelCatalog = createOfficialModelCatalog({
13005
14209
  onUpdated: () => ctx.llm.emitAdaptersUpdated?.(),
14210
+ onCacheError: (error) => ctx.logger?.debug?.("could not access the Codex model catalog cache (%s)", error?.code ?? error?.name ?? "unknown error"),
14211
+ cacheDirectory: dshHomePath("state", "codex-subscription", "model-catalog"),
13006
14212
  getAuth: (options) => resolveAuth(options),
13007
14213
  readCredential: (options) => store.read(PROVIDER, options),
13008
14214
  baseModels: () => baseProvider.getModels(),
@@ -13063,6 +14269,7 @@ function apply(ctx, config = {}) {
13063
14269
  catalog: modelCatalog,
13064
14270
  runNetwork: network.run
13065
14271
  });
14272
+ let fetchRouted = false;
13066
14273
  const preferences = {
13067
14274
  status: () => {
13068
14275
  const models = modelCatalog.getModels();
@@ -13081,6 +14288,8 @@ function apply(ctx, config = {}) {
13081
14288
  ...readCapabilitySettings(settings.get()),
13082
14289
  [QUICK_QUOTA_MODE_FIELD]: normalizeQuickQuotaMode(settings.get()[QUICK_QUOTA_MODE_FIELD], settings.get()[LEGACY_QUICK_QUOTA_FIELD]),
13083
14290
  [SEARCH_PROVIDER_FIELD]: settings.get()[SEARCH_PROVIDER_FIELD],
14291
+ [FETCH_PROVIDER_FIELD]: normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]),
14292
+ fetchRoutingAvailable: fetchRouted,
13084
14293
  [SPEED_MODE_FIELD]: settings.get()[SPEED_MODE_FIELD],
13085
14294
  [OUTPUT_VERBOSITY_FIELD]: normalizeOutputVerbosity(settings.get()[OUTPUT_VERBOSITY_FIELD]),
13086
14295
  [INPUT_IMAGE_DETAIL_FIELD]: normalizeInputImageDetail(settings.get()[INPUT_IMAGE_DETAIL_FIELD]),
@@ -13107,6 +14316,7 @@ function apply(ctx, config = {}) {
13107
14316
  };
13108
14317
  },
13109
14318
  update: async (patch) => {
14319
+ if (patch["fetchProvider"] === "codex" && !fetchRouted) throw new Error("This DSH version does not support Codex webpage reading");
13110
14320
  if (Object.hasOwn(patch, "subagentBackend")) {
13111
14321
  if (!subagentBackend) throw new Error("DSH subagent services are unavailable");
13112
14322
  await subagentBackend.select(patch.subagentBackend);
@@ -13297,13 +14507,76 @@ function apply(ctx, config = {}) {
13297
14507
  ctx.effect(() => ctx.on?.("session/event", (_session, event) => {
13298
14508
  if (event?.type === "request/context") hiddenDirectory.dependenciesChanged();
13299
14509
  }), "codex-subscription: hidden model dependencies");
13300
- ctx.llm.registerAdapter([PROVIDER], hiddenDirectory.wrap(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(adapter)), provider)));
14510
+ ctx.effect(() => {
14511
+ const lifetime = new AbortController();
14512
+ const readyAdapter = withModelCatalogReady(hiddenDirectory.wrap(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(provider.wrapRetryAdapter(adapter))), provider)), modelCatalog, { signal: lifetime.signal });
14513
+ const disposeAdapter = ctx.llm.registerAdapter([PROVIDER], readyAdapter);
14514
+ Promise.resolve().then(() => modelCatalog.refresh({ signal: lifetime.signal })).catch((error) => {
14515
+ if (!lifetime.signal.aborted) ctx.logger?.debug?.("could not refresh Codex model catalog (%s)", error?.code ?? error?.name ?? "unknown error");
14516
+ });
14517
+ return () => {
14518
+ lifetime.abort();
14519
+ disposeAdapter?.();
14520
+ modelCatalog.clear();
14521
+ };
14522
+ }, "codex-subscription: official model catalog");
13301
14523
  const currentAgent = () => ctx.get?.("agents")?.currentInitiator?.();
14524
+ const codexFetch = createCodexFetchProvider({
14525
+ allowed: () => fetchRouted && (settings.get().otherModels !== "off" || currentAgent()?.session.requestContext?.()?.provider === PROVIDER),
14526
+ getAuth: resolveAuth,
14527
+ readCredential: (options) => store.read(PROVIDER, options),
14528
+ resolveModel: () => {
14529
+ const request = currentAgent()?.session.requestContext?.();
14530
+ return request?.provider === PROVIDER ? request.model : void 0;
14531
+ },
14532
+ resolveSessionId: () => currentAgent()?.session.id,
14533
+ fetch: (input, init) => network.fetch("search", input, init)
14534
+ });
14535
+ const realFetchProviders = ctx.web.fetchProviders;
14536
+ ctx.web.registerFetchProvider?.({
14537
+ ...codexFetch,
14538
+ available: () => fetchRouted && normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex"
14539
+ });
14540
+ ctx.effect(() => {
14541
+ const web = ctx.web;
14542
+ const configuredId = () => configuredFetchProviderId(web, ctx.loader.entries());
14543
+ const router = createCodexFetchRouter({
14544
+ registry: realFetchProviders,
14545
+ configuredId,
14546
+ mode: () => fetchRouted ? normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]) : "dsh",
14547
+ codex: codexFetch
14548
+ });
14549
+ if (router !== void 0) {
14550
+ try {
14551
+ web.fetchProviders = router;
14552
+ } catch {}
14553
+ fetchRouted = web.fetchProviders === router;
14554
+ }
14555
+ if (!fetchRouted) {
14556
+ diagnosticLog.warn("fetch", "Codex webpage reading is unavailable: DSH does not support fetch routing");
14557
+ if (normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex") {
14558
+ diagnosticLog.error("fetch", "Configured Codex webpage reading could not be activated; select DSH or update the host");
14559
+ throw new Error("Configured Codex webpage reading could not be activated; select DSH or update the host");
14560
+ }
14561
+ return;
14562
+ }
14563
+ diagnosticLog.info("fetch", "webpage reading is routed without replacing the configured DSH provider");
14564
+ return () => {
14565
+ fetchRouted = false;
14566
+ if (web.fetchProviders === router) web.fetchProviders = realFetchProviders;
14567
+ };
14568
+ }, "codex-subscription: fetch router");
13302
14569
  const servesCurrentModel = () => {
13303
14570
  if (settings.get().otherModels !== "off") return true;
13304
14571
  const provider = currentAgent()?.session.requestContext?.()?.provider;
13305
14572
  return provider === void 0 || provider === PROVIDER;
13306
14573
  };
14574
+ const realSearchProviders = ctx.web.searchProviders;
14575
+ const resolveDshSearch = () => realSearchProviders?.get(searchProvider.dshProviderId());
14576
+ const gateSearch = (provider) => gateSearchProvider(provider, {
14577
+ allowed: () => settings.get().otherModels !== "off" || currentAgent()?.session.requestContext?.()?.provider === PROVIDER,
14578
+ resolveDshProvider: resolveDshSearch
14579
+ });
13307
14580
  const codexSearch = createCodexSearchProvider({
13308
14581
  resolvePreferences: () => readCapabilitySettings(settings.get()),
13309
14582
  getAuth: resolveAuth,
@@ -13316,7 +14589,7 @@ function apply(ctx, config = {}) {
13316
14589
  fetch: (input, init) => network.fetch("search", input, init)
13317
14590
  });
13318
14591
  const searchTrace = (route) => diagnosticLog.info("search", `web search: ${route}`);
13319
- const tracedCodexSearch = Object.freeze({
14592
+ const tracedCodexSearch = gateSearch({
13320
14593
  id: codexSearch.id,
13321
14594
  available: () => codexSearch.available(),
13322
14595
  async search(request, signal) {
@@ -13326,25 +14599,16 @@ function apply(ctx, config = {}) {
13326
14599
  }
13327
14600
  });
13328
14601
  ctx.web.registerSearchProvider(tracedCodexSearch);
13329
- const realSearchProviders = ctx.web.searchProviders;
13330
- const dshSearch = createDshAccountSearchProvider({
14602
+ const dshSearch = gateSearch(createDshSearchProvider({
13331
14603
  report: searchTrace,
13332
- resolveDshProvider: () => realSearchProviders?.get(searchProvider.dshProviderId()),
13333
- resolveAccount: () => ctx.get?.("deepseekAccount"),
13334
- resolveConfig: () => {
13335
- const config = [...ctx.loader.entries()].find((entry) => entry.options?.id === "web-deepseek-api")?.options?.config;
13336
- return config !== null && typeof config === "object" ? config : {};
13337
- },
13338
- resolveQuestion: () => {
13339
- return (currentAgent()?.session.deriveMessages?.() ?? []).findLast((message) => message.role === "user" && message.source?.kind === "user")?.content?.flatMap((block) => block.type === "text" ? [block.text] : []).join(" ");
13340
- }
13341
- });
14604
+ resolveDshProvider: resolveDshSearch
14605
+ }));
13342
14606
  ctx.web.registerSearchProvider(dshSearch);
13343
- const autoSearch = createCodexAutoSearchProvider({
14607
+ const autoSearch = gateSearch(createCodexAutoSearchProvider({
13344
14608
  codex: tracedCodexSearch,
13345
14609
  resolveModelProvider: () => currentAgent()?.session.requestContext?.()?.provider,
13346
14610
  resolveDshProvider: () => dshSearch
13347
- });
14611
+ }));
13348
14612
  ctx.web.registerSearchProvider(autoSearch);
13349
14613
  let searchRouted = false;
13350
14614
  ctx.effect(() => {
@@ -13352,7 +14616,7 @@ function apply(ctx, config = {}) {
13352
14616
  const router = createSearchRouter({
13353
14617
  registry: realSearchProviders,
13354
14618
  configuredId: () => searchProvider.current(),
13355
- mode: () => effectiveSearchMode(settings.get()[SEARCH_PROVIDER_FIELD], settings.get().otherModels),
14619
+ mode: () => settings.get()[SEARCH_PROVIDER_FIELD],
13356
14620
  providers: {
13357
14621
  codex: tracedCodexSearch,
13358
14622
  auto: autoSearch,
@@ -13406,6 +14670,14 @@ function apply(ctx, config = {}) {
13406
14670
  permissions: () => ctx.get?.("permissionPresets"),
13407
14671
  workspaces: () => ctx.get?.("workspaceRegistry"),
13408
14672
  attachments: () => ctx.attachments,
14673
+ remoteImages: createRemoteImageAssets({
14674
+ credentials: ({ signal }) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
14675
+ ...options,
14676
+ signal
14677
+ }), signal),
14678
+ fetch: (input, init) => network.fetch("remote", input, init),
14679
+ stateFile: dshHomePath("state", "codex-subscription", "remote-images.json")
14680
+ }),
13409
14681
  usage: () => usageReader,
13410
14682
  usageProfile: () => usageProfileReader,
13411
14683
  projections: () => ctx.get?.("sessionProjections"),
@@ -13433,6 +14705,7 @@ function apply(ctx, config = {}) {
13433
14705
  }), signal)
13434
14706
  }
13435
14707
  });
14708
+ ctx.effect(() => () => remoteBridge.close());
13436
14709
  const remoteControl = createRemoteControl({
13437
14710
  credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
13438
14711
  ...options,
@@ -13602,7 +14875,7 @@ function apply(ctx, config = {}) {
13602
14875
  remoteControl,
13603
14876
  desktopVoice: withEndCallTool(remoteBridge.desktopVoice, (tool) => ctx.tools.register(tool)),
13604
14877
  voicePreview: createVoicePreview({
13605
- fetch: (input, init) => network.fetch("remote", input, init),
14878
+ fetch: (input, init) => network.fetch("voice", input, init, { standardHttps: true }),
13606
14879
  credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
13607
14880
  ...options,
13608
14881
  signal
@@ -13635,9 +14908,6 @@ function apply(ctx, config = {}) {
13635
14908
  resolveInheritedOriginal: (sessionId, assetId) => inheritedOriginalImageRef(ctx.get?.("sessions")?.get?.(sessionId), assetId)
13636
14909
  });
13637
14910
  const handler = diagnosticOperations.wrap((endpoint, payload, signal) => endpoint.startsWith("sketch/") ? sketchBridge.rpc(endpoint, payload) : subscriptionHandler(endpoint, payload, signal));
13638
- ctx.effect(() => {
13639
- modelCatalog.refresh().catch((error) => ctx.logger?.debug?.("could not refresh Codex model catalog: %s", error.message));
13640
- }, "codex-subscription: official model catalog");
13641
14911
  ctx.inject(["connection"], (connectionContext) => connectionContext.effect(() => registerSubscriptionTransport(connectionContext.connection, handler), "codex-subscription: DSH-trusted account RPC"));
13642
14912
  }
13643
14913
  //#endregion