dsh-codex-subscription 3.1.9 → 3.2.0

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
@@ -707,6 +707,11 @@ const PREFERENCE_FIELDS = Object.freeze({
707
707
  default: DEFAULT_REASONING_EFFORT,
708
708
  error: "Invalid default reasoning effort"
709
709
  },
710
+ composerPredictions: {
711
+ choices: ["off", "on"],
712
+ default: "off",
713
+ error: "Invalid input prediction setting"
714
+ },
710
715
  connectionMode: {
711
716
  choices: ["sse", "websocket"],
712
717
  default: "sse",
@@ -1288,6 +1293,7 @@ function createCodexNetworkTransport(options = {}) {
1288
1293
  routed = true;
1289
1294
  }
1290
1295
  });
1296
+ connection.signal?.throwIfAborted();
1291
1297
  if (value instanceof Response && !value.ok) remember(area, {
1292
1298
  status: "failed",
1293
1299
  stage: "http",
@@ -1303,6 +1309,7 @@ function createCodexNetworkTransport(options = {}) {
1303
1309
  });
1304
1310
  return value;
1305
1311
  } catch (error) {
1312
+ if (connection.signal?.aborted && connection.signal.reason?.name !== "TimeoutError") throw error;
1306
1313
  if (routed) remember(area, {
1307
1314
  status: "failed",
1308
1315
  stage: "transport",
@@ -1316,7 +1323,10 @@ function createCodexNetworkTransport(options = {}) {
1316
1323
  return Object.freeze({
1317
1324
  run,
1318
1325
  history: evidence.snapshot,
1319
- fetch: (area, input, init, connection) => run(area, () => globalThis.fetch(input, init), connection),
1326
+ fetch: (area, input, init, connection) => run(area, () => globalThis.fetch(input, init), {
1327
+ ...connection,
1328
+ signal: init?.signal ?? (input instanceof Request ? input.signal : void 0) ?? connection?.signal
1329
+ }),
1320
1330
  snapshot: () => Object.fromEntries([...attempts].map(([area, value]) => [area, { ...value }]))
1321
1331
  });
1322
1332
  }
@@ -2607,6 +2617,7 @@ const RPC_ENDPOINTS = Object.freeze([
2607
2617
  "preferences/update",
2608
2618
  "default-model/status",
2609
2619
  "default-model/select",
2620
+ "predictions/generate",
2610
2621
  "runtime/status",
2611
2622
  "runtime/install",
2612
2623
  "runtime/remove",
@@ -2850,7 +2861,8 @@ const SUPPORTED_RUNTIME_VERSIONS = Object.freeze([
2850
2861
  "0.2.1-rc.1",
2851
2862
  "0.2.1-rc.2",
2852
2863
  "0.2.1-rc.3",
2853
- "0.2.1-rc.4"
2864
+ "0.2.1-rc.4",
2865
+ "0.2.2-alpha.2"
2854
2866
  ]);
2855
2867
  const require = createRequire(import.meta.url);
2856
2868
  const execute = promisify(execFile);
@@ -3596,6 +3608,15 @@ const sketchCommandArray = {
3596
3608
  };
3597
3609
  //#endregion
3598
3610
  //#region src/subscription-credentials.js
3611
+ /** Step-time capability checks read the vault only; refreshing belongs to execution. */
3612
+ async function subscriptionCredentialReady(readCredential) {
3613
+ try {
3614
+ const value = await readCredential({});
3615
+ return value?.type === "oauth" && typeof value.access === "string" && value.access.length > 0 && typeof value.accountId === "string" && value.accountId.length > 0;
3616
+ } catch {
3617
+ return false;
3618
+ }
3619
+ }
3599
3620
  async function readSubscriptionCredentials(getAuth, readCredential, signal) {
3600
3621
  for (let attempt = 0; attempt < 2; attempt++) {
3601
3622
  const auth = await getAuth({ signal });
@@ -3642,8 +3663,9 @@ function originalImageRefsEqual(left, right) {
3642
3663
  /** Resolve only an exact original reference copied into a DSH fork prefix. */
3643
3664
  function inheritedOriginalImageRef(session, assetId) {
3644
3665
  const parentSession = session?.header?.parentSession;
3666
+ const forked = typeof parentSession === "string" && parentSession.length > 0 || session?.header?.isSeeded === true;
3645
3667
  const seedLength = session?.inheritedEventCount;
3646
- if (typeof parentSession !== "string" || parentSession.length === 0 || !Number.isSafeInteger(seedLength) || seedLength < 0 || !ORIGINAL_IMAGE_ID_PATTERN.test(assetId)) return void 0;
3668
+ if (!forked || !Number.isSafeInteger(seedLength) || seedLength < 0 || !ORIGINAL_IMAGE_ID_PATTERN.test(assetId)) return void 0;
3647
3669
  if (typeof session?.snapshotEvents !== "function") return void 0;
3648
3670
  let events;
3649
3671
  try {
@@ -3660,7 +3682,7 @@ function inheritedOriginalImageRef(session, assetId) {
3660
3682
  }
3661
3683
  //#endregion
3662
3684
  //#region src/version.js
3663
- const PACKAGE_VERSION = "3.1.9";
3685
+ const PACKAGE_VERSION = "3.2.0";
3664
3686
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
3665
3687
  //#endregion
3666
3688
  //#region src/codex-images.js
@@ -9727,8 +9749,32 @@ function createUltraExecutionPreset({ catalog, resolveAgent = () => void 0, defa
9727
9749
  };
9728
9750
  }
9729
9751
  //#endregion
9752
+ //#region src/host-session-sdk.js
9753
+ const id = "@deepseek-ai/dsh-session";
9754
+ const absent = (error) => error?.code === "MODULE_NOT_FOUND" && error.message?.startsWith(`Cannot find module '${id}'`);
9755
+ const loadSdk = (base) => {
9756
+ let resolved = base;
9757
+ try {
9758
+ resolved = realpathSync(base.startsWith("file:") ? new URL(base) : base);
9759
+ } catch (error) {
9760
+ if (error.code !== "ENOENT") throw error;
9761
+ }
9762
+ return createRequire(resolved)(id);
9763
+ };
9764
+ /** Session writers must come from the host's SDK: even equal-version copies have distinct private brands. */
9765
+ function loadHostSessionSdk({ entry = process.argv[1], local = import.meta.url, load = loadSdk } = {}) {
9766
+ for (const base of [typeof entry === "string" && isAbsolute(entry) ? entry : void 0, local]) {
9767
+ if (!base) continue;
9768
+ try {
9769
+ return load(base);
9770
+ } catch (error) {
9771
+ if (!absent(error)) throw error;
9772
+ }
9773
+ }
9774
+ }
9775
+ //#endregion
9730
9776
  //#region src/remote-image-assets.js
9731
- const BASE$1 = "https://chatgpt.com/backend-api/";
9777
+ const BASE$2 = "https://chatgpt.com/backend-api/";
9732
9778
  const FILE_ID = /^file[-_][A-Za-z0-9_-]{1,200}$/u;
9733
9779
  const HASH = /^[a-f0-9]{64}$/u;
9734
9780
  const hash = (value) => createHash("sha256").update(value).digest("hex");
@@ -9818,7 +9864,7 @@ function createRemoteImageAssets({ credentials, fetch: request = globalThis.fetc
9818
9864
  async function upload(bytes, mediaType, auth, owner, key, signal) {
9819
9865
  const api = async (method, path, body) => {
9820
9866
  signal.throwIfAborted();
9821
- const response = await send(BASE$1 + path, {
9867
+ const response = await send(BASE$2 + path, {
9822
9868
  method,
9823
9869
  redirect: "error",
9824
9870
  signal: AbortSignal.any([signal, AbortSignal.timeout(6e4)]),
@@ -11516,6 +11562,11 @@ function createDshSearchProvider({ resolveDshProvider, report }) {
11516
11562
  return Object.freeze({
11517
11563
  id: DSH_SEARCH_PROVIDER_ID,
11518
11564
  available: () => true,
11565
+ async ready(llmProvider) {
11566
+ const provider = resolveDshProvider?.();
11567
+ if (!provider || provider.id === "codex-subscription-dsh") return true;
11568
+ return await provider?.ready?.(llmProvider) ?? true;
11569
+ },
11519
11570
  async search(request, signal) {
11520
11571
  const provider = resolveDshProvider?.();
11521
11572
  if (!provider || provider.id === "codex-subscription-dsh" || provider.available() !== true) throw new WebError("DSH default search is unavailable", "WEB_PROVIDER_UNAVAILABLE");
@@ -11593,6 +11644,7 @@ function createCodexSearchProvider(options) {
11593
11644
  return Object.freeze({
11594
11645
  id: CODEX_SEARCH_PROVIDER_ID,
11595
11646
  available: () => true,
11647
+ ready: () => readCapabilitySettings(options.resolvePreferences?.()).searchMode === "disabled" ? false : subscriptionCredentialReady(options.readCredential),
11596
11648
  async search(request, signal) {
11597
11649
  signal?.throwIfAborted();
11598
11650
  const preferences = readCapabilitySettings(options.resolvePreferences?.());
@@ -11698,6 +11750,14 @@ function createCodexAutoSearchProvider(options) {
11698
11750
  return Object.freeze({
11699
11751
  id: CODEX_AUTO_SEARCH_PROVIDER_ID,
11700
11752
  available: () => true,
11753
+ async ready(llmProvider) {
11754
+ if (await options.codex.ready?.(llmProvider) ?? true) return true;
11755
+ try {
11756
+ return await dsh().ready?.(llmProvider) ?? true;
11757
+ } catch {
11758
+ return false;
11759
+ }
11760
+ },
11701
11761
  async search(request, signal) {
11702
11762
  const [first, second] = options.resolveModelProvider?.() === "openai-codex" ? [viaCodex, viaDsh] : [viaDsh, viaCodex];
11703
11763
  try {
@@ -11722,8 +11782,8 @@ const OWN_IDS = /* @__PURE__ */ new Set([
11722
11782
  ]);
11723
11783
  /** Guard the provider itself, including direct/cached handles and hosts without the registry proxy. */
11724
11784
  function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
11725
- const selected = () => {
11726
- if (allowed()) return provider;
11785
+ const selected = (llmProvider) => {
11786
+ if (allowed(llmProvider)) return provider;
11727
11787
  const dsh = resolveDshProvider();
11728
11788
  if (!dsh || OWN_IDS.has(dsh.id) || dsh.available() !== true) throw new WebError("DSH default search is unavailable", "WEB_PROVIDER_UNAVAILABLE");
11729
11789
  return dsh;
@@ -11737,6 +11797,13 @@ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
11737
11797
  return false;
11738
11798
  }
11739
11799
  },
11800
+ async ready(llmProvider) {
11801
+ try {
11802
+ return await selected(llmProvider).ready?.(llmProvider) ?? true;
11803
+ } catch {
11804
+ return false;
11805
+ }
11806
+ },
11740
11807
  async search(request, signal) {
11741
11808
  return selected().search(request, signal);
11742
11809
  }
@@ -11754,6 +11821,10 @@ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
11754
11821
  */
11755
11822
  function createSearchRouter({ registry, configuredId, mode, providers }) {
11756
11823
  if (!(registry instanceof Map)) return void 0;
11824
+ const selected = () => {
11825
+ const source = mode();
11826
+ return source === "codex" ? providers.codex : source === "auto" ? providers.auto : providers.dsh;
11827
+ };
11757
11828
  const wrappers = /* @__PURE__ */ new Map();
11758
11829
  const routerFor = (id) => {
11759
11830
  let router = wrappers.get(id);
@@ -11761,9 +11832,9 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
11761
11832
  router = Object.freeze({
11762
11833
  id,
11763
11834
  available: () => true,
11835
+ ready: (llmProvider) => selected().ready?.(llmProvider) ?? true,
11764
11836
  search(request, signal) {
11765
- const selected = mode();
11766
- return (selected === "codex" ? providers.codex : selected === "auto" ? providers.auto : providers.dsh).search(request, signal);
11837
+ return selected().search(request, signal);
11767
11838
  }
11768
11839
  });
11769
11840
  wrappers.set(id, router);
@@ -11783,6 +11854,12 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
11783
11854
  //#region src/codex-fetch.js
11784
11855
  const CODEX_FETCH_PROVIDER_ID = "codex-subscription-fetch";
11785
11856
  const MAX_CONTENT = 64e3;
11857
+ const RETRYABLE = /* @__PURE__ */ new Set([
11858
+ 500,
11859
+ 502,
11860
+ 503,
11861
+ 504
11862
+ ]);
11786
11863
  const httpUrl = (value) => {
11787
11864
  try {
11788
11865
  const url = new URL(value);
@@ -11797,6 +11874,7 @@ function createCodexFetchProvider(options) {
11797
11874
  return Object.freeze({
11798
11875
  id: CODEX_FETCH_PROVIDER_ID,
11799
11876
  available: () => true,
11877
+ ready: (llmProvider) => options.allowed?.(llmProvider) === false ? false : subscriptionCredentialReady(options.readCredential),
11800
11878
  async fetch(request, signal) {
11801
11879
  signal?.throwIfAborted();
11802
11880
  if (options.allowed?.() === false) throw new WebError("Codex webpage reading is disabled for this model", "WEB_PROVIDER_UNAVAILABLE");
@@ -11814,59 +11892,78 @@ function createCodexFetchProvider(options) {
11814
11892
  const timeout = AbortSignal.timeout(options.timeoutMs ?? 3e4);
11815
11893
  const activeSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
11816
11894
  try {
11817
- const response = await fetchPage(CODEX_SEARCH_URL, {
11818
- method: "POST",
11819
- redirect: "error",
11820
- headers: {
11821
- authorization: `Bearer ${access}`,
11822
- "chatgpt-account-id": accountId,
11823
- accept: "application/json",
11824
- "content-type": "application/json",
11825
- originator: "pi",
11826
- "user-agent": USER_AGENT
11827
- },
11828
- body: JSON.stringify({
11829
- id: options.resolveSessionId?.() || randomUUID(),
11830
- model: options.resolveModel?.() || "gpt-5.6-luna",
11831
- input: url,
11832
- commands: {
11833
- open: [{ ref_id: url }],
11834
- response_length: "long"
11895
+ for (let attempt = 1; attempt <= 2; attempt++) {
11896
+ const response = await fetchPage(CODEX_SEARCH_URL, {
11897
+ method: "POST",
11898
+ redirect: "error",
11899
+ headers: {
11900
+ authorization: `Bearer ${access}`,
11901
+ "chatgpt-account-id": accountId,
11902
+ accept: "application/json",
11903
+ "content-type": "application/json",
11904
+ originator: "pi",
11905
+ "user-agent": USER_AGENT
11835
11906
  },
11836
- settings: {
11837
- allowed_callers: ["direct"],
11838
- external_web_access: true
11907
+ body: JSON.stringify({
11908
+ id: options.resolveSessionId?.() || randomUUID(),
11909
+ model: options.resolveModel?.() || "gpt-5.6-luna",
11910
+ input: url,
11911
+ commands: {
11912
+ open: [{ ref_id: url }],
11913
+ response_length: "long"
11914
+ },
11915
+ settings: {
11916
+ allowed_callers: ["direct"],
11917
+ external_web_access: true
11918
+ },
11919
+ max_output_tokens: 4096
11920
+ }),
11921
+ signal: activeSignal
11922
+ });
11923
+ activeSignal.throwIfAborted();
11924
+ diagnosticLog.info("fetch", `Codex webpage HTTP ${response.status}`, `attempt=${attempt}`);
11925
+ if (!response.ok) {
11926
+ if (RETRYABLE.has(response.status) && attempt === 1) {
11927
+ await response.body?.cancel();
11928
+ await setTimeout$1(options.retryDelayMs ?? 250, void 0, { signal: activeSignal });
11929
+ continue;
11930
+ }
11931
+ const authFailure = await authFailureMessage(response);
11932
+ 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");
11933
+ }
11934
+ const value = await response.json();
11935
+ activeSignal.throwIfAborted();
11936
+ const source = Array.isArray(value?.results) ? value.results.find((item) => httpUrl(item?.url) !== void 0 && item?.type !== "error" && item?.title !== "Internal Error") : void 0;
11937
+ const output = typeof value?.output === "string" ? value.output : "";
11938
+ const heading = output.split(/\r?\n/u, 1)[0].trim();
11939
+ const headingUrl = heading.endsWith(")") ? httpUrl(heading.slice(heading.lastIndexOf(" (") + 2, -1)) : void 0;
11940
+ const metadata = output.slice(0, 1024);
11941
+ const pageUrl = source ? httpUrl(source.url) : headingUrl && /Content type:/u.test(metadata) && /Source: open\(/u.test(metadata) ? headingUrl : void 0;
11942
+ const internalError = /^Internal Error(?:\s|\(|$)/iu.test(heading);
11943
+ if (!pageUrl || output.trim() === "" || internalError) {
11944
+ if (attempt === 1 && !source && /^Internal Error(?:\s*\(\s*\))?\s*$/iu.test(heading) && !/non-retryable|not accessible|not safe|blocked|robots|forbidden|access denied/iu.test(output)) {
11945
+ diagnosticLog.warn("fetch", "Codex webpage service returned an internal error; retrying once");
11946
+ await setTimeout$1(options.retryDelayMs ?? 250, void 0, { signal: activeSignal });
11947
+ continue;
11948
+ }
11949
+ const upstreamTimeout = internalError && /(?:^|\n)Failed to fetch [^\n]*:\s*\(\d+\)\s*Timeout fetching/iu.test(output);
11950
+ diagnosticLog.warn("fetch", "Codex webpage text unavailable", upstreamTimeout ? "upstream-timeout" : internalError ? "upstream-error" : !pageUrl ? "missing-source" : "empty-output");
11951
+ if (upstreamTimeout) throw new WebError("Codex webpage service timed out fetching this page. Try another page, or change the webpage provider in settings.", "WEB_FETCH_TIMEOUT");
11952
+ throw new WebError("Codex could not read this webpage. Try another page, or change the webpage provider in settings.", "WEB_PROVIDER_ERROR");
11953
+ }
11954
+ const lineCount = Number(metadata.match(/Total lines: (\d+)/u)?.[1]);
11955
+ const shownLines = new Set([...output.matchAll(/^L(\d+):/gmu)].map((match) => Number(match[1]))).size;
11956
+ const partialPage = Number.isSafeInteger(lineCount) && lineCount > 0 && shownLines > 0 && shownLines < lineCount;
11957
+ return {
11958
+ url: pageUrl,
11959
+ statusCode: 200,
11960
+ body: {
11961
+ kind: "text",
11962
+ content: output.slice(0, MAX_CONTENT)
11839
11963
  },
11840
- max_output_tokens: 4096
11841
- }),
11842
- signal: activeSignal
11843
- });
11844
- activeSignal.throwIfAborted();
11845
- if (!response.ok) {
11846
- const authFailure = await authFailureMessage(response);
11847
- 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");
11964
+ truncated: output.length > MAX_CONTENT || partialPage
11965
+ };
11848
11966
  }
11849
- const value = await response.json();
11850
- activeSignal.throwIfAborted();
11851
- const source = Array.isArray(value?.results) ? value.results.find((item) => httpUrl(item?.url) !== void 0 && item?.type !== "error" && item?.title !== "Internal Error") : void 0;
11852
- const output = typeof value?.output === "string" ? value.output : "";
11853
- const heading = output.split(/\r?\n/u, 1)[0].trim();
11854
- const headingUrl = heading.endsWith(")") ? httpUrl(heading.slice(heading.lastIndexOf(" (") + 2, -1)) : void 0;
11855
- const metadata = output.slice(0, 1024);
11856
- const pageUrl = source ? httpUrl(source.url) : headingUrl && /Content type:/u.test(metadata) && /Source: open\(/u.test(metadata) ? headingUrl : void 0;
11857
- if (!pageUrl || output.trim() === "" || /^Internal Error(?:\s|\()/iu.test(heading)) throw new WebError("Codex could not read this webpage", "WEB_PROVIDER_ERROR");
11858
- const lineCount = Number(metadata.match(/Total lines: (\d+)/u)?.[1]);
11859
- const shownLines = new Set([...output.matchAll(/^L(\d+):/gmu)].map((match) => Number(match[1]))).size;
11860
- const partialPage = Number.isSafeInteger(lineCount) && lineCount > 0 && shownLines > 0 && shownLines < lineCount;
11861
- return {
11862
- url: pageUrl,
11863
- statusCode: 200,
11864
- body: {
11865
- kind: "text",
11866
- content: output.slice(0, MAX_CONTENT)
11867
- },
11868
- truncated: output.length > MAX_CONTENT || partialPage
11869
- };
11870
11967
  } catch (error) {
11871
11968
  if (signal?.aborted || error?.name === "AbortError") throw new WebError("Codex webpage request aborted", "WEB_ABORTED");
11872
11969
  if (activeSignal.aborted) throw new WebError("Codex webpage request timed out", "WEB_FETCH_TIMEOUT");
@@ -11884,6 +11981,7 @@ function createCodexFetchRouter({ registry, configuredId, mode, codex }) {
11884
11981
  if (!wrappers.has(id)) wrappers.set(id, Object.freeze({
11885
11982
  id,
11886
11983
  available: () => mode() === "codex",
11984
+ ready: (llmProvider) => mode() === "codex" && (codex.ready?.(llmProvider) ?? true),
11887
11985
  fetch(request, signal) {
11888
11986
  if (mode() !== "codex") throw new WebError("Codex webpage reading is no longer selected", "WEB_PROVIDER_UNAVAILABLE");
11889
11987
  return codex.fetch(request, signal);
@@ -12259,6 +12357,7 @@ const actions = Object.freeze({
12259
12357
  "account/remove": "accounts",
12260
12358
  "preferences/update": "settings",
12261
12359
  "account/cleanup": "accounts",
12360
+ "predictions/generate": "predictions",
12262
12361
  usage: "quota",
12263
12362
  "preferences/models": "models",
12264
12363
  "storage/status": "storage",
@@ -12272,7 +12371,8 @@ const actions = Object.freeze({
12272
12371
  const QUIET = /* @__PURE__ */ new Set([
12273
12372
  "usage",
12274
12373
  "storage/status",
12275
- "preferences/models"
12374
+ "preferences/models",
12375
+ "predictions/generate"
12276
12376
  ]);
12277
12377
  function safeOperations(raw) {
12278
12378
  if (!Array.isArray(raw?.events)) return void 0;
@@ -12315,6 +12415,7 @@ function createDiagnosticOperations({ now = Date.now } = {}) {
12315
12415
  });
12316
12416
  if (status === "failed") diagnosticLog.error(actions[action], `${action} failed`);
12317
12417
  else if (status === "completed" && !QUIET.has(action)) diagnosticLog.info(actions[action], `${action} completed`);
12418
+ else if (status === "cancelled" && action === "predictions/generate") diagnosticLog.info("predictions", "predictions/generate cancelled");
12318
12419
  if (events.length > 32) {
12319
12420
  events.shift();
12320
12421
  dropped++;
@@ -12325,6 +12426,14 @@ function createDiagnosticOperations({ now = Date.now } = {}) {
12325
12426
  wrap: (handler) => async (endpoint, payload, signal) => {
12326
12427
  try {
12327
12428
  const result = await handler(endpoint, payload, signal);
12429
+ if (endpoint === "predictions/generate" && result?.ok === true) {
12430
+ const reason = {
12431
+ disabled: "disabled",
12432
+ authentication: "not signed in",
12433
+ unavailable: "not available"
12434
+ }[result.value?.reason];
12435
+ diagnosticLog.info("predictions", result.value?.prediction ? "suggestion ready" : `no suggestion${reason ? `: ${reason}` : ""}`);
12436
+ }
12328
12437
  record(endpoint, result?.ok === true ? "completed" : "failed");
12329
12438
  return result;
12330
12439
  } catch (error) {
@@ -12689,6 +12798,64 @@ function highestUsed(windows) {
12689
12798
  return values.length === 0 ? void 0 : Math.max(...values);
12690
12799
  }
12691
12800
  //#endregion
12801
+ //#region src/shared-request.js
12802
+ /** Share one fetch per key while each caller owns only its own wait. */
12803
+ function createSharedRequests() {
12804
+ const flights = /* @__PURE__ */ new Map();
12805
+ const cancelled = () => new DOMException("Shared request cancelled", "AbortError");
12806
+ return {
12807
+ has: (key) => flights.has(key),
12808
+ clear(reason = cancelled()) {
12809
+ const previous = [...flights.values()];
12810
+ flights.clear();
12811
+ for (const flight of previous) flight.controller.abort(reason);
12812
+ },
12813
+ run(key, work, signal) {
12814
+ signal?.throwIfAborted();
12815
+ let flight = flights.get(key);
12816
+ if (!flight) {
12817
+ const controller = new AbortController();
12818
+ flight = {
12819
+ controller,
12820
+ waiters: 0,
12821
+ settled: false
12822
+ };
12823
+ flight.promise = Promise.resolve().then(() => {
12824
+ controller.signal.throwIfAborted();
12825
+ return work(controller.signal);
12826
+ }).then((value) => {
12827
+ controller.signal.throwIfAborted();
12828
+ return value;
12829
+ }).finally(() => {
12830
+ flight.settled = true;
12831
+ if (flights.get(key) === flight) flights.delete(key);
12832
+ });
12833
+ flights.set(key, flight);
12834
+ }
12835
+ flight.waiters++;
12836
+ return new Promise((resolve, reject) => {
12837
+ let done = false;
12838
+ const finish = (callback, value) => {
12839
+ if (done) return;
12840
+ done = true;
12841
+ signal?.removeEventListener("abort", abort);
12842
+ flight.controller.signal.removeEventListener("abort", abort);
12843
+ if (--flight.waiters === 0 && !flight.settled) {
12844
+ if (flights.get(key) === flight) flights.delete(key);
12845
+ flight.controller.abort(cancelled());
12846
+ }
12847
+ callback(value);
12848
+ };
12849
+ const abort = () => finish(reject, signal?.aborted ? signal.reason : flight.controller.signal.reason);
12850
+ signal?.addEventListener("abort", abort, { once: true });
12851
+ flight.controller.signal.addEventListener("abort", abort, { once: true });
12852
+ flight.promise.then((value) => finish(resolve, value), (error) => finish(reject, error));
12853
+ if (signal?.aborted || flight.controller.signal.aborted) abort();
12854
+ });
12855
+ }
12856
+ };
12857
+ }
12858
+ //#endregion
12692
12859
  //#region src/usage.js
12693
12860
  const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
12694
12861
  const DEFAULT_TIMEOUT_MS$1 = 15e3;
@@ -12880,8 +13047,8 @@ function createCodexUsageReader(options) {
12880
13047
  const maxRetryAfterMs = options.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS;
12881
13048
  let cached;
12882
13049
  let failed;
12883
- let inFlight;
12884
13050
  let generation = 0;
13051
+ const requests = createSharedRequests();
12885
13052
  const load = async (signal) => {
12886
13053
  const { access, accountId } = await readSubscriptionCredentials(getAuth, readCredential, signal);
12887
13054
  if (typeof access !== "string" || access.length === 0 || typeof accountId !== "string" || accountId.length === 0) throw new Error("ChatGPT subscription is not signed in");
@@ -12915,36 +13082,37 @@ function createCodexUsageReader(options) {
12915
13082
  };
12916
13083
  return Object.freeze({
12917
13084
  read({ force = false, signal } = {}) {
13085
+ if (signal?.aborted) return Promise.reject(signal.reason);
12918
13086
  if (failed !== void 0 && now() < failed.retryAt) return Promise.reject(new Error(failed.message));
12919
13087
  if (!force && cached !== void 0 && now() - cached.fetchedAt < ttlFor(cached)) return Promise.resolve(structuredClone(cached));
12920
- if (inFlight !== void 0) return inFlight.then(structuredClone);
12921
- const currentGeneration = generation;
12922
- const current = load(signal).then((value) => {
12923
- if (generation === currentGeneration) {
12924
- cached = structuredClone(value);
12925
- failed = void 0;
12926
- }
12927
- return structuredClone(value);
12928
- }).catch((error) => {
12929
- if (generation === currentGeneration && error?.name !== "AbortError") {
12930
- const delay = Number.isFinite(error?.retryAfterMs) ? error.retryAfterMs : failureTtlMs;
12931
- failed = {
12932
- message: error instanceof Error ? error.message : "ChatGPT usage request failed",
12933
- retryAt: now() + delay
12934
- };
13088
+ return requests.run("read", async (sharedSignal) => {
13089
+ const currentGeneration = generation;
13090
+ try {
13091
+ const value = await load(sharedSignal);
13092
+ sharedSignal.throwIfAborted();
13093
+ if (generation === currentGeneration) {
13094
+ cached = structuredClone(value);
13095
+ failed = void 0;
13096
+ }
13097
+ return value;
13098
+ } catch (error) {
13099
+ sharedSignal.throwIfAborted();
13100
+ if (generation === currentGeneration && error?.name !== "AbortError") {
13101
+ const delay = Number.isFinite(error?.retryAfterMs) ? error.retryAfterMs : failureTtlMs;
13102
+ failed = {
13103
+ message: error instanceof Error ? error.message : "ChatGPT usage request failed",
13104
+ retryAt: now() + delay
13105
+ };
13106
+ }
13107
+ throw error;
12935
13108
  }
12936
- throw error;
12937
- }).finally(() => {
12938
- if (inFlight === current) inFlight = void 0;
12939
- });
12940
- inFlight = current;
12941
- return current;
13109
+ }, signal).then(structuredClone);
12942
13110
  },
12943
13111
  clear() {
12944
13112
  generation += 1;
12945
13113
  cached = void 0;
12946
13114
  failed = void 0;
12947
- inFlight = void 0;
13115
+ requests.clear();
12948
13116
  }
12949
13117
  });
12950
13118
  }
@@ -13103,7 +13271,8 @@ function parsePlanHistory(value) {
13103
13271
  }
13104
13272
  /** Reads one authenticated report through the same credentials as the quota reader; a 404 means the account has no such report. */
13105
13273
  function createReportReader({ url, parse, label, getAuth, readCredential, fetch: fetchReport = fetch, now = Date.now, ttlMs = TTL_MS }) {
13106
- let cached, failed, inFlight, generation = 0;
13274
+ let cached, failed, generation = 0;
13275
+ const requests = createSharedRequests();
13107
13276
  const load = async (signal) => {
13108
13277
  const { access, accountId } = await readSubscriptionCredentials(getAuth, readCredential, signal);
13109
13278
  if (typeof access !== "string" || access.length === 0 || typeof accountId !== "string" || accountId.length === 0) throw new Error("ChatGPT subscription is not signed in");
@@ -13139,33 +13308,34 @@ function createReportReader({ url, parse, label, getAuth, readCredential, fetch:
13139
13308
  };
13140
13309
  return Object.freeze({
13141
13310
  read({ force = false, signal } = {}) {
13311
+ if (signal?.aborted) return Promise.reject(signal.reason);
13142
13312
  if (failed !== void 0 && now() < failed.retryAt) return Promise.reject(new Error(failed.message));
13143
- if (inFlight !== void 0) return inFlight.then(structuredClone);
13144
- if (!force && cached !== void 0 && now() - cached.fetchedAt < ttlMs) return Promise.resolve(structuredClone(cached));
13145
- const current = generation;
13146
- const run = load(signal).then((value) => {
13147
- if (generation === current) {
13148
- cached = structuredClone(value);
13149
- failed = void 0;
13313
+ if (!requests.has("read") && !force && cached !== void 0 && now() - cached.fetchedAt < ttlMs) return Promise.resolve(structuredClone(cached));
13314
+ return requests.run("read", async (sharedSignal) => {
13315
+ const current = generation;
13316
+ try {
13317
+ const value = await load(sharedSignal);
13318
+ sharedSignal.throwIfAborted();
13319
+ if (generation === current) {
13320
+ cached = structuredClone(value);
13321
+ failed = void 0;
13322
+ }
13323
+ return value;
13324
+ } catch (error) {
13325
+ sharedSignal.throwIfAborted();
13326
+ if (generation === current && error?.name !== "AbortError") failed = {
13327
+ message: error instanceof Error ? error.message : `ChatGPT ${label} request failed`,
13328
+ retryAt: now() + FAILURE_TTL_MS
13329
+ };
13330
+ throw error;
13150
13331
  }
13151
- return structuredClone(value);
13152
- }).catch((error) => {
13153
- if (generation === current && error?.name !== "AbortError") failed = {
13154
- message: error instanceof Error ? error.message : `ChatGPT ${label} request failed`,
13155
- retryAt: now() + FAILURE_TTL_MS
13156
- };
13157
- throw error;
13158
- }).finally(() => {
13159
- if (inFlight === run) inFlight = void 0;
13160
- });
13161
- inFlight = run;
13162
- return run;
13332
+ }, signal).then(structuredClone);
13163
13333
  },
13164
13334
  clear() {
13165
13335
  generation += 1;
13166
13336
  cached = void 0;
13167
13337
  failed = void 0;
13168
- inFlight = void 0;
13338
+ requests.clear();
13169
13339
  }
13170
13340
  });
13171
13341
  }
@@ -14445,8 +14615,18 @@ async function settlesLive(preferences, patch, signal, { attempts = 8, delayMs =
14445
14615
  }
14446
14616
  return live();
14447
14617
  }
14448
- function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageReader, planHistoryReader, usageProfileReader, resetCreditService, preferences, defaultModel, runtimeManagement, remoteControl, desktopVoice, nativeVoice, voicePreview, diagnosticsReader, modelCatalog, originalImages, resolveInheritedOriginal, closeConnections, onAccountChanged, onCleanupFailure }) {
14618
+ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageReader, planHistoryReader, usageProfileReader, resetCreditService, preferences, defaultModel, runtimeManagement, remoteControl, desktopVoice, nativeVoice, voicePreview, composerPredictions, diagnosticsReader, modelCatalog, originalImages, resolveInheritedOriginal, closeConnections, onAccountChanged, onCleanupFailure }) {
14449
14619
  return async (endpoint, payload, signal) => {
14620
+ if (endpoint === "predictions/generate") try {
14621
+ signal?.throwIfAborted();
14622
+ return {
14623
+ ok: true,
14624
+ value: composerPredictions ? await composerPredictions.generate(payload, signal) : { prediction: null }
14625
+ };
14626
+ } catch (error) {
14627
+ if (signal?.aborted) throw error;
14628
+ return publicError(error?.code === "invalid-input" ? "invalid-input" : "operation-error", "Could not generate an input prediction");
14629
+ }
14450
14630
  if (endpoint.startsWith("voice/native/")) try {
14451
14631
  signal.throwIfAborted();
14452
14632
  if (!nativeVoice) return publicError("voice-native-unavailable", "Native voice is unavailable");
@@ -14850,86 +15030,365 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
14850
15030
  }
14851
15031
  //#endregion
14852
15032
  //#region src/voice-preview.js
14853
- const BASE = "https://chatgpt.com/backend-api";
15033
+ const BASE$1 = "https://chatgpt.com/backend-api";
14854
15034
  const CATALOG_TTL_MS = 10 * 6e4;
14855
15035
  const MAX_CLIP_BYTES = 2 * 1024 * 1024;
15036
+ const MAX_CACHED_AUDIO_BYTES = 8 * 1024 * 1024;
14856
15037
  const PREVIEW_HOSTS = /^https:\/\/[a-z0-9.-]*oaistatic\.com\//u;
14857
15038
  const failure$1 = (code, message) => Object.assign(new Error(message), { code });
14858
- function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, base = BASE }) {
15039
+ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, base = BASE$1, maxCachedAudioBytes = MAX_CACHED_AUDIO_BYTES }) {
14859
15040
  const catalogs = /* @__PURE__ */ new Map();
14860
15041
  const clips = /* @__PURE__ */ new Map();
15042
+ const requests = createSharedRequests();
15043
+ const cacheLimit = Number.isSafeInteger(maxCachedAudioBytes) && maxCachedAudioBytes >= 0 ? maxCachedAudioBytes : MAX_CACHED_AUDIO_BYTES;
15044
+ let accountId, generation = 0, audioBytes = 0;
14861
15045
  const languageOf = (value) => {
14862
15046
  const language = normalizeVoiceLanguage(value);
14863
15047
  return language === "auto" ? "en" : language;
14864
15048
  };
14865
- const readCatalog = async (language, signal) => {
15049
+ const cancelled = () => new DOMException("Voice preview scope changed", "AbortError");
15050
+ const clear = () => {
15051
+ generation++;
15052
+ accountId = void 0;
15053
+ catalogs.clear();
15054
+ clips.clear();
15055
+ audioBytes = 0;
15056
+ requests.clear(cancelled());
15057
+ };
15058
+ const scope = async (signal) => {
15059
+ signal?.throwIfAborted();
15060
+ const current = generation, auth = await credentials(signal);
15061
+ signal?.throwIfAborted();
15062
+ if (current !== generation) throw cancelled();
15063
+ if (!auth?.access || !auth.accountId) {
15064
+ clear();
15065
+ throw failure$1("voice-auth", "ChatGPT sign-in is required");
15066
+ }
15067
+ if (accountId !== void 0 && accountId !== auth.accountId) clear();
15068
+ accountId = auth.accountId;
15069
+ return {
15070
+ ...auth,
15071
+ generation
15072
+ };
15073
+ };
15074
+ const readCatalog = async (auth, language, signal) => {
14866
15075
  signal?.throwIfAborted();
15076
+ if (auth.generation !== generation) throw cancelled();
14867
15077
  const catalog = catalogs.get(language);
14868
15078
  if (catalog && now() - catalog.at < CATALOG_TTL_MS) return catalog.voices;
14869
- let value;
14870
- try {
14871
- const { access, accountId } = await credentials(signal);
14872
- if (!access || !accountId) throw failure$1("voice-auth", "ChatGPT sign-in is required");
14873
- const response = await fetch(`${base}/settings/voices?spoken_language=${language}`, {
14874
- headers: {
14875
- authorization: `Bearer ${access}`,
14876
- "chatgpt-account-id": accountId,
14877
- accept: "application/json",
14878
- "user-agent": userAgent
14879
- },
14880
- signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3)
15079
+ return requests.run(`catalog:${language}`, async (sharedSignal) => {
15080
+ let value;
15081
+ try {
15082
+ const response = await fetch(`${base}/settings/voices?spoken_language=${language}`, {
15083
+ headers: {
15084
+ authorization: `Bearer ${auth.access}`,
15085
+ "chatgpt-account-id": auth.accountId,
15086
+ accept: "application/json",
15087
+ "user-agent": userAgent
15088
+ },
15089
+ signal: AbortSignal.any([sharedSignal, AbortSignal.timeout(15e3)])
15090
+ });
15091
+ if (response.status === 401) throw failure$1("voice-auth", "ChatGPT sign-in needs renewal");
15092
+ if (!response.ok) throw failure$1("voice-catalog", `voice catalog HTTP ${response.status}`);
15093
+ value = await response.json();
15094
+ if (!Array.isArray(value?.voices)) throw failure$1("voice-catalog", "Invalid voice catalog");
15095
+ sharedSignal.throwIfAborted();
15096
+ } catch (error) {
15097
+ sharedSignal.throwIfAborted();
15098
+ if (error?.code === "voice-auth" || error?.code === "voice-catalog") throw error;
15099
+ throw failure$1("voice-catalog", "Could not load the voice catalog");
15100
+ }
15101
+ 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));
15102
+ if (auth.generation !== generation) throw cancelled();
15103
+ catalogs.set(language, {
15104
+ at: now(),
15105
+ voices
14881
15106
  });
14882
- if (response.status === 401) throw failure$1("voice-auth", "ChatGPT sign-in needs renewal");
14883
- if (!response.ok) throw failure$1("voice-catalog", `voice catalog HTTP ${response.status}`);
14884
- value = await response.json();
14885
- if (!Array.isArray(value?.voices)) throw failure$1("voice-catalog", "Invalid voice catalog");
14886
- signal?.throwIfAborted();
14887
- } catch (error) {
14888
- signal?.throwIfAborted();
14889
- if (error?.code === "voice-auth" || error?.code === "voice-catalog") throw error;
14890
- throw failure$1("voice-catalog", "Could not load the voice catalog");
14891
- }
14892
- 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));
14893
- catalogs.set(language, {
14894
- at: now(),
14895
- voices
14896
- });
14897
- return voices;
15107
+ return voices;
15108
+ }, signal);
14898
15109
  };
14899
15110
  return {
15111
+ clear,
14900
15112
  /** Which voices ChatGPT's own catalog offers right now (lower-case names), so the settings can mark the others unavailable. */
14901
15113
  async available(language, signal) {
14902
- return (await readCatalog(languageOf(language), signal)).map((entry) => entry.name.toLowerCase());
15114
+ const auth = await scope(signal);
15115
+ const voices = await readCatalog(auth, languageOf(language), signal);
15116
+ signal?.throwIfAborted();
15117
+ if (auth.generation !== generation) throw cancelled();
15118
+ return voices.map((entry) => entry.name.toLowerCase());
14903
15119
  },
14904
15120
  /** The clip of one voice (by its Codex name, e.g. "spruce") as a data URL, with the catalog's description. */
14905
15121
  async preview(voice, selectedLanguage, signal) {
14906
15122
  signal?.throwIfAborted();
14907
15123
  if (typeof voice !== "string" || !/^[a-z]{2,16}$/u.test(voice)) return void 0;
15124
+ const auth = await scope(signal);
14908
15125
  const language = languageOf(selectedLanguage);
14909
- const key = `${language}:${voice}`;
14910
- if (clips.has(key)) return clips.get(key);
14911
- const entry = (await readCatalog(language, signal)).find((item) => item.name.toLowerCase() === voice || item.voice === voice);
15126
+ const entry = (await readCatalog(auth, language, signal)).find((item) => item.name.toLowerCase() === voice || item.voice === voice);
15127
+ signal?.throwIfAborted();
15128
+ if (auth.generation !== generation) throw cancelled();
14912
15129
  if (!entry) return void 0;
14913
- let bytes;
14914
- try {
14915
- const response = await fetch(entry.preview_url, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3) });
14916
- if (!response.ok) throw failure$1("voice-download", `voice sample HTTP ${response.status}`);
14917
- bytes = Buffer.from(await response.arrayBuffer());
14918
- if (bytes.byteLength === 0 || bytes.byteLength > MAX_CLIP_BYTES) throw failure$1("voice-download", "voice sample has an unexpected size");
14919
- signal?.throwIfAborted();
14920
- } catch {
14921
- signal?.throwIfAborted();
14922
- throw failure$1("voice-download", "Could not download the voice sample");
14923
- }
14924
- const type = /\.mp3(?:$|\?)/u.test(entry.preview_url) ? "audio/mpeg" : "audio/mp4";
14925
- const result = {
15130
+ const key = `${language}:${voice}:${entry.preview_url}`;
15131
+ let audio = clips.get(key);
15132
+ if (audio) {
15133
+ clips.delete(key);
15134
+ clips.set(key, audio);
15135
+ } else audio = await requests.run(`clip:${key}`, async (sharedSignal) => {
15136
+ let bytes;
15137
+ try {
15138
+ const response = await fetch(entry.preview_url, { signal: AbortSignal.any([sharedSignal, AbortSignal.timeout(15e3)]) });
15139
+ if (!response.ok) throw failure$1("voice-download", `voice sample HTTP ${response.status}`);
15140
+ bytes = Buffer.from(await response.arrayBuffer());
15141
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_CLIP_BYTES) throw failure$1("voice-download", "voice sample has an unexpected size");
15142
+ sharedSignal.throwIfAborted();
15143
+ } catch {
15144
+ sharedSignal.throwIfAborted();
15145
+ throw failure$1("voice-download", "Could not download the voice sample");
15146
+ }
15147
+ const value = `data:${/\.mp3(?:$|\?)/u.test(entry.preview_url) ? "audio/mpeg" : "audio/mp4"};base64,${bytes.toString("base64")}`;
15148
+ if (auth.generation !== generation) throw cancelled();
15149
+ if (value.length <= cacheLimit) {
15150
+ while (clips.size >= 40 || audioBytes + value.length > cacheLimit) {
15151
+ const oldest = clips.keys().next().value;
15152
+ if (oldest === void 0) break;
15153
+ audioBytes -= clips.get(oldest).length;
15154
+ clips.delete(oldest);
15155
+ }
15156
+ clips.set(key, value);
15157
+ audioBytes += value.length;
15158
+ }
15159
+ return value;
15160
+ }, signal);
15161
+ signal?.throwIfAborted();
15162
+ if (auth.generation !== generation) throw cancelled();
15163
+ return {
14926
15164
  name: entry.name,
14927
15165
  description: typeof entry.description === "string" ? entry.description.slice(0, 120) : "",
14928
15166
  accent: typeof entry.accent === "string" ? entry.accent.slice(0, 60) : "",
14929
- audio: `data:${type};base64,${bytes.toString("base64")}`
15167
+ audio
14930
15168
  };
14931
- if (clips.size < 40) clips.set(key, result);
14932
- return result;
15169
+ }
15170
+ };
15171
+ }
15172
+ //#endregion
15173
+ //#region src/composer-predictions.js
15174
+ const BASE = "https://chatgpt.com/backend-api";
15175
+ const MODELS = /* @__PURE__ */ new Set([
15176
+ "gpt-6-astra",
15177
+ "gpt-6.1-sol",
15178
+ "gpt-6.1-terra"
15179
+ ]);
15180
+ const invalid = () => Object.assign(/* @__PURE__ */ new Error("Invalid prediction request"), { code: "invalid-input" });
15181
+ const cancelled = () => new DOMException("Prediction scope changed", "AbortError");
15182
+ function predictionInput(value) {
15183
+ if (!value || !MODELS.has(value.model) || typeof value.sessionId !== "string" || !value.sessionId || value.sessionId.length > 512 || typeof value.turnId !== "string" || !value.turnId || value.turnId.length > 512 || !Array.isArray(value.messages) || value.messages.length < 2 || value.messages.length > 12) throw invalid();
15184
+ let length = 0;
15185
+ const messages = value.messages.map((message) => {
15186
+ if (!message || !["user", "assistant"].includes(message.role) || typeof message.text !== "string" || !message.text.trim()) throw invalid();
15187
+ length += message.text.length;
15188
+ return {
15189
+ role: message.role,
15190
+ text: message.text
15191
+ };
15192
+ });
15193
+ if (length > 24e3 || messages.at(-1).role !== "assistant" || !messages.some((message) => message.role === "user")) throw invalid();
15194
+ return {
15195
+ sessionId: value.sessionId,
15196
+ turnId: value.turnId,
15197
+ model: value.model,
15198
+ messages
15199
+ };
15200
+ }
15201
+ async function boundedText(response, limit) {
15202
+ if (!response.body) throw new Error("Empty prediction response");
15203
+ const reader = response.body.getReader(), chunks = [];
15204
+ let size = 0;
15205
+ try {
15206
+ while (true) {
15207
+ const { value, done } = await reader.read();
15208
+ if (done) break;
15209
+ size += value.byteLength;
15210
+ if (size > limit) {
15211
+ await reader.cancel();
15212
+ throw new Error("Prediction response too large");
15213
+ }
15214
+ chunks.push(Buffer.from(value));
15215
+ }
15216
+ return Buffer.concat(chunks).toString("utf8");
15217
+ } finally {
15218
+ reader.releaseLock();
15219
+ }
15220
+ }
15221
+ function predictionText(sse) {
15222
+ let completed;
15223
+ for (const line of sse.split(/\r?\n/u)) {
15224
+ if (!line.startsWith("data: ") || line === "data: [DONE]") continue;
15225
+ const event = JSON.parse(line.slice(6));
15226
+ if (event.type === "error" || event.type === "response.failed" || event.type === "response.incomplete") throw new Error("Prediction generation failed");
15227
+ if (event.type === "response.completed") completed = event.response;
15228
+ }
15229
+ if (completed?.status !== "completed" || !Array.isArray(completed.output) || completed.output.some((item) => !["reasoning", "message"].includes(item.type))) throw new Error("Prediction did not complete as text");
15230
+ const text = completed.output.filter((item) => item.type === "message" && item.role === "assistant").flatMap((item) => item.content ?? []).filter((part) => part.type === "output_text").map((part) => part.text).join("");
15231
+ const result = JSON.parse(text);
15232
+ if (result.suggestion === null || result.suggestion === "") return null;
15233
+ if (typeof result.suggestion !== "string" || result.suggestion.length > 600 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/u.test(result.suggestion)) throw new Error("Invalid prediction text");
15234
+ return result.suggestion.trim() || null;
15235
+ }
15236
+ /** Optional, isolated next-message inference. Never runs tools or mutates the source conversation. */
15237
+ function createComposerPredictions({ fetch, credentials, enabled, userAgent, now = Date.now, base = BASE, timeoutMs = 3e4 }) {
15238
+ const requests = createSharedRequests(), results = /* @__PURE__ */ new Map();
15239
+ let generation = 0, accountId, config;
15240
+ const clear = () => {
15241
+ generation++;
15242
+ accountId = void 0;
15243
+ config = void 0;
15244
+ results.clear();
15245
+ requests.clear(cancelled());
15246
+ };
15247
+ const active = (auth, signal) => {
15248
+ signal?.throwIfAborted();
15249
+ if (auth.generation !== generation || !enabled()) throw cancelled();
15250
+ };
15251
+ const headers = (auth) => ({
15252
+ authorization: `Bearer ${auth.access}`,
15253
+ "chatgpt-account-id": auth.accountId,
15254
+ "user-agent": userAgent
15255
+ });
15256
+ const configuration = async (auth, signal) => {
15257
+ active(auth, signal);
15258
+ if (config && now() - config.at < 3e5) return config.value;
15259
+ return requests.run("config", async (sharedSignal) => {
15260
+ const response = await fetch(`${base}/wham/predictions/config`, {
15261
+ redirect: "error",
15262
+ headers: {
15263
+ ...headers(auth),
15264
+ accept: "application/json"
15265
+ },
15266
+ signal: AbortSignal.any([sharedSignal, AbortSignal.timeout(15e3)])
15267
+ });
15268
+ if (!response.ok) {
15269
+ await response.body?.cancel();
15270
+ throw new Error("Prediction capability unavailable");
15271
+ }
15272
+ const value = JSON.parse(await boundedText(response, 32e3));
15273
+ if (typeof value?.is_enabled !== "boolean" || value.is_enabled && (typeof value.prompt !== "string" || !value.prompt || value.prompt.length > 16e3) || value.unsupported_models !== void 0 && (!Array.isArray(value.unsupported_models) || value.unsupported_models.some((model) => typeof model !== "string"))) throw new Error("Invalid prediction capability");
15274
+ active(auth, sharedSignal);
15275
+ config = {
15276
+ at: now(),
15277
+ value
15278
+ };
15279
+ return value;
15280
+ }, signal);
15281
+ };
15282
+ return {
15283
+ clear,
15284
+ async generate(raw, signal) {
15285
+ signal?.throwIfAborted();
15286
+ if (!enabled()) return {
15287
+ prediction: null,
15288
+ reason: "disabled"
15289
+ };
15290
+ const input = predictionInput(raw), initialGeneration = generation;
15291
+ const credential = await credentials(signal);
15292
+ signal?.throwIfAborted();
15293
+ if (initialGeneration !== generation) throw cancelled();
15294
+ if (!credential?.access || !credential.accountId) return {
15295
+ prediction: null,
15296
+ reason: "authentication"
15297
+ };
15298
+ if (accountId !== void 0 && credential.accountId !== accountId) clear();
15299
+ accountId = credential.accountId;
15300
+ const auth = {
15301
+ ...credential,
15302
+ generation
15303
+ };
15304
+ const cap = await configuration(auth, signal);
15305
+ active(auth, signal);
15306
+ if (!cap.is_enabled || cap.unsupported_models?.includes(input.model)) return {
15307
+ prediction: null,
15308
+ reason: "unavailable"
15309
+ };
15310
+ const key = createHash("sha256").update(JSON.stringify(input)).digest("hex");
15311
+ const cached = results.get(key);
15312
+ if (cached && now() - cached.at < 3e5) return { prediction: cached.prediction };
15313
+ return requests.run(`prediction:${key}`, async (sharedSignal) => {
15314
+ active(auth, sharedSignal);
15315
+ const metadata = JSON.stringify({
15316
+ thread_source: "composer_predictions",
15317
+ turn_trigger: "composer_predictions",
15318
+ model: input.model,
15319
+ prediction_source_thread_id: input.sessionId,
15320
+ prediction_source_turn_id: input.turnId,
15321
+ prediction_trigger: "live"
15322
+ });
15323
+ const effort = [
15324
+ "none",
15325
+ "minimal",
15326
+ "low",
15327
+ "medium",
15328
+ "high",
15329
+ "xhigh"
15330
+ ].includes(cap.prediction_reasoning_effort) ? cap.prediction_reasoning_effort : "high";
15331
+ const body = {
15332
+ model: input.model,
15333
+ instructions: "Predict a follow-up message from the user, using the conversation. Return only the requested JSON. Do not call tools or perform tasks.",
15334
+ input: [...input.messages.map((message) => ({
15335
+ role: message.role,
15336
+ content: [{
15337
+ type: message.role === "user" ? "input_text" : "output_text",
15338
+ text: message.text
15339
+ }]
15340
+ })), {
15341
+ role: "user",
15342
+ content: [{
15343
+ type: "input_text",
15344
+ text: cap.prompt
15345
+ }]
15346
+ }],
15347
+ reasoning: { effort },
15348
+ tools: [],
15349
+ tool_choice: "none",
15350
+ parallel_tool_calls: false,
15351
+ store: false,
15352
+ stream: true,
15353
+ include: ["reasoning.encrypted_content"],
15354
+ text: { format: {
15355
+ type: "json_schema",
15356
+ name: "composer_prediction",
15357
+ strict: true,
15358
+ schema: {
15359
+ type: "object",
15360
+ properties: { suggestion: { type: ["string", "null"] } },
15361
+ required: ["suggestion"],
15362
+ additionalProperties: false
15363
+ }
15364
+ } },
15365
+ client_metadata: { "x-codex-turn-metadata": metadata }
15366
+ };
15367
+ const response = await fetch(`${base}/codex/responses`, {
15368
+ method: "POST",
15369
+ redirect: "error",
15370
+ headers: {
15371
+ ...headers(auth),
15372
+ accept: "text/event-stream",
15373
+ "content-type": "application/json",
15374
+ "x-codex-turn-metadata": metadata
15375
+ },
15376
+ body: JSON.stringify(body),
15377
+ signal: AbortSignal.any([sharedSignal, AbortSignal.timeout(timeoutMs)])
15378
+ });
15379
+ if (!response.ok) {
15380
+ await response.body?.cancel();
15381
+ throw new Error(`Prediction request failed (HTTP ${response.status})`);
15382
+ }
15383
+ const prediction = predictionText(await boundedText(response, 1024 * 1024));
15384
+ active(auth, sharedSignal);
15385
+ if (results.size >= 32) results.delete(results.keys().next().value);
15386
+ results.set(key, {
15387
+ at: now(),
15388
+ prediction
15389
+ });
15390
+ return { prediction };
15391
+ }, signal);
14933
15392
  }
14934
15393
  };
14935
15394
  }
@@ -15751,12 +16210,7 @@ function apply(ctx, config = {}) {
15751
16210
  3e5
15752
16211
  ]
15753
16212
  });
15754
- let appendUltraPolicy;
15755
- try {
15756
- appendUltraPolicy = createRequire(import.meta.url)("@deepseek-ai/dsh-session").appendPluginRecord;
15757
- } catch (error) {
15758
- if (!(error?.code === "MODULE_NOT_FOUND" && error.message?.startsWith("Cannot find module '@deepseek-ai/dsh-session'"))) throw error;
15759
- }
16213
+ const appendUltraPolicy = loadHostSessionSdk()?.appendPluginRecord;
15760
16214
  const ultra = createUltraExecutionPreset({
15761
16215
  catalog: modelCatalog,
15762
16216
  resolveAgent: () => ctx.get?.("agents")?.currentInitiator?.(),
@@ -15825,6 +16279,7 @@ function apply(ctx, config = {}) {
15825
16279
  connectionMode: settings.get().connectionMode ?? "sse",
15826
16280
  reviewModel: settings.get().reviewModel ?? "session",
15827
16281
  remoteControl: settings.get().remoteControl ?? "off",
16282
+ composerPredictions: settings.get().composerPredictions === "on" ? "on" : "off",
15828
16283
  otherModels: settings.get().otherModels === "off" ? "off" : "on",
15829
16284
  subagentBackend: settings.get().subagentBackend ?? "dsh",
15830
16285
  subagentBackendAvailable: subagentBackend !== void 0,
@@ -16074,7 +16529,7 @@ function apply(ctx, config = {}) {
16074
16529
  }, "codex-subscription: official model catalog");
16075
16530
  const currentAgent = () => ctx.get?.("agents")?.currentInitiator?.();
16076
16531
  const codexFetch = createCodexFetchProvider({
16077
- allowed: () => fetchRouted && (settings.get().otherModels !== "off" || currentAgent()?.session.requestContext?.()?.provider === PROVIDER),
16532
+ allowed: (llmProvider) => fetchRouted && (settings.get().otherModels !== "off" || (llmProvider ?? currentAgent()?.session.requestContext?.()?.provider) === PROVIDER),
16078
16533
  getAuth: resolveAuth,
16079
16534
  readCredential: (options) => store.read(PROVIDER, options),
16080
16535
  resolveModel: () => {
@@ -16126,7 +16581,7 @@ function apply(ctx, config = {}) {
16126
16581
  const realSearchProviders = ctx.web.searchProviders;
16127
16582
  const resolveDshSearch = () => realSearchProviders?.get(searchProvider.dshProviderId());
16128
16583
  const gateSearch = (provider) => gateSearchProvider(provider, {
16129
- allowed: () => settings.get().otherModels !== "off" || currentAgent()?.session.requestContext?.()?.provider === PROVIDER,
16584
+ allowed: (llmProvider) => settings.get().otherModels !== "off" || (llmProvider ?? currentAgent()?.session.requestContext?.()?.provider) === PROVIDER,
16130
16585
  resolveDshProvider: resolveDshSearch
16131
16586
  });
16132
16587
  const codexSearch = createCodexSearchProvider({
@@ -16144,6 +16599,7 @@ function apply(ctx, config = {}) {
16144
16599
  const tracedCodexSearch = gateSearch({
16145
16600
  id: codexSearch.id,
16146
16601
  available: () => codexSearch.available(),
16602
+ ready: (llmProvider) => codexSearch.ready(llmProvider),
16147
16603
  async search(request, signal) {
16148
16604
  const result = await codexSearch.search(request, signal);
16149
16605
  searchTrace("answered by Codex subscription");
@@ -16434,6 +16890,28 @@ function apply(ctx, config = {}) {
16434
16890
  close();
16435
16891
  };
16436
16892
  });
16893
+ const voicePreview = createVoicePreview({
16894
+ fetch: (input, init) => network.fetch("voice", input, init, { standardHttps: true }),
16895
+ credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
16896
+ ...options,
16897
+ signal
16898
+ }), signal),
16899
+ userAgent: USER_AGENT
16900
+ });
16901
+ ctx.effect(() => () => voicePreview.clear());
16902
+ const composerPredictions = createComposerPredictions({
16903
+ fetch: (input, init) => network.fetch("predictions", input, init, { standardHttps: true }),
16904
+ credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
16905
+ ...options,
16906
+ signal
16907
+ }), signal),
16908
+ enabled: () => settings.get().composerPredictions === "on",
16909
+ userAgent: USER_AGENT
16910
+ });
16911
+ ctx.effect(() => () => composerPredictions.clear());
16912
+ ctx.effect(() => settings.watch((value) => {
16913
+ if (value.composerPredictions !== "on") composerPredictions.clear();
16914
+ }));
16437
16915
  const subscriptionHandler = createSubscriptionRpcHandler({
16438
16916
  authHandler: createCodexRpcHandler(coordinator, { openExternal: openCodexAuthUrl }),
16439
16917
  usageReader,
@@ -16447,17 +16925,13 @@ function apply(ctx, config = {}) {
16447
16925
  remoteControl,
16448
16926
  desktopVoice,
16449
16927
  nativeVoice,
16450
- voicePreview: createVoicePreview({
16451
- fetch: (input, init) => network.fetch("voice", input, init, { standardHttps: true }),
16452
- credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
16453
- ...options,
16454
- signal
16455
- }), signal),
16456
- userAgent: USER_AGENT
16457
- }),
16928
+ voicePreview,
16929
+ composerPredictions,
16458
16930
  onAccountChanged: () => {
16459
16931
  connectorsClient.clear();
16460
16932
  usageProfileReader.clear();
16933
+ voicePreview.clear();
16934
+ composerPredictions.clear();
16461
16935
  quotaRetryHandler.notifyAccountChanged();
16462
16936
  },
16463
16937
  diagnosticsReader: () => createSubscriptionDiagnostics({