dsh-codex-subscription 3.1.8 → 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
@@ -6,7 +6,6 @@ import { appendFileSync, constants, mkdirSync, readFileSync, readdirSync, realpa
6
6
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
7
  import { request } from "node:https";
8
8
  import { AsyncLocalStorage } from "node:async_hooks";
9
- import { PassThrough, Readable } from "node:stream";
10
9
  import { promisify } from "node:util";
11
10
  import { HttpsProxyAgent } from "https-proxy-agent";
12
11
  import WebSocket from "ws";
@@ -17,6 +16,7 @@ import { openaiCodexProvider as createOpenAICodexProvider } from "@earendil-work
17
16
  import { createModels } from "@earendil-works/pi-ai";
18
17
  import { clientRequestSchema } from "@deepseek-ai/dsh-client-connection";
19
18
  import { lstat, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
19
+ import { PassThrough } from "node:stream";
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";
@@ -24,6 +24,7 @@ import { setTimeout as setTimeout$1 } from "node:timers/promises";
24
24
  import { dshHomePath, resolveDshHome } from "@deepseek-ai/dsh-home-paths";
25
25
  import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
26
26
  import { WebError } from "@deepseek-ai/dsh-web";
27
+ import { performance } from "node:perf_hooks";
27
28
  //#region src/settings-adapter.js
28
29
  function createSettingsAdapter(ctx, config) {
29
30
  if (typeof ctx.settings.configure !== "function" || typeof ctx.settings.update !== "function") throw new Error("DSH settings API is unavailable");
@@ -470,7 +471,8 @@ const DEFAULT_REASONING_EFFORTS = Object.freeze([
470
471
  "medium",
471
472
  "high",
472
473
  "xhigh",
473
- "max"
474
+ "max",
475
+ "ultra"
474
476
  ]);
475
477
  const DEFAULT_REASONING_EFFORT = "auto";
476
478
  const normalizeDefaultReasoningEffort = (value) => DEFAULT_REASONING_EFFORTS.includes(value) ? value : DEFAULT_REASONING_EFFORT;
@@ -705,6 +707,11 @@ const PREFERENCE_FIELDS = Object.freeze({
705
707
  default: DEFAULT_REASONING_EFFORT,
706
708
  error: "Invalid default reasoning effort"
707
709
  },
710
+ composerPredictions: {
711
+ choices: ["off", "on"],
712
+ default: "off",
713
+ error: "Invalid input prediction setting"
714
+ },
708
715
  connectionMode: {
709
716
  choices: ["sse", "websocket"],
710
717
  default: "sse",
@@ -1110,12 +1117,49 @@ function transportError(error, signal) {
1110
1117
  return Object.assign(new Error(`Network transport failure (${error.code}): ${error.message}`, { cause: error }), { code: error.code });
1111
1118
  }
1112
1119
  function transportResponseBody(response, signal) {
1113
- const body = new PassThrough();
1114
- response.on("error", (error) => body.destroy(transportError(error, signal)));
1115
- body.on("close", () => response.destroy());
1116
- const stream = Readable.toWeb(body);
1117
- response.pipe(body);
1118
- return stream;
1120
+ const iterator = response[Symbol.asyncIterator]();
1121
+ let finished = false, controller;
1122
+ const cleanup = () => signal?.removeEventListener("abort", abort);
1123
+ const fail = (error) => {
1124
+ if (finished) return;
1125
+ finished = true;
1126
+ cleanup();
1127
+ controller.error(transportError(error, signal));
1128
+ response.destroy();
1129
+ };
1130
+ const abort = () => fail(signal.reason);
1131
+ return new ReadableStream({
1132
+ start(value) {
1133
+ controller = value;
1134
+ response.on("error", fail);
1135
+ response.once("close", () => {
1136
+ if (!response.readableEnded) fail(Object.assign(/* @__PURE__ */ new Error("Response body closed before completion"), { code: "ERR_STREAM_PREMATURE_CLOSE" }));
1137
+ });
1138
+ signal?.addEventListener("abort", abort, { once: true });
1139
+ if (signal?.aborted) abort();
1140
+ },
1141
+ async pull() {
1142
+ try {
1143
+ const { value, done } = await iterator.next();
1144
+ if (finished) return;
1145
+ if (done) {
1146
+ finished = true;
1147
+ cleanup();
1148
+ controller.close();
1149
+ } else controller.enqueue(new Uint8Array(value));
1150
+ } catch (error) {
1151
+ fail(error);
1152
+ }
1153
+ },
1154
+ async cancel() {
1155
+ finished = true;
1156
+ cleanup();
1157
+ response.destroy();
1158
+ try {
1159
+ await iterator.return();
1160
+ } catch {}
1161
+ }
1162
+ });
1119
1163
  }
1120
1164
  function fetchThroughProxy(input, init, proxyUrl) {
1121
1165
  const target = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
@@ -1249,6 +1293,7 @@ function createCodexNetworkTransport(options = {}) {
1249
1293
  routed = true;
1250
1294
  }
1251
1295
  });
1296
+ connection.signal?.throwIfAborted();
1252
1297
  if (value instanceof Response && !value.ok) remember(area, {
1253
1298
  status: "failed",
1254
1299
  stage: "http",
@@ -1264,6 +1309,7 @@ function createCodexNetworkTransport(options = {}) {
1264
1309
  });
1265
1310
  return value;
1266
1311
  } catch (error) {
1312
+ if (connection.signal?.aborted && connection.signal.reason?.name !== "TimeoutError") throw error;
1267
1313
  if (routed) remember(area, {
1268
1314
  status: "failed",
1269
1315
  stage: "transport",
@@ -1277,7 +1323,10 @@ function createCodexNetworkTransport(options = {}) {
1277
1323
  return Object.freeze({
1278
1324
  run,
1279
1325
  history: evidence.snapshot,
1280
- 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
+ }),
1281
1330
  snapshot: () => Object.fromEntries([...attempts].map(([area, value]) => [area, { ...value }]))
1282
1331
  });
1283
1332
  }
@@ -1902,7 +1951,7 @@ function isDshAutoReview(context) {
1902
1951
  * persistence, headers, transport, and model behavior remain owned by the
1903
1952
  * original provider.
1904
1953
  */
1905
- 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() } = {}) {
1954
+ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, resolveOutputVerbosity = () => OUTPUT_VERBOSITY_DEFAULT, resolveInputImageDetail = () => void 0, resolveReasoningSummary = () => void 0, resolveContextMode = () => void 0, resolveCustomContextWindow = () => void 0, resolveReviewModel = () => REVIEW_MODEL_SESSION, catalog, connection, compaction, reasoning, ultra, runNetwork = (_area, operation) => operation() } = {}) {
1906
1955
  const provider = createOpenAICodexProvider();
1907
1956
  const retryBridge = createModelRetryBridge();
1908
1957
  const requestToken = Object.freeze({
@@ -1953,7 +2002,8 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1953
2002
  } },
1954
2003
  ...serviceTier === void 0 ? {} : { service_tier: serviceTier }
1955
2004
  };
1956
- return reasoning?.preparePayload(finalPayload, requestModel) ?? finalPayload;
2005
+ const reasoned = reasoning?.preparePayload(finalPayload, requestModel) ?? finalPayload;
2006
+ return ultra?.preparePayload(reasoned) ?? reasoned;
1957
2007
  }
1958
2008
  };
1959
2009
  };
@@ -2229,7 +2279,7 @@ const REASONING_LIMITS = Object.freeze({
2229
2279
  bytes: 16 * 1024 * 1024,
2230
2280
  updates: 128
2231
2281
  });
2232
- const record$8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2282
+ const record$9 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2233
2283
  const efforts = /* @__PURE__ */ new Set([
2234
2284
  "low",
2235
2285
  "medium",
@@ -2243,13 +2293,13 @@ const reasoningDigest = (value) => {
2243
2293
  const text = boundedStringify(value, REASONING_LIMITS.bytes);
2244
2294
  return text === void 0 ? void 0 : reasoningHash(text);
2245
2295
  };
2246
- const boundary = (value, update = false) => record$8(value) && Object.keys(value).every((key) => [
2296
+ const boundary = (value, update = false) => record$9(value) && Object.keys(value).every((key) => [
2247
2297
  "offset",
2248
2298
  "hash",
2249
2299
  ...update ? ["effort"] : []
2250
2300
  ].includes(key)) && Number.isInteger(value.offset) && value.offset >= 0 && value.offset <= REASONING_LIMITS.items && isHash(value.hash);
2251
2301
  function isReasoningState(value) {
2252
- 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) => ![
2302
+ 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) => ![
2253
2303
  "version",
2254
2304
  "scope",
2255
2305
  "envelope",
@@ -2283,7 +2333,7 @@ function rewriteReasoning(payload, { model, scope, previous, fresh = false }) {
2283
2333
  payload,
2284
2334
  reason
2285
2335
  });
2286
- 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");
2336
+ 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");
2287
2337
  if (payload.context_management !== void 0) return skip("cloud-compaction");
2288
2338
  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) => [
2289
2339
  "configuration_update",
@@ -2567,6 +2617,7 @@ const RPC_ENDPOINTS = Object.freeze([
2567
2617
  "preferences/update",
2568
2618
  "default-model/status",
2569
2619
  "default-model/select",
2620
+ "predictions/generate",
2570
2621
  "runtime/status",
2571
2622
  "runtime/install",
2572
2623
  "runtime/remove",
@@ -2579,6 +2630,11 @@ const RPC_ENDPOINTS = Object.freeze([
2579
2630
  "voice/interrupt",
2580
2631
  "voice/preview",
2581
2632
  "voice/catalog",
2633
+ "voice/native/probe",
2634
+ "voice/native/start",
2635
+ "voice/native/status",
2636
+ "voice/native/control",
2637
+ "voice/native/stop",
2582
2638
  "remote/status",
2583
2639
  "remote/enable",
2584
2640
  "remote/disable",
@@ -2597,6 +2653,20 @@ const RPC_ENDPOINTS = Object.freeze([
2597
2653
  ]);
2598
2654
  //#endregion
2599
2655
  //#region src/subscription-transport.js
2656
+ const localNativeRequest = (request) => {
2657
+ try {
2658
+ const target = new URL(request.url);
2659
+ const origin = new URL(request.headers.get("origin"));
2660
+ const authority = request.headers.get("host") ?? target.host;
2661
+ return ["http:", "https:"].includes(origin.protocol) && !origin.username && !origin.password && [
2662
+ "localhost",
2663
+ "127.0.0.1",
2664
+ "[::1]"
2665
+ ].includes(origin.hostname) && authority === origin.host;
2666
+ } catch {
2667
+ return false;
2668
+ }
2669
+ };
2600
2670
  /** Exact routes stay inside DSH's authenticated /api bridge and body limit. */
2601
2671
  function registerSubscriptionTransport(connection, handler) {
2602
2672
  const disposers = [];
@@ -2608,6 +2678,7 @@ function registerSubscriptionTransport(connection, handler) {
2608
2678
  methods: ["POST"],
2609
2679
  requestBody: "buffered",
2610
2680
  async fetch(request) {
2681
+ if (endpoint.startsWith("voice/native/") && !localNativeRequest(request)) return new Response("native voice requires the local desktop", { status: 403 });
2611
2682
  if (request.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "application/json") return new Response("content type must be application/json", { status: 415 });
2612
2683
  let body;
2613
2684
  try {
@@ -2790,7 +2861,8 @@ const SUPPORTED_RUNTIME_VERSIONS = Object.freeze([
2790
2861
  "0.2.1-rc.1",
2791
2862
  "0.2.1-rc.2",
2792
2863
  "0.2.1-rc.3",
2793
- "0.2.1-rc.4"
2864
+ "0.2.1-rc.4",
2865
+ "0.2.2-alpha.2"
2794
2866
  ]);
2795
2867
  const require = createRequire(import.meta.url);
2796
2868
  const execute = promisify(execFile);
@@ -3536,6 +3608,15 @@ const sketchCommandArray = {
3536
3608
  };
3537
3609
  //#endregion
3538
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
+ }
3539
3620
  async function readSubscriptionCredentials(getAuth, readCredential, signal) {
3540
3621
  for (let attempt = 0; attempt < 2; attempt++) {
3541
3622
  const auth = await getAuth({ signal });
@@ -3582,8 +3663,9 @@ function originalImageRefsEqual(left, right) {
3582
3663
  /** Resolve only an exact original reference copied into a DSH fork prefix. */
3583
3664
  function inheritedOriginalImageRef(session, assetId) {
3584
3665
  const parentSession = session?.header?.parentSession;
3666
+ const forked = typeof parentSession === "string" && parentSession.length > 0 || session?.header?.isSeeded === true;
3585
3667
  const seedLength = session?.inheritedEventCount;
3586
- 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;
3587
3669
  if (typeof session?.snapshotEvents !== "function") return void 0;
3588
3670
  let events;
3589
3671
  try {
@@ -3600,7 +3682,7 @@ function inheritedOriginalImageRef(session, assetId) {
3600
3682
  }
3601
3683
  //#endregion
3602
3684
  //#region src/version.js
3603
- const PACKAGE_VERSION = "3.1.8";
3685
+ const PACKAGE_VERSION = "3.2.0";
3604
3686
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
3605
3687
  //#endregion
3606
3688
  //#region src/codex-images.js
@@ -3628,7 +3710,7 @@ const FULL_ATTACHMENT_ID = /^sha256:[0-9a-f]{64}$/u;
3628
3710
  const BARE_ATTACHMENT_DIGEST = /^[0-9a-f]{64}$/iu;
3629
3711
  const PATH_LIKE_ATTACHMENT_ID = /[\\/]/u;
3630
3712
  const FILE_NAME_ATTACHMENT_ID = /\.[A-Za-z0-9]{1,16}$/u;
3631
- const record$7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3713
+ const record$8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3632
3714
  const nonEmpty$2 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
3633
3715
  const NETWORK_REASONS = {
3634
3716
  UND_ERR_HEADERS_TIMEOUT: "the image service sent no response within 5 minutes",
@@ -3714,7 +3796,7 @@ function decodeCodexPng(value, maximumBytes) {
3714
3796
  return new Uint8Array(data);
3715
3797
  }
3716
3798
  function imageReference(value) {
3717
- const originalDimensions = record$7(value.originalDimensions) ? {
3799
+ const originalDimensions = record$8(value.originalDimensions) ? {
3718
3800
  width: value.originalDimensions.width,
3719
3801
  height: value.originalDimensions.height
3720
3802
  } : void 0;
@@ -3742,7 +3824,7 @@ function invalidAttachmentId(value) {
3742
3824
  function referenceOf(value, attachments) {
3743
3825
  const attachmentId = normalizeAttachmentId(value?.attachmentId);
3744
3826
  if (attachmentId === void 0) invalidAttachmentId(value);
3745
- 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");
3827
+ 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");
3746
3828
  return imageReference({
3747
3829
  ...value,
3748
3830
  attachmentId
@@ -3752,7 +3834,7 @@ function sessionImageReferences(messages) {
3752
3834
  const references = /* @__PURE__ */ new Map();
3753
3835
  const visit = (content) => {
3754
3836
  if (!Array.isArray(content)) return;
3755
- for (const block of content) if (block?.type === "image" && record$7(block.attachment)) {
3837
+ for (const block of content) if (block?.type === "image" && record$8(block.attachment)) {
3756
3838
  const id = normalizeAttachmentId(block.attachment.attachmentId);
3757
3839
  if (id !== void 0) references.set(id, block.attachment);
3758
3840
  } else if (block?.type === "tool-result") visit(block.content);
@@ -3917,7 +3999,7 @@ async function limitMessage(response, now = Date.now()) {
3917
3999
  } catch {
3918
4000
  return fallback;
3919
4001
  }
3920
- if (!record$7(error)) return fallback;
4002
+ if (!record$8(error)) return fallback;
3921
4003
  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;
3922
4004
  if (at === void 0) return fallback;
3923
4005
  const minutes = Math.max(1, Math.ceil((at - now) / 6e4));
@@ -3929,7 +4011,7 @@ async function refusalMessage(response, editing) {
3929
4011
  let reason;
3930
4012
  try {
3931
4013
  const value = JSON.parse(await readTextWithin(response, 16 * 1024));
3932
- const error = record$7(value?.error) ? value.error : void 0;
4014
+ const error = record$8(value?.error) ? value.error : void 0;
3933
4015
  reason = [
3934
4016
  error?.message,
3935
4017
  value?.detail,
@@ -3954,7 +4036,7 @@ async function readTextWithin(response, maximumBytes) {
3954
4036
  }
3955
4037
  function responseMetadata(value) {
3956
4038
  const data = Array.isArray(value?.data) ? value.data[0] : void 0;
3957
- const encoded = record$7(data) ? data.b64_json : void 0;
4039
+ const encoded = record$8(data) ? data.b64_json : void 0;
3958
4040
  if (typeof encoded !== "string") throw new Error("Codex returned no image data");
3959
4041
  return {
3960
4042
  encoded,
@@ -4435,6 +4517,16 @@ const FIELDS = /* @__PURE__ */ new Set([
4435
4517
  "event",
4436
4518
  "error"
4437
4519
  ]);
4520
+ for (const name of [
4521
+ "direction",
4522
+ "cursorDirection",
4523
+ "requestedView",
4524
+ "cursorView",
4525
+ "cursorThreadMatches",
4526
+ "cursorTurnScoped",
4527
+ "requestedTurnScoped",
4528
+ "cursorTurnMatches"
4529
+ ]) FIELDS.add(name);
4438
4530
  function phoneLog(event, details = {}, level = "info") {
4439
4531
  const fields = {};
4440
4532
  for (const [name, value] of Object.entries(details)) {
@@ -6447,6 +6539,7 @@ function createRealtimeVoice(options) {
6447
6539
  ws,
6448
6540
  notify,
6449
6541
  ended: false,
6542
+ inputReady: false,
6450
6543
  chain: Promise.resolve(),
6451
6544
  tail: [],
6452
6545
  lines: [],
@@ -6510,6 +6603,7 @@ function createRealtimeVoice(options) {
6510
6603
  ws.on("message", (data) => {
6511
6604
  try {
6512
6605
  const value = JSON.parse(String(data));
6606
+ if (!session.ended && value.type === "session.input_audio.append" && typeof value.audio === "string" && value.audio.length > 0) session.inputReady = true;
6513
6607
  const id = value.client_event_id ?? value.error?.event_id;
6514
6608
  if (id && session.controls.delete(id)) {
6515
6609
  if (value.type === "error") log.warn("voice", "the voice service refused an interruption command", String(value.error?.message ?? "").slice(0, 200));
@@ -6656,6 +6750,7 @@ function createRealtimeVoice(options) {
6656
6750
  const session = sessions.get(threadId);
6657
6751
  return session ? {
6658
6752
  active: true,
6753
+ inputReady: session.inputReady,
6659
6754
  working: session.working > 0,
6660
6755
  closing: session.closing === true,
6661
6756
  lines: session.lines.slice(-6)
@@ -6672,6 +6767,195 @@ function createRealtimeVoice(options) {
6672
6767
  };
6673
6768
  }
6674
6769
  //#endregion
6770
+ //#region src/remote-control-capabilities.js
6771
+ const record$7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
6772
+ const decimal$1 = (value) => typeof value === "string" && /^-?\d+(?:\.\d+)?$/u.test(value) ? value : null;
6773
+ const integer = (value) => Number.isSafeInteger(value) && value >= 0;
6774
+ const percentage = (value) => Number.isFinite(value) && value >= 0 && value <= 100;
6775
+ const plans = /* @__PURE__ */ new Set([
6776
+ "free",
6777
+ "go",
6778
+ "plus",
6779
+ "pro",
6780
+ "prolite",
6781
+ "promax",
6782
+ "team",
6783
+ "self_serve_business_prolite",
6784
+ "self_serve_business_usage_based",
6785
+ "business",
6786
+ "ent26",
6787
+ "enterprise_cbp_automation",
6788
+ "enterprise_cbp_usage_based",
6789
+ "enterprise",
6790
+ "edu",
6791
+ "edu_plus",
6792
+ "edu_pro",
6793
+ "unknown"
6794
+ ]);
6795
+ const reachedTypes = /* @__PURE__ */ new Set([
6796
+ "rate_limit_reached",
6797
+ "workspace_owner_credits_depleted",
6798
+ "workspace_member_credits_depleted",
6799
+ "workspace_owner_usage_limit_reached",
6800
+ "workspace_member_usage_limit_reached"
6801
+ ]);
6802
+ function creditsOf$1(value) {
6803
+ if (!record$7(value) || typeof value.unlimited !== "boolean") return null;
6804
+ return {
6805
+ hasCredits: true,
6806
+ unlimited: value.unlimited,
6807
+ balance: decimal$1(value.balance)
6808
+ };
6809
+ }
6810
+ function individualOf$1(value) {
6811
+ if (!record$7(value) || decimal$1(value.limit) === null || decimal$1(value.used) === null || !percentage(value.remainingPercent) || !integer(value.resetsAt)) return null;
6812
+ return {
6813
+ limit: value.limit,
6814
+ used: value.used,
6815
+ remainingPercent: Math.round(value.remainingPercent),
6816
+ resetsAt: value.resetsAt
6817
+ };
6818
+ }
6819
+ const windowOf$1 = (value) => record$7(value) && percentage(value.usedPercent) ? {
6820
+ usedPercent: Math.round(value.usedPercent),
6821
+ windowDurationMins: Number.isFinite(value.windowSeconds) && value.windowSeconds > 0 ? Math.round(value.windowSeconds / 60) : null,
6822
+ resetsAt: integer(value.resetsAt) ? value.resetsAt : null
6823
+ } : null;
6824
+ /** Project the existing safe usage reading into the app-server account snapshot. */
6825
+ function phoneRateLimits(read) {
6826
+ const limits = Array.isArray(read?.rateLimits) ? read.rateLimits : [];
6827
+ const main = limits.find((limit) => limit.id === "codex") ?? limits[0];
6828
+ const accountBucket = (limit) => limit === main && (limit === void 0 || limit.id === "codex");
6829
+ const snapshot = (limit) => ({
6830
+ limitId: limit?.id ?? "codex",
6831
+ limitName: limit?.name ?? null,
6832
+ normalModelSlug: null,
6833
+ primary: windowOf$1(limit?.windows?.[0]),
6834
+ secondary: windowOf$1(limit?.windows?.[1]),
6835
+ credits: accountBucket(limit) ? creditsOf$1(read?.credits) : null,
6836
+ individualLimit: accountBucket(limit) ? individualOf$1(read?.individualLimit) : null,
6837
+ spendControlReached: typeof read?.spendControlReached === "boolean" ? read.spendControlReached : null,
6838
+ planType: read?.planType == null ? null : plans.has(read.planType) ? read.planType : "unknown",
6839
+ rateLimitReachedType: reachedTypes.has(read?.rateLimitReachedType) ? read.rateLimitReachedType : null
6840
+ });
6841
+ const resets = read?.resetCredits;
6842
+ return {
6843
+ ordinaryUsageAllowed: null,
6844
+ rateLimits: snapshot(main),
6845
+ rateLimitsByLimitId: read ? Object.fromEntries(limits.map((limit) => [limit.id, snapshot(limit)])) : null,
6846
+ rateLimitResetCredits: record$7(resets) && integer(resets.availableCount) ? {
6847
+ availableCount: resets.availableCount,
6848
+ credits: null
6849
+ } : null,
6850
+ accountId: null,
6851
+ rateLimitUpsell: null
6852
+ };
6853
+ }
6854
+ /** Migration hints use the same provider/model identity as the phone model picker. */
6855
+ function phoneModelUpgrade(metadata, encodeModel) {
6856
+ const target = metadata?.upgradeTo ?? metadata?.retirement?.upgradeTo;
6857
+ if (typeof target !== "string" || !target.trim() || target.length > 256 || /[\u0000-\u001f\u007f]/u.test(target)) return {
6858
+ upgrade: null,
6859
+ upgradeInfo: null
6860
+ };
6861
+ const model = encodeModel(target);
6862
+ const at = metadata?.retirement?.at;
6863
+ return {
6864
+ upgrade: model,
6865
+ upgradeInfo: {
6866
+ model,
6867
+ retirementAt: integer(at) && at > 0 ? Math.floor(at / 1e3) : null,
6868
+ upgradeCopy: null,
6869
+ modelLink: null,
6870
+ migrationMarkdown: null
6871
+ }
6872
+ };
6873
+ }
6874
+ //#endregion
6875
+ //#region src/remote-history-page.js
6876
+ const PREFIX = "history1:";
6877
+ const encode = (value) => PREFIX + Buffer.from(JSON.stringify(value)).toString("base64url");
6878
+ const decode = (cursor) => {
6879
+ if (typeof cursor !== "string" || cursor.length > 4096 || !cursor.startsWith(PREFIX)) throw invalidParams("Invalid history cursor");
6880
+ try {
6881
+ const value = JSON.parse(Buffer.from(cursor.slice(9), "base64url").toString());
6882
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalidParams("Invalid history cursor");
6883
+ return value;
6884
+ } catch {
6885
+ throw invalidParams("Invalid history cursor");
6886
+ }
6887
+ };
6888
+ const scopeParts = (scope) => {
6889
+ try {
6890
+ const value = JSON.parse(scope);
6891
+ return Array.isArray(value) ? value : [];
6892
+ } catch {
6893
+ return [];
6894
+ }
6895
+ };
6896
+ const scopeKey = (scope) => {
6897
+ const parts = scopeParts(scope);
6898
+ return parts[1] === "items" ? JSON.stringify(parts.slice(0, 2)) : scope;
6899
+ };
6900
+ const anchorCursor = (id, scope, direction, inclusive) => encode({
6901
+ v: 2,
6902
+ s: scopeKey(scope),
6903
+ d: direction,
6904
+ a: id,
6905
+ i: inclusive
6906
+ });
6907
+ function initialHistoryCursor(list, scope) {
6908
+ const anchor = list.at(-1)?.id;
6909
+ return anchor === void 0 ? null : anchorCursor(anchor, scope, "desc", true);
6910
+ }
6911
+ function historyPage(list, params, scope, defaultDirection = "desc", accept = () => true) {
6912
+ const cursor = params?.cursor;
6913
+ const legacyOffset = typeof cursor === "string" && /^\d+$/u.test(cursor);
6914
+ const saved = cursor == null || legacyOffset ? void 0 : decode(cursor);
6915
+ const direction = params?.sortDirection ?? saved?.d ?? defaultDirection;
6916
+ if (!["asc", "desc"].includes(direction)) throw invalidParams("Invalid history sort direction");
6917
+ const limit = params?.limit ?? 50;
6918
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw invalidParams("History page limit must be between 1 and 100");
6919
+ if (saved && (![1, 2].includes(saved.v) || scopeKey(saved.s) !== scopeKey(scope) || typeof saved.a !== "string" || saved.v === 2 && typeof saved.i !== "boolean")) {
6920
+ const currentScope = scopeParts(scope), cursorScope = scopeParts(saved.s);
6921
+ const view = (value) => ["turns", "items"].includes(value) ? value : "unknown";
6922
+ phoneLog("history cursor rejected", {
6923
+ direction,
6924
+ cursorDirection: ["asc", "desc"].includes(saved.d) ? saved.d : "unknown",
6925
+ requestedView: view(currentScope[1]),
6926
+ cursorView: view(cursorScope[1]),
6927
+ cursorThreadMatches: currentScope[0] === cursorScope[0],
6928
+ cursorTurnScoped: !!cursorScope[2],
6929
+ requestedTurnScoped: !!currentScope[2],
6930
+ cursorTurnMatches: currentScope[2] === cursorScope[2]
6931
+ }, "warn");
6932
+ throw invalidParams("History cursor belongs to another view");
6933
+ }
6934
+ const ordered = direction === "asc" ? list : list.toReversed();
6935
+ const start = legacyOffset ? Number(cursor) : saved ? ordered.findIndex((item) => item.id === saved.a) : 0;
6936
+ if (!Number.isSafeInteger(start) || start < 0) throw invalidParams("History cursor is no longer available");
6937
+ const candidates = legacyOffset ? ordered.filter(accept).slice(start) : ordered.slice(start + (saved?.v === 2 && !saved.i ? 1 : 0)).filter(accept);
6938
+ const data = candidates.slice(0, limit);
6939
+ return {
6940
+ data,
6941
+ nextCursor: candidates.length > data.length ? anchorCursor(data.at(-1).id, scope, direction, false) : null,
6942
+ backwardsCursor: data.length ? anchorCursor(data[0].id, scope, direction === "asc" ? "desc" : "asc", true) : null
6943
+ };
6944
+ }
6945
+ function historyIndex(messages, turns) {
6946
+ const positions = new Map(messages.map((message, index) => [message.id, index]));
6947
+ const ranges = turns.map((turn) => ({
6948
+ ...turn,
6949
+ items: turn.items.map((item) => item.type === "userMessage" ? item : {
6950
+ id: item.id,
6951
+ type: item.type
6952
+ }),
6953
+ from: positions.get(turn.id) ?? 0
6954
+ }));
6955
+ for (let i = 0; i < ranges.length; i++) ranges[i].to = ranges[i + 1]?.from ?? messages.length;
6956
+ return ranges;
6957
+ }
6958
+ //#endregion
6675
6959
  //#region src/remote-control-image-output.js
6676
6960
  const images = /* @__PURE__ */ new WeakMap();
6677
6961
  const renderedSources = /* @__PURE__ */ new WeakMap();
@@ -6822,33 +7106,6 @@ function page(list, params) {
6822
7106
  };
6823
7107
  }
6824
7108
  /** Codex usage as the phone's rate-limit snapshot (primary and secondary windows of the main limit). */
6825
- function rateLimits(read) {
6826
- const toWindow = (entry) => entry && {
6827
- usedPercent: Math.round(entry.usedPercent),
6828
- windowDurationMins: Math.round(entry.windowSeconds / 60),
6829
- resetsAt: entry.resetsAt ?? null
6830
- };
6831
- const snapshot = (limit) => ({
6832
- limitId: limit?.id ?? "codex",
6833
- limitName: limit?.name ?? null,
6834
- normalModelSlug: null,
6835
- primary: toWindow(limit?.windows?.[0]) ?? null,
6836
- secondary: toWindow(limit?.windows?.[1]) ?? null,
6837
- credits: null,
6838
- individualLimit: null,
6839
- spendControlReached: read?.spendControlReached ?? null,
6840
- planType: read?.planType ?? null,
6841
- rateLimitReachedType: read?.rateLimitReachedType ?? null
6842
- });
6843
- return {
6844
- ordinaryUsageAllowed: null,
6845
- rateLimits: snapshot(read?.rateLimits?.find((limit) => limit.id === "codex") ?? read?.rateLimits?.[0]),
6846
- rateLimitsByLimitId: read ? Object.fromEntries((read.rateLimits ?? []).map((limit) => [limit.id, snapshot(limit)])) : null,
6847
- rateLimitResetCredits: null,
6848
- accountId: null,
6849
- rateLimitUpsell: null
6850
- };
6851
- }
6852
7109
  /** First place `term` appears in `text`: a short passage around it and the match's UTF-16 range inside that passage. */
6853
7110
  function occurrence(text, term, radius = 60) {
6854
7111
  const at = String(text).toLocaleLowerCase().indexOf(String(term).toLocaleLowerCase());
@@ -7044,7 +7301,7 @@ const toolOutput = (message, imageUrls, imageAssets) => [{
7044
7301
  /** Images the person attached to a message of their own. */
7045
7302
  const typedImages = (message) => message.role === "user" && (message.source === void 0 || message.source?.kind === "user") ? (message.content ?? []).filter((block) => block?.type === "image" && block.attachment) : [];
7046
7303
  /** `imageUrls` maps an attachment id to a data URL the phone can show; images without one are left out. */
7047
- function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new Map(), cwd = void 0, imageAssets = /* @__PURE__ */ new Map()) {
7304
+ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new Map(), cwd = void 0, imageAssets = /* @__PURE__ */ new Map(), indexOnly = false) {
7048
7305
  const turns = [];
7049
7306
  let turn;
7050
7307
  const calls = /* @__PURE__ */ new Map();
@@ -7059,7 +7316,7 @@ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new
7059
7316
  for (const message of messages) if (message.role === "user") {
7060
7317
  const text = typedText(message);
7061
7318
  const pictures = typedImages(message).map((block) => imageAssets.get(block.attachment.attachmentId)?.downloadUrl ?? imageUrls.get(block.attachment.attachmentId)).filter(Boolean);
7062
- if (text === "" && pictures.length === 0) continue;
7319
+ if (text === "" && pictures.length === 0 && !(indexOnly && typedImages(message).length)) continue;
7063
7320
  close();
7064
7321
  turn = {
7065
7322
  ...emptyTurn(),
@@ -7082,6 +7339,7 @@ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new
7082
7339
  } else if (message.role === "assistant") {
7083
7340
  turn ??= {
7084
7341
  ...emptyTurn(),
7342
+ id: message.id,
7085
7343
  startedAt: seconds(at)
7086
7344
  };
7087
7345
  for (const [index, block] of message.content.entries()) {
@@ -7237,7 +7495,7 @@ function createPhoneConfig(file) {
7237
7495
  }
7238
7496
  };
7239
7497
  }
7240
- 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 }) {
7498
+ 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, modelMetadata = () => void 0, historySource = void 0, speed = void 0, trace = () => {}, phoneReturnMs = PHONE_RETURN_MS, userAgent, appServerUserAgent = userAgent, configFile = void 0, voice = void 0 }) {
7241
7499
  const subscribers = /* @__PURE__ */ new Map();
7242
7500
  const threadSources = /* @__PURE__ */ new Map();
7243
7501
  const active = /* @__PURE__ */ new Map();
@@ -7431,7 +7689,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7431
7689
  await Promise.all(wanted.map(async (block) => {
7432
7690
  const started = Date.now();
7433
7691
  try {
7434
- const stored = await store.readImage(block.attachment, AbortSignal.timeout(1e4));
7692
+ const timeout = AbortSignal.timeout(1e4);
7693
+ const stored = await store.readImage(block.attachment, parentSignal ? AbortSignal.any([parentSignal, timeout]) : timeout);
7435
7694
  urls.set(block.attachment.attachmentId, `data:${stored.ref.mediaType};base64,${Buffer.from(stored.data).toString("base64")}`);
7436
7695
  phoneLog("image read completed", {
7437
7696
  attachmentId: block.attachment.attachmentId,
@@ -7569,6 +7828,127 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7569
7828
  });
7570
7829
  return result;
7571
7830
  };
7831
+ const historyIndexes = /* @__PURE__ */ new WeakMap();
7832
+ const historySnapshot = async (id, signal) => {
7833
+ signal?.throwIfAborted();
7834
+ let source;
7835
+ try {
7836
+ source = await historySource?.read(id, { signal });
7837
+ } catch (error) {
7838
+ if (error?.code === "SESSION_QUERY_SESSION_NOT_FOUND") throw notFound(id);
7839
+ throw error;
7840
+ }
7841
+ const session = (source ? void 0 : await agentFor(id))?.session;
7842
+ const messages = source?.messages ?? session.deriveMessages();
7843
+ const meta = source?.meta ?? session.meta;
7844
+ const events = source?.events;
7845
+ const cwd = directoryOf(events ? {
7846
+ meta,
7847
+ snapshotEvents: () => events
7848
+ } : session);
7849
+ const owner = events && Object.isFrozen(events) ? events : session ?? messages;
7850
+ const revision = source?.cursor ?? session?.seq ?? messages;
7851
+ let cached = historyIndexes.get(owner);
7852
+ if (!cached || cached.revision !== revision) {
7853
+ cached = {
7854
+ revision,
7855
+ ranges: historyIndex(messages, projectTurns(messages, meta?.createdAt, /* @__PURE__ */ new Map(), cwd, /* @__PURE__ */ new Map(), true))
7856
+ };
7857
+ historyIndexes.set(owner, cached);
7858
+ }
7859
+ const live = active.get(id);
7860
+ if (live?.userItem) for (const message of messages) reconcileUser(id, live, message);
7861
+ const outline = withLiveTurn(id, cached.ranges);
7862
+ return {
7863
+ meta,
7864
+ messages,
7865
+ cwd,
7866
+ ranges: cached.ranges,
7867
+ outline
7868
+ };
7869
+ };
7870
+ const renderHistory = async (id, snapshot, selected, signal) => {
7871
+ signal?.throwIfAborted();
7872
+ const wanted = new Set(selected.map((turn) => turn.id));
7873
+ const ranges = snapshot.ranges.filter((range) => wanted.has(turnAliases.get(`${id}\0${range.id}`) ?? range.id));
7874
+ const messages = ranges.flatMap((range) => snapshot.messages.slice(range.from, range.to));
7875
+ const { urls, assets } = await imageUrlsOf(messages, signal);
7876
+ signal?.throwIfAborted();
7877
+ const turns = ranges.flatMap((range) => projectTurns(snapshot.messages.slice(range.from, range.to), snapshot.meta?.createdAt, urls, snapshot.cwd, assets, true));
7878
+ const visible = wanted.has(active.get(id)?.turn.id) ? withLiveTurn(id, turns) : withShownIds(id, turns);
7879
+ const byId = new Map(visible.map((turn) => [turn.id, turn]));
7880
+ return selected.map((turn) => byId.get(turn.id)).filter(Boolean);
7881
+ };
7882
+ const listHistoryTurns = async (params, signal) => {
7883
+ if (params?.itemsView != null && ![
7884
+ "full",
7885
+ "summary",
7886
+ "notLoaded"
7887
+ ].includes(params.itemsView)) throw invalidParams("Invalid turn items view");
7888
+ const id = params?.threadId;
7889
+ const snapshot = await historySnapshot(id, signal);
7890
+ const result = historyPage(snapshot.outline, params, JSON.stringify([id, "turns"]));
7891
+ const full = params?.itemsView == null || params.itemsView === "full";
7892
+ const data = (full ? await renderHistory(id, snapshot, result.data, signal) : result.data.map((turn) => ({
7893
+ ...turn,
7894
+ items: [],
7895
+ itemsView: "notLoaded"
7896
+ }))).map(({ from, to, ...turn }) => turn);
7897
+ phoneLog("history page completed", {
7898
+ threadId: id,
7899
+ type: full ? "full" : "notLoaded",
7900
+ turns: data.length
7901
+ });
7902
+ return {
7903
+ ...result,
7904
+ data
7905
+ };
7906
+ };
7907
+ const listHistoryItems = async (params, signal) => {
7908
+ const id = params?.threadId;
7909
+ if (params?.turnId != null && (typeof params.turnId !== "string" || params.turnId === "")) throw invalidParams("turnId must be nonempty");
7910
+ const snapshot = await historySnapshot(id, signal);
7911
+ const turns = snapshot.outline;
7912
+ if (params?.turnId && !turns.some((turn) => turn.id === params.turnId)) throw invalidParams("Turn not found");
7913
+ let items = turns.flatMap((turn) => turn.items.map((item) => ({
7914
+ id: JSON.stringify([turn.id, item.id]),
7915
+ turnId: turn.id,
7916
+ itemId: item.id
7917
+ })));
7918
+ let cursor = params?.cursor;
7919
+ if (cursor && typeof cursor === "object") {
7920
+ if (cursor.type !== "item" || typeof cursor.itemId !== "string" || !cursor.itemId || !params.turnId) throw invalidParams("An item anchor requires a turnId and itemId");
7921
+ const at = items.findIndex((item) => item.itemId === cursor.itemId && item.turnId === params.turnId);
7922
+ if (at < 0) throw invalidParams("Item anchor not found in this turn");
7923
+ items = params?.sortDirection === "desc" ? items.slice(0, at) : items.slice(at + 1);
7924
+ cursor = void 0;
7925
+ }
7926
+ phoneLog("history items page requested", {
7927
+ threadId: id,
7928
+ turnId: params?.turnId,
7929
+ direction: ["asc", "desc"].includes(params?.sortDirection) ? params.sortDirection : "default",
7930
+ type: params?.cursor && typeof params.cursor === "object" ? "itemAnchor" : params?.cursor ? "opaqueCursor" : "firstPage"
7931
+ });
7932
+ const result = historyPage(items, {
7933
+ ...params,
7934
+ cursor
7935
+ }, JSON.stringify([id, "items"]), "asc", (item) => !params?.turnId || item.turnId === params.turnId);
7936
+ const wanted = new Set(result.data.map((item) => item.turnId));
7937
+ const rendered = await renderHistory(id, snapshot, turns.filter((turn) => wanted.has(turn.id)), signal);
7938
+ const byTurn = new Map(rendered.map((turn) => [turn.id, new Map(turn.items.map((item) => [item.id, item]))]));
7939
+ return {
7940
+ ...result,
7941
+ data: result.data.flatMap((entry) => {
7942
+ const item = byTurn.get(entry.turnId)?.get(entry.itemId);
7943
+ return item ? [{
7944
+ turnId: entry.turnId,
7945
+ item,
7946
+ startedAt: null,
7947
+ completedAt: null
7948
+ }] : [];
7949
+ })
7950
+ };
7951
+ };
7572
7952
  /** Apply a model or effort the phone picked; DSH validates it against its own catalog. */
7573
7953
  const TIER_OF = {
7574
7954
  fast: "priority",
@@ -7978,6 +8358,19 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7978
8358
  snippets
7979
8359
  };
7980
8360
  };
8361
+ const readThreadMetadata = async (id, signal) => {
8362
+ const entry = (await service().list({}, signal)).items?.find((item) => item.sessionId === id && item.origin !== "subagent");
8363
+ if (!entry) throw notFound(id);
8364
+ return thread({
8365
+ id,
8366
+ cwd: entry.cwd,
8367
+ createdAt: entry.createdAt ?? entry.updatedAt,
8368
+ updatedAt: entry.updatedAt,
8369
+ running: entry.running,
8370
+ projectId: projectIdOf(id),
8371
+ title: entry.projections?.values?.title ?? null
8372
+ });
8373
+ };
7981
8374
  const matches = (entry, term, snippets) => {
7982
8375
  const needle = typeof term === "string" ? term.trim().toLocaleLowerCase() : "";
7983
8376
  return needle === "" || snippets.has(entry.id) || `${entry.name ?? ""} ${entry.preview}`.toLocaleLowerCase().includes(needle);
@@ -8087,8 +8480,10 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8087
8480
  inputModalities: modalities.get(model.id)?.length ? modalities.get(model.id) : ["text"],
8088
8481
  supportsPersonality: false,
8089
8482
  additionalSpeedTiers: tiersOf(group.id, model.id).map((tier) => tier.id),
8090
- upgrade: null,
8091
- upgradeInfo: null,
8483
+ ...phoneModelUpgrade(modelMetadata(group.id, model.id), (target) => modelKey({
8484
+ provider: group.id,
8485
+ model: target
8486
+ })),
8092
8487
  availabilityNux: null,
8093
8488
  serviceTiers: tiersOf(group.id, model.id),
8094
8489
  defaultServiceTier: null
@@ -8292,15 +8687,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8292
8687
  };
8293
8688
  },
8294
8689
  "currentTime/read": () => ({ currentTimeAt: seconds(Date.now()) }),
8295
- "account/rateLimits/read": async () => rateLimits(await usage()?.read?.().catch(() => void 0)),
8296
- "thread/turns/list": async (params) => {
8297
- const { thread: value } = await openThread(params?.threadId);
8298
- const ordered = params?.sortDirection === "asc" ? value.turns : value.turns.toReversed();
8299
- return {
8300
- ...page(ordered, params),
8301
- backwardsCursor: ordered.length ? String(0) : null
8302
- };
8303
- },
8690
+ "account/rateLimits/read": async () => phoneRateLimits(await usage()?.read?.().catch(() => void 0)),
8691
+ "thread/turns/list": (params, { signal } = {}) => listHistoryTurns(params, signal),
8692
+ "thread/items/list": (params, { signal } = {}) => listHistoryItems(params, signal),
8304
8693
  "thread/fork": async (params, { notify }) => {
8305
8694
  const forked = await service().fork({ sessionId: params?.threadId });
8306
8695
  const agent = await agentFor(forked.sessionId);
@@ -8396,8 +8785,28 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8396
8785
  await registry.unarchiveSession(params?.threadId);
8397
8786
  return { thread: (await openThread(params?.threadId)).thread };
8398
8787
  },
8399
- "thread/read": async (params, { signal } = {}) => ({ thread: (await openThread(params?.threadId, void 0, signal)).thread }),
8788
+ "thread/read": async (params, { signal } = {}) => ({ thread: params?.includeTurns === false ? {
8789
+ ...await readThreadMetadata(params?.threadId, signal),
8790
+ historyMode: "paginated"
8791
+ } : (await openThread(params?.threadId, void 0, signal)).thread }),
8400
8792
  "thread/resume": async (params, { notify, signal }) => {
8793
+ if (params?.excludeTurns === true) {
8794
+ const value = {
8795
+ ...await readThreadMetadata(params?.threadId, signal),
8796
+ historyMode: "paginated"
8797
+ };
8798
+ const snapshot = await historySnapshot(params.threadId, signal);
8799
+ const agent = await agentFor(params.threadId);
8800
+ if (notify) subscribe(params.threadId, notify);
8801
+ await (catalog ? void 0 : loadCatalog().catch(() => void 0));
8802
+ const itemAnchors = snapshot.outline.flatMap((turn) => turn.items.map((item) => ({ id: JSON.stringify([turn.id, item.id]) })));
8803
+ return {
8804
+ ...settings(agent, value.cwd),
8805
+ thread: value,
8806
+ turnsBackwardsCursor: initialHistoryCursor(snapshot.outline, JSON.stringify([params.threadId, "turns"])),
8807
+ itemsBackwardsCursor: initialHistoryCursor(itemAnchors, JSON.stringify([params.threadId, "items"]))
8808
+ };
8809
+ }
8401
8810
  const { agent, thread: value } = await openThread(params?.threadId, notify, signal);
8402
8811
  return {
8403
8812
  ...settings(agent, value.cwd),
@@ -9057,8 +9466,315 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9057
9466
  };
9058
9467
  }
9059
9468
  //#endregion
9469
+ //#region src/remote-history-source.js
9470
+ const unavailableModule = (error, id) => error?.code === "MODULE_NOT_FOUND" && error.message?.startsWith(`Cannot find module '${id}'`) || error?.code === "ERR_PACKAGE_PATH_NOT_EXPORTED" && error.message?.includes("'./message-projections'") && error.message.replaceAll("\\", "/").includes("/@deepseek-ai/dsh-session-format-catalog/package.json");
9471
+ const failure$2 = (code, message) => Object.assign(new Error(message), { code });
9472
+ /** Read a detached native observation. No agent attachment or private log reader. */
9473
+ function createRemoteHistorySource({ query, loadModule = createRequire(import.meta.url) }) {
9474
+ const derived = /* @__PURE__ */ new WeakMap();
9475
+ let sdk;
9476
+ const modules = () => {
9477
+ if (sdk) return sdk;
9478
+ const load = (id) => {
9479
+ try {
9480
+ return loadModule(id);
9481
+ } catch (error) {
9482
+ if (!unavailableModule(error, id)) throw error;
9483
+ }
9484
+ };
9485
+ const session = load("@deepseek-ai/dsh-session");
9486
+ if (!session) return void 0;
9487
+ const catalog = load("@deepseek-ai/dsh-session-format-catalog/message-projections");
9488
+ if (typeof session.foldSurface !== "function" || typeof session.deriveEventMessage !== "function" || !Array.isArray(catalog?.currentSessionMessageProjections)) return void 0;
9489
+ sdk = {
9490
+ ...session,
9491
+ projections: catalog.currentSessionMessageProjections
9492
+ };
9493
+ return sdk;
9494
+ };
9495
+ return Object.freeze({ async read(id, { signal } = {}) {
9496
+ signal?.throwIfAborted();
9497
+ const service = query();
9498
+ if (typeof service?.observeSession !== "function") return void 0;
9499
+ const native = modules();
9500
+ if (!native) return void 0;
9501
+ const source = await service.observeSession(id, {
9502
+ signal,
9503
+ projectionMode: "none"
9504
+ });
9505
+ try {
9506
+ signal?.throwIfAborted();
9507
+ const header = source?.header;
9508
+ if (header?.id !== id) throw failure$2("SESSION_QUERY_SOURCE_CONFLICT", "Session observation identity does not match the thread");
9509
+ if (header.origin === "subagent" || typeof header.cwd !== "string" || header.cwd.trim() === "") throw failure$2("SESSION_QUERY_SESSION_NOT_FOUND", "Thread is not available");
9510
+ const events = source.events;
9511
+ if (!Array.isArray(events)) throw failure$2("SESSION_QUERY_CORRUPT_SESSION", "Session observation has no event array");
9512
+ let messages = derived.get(events);
9513
+ if (!messages) {
9514
+ const surface = native.foldSurface(events, native.projections);
9515
+ messages = Object.freeze(surface.nodes.map((seq) => native.deriveEventMessage(events[seq], surface.projectedMessages)).filter(Boolean));
9516
+ if (Object.isFrozen(events)) derived.set(events, messages);
9517
+ }
9518
+ signal?.throwIfAborted();
9519
+ return {
9520
+ meta: header,
9521
+ messages,
9522
+ events,
9523
+ cursor: source.cursor,
9524
+ source: source.source,
9525
+ revision: source.revision,
9526
+ inheritedEventCount: source.inheritedEventCount
9527
+ };
9528
+ } finally {
9529
+ source?.[Symbol.dispose]?.();
9530
+ }
9531
+ } });
9532
+ }
9533
+ //#endregion
9534
+ //#region src/ultra-execution.js
9535
+ const ULTRA_POLICY_RECORD = "plugin:dsh-codex-subscription/ultra-policy";
9536
+ const providerId = "openai-codex";
9537
+ const unavailable$1 = (message) => new LlmError(message, "UNSUPPORTED_OPTION");
9538
+ const scopedTools = (agent) => agent?.ctx?.get?.("tools") ?? (Object.hasOwn(agent?.ctx ?? {}, "tools") ? agent.ctx.tools : void 0);
9539
+ /** Native DSH tools/providers only; never install a provider or change a preset. */
9540
+ function nativeDelegations(ctx, agent) {
9541
+ const tools = scopedTools(agent) ?? ctx.get?.("tools");
9542
+ const subagents = ctx.get?.("subagents");
9543
+ return presetEntries(ctx).flatMap((entry) => {
9544
+ const config = entry.fiber?.config ?? entry.options?.config;
9545
+ if (entry.options?.name !== "@deepseek-ai/dsh-tool-subagent" || !["spawn", "codex-subscription-subagent"].includes(config?.provider) || !subagents?.getProvider?.(config.provider)) return [];
9546
+ const name = config.toolName ?? "subagent";
9547
+ const definition = tools?.get?.(name, agent);
9548
+ return agent && !definition ? [] : [{
9549
+ name,
9550
+ definition
9551
+ }];
9552
+ });
9553
+ }
9554
+ /**
9555
+ * Ultra keeps its user-visible selection in Harness headers. Only the inner
9556
+ * adapter receives the model's native effort. DSH owns child scheduling,
9557
+ * sandbox/approval decisions, concurrency/depth budgets and cancellation.
9558
+ */
9559
+ function createUltraExecutionPreset({ catalog, resolveAgent = () => void 0, defaultEffort = () => void 0, delegations = nativeDelegations, record } = {}) {
9560
+ const scope = new AsyncLocalStorage(), bindings = /* @__PURE__ */ new Map();
9561
+ let context, installed = false;
9562
+ const metadata = (id) => catalog?.metadata?.(id)?.ultra;
9563
+ const available = () => installed && typeof record === "function" && typeof context?.get?.("tools")?.guard === "function" && delegations(context).length > 0;
9564
+ const supported = (id) => available() && metadata(id) !== void 0;
9565
+ const deactivate = (binding) => {
9566
+ binding.removeAbort?.();
9567
+ binding.removeAbort = void 0;
9568
+ if (binding.state) binding.state.active = false;
9569
+ };
9570
+ const disposeAgent = (agent) => {
9571
+ const binding = bindings.get(agent);
9572
+ if (!binding) return;
9573
+ deactivate(binding);
9574
+ binding.disposeGuard();
9575
+ bindings.delete(agent);
9576
+ };
9577
+ const bind = (agent) => {
9578
+ let binding = bindings.get(agent);
9579
+ if (binding) return binding;
9580
+ const tools = scopedTools(agent);
9581
+ if (typeof tools?.guard !== "function") throw unavailable$1("Ultra requires the native DSH agent tool policy service");
9582
+ binding = { state: void 0 };
9583
+ binding.disposeGuard = tools.guard((exec) => {
9584
+ const state = binding.state;
9585
+ if (!state || !state.tools.some((tool) => tool.name === exec.name)) return;
9586
+ if (!state.active || state.signal.aborted || exec.agent !== agent) return "Ultra delegation belongs to an inactive or cancelled request";
9587
+ const tool = state.tools.find((tool) => tool.name === exec.name);
9588
+ if (tools.get(exec.name, agent) !== tool.definition) return "Ultra delegation tool changed after request preparation; retry the request";
9589
+ });
9590
+ bindings.set(agent, binding);
9591
+ return binding;
9592
+ };
9593
+ const request = (agent, config, signal, turn) => {
9594
+ const existing = bindings.get(agent);
9595
+ if (existing) deactivate(existing);
9596
+ const implicitUltra = config.reasoningEffort === void 0 && defaultEffort(config.model) === "ultra" && supported(config.model) && delegations(context, agent).length > 0 && typeof scopedTools(agent)?.guard === "function";
9597
+ const selected = config.reasoningEffort ?? (implicitUltra ? "ultra" : void 0);
9598
+ if (config.provider !== providerId || selected !== "ultra") {
9599
+ const binding = bindings.get(agent);
9600
+ if (binding) {
9601
+ deactivate(binding);
9602
+ binding.state = void 0;
9603
+ }
9604
+ return;
9605
+ }
9606
+ signal.throwIfAborted();
9607
+ const preset = metadata(config.model);
9608
+ if (!supported(config.model) || !preset) throw unavailable$1("This account/model does not advertise an available DSH Ultra execution preset");
9609
+ const tools = [...new Map(delegations(context, agent).map((tool) => [tool.name, tool])).values()];
9610
+ if (!tools.length) throw unavailable$1("Ultra requires an independent subagent tool in the selected Agent preset");
9611
+ const binding = bind(agent);
9612
+ const previous = binding.state;
9613
+ deactivate(binding);
9614
+ const policy = Object.freeze({
9615
+ version: 1,
9616
+ provider: config.provider,
9617
+ model: config.model,
9618
+ requestedEffort: "ultra",
9619
+ effectiveEffort: preset.effectiveEffort,
9620
+ delegationPolicy: "proactive",
9621
+ tools: Object.freeze(tools.map((tool) => tool.name)),
9622
+ turn
9623
+ });
9624
+ const state = {
9625
+ policy,
9626
+ tools,
9627
+ signal,
9628
+ active: true,
9629
+ preset: { ...preset }
9630
+ };
9631
+ binding.state = state;
9632
+ const abort = () => {
9633
+ state.active = false;
9634
+ };
9635
+ signal.addEventListener("abort", abort, { once: true });
9636
+ binding.removeAbort = () => signal.removeEventListener("abort", abort);
9637
+ try {
9638
+ if (JSON.stringify(previous?.policy) !== JSON.stringify(policy)) record(agent.session, ULTRA_POLICY_RECORD, policy);
9639
+ } catch (error) {
9640
+ deactivate(binding);
9641
+ throw error;
9642
+ }
9643
+ };
9644
+ const describe = (info) => !info?.reasoning || !supported(info.id) || resolveAgent() && (!delegations(context, resolveAgent()).length || typeof scopedTools(resolveAgent())?.guard !== "function") ? info : {
9645
+ ...info,
9646
+ reasoning: {
9647
+ ...info.reasoning,
9648
+ efforts: [...info.reasoning.efforts.filter((effort) => effort.id !== "ultra"), {
9649
+ id: "ultra",
9650
+ name: `Ultra (DSH parallel · ${metadata(info.id).effectiveEffort})`
9651
+ }]
9652
+ }
9653
+ };
9654
+ const stream = (factory, options, captured) => (async function* () {
9655
+ const auxiliary = ["session-title", "compaction"].includes(options.purpose) || isDshAutoReview(options);
9656
+ let state;
9657
+ let input = options;
9658
+ if (options.provider === providerId && options.reasoningEffort === "ultra") {
9659
+ if (!captured) throw unavailable$1("This account/model does not advertise Ultra");
9660
+ const agent = resolveAgent();
9661
+ if (!auxiliary) {
9662
+ state = bindings.get(agent)?.state;
9663
+ if (!state?.active || state.signal.aborted || agent?.session?.id !== options.sessionId || state.policy.model !== options.model || state.preset.effectiveEffort !== captured.effectiveEffort) throw unavailable$1("Ultra requires a matching live DSH request policy; retry through the Agent");
9664
+ }
9665
+ input = {
9666
+ ...options,
9667
+ reasoningEffort: captured.effectiveEffort === "none" ? "off" : captured.effectiveEffort
9668
+ };
9669
+ }
9670
+ const iterator = scope.run(state, () => factory(input)[Symbol.asyncIterator]());
9671
+ try {
9672
+ for (;;) {
9673
+ const next = await scope.run(state, () => iterator.next());
9674
+ if (next.done) return next.value;
9675
+ yield next.value;
9676
+ }
9677
+ } finally {
9678
+ await scope.run(state, () => iterator.return?.());
9679
+ }
9680
+ })();
9681
+ return {
9682
+ available,
9683
+ supported,
9684
+ snapshot: (agent) => {
9685
+ const state = bindings.get(agent)?.state;
9686
+ return state ? {
9687
+ ...state.policy,
9688
+ tools: [...state.policy.tools],
9689
+ active: state.active && !state.signal.aborted
9690
+ } : void 0;
9691
+ },
9692
+ install(ctx) {
9693
+ if (installed) throw new Error("Ultra execution preset is already installed");
9694
+ context = ctx;
9695
+ installed = true;
9696
+ const disposeRequest = ctx.on("agent/request", async ({ agent, signal, turn }, next) => {
9697
+ const config = await next();
9698
+ request(agent, config, signal, turn);
9699
+ return config;
9700
+ });
9701
+ const disposeAgentListener = ctx.on("agent/disposed", ({ agent }) => disposeAgent(agent));
9702
+ const disposeEnd = ctx.on("session/event", (session, event) => {
9703
+ if (event.type !== "turn/end") return;
9704
+ for (const [agent, binding] of bindings) if (agent.session === session && binding.state?.policy.turn === event.data.turn) deactivate(binding);
9705
+ });
9706
+ return () => {
9707
+ installed = false;
9708
+ disposeRequest();
9709
+ disposeAgentListener();
9710
+ disposeEnd();
9711
+ for (const agent of [...bindings.keys()]) disposeAgent(agent);
9712
+ context = void 0;
9713
+ };
9714
+ },
9715
+ wrapAdapter(adapter) {
9716
+ return new Proxy(adapter, { get(target, property) {
9717
+ const value = Reflect.get(target, property, target);
9718
+ if (property === "resolveModel" && typeof value === "function") return async (...args) => args[0] === providerId ? describe(await value.apply(target, args)) : value.apply(target, args);
9719
+ if (property === "prepareCall" && typeof value === "function") return async (...args) => {
9720
+ const call = await value.apply(target, args);
9721
+ if (args[0] !== providerId) return call;
9722
+ const captured = supported(args[1]) ? { ...metadata(args[1]) } : void 0;
9723
+ return {
9724
+ ...call,
9725
+ model: describe(call.model),
9726
+ stream: (options) => stream((input) => call.stream(input), options, captured)
9727
+ };
9728
+ };
9729
+ if (property === "stream" && typeof value === "function") return (options) => stream((input) => value.call(target, input), options, supported(options.model) ? { ...metadata(options.model) } : void 0);
9730
+ return typeof value === "function" ? value.bind(target) : value;
9731
+ } });
9732
+ },
9733
+ preparePayload(payload) {
9734
+ const state = scope.getStore();
9735
+ if (!state) return payload;
9736
+ if (!state.active || state.signal.aborted || payload.model !== state.policy.model) throw unavailable$1("Ultra request policy is no longer active");
9737
+ if (payload.reasoning?.effort === "ultra" || payload.input?.some((item) => item.type === "configuration_update" && item.reasoning?.effort === "ultra")) throw unavailable$1("Ultra must resolve to a native model effort before sending");
9738
+ if (payload.instructions != null && typeof payload.instructions !== "string") throw unavailable$1("Ultra requires the native Codex instructions contract");
9739
+ const guidance = `DSH Ultra execution preset: the selected model uses ${state.policy.effectiveEffort} reasoning. Proactively delegate useful, bounded independent work with ${state.policy.tools.map((name) => `\`${name}\``).join(" or ")} and continue useful work while it runs. Use the native subagent controls to receive results. Do simple work directly. Respect explicit user limits, the existing depth/concurrency limits, sandbox and approvals; this preset grants no additional permissions. Do not create agents merely to use this preset.`;
9740
+ return {
9741
+ ...payload,
9742
+ ...state.policy.effectiveEffort === "none" ? { reasoning: {
9743
+ ...payload.reasoning,
9744
+ effort: "none"
9745
+ } } : {},
9746
+ instructions: `${payload.instructions ?? ""}\n\n<multi_agent_mode>\n${guidance}\n</multi_agent_mode>`
9747
+ };
9748
+ }
9749
+ };
9750
+ }
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
9060
9776
  //#region src/remote-image-assets.js
9061
- const BASE$1 = "https://chatgpt.com/backend-api/";
9777
+ const BASE$2 = "https://chatgpt.com/backend-api/";
9062
9778
  const FILE_ID = /^file[-_][A-Za-z0-9_-]{1,200}$/u;
9063
9779
  const HASH = /^[a-f0-9]{64}$/u;
9064
9780
  const hash = (value) => createHash("sha256").update(value).digest("hex");
@@ -9148,7 +9864,7 @@ function createRemoteImageAssets({ credentials, fetch: request = globalThis.fetc
9148
9864
  async function upload(bytes, mediaType, auth, owner, key, signal) {
9149
9865
  const api = async (method, path, body) => {
9150
9866
  signal.throwIfAborted();
9151
- const response = await send(BASE$1 + path, {
9867
+ const response = await send(BASE$2 + path, {
9152
9868
  method,
9153
9869
  redirect: "error",
9154
9870
  signal: AbortSignal.any([signal, AbortSignal.timeout(6e4)]),
@@ -10334,6 +11050,24 @@ function isRecord(value) {
10334
11050
  return value !== null && typeof value === "object" && !Array.isArray(value);
10335
11051
  }
10336
11052
  //#endregion
11053
+ //#region src/ultra-effort.js
11054
+ const NATIVE_CODEX_EFFORTS = Object.freeze([
11055
+ "none",
11056
+ "minimal",
11057
+ "low",
11058
+ "medium",
11059
+ "high",
11060
+ "xhigh",
11061
+ "max"
11062
+ ]);
11063
+ function ultraCatalogPreset(value) {
11064
+ const supported = (Array.isArray(value?.supported_reasoning_levels) ? value.supported_reasoning_levels : []).map((item) => item?.effort).filter((effort) => typeof effort === "string");
11065
+ if (!supported.includes("ultra")) return void 0;
11066
+ const override = value.multi_agent_reasoning_effort;
11067
+ const effectiveEffort = override !== "ultra" && supported.includes(override) ? override : supported.includes("max") ? "max" : supported.findLast((effort) => effort !== "ultra") ?? "medium";
11068
+ return NATIVE_CODEX_EFFORTS.includes(effectiveEffort) ? Object.freeze({ effectiveEffort }) : void 0;
11069
+ }
11070
+ //#endregion
10337
11071
  //#region src/model-catalog.js
10338
11072
  const CODEX_MODELS_URL = `https://chatgpt.com/backend-api/codex/models?client_version=${encodeURIComponent(PACKAGE_VERSION)}`;
10339
11073
  const LEVELS = [
@@ -10350,7 +11084,8 @@ const record$6 = (value) => value !== null && typeof value === "object" && !Arra
10350
11084
  const nonEmpty$1 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
10351
11085
  const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0 ? value : void 0;
10352
11086
  function upgradeModelId(value) {
10353
- 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);
11087
+ const modelId = (value) => typeof value === "string" && /^[a-z][a-z0-9._-]{0,79}$/u.test(value) ? value : void 0;
11088
+ return modelId(typeof value.upgrade === "string" ? nonEmpty$1(value.upgrade) : record$6(value.upgrade) ? nonEmpty$1(value.upgrade.model) : void 0) ?? modelId(record$6(value.upgrade_info) ? nonEmpty$1(value.upgrade_info.model) : void 0) ?? modelId(record$6(value.upgradeInfo) ? nonEmpty$1(value.upgradeInfo.model) : void 0);
10354
11089
  }
10355
11090
  function retirementMillis(value) {
10356
11091
  for (const source of [
@@ -10414,7 +11149,11 @@ function serviceTierEntries(value) {
10414
11149
  return found;
10415
11150
  }
10416
11151
  function unsupportedCapabilities(value) {
10417
- const reasoning = capabilityNames((value.supported_reasoning_levels ?? []).map((item) => item?.effort)).filter((level) => !["none", ...LEVELS.slice(1)].includes(level));
11152
+ const reasoning = capabilityNames((value.supported_reasoning_levels ?? []).map((item) => item?.effort)).filter((level) => ![
11153
+ "none",
11154
+ ...LEVELS.slice(1),
11155
+ ...ultraCatalogPreset(value) ? ["ultra"] : []
11156
+ ].includes(level));
10418
11157
  const inputs = capabilityNames(Array.isArray(value.input_modalities) ? value.input_modalities : []).filter((input) => !["text", "image"].includes(input));
10419
11158
  const speeds = capabilityNames([...Array.isArray(value.additional_speed_tiers) ? value.additional_speed_tiers : [], ...Array.isArray(value.service_tiers) ? value.service_tiers.map((tier) => tier?.id) : []]).filter((tier) => ![
10420
11159
  "auto",
@@ -10457,12 +11196,14 @@ function visibleModel(value, displayNames, now) {
10457
11196
  at: retirement.at,
10458
11197
  upgradeTo: retirement.upgradeTo
10459
11198
  } },
11199
+ ...upgradeTo === void 0 ? {} : { upgradeTo },
10460
11200
  priority: Number.isFinite(value.priority) ? value.priority : 0,
10461
11201
  input: input.length > 0 ? input : ["text"],
10462
11202
  contextWindow: positiveInteger(value.context_window) ?? positiveInteger(value.max_context_window),
10463
11203
  ...positiveInteger(value.max_context_window) === void 0 ? {} : { maxContextWindow: value.max_context_window },
10464
11204
  reasoning: supported.length > 0,
10465
11205
  supportsReasoningEffortUpdates: value.supports_reasoning_effort_updates === true,
11206
+ ...ultraCatalogPreset(value) === void 0 ? {} : { ultra: ultraCatalogPreset(value) },
10466
11207
  thinkingLevelMap,
10467
11208
  ...defaultReasoningEffort === void 0 ? {} : { defaultReasoningEffort },
10468
11209
  supportVerbosity: value.support_verbosity === true,
@@ -10821,6 +11562,11 @@ function createDshSearchProvider({ resolveDshProvider, report }) {
10821
11562
  return Object.freeze({
10822
11563
  id: DSH_SEARCH_PROVIDER_ID,
10823
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
+ },
10824
11570
  async search(request, signal) {
10825
11571
  const provider = resolveDshProvider?.();
10826
11572
  if (!provider || provider.id === "codex-subscription-dsh" || provider.available() !== true) throw new WebError("DSH default search is unavailable", "WEB_PROVIDER_UNAVAILABLE");
@@ -10898,6 +11644,7 @@ function createCodexSearchProvider(options) {
10898
11644
  return Object.freeze({
10899
11645
  id: CODEX_SEARCH_PROVIDER_ID,
10900
11646
  available: () => true,
11647
+ ready: () => readCapabilitySettings(options.resolvePreferences?.()).searchMode === "disabled" ? false : subscriptionCredentialReady(options.readCredential),
10901
11648
  async search(request, signal) {
10902
11649
  signal?.throwIfAborted();
10903
11650
  const preferences = readCapabilitySettings(options.resolvePreferences?.());
@@ -11003,6 +11750,14 @@ function createCodexAutoSearchProvider(options) {
11003
11750
  return Object.freeze({
11004
11751
  id: CODEX_AUTO_SEARCH_PROVIDER_ID,
11005
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
+ },
11006
11761
  async search(request, signal) {
11007
11762
  const [first, second] = options.resolveModelProvider?.() === "openai-codex" ? [viaCodex, viaDsh] : [viaDsh, viaCodex];
11008
11763
  try {
@@ -11027,8 +11782,8 @@ const OWN_IDS = /* @__PURE__ */ new Set([
11027
11782
  ]);
11028
11783
  /** Guard the provider itself, including direct/cached handles and hosts without the registry proxy. */
11029
11784
  function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
11030
- const selected = () => {
11031
- if (allowed()) return provider;
11785
+ const selected = (llmProvider) => {
11786
+ if (allowed(llmProvider)) return provider;
11032
11787
  const dsh = resolveDshProvider();
11033
11788
  if (!dsh || OWN_IDS.has(dsh.id) || dsh.available() !== true) throw new WebError("DSH default search is unavailable", "WEB_PROVIDER_UNAVAILABLE");
11034
11789
  return dsh;
@@ -11042,6 +11797,13 @@ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
11042
11797
  return false;
11043
11798
  }
11044
11799
  },
11800
+ async ready(llmProvider) {
11801
+ try {
11802
+ return await selected(llmProvider).ready?.(llmProvider) ?? true;
11803
+ } catch {
11804
+ return false;
11805
+ }
11806
+ },
11045
11807
  async search(request, signal) {
11046
11808
  return selected().search(request, signal);
11047
11809
  }
@@ -11059,6 +11821,10 @@ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
11059
11821
  */
11060
11822
  function createSearchRouter({ registry, configuredId, mode, providers }) {
11061
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
+ };
11062
11828
  const wrappers = /* @__PURE__ */ new Map();
11063
11829
  const routerFor = (id) => {
11064
11830
  let router = wrappers.get(id);
@@ -11066,9 +11832,9 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
11066
11832
  router = Object.freeze({
11067
11833
  id,
11068
11834
  available: () => true,
11835
+ ready: (llmProvider) => selected().ready?.(llmProvider) ?? true,
11069
11836
  search(request, signal) {
11070
- const selected = mode();
11071
- return (selected === "codex" ? providers.codex : selected === "auto" ? providers.auto : providers.dsh).search(request, signal);
11837
+ return selected().search(request, signal);
11072
11838
  }
11073
11839
  });
11074
11840
  wrappers.set(id, router);
@@ -11088,6 +11854,12 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
11088
11854
  //#region src/codex-fetch.js
11089
11855
  const CODEX_FETCH_PROVIDER_ID = "codex-subscription-fetch";
11090
11856
  const MAX_CONTENT = 64e3;
11857
+ const RETRYABLE = /* @__PURE__ */ new Set([
11858
+ 500,
11859
+ 502,
11860
+ 503,
11861
+ 504
11862
+ ]);
11091
11863
  const httpUrl = (value) => {
11092
11864
  try {
11093
11865
  const url = new URL(value);
@@ -11102,6 +11874,7 @@ function createCodexFetchProvider(options) {
11102
11874
  return Object.freeze({
11103
11875
  id: CODEX_FETCH_PROVIDER_ID,
11104
11876
  available: () => true,
11877
+ ready: (llmProvider) => options.allowed?.(llmProvider) === false ? false : subscriptionCredentialReady(options.readCredential),
11105
11878
  async fetch(request, signal) {
11106
11879
  signal?.throwIfAborted();
11107
11880
  if (options.allowed?.() === false) throw new WebError("Codex webpage reading is disabled for this model", "WEB_PROVIDER_UNAVAILABLE");
@@ -11119,59 +11892,78 @@ function createCodexFetchProvider(options) {
11119
11892
  const timeout = AbortSignal.timeout(options.timeoutMs ?? 3e4);
11120
11893
  const activeSignal = signal === void 0 ? timeout : AbortSignal.any([signal, timeout]);
11121
11894
  try {
11122
- const response = await fetchPage(CODEX_SEARCH_URL, {
11123
- method: "POST",
11124
- redirect: "error",
11125
- headers: {
11126
- authorization: `Bearer ${access}`,
11127
- "chatgpt-account-id": accountId,
11128
- accept: "application/json",
11129
- "content-type": "application/json",
11130
- originator: "pi",
11131
- "user-agent": USER_AGENT
11132
- },
11133
- body: JSON.stringify({
11134
- id: options.resolveSessionId?.() || randomUUID(),
11135
- model: options.resolveModel?.() || "gpt-5.6-luna",
11136
- input: url,
11137
- commands: {
11138
- open: [{ ref_id: url }],
11139
- 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
11140
11906
  },
11141
- settings: {
11142
- allowed_callers: ["direct"],
11143
- 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)
11144
11963
  },
11145
- max_output_tokens: 4096
11146
- }),
11147
- signal: activeSignal
11148
- });
11149
- activeSignal.throwIfAborted();
11150
- if (!response.ok) {
11151
- const authFailure = await authFailureMessage(response);
11152
- 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
+ };
11153
11966
  }
11154
- const value = await response.json();
11155
- activeSignal.throwIfAborted();
11156
- const source = Array.isArray(value?.results) ? value.results.find((item) => httpUrl(item?.url) !== void 0 && item?.type !== "error" && item?.title !== "Internal Error") : void 0;
11157
- const output = typeof value?.output === "string" ? value.output : "";
11158
- const heading = output.split(/\r?\n/u, 1)[0].trim();
11159
- const headingUrl = heading.endsWith(")") ? httpUrl(heading.slice(heading.lastIndexOf(" (") + 2, -1)) : void 0;
11160
- const metadata = output.slice(0, 1024);
11161
- const pageUrl = source ? httpUrl(source.url) : headingUrl && /Content type:/u.test(metadata) && /Source: open\(/u.test(metadata) ? headingUrl : void 0;
11162
- if (!pageUrl || output.trim() === "" || /^Internal Error(?:\s|\()/iu.test(heading)) throw new WebError("Codex could not read this webpage", "WEB_PROVIDER_ERROR");
11163
- const lineCount = Number(metadata.match(/Total lines: (\d+)/u)?.[1]);
11164
- const shownLines = new Set([...output.matchAll(/^L(\d+):/gmu)].map((match) => Number(match[1]))).size;
11165
- const partialPage = Number.isSafeInteger(lineCount) && lineCount > 0 && shownLines > 0 && shownLines < lineCount;
11166
- return {
11167
- url: pageUrl,
11168
- statusCode: 200,
11169
- body: {
11170
- kind: "text",
11171
- content: output.slice(0, MAX_CONTENT)
11172
- },
11173
- truncated: output.length > MAX_CONTENT || partialPage
11174
- };
11175
11967
  } catch (error) {
11176
11968
  if (signal?.aborted || error?.name === "AbortError") throw new WebError("Codex webpage request aborted", "WEB_ABORTED");
11177
11969
  if (activeSignal.aborted) throw new WebError("Codex webpage request timed out", "WEB_FETCH_TIMEOUT");
@@ -11189,6 +11981,7 @@ function createCodexFetchRouter({ registry, configuredId, mode, codex }) {
11189
11981
  if (!wrappers.has(id)) wrappers.set(id, Object.freeze({
11190
11982
  id,
11191
11983
  available: () => mode() === "codex",
11984
+ ready: (llmProvider) => mode() === "codex" && (codex.ready?.(llmProvider) ?? true),
11192
11985
  fetch(request, signal) {
11193
11986
  if (mode() !== "codex") throw new WebError("Codex webpage reading is no longer selected", "WEB_PROVIDER_UNAVAILABLE");
11194
11987
  return codex.fetch(request, signal);
@@ -11564,6 +12357,7 @@ const actions = Object.freeze({
11564
12357
  "account/remove": "accounts",
11565
12358
  "preferences/update": "settings",
11566
12359
  "account/cleanup": "accounts",
12360
+ "predictions/generate": "predictions",
11567
12361
  usage: "quota",
11568
12362
  "preferences/models": "models",
11569
12363
  "storage/status": "storage",
@@ -11577,7 +12371,8 @@ const actions = Object.freeze({
11577
12371
  const QUIET = /* @__PURE__ */ new Set([
11578
12372
  "usage",
11579
12373
  "storage/status",
11580
- "preferences/models"
12374
+ "preferences/models",
12375
+ "predictions/generate"
11581
12376
  ]);
11582
12377
  function safeOperations(raw) {
11583
12378
  if (!Array.isArray(raw?.events)) return void 0;
@@ -11620,6 +12415,7 @@ function createDiagnosticOperations({ now = Date.now } = {}) {
11620
12415
  });
11621
12416
  if (status === "failed") diagnosticLog.error(actions[action], `${action} failed`);
11622
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");
11623
12419
  if (events.length > 32) {
11624
12420
  events.shift();
11625
12421
  dropped++;
@@ -11630,6 +12426,14 @@ function createDiagnosticOperations({ now = Date.now } = {}) {
11630
12426
  wrap: (handler) => async (endpoint, payload, signal) => {
11631
12427
  try {
11632
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
+ }
11633
12437
  record(endpoint, result?.ok === true ? "completed" : "failed");
11634
12438
  return result;
11635
12439
  } catch (error) {
@@ -11994,6 +12798,64 @@ function highestUsed(windows) {
11994
12798
  return values.length === 0 ? void 0 : Math.max(...values);
11995
12799
  }
11996
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
11997
12859
  //#region src/usage.js
11998
12860
  const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
11999
12861
  const DEFAULT_TIMEOUT_MS$1 = 15e3;
@@ -12185,8 +13047,8 @@ function createCodexUsageReader(options) {
12185
13047
  const maxRetryAfterMs = options.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS;
12186
13048
  let cached;
12187
13049
  let failed;
12188
- let inFlight;
12189
13050
  let generation = 0;
13051
+ const requests = createSharedRequests();
12190
13052
  const load = async (signal) => {
12191
13053
  const { access, accountId } = await readSubscriptionCredentials(getAuth, readCredential, signal);
12192
13054
  if (typeof access !== "string" || access.length === 0 || typeof accountId !== "string" || accountId.length === 0) throw new Error("ChatGPT subscription is not signed in");
@@ -12220,36 +13082,37 @@ function createCodexUsageReader(options) {
12220
13082
  };
12221
13083
  return Object.freeze({
12222
13084
  read({ force = false, signal } = {}) {
13085
+ if (signal?.aborted) return Promise.reject(signal.reason);
12223
13086
  if (failed !== void 0 && now() < failed.retryAt) return Promise.reject(new Error(failed.message));
12224
13087
  if (!force && cached !== void 0 && now() - cached.fetchedAt < ttlFor(cached)) return Promise.resolve(structuredClone(cached));
12225
- if (inFlight !== void 0) return inFlight.then(structuredClone);
12226
- const currentGeneration = generation;
12227
- const current = load(signal).then((value) => {
12228
- if (generation === currentGeneration) {
12229
- cached = structuredClone(value);
12230
- failed = void 0;
12231
- }
12232
- return structuredClone(value);
12233
- }).catch((error) => {
12234
- if (generation === currentGeneration && error?.name !== "AbortError") {
12235
- const delay = Number.isFinite(error?.retryAfterMs) ? error.retryAfterMs : failureTtlMs;
12236
- failed = {
12237
- message: error instanceof Error ? error.message : "ChatGPT usage request failed",
12238
- retryAt: now() + delay
12239
- };
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;
12240
13108
  }
12241
- throw error;
12242
- }).finally(() => {
12243
- if (inFlight === current) inFlight = void 0;
12244
- });
12245
- inFlight = current;
12246
- return current;
13109
+ }, signal).then(structuredClone);
12247
13110
  },
12248
13111
  clear() {
12249
13112
  generation += 1;
12250
13113
  cached = void 0;
12251
13114
  failed = void 0;
12252
- inFlight = void 0;
13115
+ requests.clear();
12253
13116
  }
12254
13117
  });
12255
13118
  }
@@ -12408,7 +13271,8 @@ function parsePlanHistory(value) {
12408
13271
  }
12409
13272
  /** Reads one authenticated report through the same credentials as the quota reader; a 404 means the account has no such report. */
12410
13273
  function createReportReader({ url, parse, label, getAuth, readCredential, fetch: fetchReport = fetch, now = Date.now, ttlMs = TTL_MS }) {
12411
- let cached, failed, inFlight, generation = 0;
13274
+ let cached, failed, generation = 0;
13275
+ const requests = createSharedRequests();
12412
13276
  const load = async (signal) => {
12413
13277
  const { access, accountId } = await readSubscriptionCredentials(getAuth, readCredential, signal);
12414
13278
  if (typeof access !== "string" || access.length === 0 || typeof accountId !== "string" || accountId.length === 0) throw new Error("ChatGPT subscription is not signed in");
@@ -12444,33 +13308,34 @@ function createReportReader({ url, parse, label, getAuth, readCredential, fetch:
12444
13308
  };
12445
13309
  return Object.freeze({
12446
13310
  read({ force = false, signal } = {}) {
13311
+ if (signal?.aborted) return Promise.reject(signal.reason);
12447
13312
  if (failed !== void 0 && now() < failed.retryAt) return Promise.reject(new Error(failed.message));
12448
- if (!force && cached !== void 0 && now() - cached.fetchedAt < ttlMs) return Promise.resolve(structuredClone(cached));
12449
- if (inFlight !== void 0) return inFlight.then(structuredClone);
12450
- const current = generation;
12451
- const run = load(signal).then((value) => {
12452
- if (generation === current) {
12453
- cached = structuredClone(value);
12454
- 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;
12455
13331
  }
12456
- return structuredClone(value);
12457
- }).catch((error) => {
12458
- if (generation === current && error?.name !== "AbortError") failed = {
12459
- message: error instanceof Error ? error.message : `ChatGPT ${label} request failed`,
12460
- retryAt: now() + FAILURE_TTL_MS
12461
- };
12462
- throw error;
12463
- }).finally(() => {
12464
- if (inFlight === run) inFlight = void 0;
12465
- });
12466
- inFlight = run;
12467
- return run;
13332
+ }, signal).then(structuredClone);
12468
13333
  },
12469
13334
  clear() {
12470
13335
  generation += 1;
12471
13336
  cached = void 0;
12472
13337
  failed = void 0;
12473
- inFlight = void 0;
13338
+ requests.clear();
12474
13339
  }
12475
13340
  });
12476
13341
  }
@@ -13750,8 +14615,68 @@ async function settlesLive(preferences, patch, signal, { attempts = 8, delayMs =
13750
14615
  }
13751
14616
  return live();
13752
14617
  }
13753
- function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageReader, planHistoryReader, usageProfileReader, resetCreditService, preferences, defaultModel, runtimeManagement, remoteControl, desktopVoice, 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 }) {
13754
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
+ }
14630
+ if (endpoint.startsWith("voice/native/")) try {
14631
+ signal.throwIfAborted();
14632
+ if (!nativeVoice) return publicError("voice-native-unavailable", "Native voice is unavailable");
14633
+ const action = endpoint.slice(13);
14634
+ if (action === "probe") return {
14635
+ ok: true,
14636
+ value: await nativeVoice.probe(signal)
14637
+ };
14638
+ const sessionId = payload?.sessionId;
14639
+ if (typeof sessionId !== "string" || !sessionId || sessionId.length > 512) return publicError("invalid-input", "Invalid voice request");
14640
+ if (action === "start") {
14641
+ const current = preferences?.status?.() ?? {};
14642
+ if (current.voiceCall !== "on") return publicError("unavailable", "Voice is turned off");
14643
+ if (payload.captureAllowed !== true) return publicError("invalid-input", "Microphone permission is required");
14644
+ return {
14645
+ ok: true,
14646
+ value: await nativeVoice.start({
14647
+ sessionId,
14648
+ captureAllowed: true,
14649
+ voice: current.voiceVoice,
14650
+ language: current.voiceLanguage
14651
+ }, signal)
14652
+ };
14653
+ }
14654
+ const leaseToken = payload?.leaseToken;
14655
+ if (typeof leaseToken !== "string" || leaseToken.length < 16 || leaseToken.length > 128) return publicError("invalid-input", "Invalid voice owner");
14656
+ if (action === "status") return {
14657
+ ok: true,
14658
+ value: nativeVoice.status(sessionId, leaseToken)
14659
+ };
14660
+ if (action === "stop") return {
14661
+ ok: true,
14662
+ value: await nativeVoice.stop({
14663
+ sessionId,
14664
+ leaseToken
14665
+ })
14666
+ };
14667
+ if (action === "control" && ["mute", "outputMute"].includes(payload.action) && typeof payload.muted === "boolean") return {
14668
+ ok: true,
14669
+ value: await nativeVoice[payload.action]({
14670
+ sessionId,
14671
+ leaseToken,
14672
+ muted: payload.muted
14673
+ })
14674
+ };
14675
+ return publicError("invalid-input", "Invalid voice request");
14676
+ } catch (error) {
14677
+ if (signal.aborted) throw error;
14678
+ return publicError(error?.code === "voice-native-unavailable" ? "voice-native-unavailable" : "operation-error", "Could not use native voice");
14679
+ }
13755
14680
  if (endpoint === "default-model/status" || endpoint === "default-model/select") try {
13756
14681
  signal.throwIfAborted();
13757
14682
  if (!defaultModel) return publicError("unavailable", "The default model is unavailable");
@@ -13800,6 +14725,8 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13800
14725
  }
13801
14726
  const current = preferences?.status?.() ?? {};
13802
14727
  if (current.voiceCall !== "on") return publicError("unavailable", "Voice is turned off");
14728
+ await nativeVoice?.close();
14729
+ signal.throwIfAborted();
13803
14730
  return {
13804
14731
  ok: true,
13805
14732
  value: await desktopVoice.start({
@@ -13924,6 +14851,7 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13924
14851
  verbosityModels: Array.isArray(value?.verbosityModels) ? value.verbosityModels : [],
13925
14852
  fastModels: Array.isArray(value?.fastModels) ? value.fastModels : [],
13926
14853
  ultrafastModels: Array.isArray(value?.ultrafastModels) ? value.ultrafastModels : [],
14854
+ ultraModels: Array.isArray(value?.ultraModels) ? value.ultraModels : [],
13927
14855
  catalogStatus: value?.catalogStatus
13928
14856
  }
13929
14857
  };
@@ -14102,86 +15030,365 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
14102
15030
  }
14103
15031
  //#endregion
14104
15032
  //#region src/voice-preview.js
14105
- const BASE = "https://chatgpt.com/backend-api";
15033
+ const BASE$1 = "https://chatgpt.com/backend-api";
14106
15034
  const CATALOG_TTL_MS = 10 * 6e4;
14107
15035
  const MAX_CLIP_BYTES = 2 * 1024 * 1024;
15036
+ const MAX_CACHED_AUDIO_BYTES = 8 * 1024 * 1024;
14108
15037
  const PREVIEW_HOSTS = /^https:\/\/[a-z0-9.-]*oaistatic\.com\//u;
14109
- const failure = (code, message) => Object.assign(new Error(message), { code });
14110
- function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, base = BASE }) {
15038
+ const failure$1 = (code, message) => Object.assign(new Error(message), { code });
15039
+ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, base = BASE$1, maxCachedAudioBytes = MAX_CACHED_AUDIO_BYTES }) {
14111
15040
  const catalogs = /* @__PURE__ */ new Map();
14112
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;
14113
15045
  const languageOf = (value) => {
14114
15046
  const language = normalizeVoiceLanguage(value);
14115
15047
  return language === "auto" ? "en" : language;
14116
15048
  };
14117
- 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) => {
14118
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) => {
15075
+ signal?.throwIfAborted();
15076
+ if (auth.generation !== generation) throw cancelled();
14119
15077
  const catalog = catalogs.get(language);
14120
15078
  if (catalog && now() - catalog.at < CATALOG_TTL_MS) return catalog.voices;
14121
- let value;
14122
- try {
14123
- const { access, accountId } = await credentials(signal);
14124
- if (!access || !accountId) throw failure("voice-auth", "ChatGPT sign-in is required");
14125
- const response = await fetch(`${base}/settings/voices?spoken_language=${language}`, {
14126
- headers: {
14127
- authorization: `Bearer ${access}`,
14128
- "chatgpt-account-id": accountId,
14129
- accept: "application/json",
14130
- "user-agent": userAgent
14131
- },
14132
- 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
14133
15106
  });
14134
- if (response.status === 401) throw failure("voice-auth", "ChatGPT sign-in needs renewal");
14135
- if (!response.ok) throw failure("voice-catalog", `voice catalog HTTP ${response.status}`);
14136
- value = await response.json();
14137
- if (!Array.isArray(value?.voices)) throw failure("voice-catalog", "Invalid voice catalog");
14138
- signal?.throwIfAborted();
14139
- } catch (error) {
14140
- signal?.throwIfAborted();
14141
- if (error?.code === "voice-auth" || error?.code === "voice-catalog") throw error;
14142
- throw failure("voice-catalog", "Could not load the voice catalog");
14143
- }
14144
- 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));
14145
- catalogs.set(language, {
14146
- at: now(),
14147
- voices
14148
- });
14149
- return voices;
15107
+ return voices;
15108
+ }, signal);
14150
15109
  };
14151
15110
  return {
15111
+ clear,
14152
15112
  /** Which voices ChatGPT's own catalog offers right now (lower-case names), so the settings can mark the others unavailable. */
14153
15113
  async available(language, signal) {
14154
- 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());
14155
15119
  },
14156
15120
  /** The clip of one voice (by its Codex name, e.g. "spruce") as a data URL, with the catalog's description. */
14157
15121
  async preview(voice, selectedLanguage, signal) {
14158
15122
  signal?.throwIfAborted();
14159
15123
  if (typeof voice !== "string" || !/^[a-z]{2,16}$/u.test(voice)) return void 0;
15124
+ const auth = await scope(signal);
14160
15125
  const language = languageOf(selectedLanguage);
14161
- const key = `${language}:${voice}`;
14162
- if (clips.has(key)) return clips.get(key);
14163
- 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();
14164
15129
  if (!entry) return void 0;
14165
- let bytes;
14166
- try {
14167
- const response = await fetch(entry.preview_url, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3) });
14168
- if (!response.ok) throw failure("voice-download", `voice sample HTTP ${response.status}`);
14169
- bytes = Buffer.from(await response.arrayBuffer());
14170
- if (bytes.byteLength === 0 || bytes.byteLength > MAX_CLIP_BYTES) throw failure("voice-download", "voice sample has an unexpected size");
14171
- signal?.throwIfAborted();
14172
- } catch {
14173
- signal?.throwIfAborted();
14174
- throw failure("voice-download", "Could not download the voice sample");
14175
- }
14176
- const type = /\.mp3(?:$|\?)/u.test(entry.preview_url) ? "audio/mpeg" : "audio/mp4";
14177
- 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 {
14178
15164
  name: entry.name,
14179
15165
  description: typeof entry.description === "string" ? entry.description.slice(0, 120) : "",
14180
15166
  accent: typeof entry.accent === "string" ? entry.accent.slice(0, 60) : "",
14181
- audio: `data:${type};base64,${bytes.toString("base64")}`
15167
+ audio
14182
15168
  };
14183
- if (clips.size < 40) clips.set(key, result);
14184
- 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);
14185
15392
  }
14186
15393
  };
14187
15394
  }
@@ -14254,6 +15461,628 @@ function withEndCallTool(desktopVoice, register) {
14254
15461
  });
14255
15462
  }
14256
15463
  //#endregion
15464
+ //#region src/voice-barge-in.js
15465
+ /** Mute playback promptly, and restore it only after interrupted audio has drained. */
15466
+ function createBargeInGate({ interrupt, changed, speechMs = 120, silenceMs = 400, outputTailMs = 0 }) {
15467
+ let speakingAt, quietAt, outputQuietAt, suppressed = false, drained = false;
15468
+ let outputActiveAt;
15469
+ return { sample({ mic, output, now }) {
15470
+ if (mic > .12) {
15471
+ speakingAt ??= now;
15472
+ quietAt = void 0;
15473
+ } else {
15474
+ speakingAt = void 0;
15475
+ quietAt ??= now;
15476
+ }
15477
+ if (output < .025) outputQuietAt ??= now;
15478
+ else outputQuietAt = void 0;
15479
+ if (output > .025) outputActiveAt = now;
15480
+ const recentOutput = outputTailMs > 0 && outputActiveAt !== void 0 && now - outputActiveAt <= outputTailMs;
15481
+ if (!suppressed && speakingAt !== void 0 && now - speakingAt >= speechMs && (output > .025 || recentOutput)) {
15482
+ suppressed = true;
15483
+ drained = false;
15484
+ changed(true);
15485
+ interrupt();
15486
+ }
15487
+ if (suppressed && outputQuietAt !== void 0 && now - outputQuietAt >= 250) drained = true;
15488
+ if (suppressed && drained && quietAt !== void 0 && now - quietAt >= silenceMs) {
15489
+ suppressed = false;
15490
+ speakingAt = void 0;
15491
+ changed(false);
15492
+ }
15493
+ } };
15494
+ }
15495
+ //#endregion
15496
+ //#region src/voice-native-host.js
15497
+ const MAX_LINE = 128 * 1024;
15498
+ const START_TIMEOUT = 3e4;
15499
+ const LEASE_TIMEOUT = 1e4;
15500
+ const helperFile = fileURLToPath(new URL("../native/linux-voice-helper.py", import.meta.url));
15501
+ const failure = (code, message = "Native voice is unavailable") => Object.assign(new Error(message), { code });
15502
+ const aborted = () => Object.assign(/* @__PURE__ */ new Error("Native voice was cancelled"), {
15503
+ name: "AbortError",
15504
+ code: "ABORT_ERR"
15505
+ });
15506
+ function withAbort(promise, signal) {
15507
+ if (signal.aborted) {
15508
+ Promise.resolve(promise).catch(() => {});
15509
+ return Promise.reject(aborted());
15510
+ }
15511
+ let cancel;
15512
+ const cancellation = new Promise((_, reject) => {
15513
+ cancel = () => reject(aborted());
15514
+ signal.addEventListener("abort", cancel, { once: true });
15515
+ });
15516
+ return Promise.race([promise, cancellation]).finally(() => signal.removeEventListener("abort", cancel));
15517
+ }
15518
+ /** Fixed JSON-lines transport. Stderr and SDP are never forwarded to diagnostics. */
15519
+ function helperPort(spawn, python, path, onEvent, onFailure) {
15520
+ const env = {};
15521
+ for (const key of [
15522
+ "PATH",
15523
+ "HOME",
15524
+ "LANG",
15525
+ "LC_ALL",
15526
+ "LC_CTYPE",
15527
+ "XDG_RUNTIME_DIR",
15528
+ "XDG_CONFIG_HOME",
15529
+ "XDG_DATA_HOME",
15530
+ "DBUS_SESSION_BUS_ADDRESS",
15531
+ "PULSE_SERVER",
15532
+ "PULSE_COOKIE",
15533
+ "GI_TYPELIB_PATH",
15534
+ "GST_PLUGIN_PATH",
15535
+ "LD_LIBRARY_PATH"
15536
+ ]) if (process.env[key] !== void 0) env[key] = process.env[key];
15537
+ env.PYTHONUNBUFFERED = "1";
15538
+ const child = spawn(python, [path], {
15539
+ shell: false,
15540
+ stdio: [
15541
+ "pipe",
15542
+ "pipe",
15543
+ "pipe"
15544
+ ],
15545
+ env
15546
+ });
15547
+ const pending = /* @__PURE__ */ new Map(), waiting = /* @__PURE__ */ new Map(), events = /* @__PURE__ */ new Map();
15548
+ let buffer = Buffer.alloc(0), sequence = 0, broken, closing = false, exited = false, shutdown;
15549
+ let finished;
15550
+ const exit = new Promise((resolve) => {
15551
+ finished = resolve;
15552
+ });
15553
+ const fail = (code) => {
15554
+ if (broken || closing) return;
15555
+ broken = failure(code);
15556
+ for (const value of pending.values()) value.reject(broken);
15557
+ for (const values of waiting.values()) for (const value of values) value.reject(broken);
15558
+ pending.clear();
15559
+ waiting.clear();
15560
+ onFailure?.(broken);
15561
+ };
15562
+ const receive = (message) => {
15563
+ if (!message || typeof message !== "object" || Array.isArray(message)) {
15564
+ fail("native-protocol");
15565
+ return;
15566
+ }
15567
+ if (Object.hasOwn(message, "id")) {
15568
+ const entry = pending.get(message.id);
15569
+ if (!entry) return;
15570
+ pending.delete(message.id);
15571
+ if (message.ok === true) entry.resolve(message);
15572
+ else entry.reject(failure("native-command"));
15573
+ return;
15574
+ }
15575
+ if (message.event === "error") {
15576
+ fail("native-helper");
15577
+ return;
15578
+ }
15579
+ if (message.event === "closed" || message.event === "state" && [
15580
+ "failed",
15581
+ "closed",
15582
+ "disconnected"
15583
+ ].includes(message.state)) {
15584
+ fail("native-disconnected");
15585
+ return;
15586
+ }
15587
+ const key = message.event === "state" ? "state:" + message.state : message.event;
15588
+ if (key === "offer" || key === "state:connected") {
15589
+ events.set(key, message);
15590
+ for (const waiter of waiting.get(key) ?? []) waiter.resolve(message);
15591
+ waiting.delete(key);
15592
+ }
15593
+ onEvent?.(message);
15594
+ };
15595
+ child.stdout.on("data", (chunk) => {
15596
+ if (broken || closing) return;
15597
+ const incoming = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
15598
+ let offset = 0;
15599
+ while (offset < incoming.length) {
15600
+ const newline = incoming.indexOf(10, offset);
15601
+ const end = newline === -1 ? incoming.length : newline;
15602
+ const part = incoming.subarray(offset, end);
15603
+ if (buffer.length + part.length + (newline === -1 ? 0 : 1) > MAX_LINE) {
15604
+ fail("native-protocol-size");
15605
+ return;
15606
+ }
15607
+ if (newline === -1) {
15608
+ if (buffer.length + part.length >= MAX_LINE) {
15609
+ fail("native-protocol-size");
15610
+ return;
15611
+ }
15612
+ buffer = buffer.length ? Buffer.concat([buffer, part]) : Buffer.from(part);
15613
+ return;
15614
+ }
15615
+ const line = buffer.length ? Buffer.concat([buffer, part]) : part;
15616
+ buffer = Buffer.alloc(0);
15617
+ try {
15618
+ receive(JSON.parse(line.toString("utf8")));
15619
+ } catch {
15620
+ fail("native-protocol");
15621
+ return;
15622
+ }
15623
+ if (broken || closing) return;
15624
+ offset = end + 1;
15625
+ }
15626
+ });
15627
+ child.stdout.on("end", () => fail("native-eof"));
15628
+ child.stdout.on("error", () => fail("native-io"));
15629
+ child.stdin.on("error", () => fail("native-io"));
15630
+ child.stderr?.on("error", () => {});
15631
+ child.stderr?.resume();
15632
+ child.on("error", () => {
15633
+ fail("native-spawn");
15634
+ if (!child.pid) {
15635
+ exited = true;
15636
+ finished();
15637
+ }
15638
+ });
15639
+ child.on("exit", () => fail("native-exit"));
15640
+ child.on("close", () => {
15641
+ exited = true;
15642
+ finished();
15643
+ fail("native-exit");
15644
+ });
15645
+ const request = (type, fields = {}, timeout = 5e3) => {
15646
+ if (broken || closing) return Promise.reject(broken ?? failure("native-closed"));
15647
+ const id = ++sequence;
15648
+ const data = JSON.stringify({
15649
+ ...fields,
15650
+ id,
15651
+ type
15652
+ }) + "\n";
15653
+ if (Buffer.byteLength(data) > MAX_LINE) return Promise.reject(failure("native-protocol-size"));
15654
+ return new Promise((resolve, reject) => {
15655
+ const timer = setTimeout(() => {
15656
+ pending.delete(id);
15657
+ reject(failure("native-command-timeout"));
15658
+ }, timeout);
15659
+ pending.set(id, {
15660
+ resolve: (value) => {
15661
+ clearTimeout(timer);
15662
+ resolve(value);
15663
+ },
15664
+ reject: (error) => {
15665
+ clearTimeout(timer);
15666
+ reject(error);
15667
+ }
15668
+ });
15669
+ try {
15670
+ child.stdin.write(data);
15671
+ } catch {
15672
+ pending.get(id)?.reject(failure("native-io"));
15673
+ pending.delete(id);
15674
+ }
15675
+ });
15676
+ };
15677
+ return {
15678
+ request,
15679
+ closed: exit,
15680
+ wait(key) {
15681
+ if (broken || closing) return Promise.reject(broken ?? failure("native-closed"));
15682
+ if (events.has(key)) return Promise.resolve(events.get(key));
15683
+ return new Promise((resolve, reject) => {
15684
+ const values = waiting.get(key) ?? [];
15685
+ values.push({
15686
+ resolve,
15687
+ reject
15688
+ });
15689
+ waiting.set(key, values);
15690
+ });
15691
+ },
15692
+ close() {
15693
+ if (shutdown) return shutdown;
15694
+ closing = true;
15695
+ for (const entry of pending.values()) entry.reject(failure("native-closed"));
15696
+ for (const values of waiting.values()) for (const entry of values) entry.reject(failure("native-closed"));
15697
+ pending.clear();
15698
+ waiting.clear();
15699
+ events.clear();
15700
+ buffer = Buffer.alloc(0);
15701
+ shutdown = (async () => {
15702
+ try {
15703
+ child.stdin.end();
15704
+ } catch {}
15705
+ const wait = async (ms) => {
15706
+ let timer;
15707
+ await Promise.race([exit, new Promise((resolve) => {
15708
+ timer = setTimeout(resolve, ms);
15709
+ })]);
15710
+ clearTimeout(timer);
15711
+ };
15712
+ if (!exited) await wait(750);
15713
+ if (!exited) {
15714
+ try {
15715
+ child.kill("SIGTERM");
15716
+ } catch {}
15717
+ await wait(500);
15718
+ }
15719
+ if (!exited) {
15720
+ try {
15721
+ child.kill("SIGKILL");
15722
+ } catch {}
15723
+ await wait(500);
15724
+ }
15725
+ if (!exited) throw failure("native-helper-cleanup", "The native audio process has not exited");
15726
+ })();
15727
+ return shutdown;
15728
+ }
15729
+ };
15730
+ }
15731
+ /** One native device lease, backed by the existing authenticated desktop call service. */
15732
+ function createNativeVoiceHost({ desktopVoice, spawn: spawn$1 = spawn, platform = process.platform, helperPath = helperFile, python = "python3", log } = {}) {
15733
+ let current, last, closing, probing = false;
15734
+ const probes = /* @__PURE__ */ new Set(), remotePending = /* @__PURE__ */ new Map();
15735
+ const owns = (call, sessionId, leaseToken) => call && call.sessionId === sessionId && call.leaseToken === leaseToken;
15736
+ const safeLog = (code) => {
15737
+ try {
15738
+ log?.warn?.("voice-native", code);
15739
+ } catch {}
15740
+ };
15741
+ const info = (code) => {
15742
+ try {
15743
+ log?.info?.("voice-native", code);
15744
+ } catch {}
15745
+ };
15746
+ const stopRemote = (call) => {
15747
+ if (!call.remoteRequested) return;
15748
+ try {
15749
+ Promise.resolve(desktopVoice.stop(call.sessionId)).catch(() => safeLog("native-remote-cleanup"));
15750
+ } catch {
15751
+ safeLog("native-remote-cleanup");
15752
+ }
15753
+ };
15754
+ const closeCall = (call, code) => {
15755
+ if (call.closing) return call.closing;
15756
+ call.ended = true;
15757
+ call.state = "closed";
15758
+ info(code);
15759
+ clearTimeout(call.deadline);
15760
+ clearInterval(call.heartbeat);
15761
+ call.removeAbort?.();
15762
+ call.controller.abort();
15763
+ stopRemote(call);
15764
+ last = {
15765
+ sessionId: call.sessionId,
15766
+ leaseToken: call.leaseToken,
15767
+ code
15768
+ };
15769
+ const released = () => {
15770
+ if (current === call) current = void 0;
15771
+ };
15772
+ call.port?.closed.then(released);
15773
+ call.closing = Promise.resolve(call.port?.close()).then(released);
15774
+ call.closing.catch(() => safeLog("native-helper-cleanup"));
15775
+ return call.closing;
15776
+ };
15777
+ const owner = (params) => {
15778
+ if (!owns(current, params?.sessionId, params?.leaseToken) || current.ended) throw failure("native-voice-owner", "This window does not own the native voice call");
15779
+ return current;
15780
+ };
15781
+ const inactive = (code) => ({
15782
+ active: false,
15783
+ native: true,
15784
+ nativeState: "closed",
15785
+ leaseValid: false,
15786
+ levels: {
15787
+ mic: 0,
15788
+ assistant: 0
15789
+ },
15790
+ ...code ? { code } : {}
15791
+ });
15792
+ return Object.freeze({
15793
+ async probe(signal) {
15794
+ if (platform !== "linux") return {
15795
+ available: false,
15796
+ platform,
15797
+ code: "native-unsupported"
15798
+ };
15799
+ if (signal?.aborted) throw aborted();
15800
+ if (probing || closing) return {
15801
+ available: false,
15802
+ platform,
15803
+ code: "native-voice-busy"
15804
+ };
15805
+ probing = true;
15806
+ const controller = new AbortController();
15807
+ const cancel = () => controller.abort();
15808
+ signal?.addEventListener("abort", cancel, { once: true });
15809
+ let port;
15810
+ const timer = setTimeout(cancel, 5e3);
15811
+ try {
15812
+ port = helperPort(spawn$1, python, helperPath, void 0, cancel);
15813
+ probes.add(port);
15814
+ port.closed.then(() => {
15815
+ probes.delete(port);
15816
+ probing = false;
15817
+ });
15818
+ const response = await withAbort(port.request("probe"), controller.signal);
15819
+ const missing = Array.isArray(response.missing) ? response.missing.filter((x) => typeof x === "string" && /^[a-z0-9_-]{1,48}$/i.test(x)).slice(0, 32) : [];
15820
+ return {
15821
+ available: response.available === true,
15822
+ platform,
15823
+ missing
15824
+ };
15825
+ } catch (error) {
15826
+ if (signal?.aborted) throw aborted();
15827
+ return {
15828
+ available: false,
15829
+ platform,
15830
+ code: "native-unavailable"
15831
+ };
15832
+ } finally {
15833
+ clearTimeout(timer);
15834
+ signal?.removeEventListener("abort", cancel);
15835
+ if (port) {
15836
+ await port.close();
15837
+ probes.delete(port);
15838
+ } else probing = false;
15839
+ }
15840
+ },
15841
+ async start({ sessionId, captureAllowed, voice, language } = {}, signal) {
15842
+ if (platform !== "linux" || typeof desktopVoice?.start !== "function" || typeof desktopVoice?.stop !== "function" || typeof desktopVoice?.status !== "function") throw failure("native-unsupported");
15843
+ if (captureAllowed !== true) throw failure("native-capture-permission", "Microphone capture requires confirmation");
15844
+ if (typeof sessionId !== "string" || !sessionId || sessionId.length > 512) throw failure("native-session");
15845
+ if (signal?.aborted) throw aborted();
15846
+ if (closing || current || remotePending.has(sessionId)) throw failure("native-voice-busy", "Native voice is already in use");
15847
+ if (desktopVoice.status(sessionId)?.active === true) throw failure("native-voice-busy", "This conversation already has a voice call");
15848
+ const call = {
15849
+ sessionId,
15850
+ leaseToken: randomUUID(),
15851
+ controller: new AbortController(),
15852
+ state: "starting",
15853
+ levels: {
15854
+ mic: 0,
15855
+ assistant: 0
15856
+ },
15857
+ muted: false,
15858
+ outputMuted: false,
15859
+ interrupted: false,
15860
+ interruptions: 0
15861
+ };
15862
+ info("native-starting");
15863
+ current = call;
15864
+ const cancel = () => {
15865
+ closeCall(call, "native-cancelled");
15866
+ };
15867
+ signal?.addEventListener("abort", cancel, { once: true });
15868
+ call.removeAbort = () => signal?.removeEventListener("abort", cancel);
15869
+ if (signal?.aborted) {
15870
+ await closeCall(call, "native-cancelled");
15871
+ throw aborted();
15872
+ }
15873
+ call.deadline = setTimeout(() => {
15874
+ closeCall(call, "native-start-timeout");
15875
+ }, START_TIMEOUT);
15876
+ const control = (type) => {
15877
+ if (call.ended) return;
15878
+ call.port.request(type).catch(() => {
15879
+ closeCall(call, "native-control");
15880
+ });
15881
+ };
15882
+ const gate = createBargeInGate({
15883
+ outputTailMs: 500,
15884
+ silenceMs: 700,
15885
+ changed(value) {
15886
+ call.interrupted = value;
15887
+ if (value) call.interruptions++;
15888
+ info(value ? "native-speech-interrupt" : "native-speech-resume");
15889
+ control(value ? "interrupt" : "resume");
15890
+ },
15891
+ interrupt() {
15892
+ try {
15893
+ Promise.resolve(desktopVoice.interrupt(sessionId)).catch(() => {
15894
+ closeCall(call, "native-interrupt");
15895
+ });
15896
+ } catch {
15897
+ closeCall(call, "native-interrupt");
15898
+ }
15899
+ }
15900
+ });
15901
+ try {
15902
+ call.port = helperPort(spawn$1, python, helperPath, (event) => {
15903
+ if (call.ended || event.event !== "level") return;
15904
+ if (![event.mic, event.assistant].every((x) => typeof x === "number" && Number.isFinite(x) && x >= 0 && x <= 1)) return;
15905
+ call.levels = {
15906
+ mic: call.muted ? 0 : Math.min(1, event.mic * 3.2),
15907
+ assistant: Math.min(1, event.assistant * 3.2)
15908
+ };
15909
+ if (call.state === "connected") gate.sample({
15910
+ mic: call.levels.mic,
15911
+ output: call.levels.assistant,
15912
+ now: performance.now()
15913
+ });
15914
+ }, (error) => {
15915
+ closeCall(call, error.code);
15916
+ });
15917
+ if (call.ended) {
15918
+ await call.port.close();
15919
+ throw aborted();
15920
+ }
15921
+ await withAbort(call.port.request("start", { captureAllowed: true }), call.controller.signal);
15922
+ const { sdp } = await withAbort(call.port.wait("offer"), call.controller.signal);
15923
+ if (typeof sdp !== "string" || !sdp.startsWith("v=0") || Buffer.byteLength(sdp) > 64 * 1024) throw failure("native-offer");
15924
+ call.remoteRequested = true;
15925
+ const remote = Promise.resolve().then(() => {
15926
+ call.controller.signal.throwIfAborted();
15927
+ return desktopVoice.start({
15928
+ sessionId,
15929
+ sdp,
15930
+ voice,
15931
+ language,
15932
+ signal: call.controller.signal
15933
+ });
15934
+ }).finally(() => {
15935
+ if (call.ended) stopRemote(call);
15936
+ if (remotePending.get(sessionId) === remote) remotePending.delete(sessionId);
15937
+ });
15938
+ remotePending.set(sessionId, remote);
15939
+ const result = await withAbort(remote, call.controller.signal);
15940
+ if (typeof result?.answer !== "string" || !result.answer.startsWith("v=0") || Buffer.byteLength(result.answer) >= 100 * 1024) throw failure("native-answer");
15941
+ await withAbort(call.port.request("remote", {
15942
+ descriptionType: "answer",
15943
+ sdp: result.answer
15944
+ }), call.controller.signal);
15945
+ await withAbort(call.port.wait("state:connected"), call.controller.signal);
15946
+ let readyTimer;
15947
+ try {
15948
+ await withAbort(new Promise((resolve, reject) => {
15949
+ const check = () => {
15950
+ try {
15951
+ const status = desktopVoice.status(sessionId);
15952
+ if (status?.active === false) {
15953
+ reject(failure("native-remote-ended"));
15954
+ return;
15955
+ }
15956
+ if (status?.inputReady !== false) {
15957
+ resolve();
15958
+ return;
15959
+ }
15960
+ readyTimer = setTimeout(check, 50);
15961
+ } catch {
15962
+ reject(failure("native-remote-status"));
15963
+ }
15964
+ };
15965
+ check();
15966
+ }), call.controller.signal);
15967
+ } finally {
15968
+ clearTimeout(readyTimer);
15969
+ }
15970
+ call.state = "connected";
15971
+ call.renewed = performance.now();
15972
+ info("native-connected");
15973
+ clearTimeout(call.deadline);
15974
+ call.removeAbort?.();
15975
+ call.removeAbort = void 0;
15976
+ call.heartbeat = setInterval(() => {
15977
+ if (performance.now() - call.renewed >= LEASE_TIMEOUT) {
15978
+ closeCall(call, "native-lease-expired");
15979
+ return;
15980
+ }
15981
+ try {
15982
+ if (desktopVoice.status(sessionId)?.active === false) closeCall(call, "native-remote-ended");
15983
+ } catch {
15984
+ closeCall(call, "native-remote-status");
15985
+ }
15986
+ }, 1e3);
15987
+ call.heartbeat.unref?.();
15988
+ return {
15989
+ sessionId,
15990
+ leaseToken: call.leaseToken,
15991
+ native: true,
15992
+ nativeState: "connected"
15993
+ };
15994
+ } catch (error) {
15995
+ const code = last?.leaseToken === call.leaseToken && last.code || (typeof error?.code === "string" && error.code.startsWith("native-") ? error.code : "native-start-failed");
15996
+ await closeCall(call, code);
15997
+ if (signal?.aborted) throw aborted();
15998
+ throw failure(code);
15999
+ }
16000
+ },
16001
+ status(sessionId, leaseToken) {
16002
+ if (!owns(current, sessionId, leaseToken) || current.ended) return inactive(owns(last, sessionId, leaseToken) ? last.code : "native-voice-owner");
16003
+ const call = current;
16004
+ call.renewed = performance.now();
16005
+ let remote;
16006
+ try {
16007
+ remote = desktopVoice.status(sessionId);
16008
+ } catch {
16009
+ closeCall(call, "native-remote-status");
16010
+ return inactive("native-remote-status");
16011
+ }
16012
+ if (remote?.active === false) {
16013
+ closeCall(call, "native-remote-ended");
16014
+ return inactive("native-remote-ended");
16015
+ }
16016
+ return {
16017
+ ...remote,
16018
+ active: call.state === "connected",
16019
+ native: true,
16020
+ nativeState: call.state,
16021
+ leaseValid: true,
16022
+ levels: { ...call.levels },
16023
+ muted: call.muted,
16024
+ outputMuted: call.outputMuted,
16025
+ interrupted: call.interrupted,
16026
+ interruptions: call.interruptions
16027
+ };
16028
+ },
16029
+ async mute(params) {
16030
+ const call = owner(params);
16031
+ if (typeof params.muted !== "boolean") throw failure("native-control");
16032
+ try {
16033
+ await call.port.request("mute", { muted: params.muted });
16034
+ call.muted = params.muted;
16035
+ if (call.muted) call.levels.mic = 0;
16036
+ } catch {
16037
+ await closeCall(call, "native-control");
16038
+ throw failure("native-control");
16039
+ }
16040
+ return { muted: call.muted };
16041
+ },
16042
+ async outputMute(params) {
16043
+ const call = owner(params);
16044
+ if (typeof params.muted !== "boolean") throw failure("native-control");
16045
+ try {
16046
+ await call.port.request("outputMute", { muted: params.muted });
16047
+ call.outputMuted = params.muted;
16048
+ } catch {
16049
+ await closeCall(call, "native-control");
16050
+ throw failure("native-control");
16051
+ }
16052
+ return { outputMuted: call.outputMuted };
16053
+ },
16054
+ async stop(params) {
16055
+ if (!owns(current, params?.sessionId, params?.leaseToken)) return { stopped: false };
16056
+ await closeCall(current, "native-stopped");
16057
+ return { stopped: true };
16058
+ },
16059
+ close(signal) {
16060
+ if (closing) return closing;
16061
+ closing = (async () => {
16062
+ await Promise.all([current && closeCall(current, "native-disposed"), ...[...probes].map((port) => port.close())]);
16063
+ if (remotePending.size) {
16064
+ const controller = new AbortController();
16065
+ const cancel = () => controller.abort();
16066
+ const timer = setTimeout(cancel, 5e3);
16067
+ signal?.addEventListener("abort", cancel, { once: true });
16068
+ if (signal?.aborted) cancel();
16069
+ try {
16070
+ await withAbort(Promise.allSettled([...remotePending.values()]), controller.signal);
16071
+ } catch {
16072
+ throw signal?.aborted ? aborted() : failure("native-voice-busy", "The previous voice call is still closing");
16073
+ } finally {
16074
+ clearTimeout(timer);
16075
+ signal?.removeEventListener("abort", cancel);
16076
+ }
16077
+ }
16078
+ })().finally(() => {
16079
+ closing = void 0;
16080
+ });
16081
+ return closing;
16082
+ }
16083
+ });
16084
+ }
16085
+ //#endregion
14257
16086
  //#region src/index.js
14258
16087
  const z = createRequire(import.meta.resolve("@deepseek-ai/dsh-settings"))("@deepseek-ai/schemastery");
14259
16088
  const name = "codex-subscription";
@@ -14381,6 +16210,14 @@ function apply(ctx, config = {}) {
14381
16210
  3e5
14382
16211
  ]
14383
16212
  });
16213
+ const appendUltraPolicy = loadHostSessionSdk()?.appendPluginRecord;
16214
+ const ultra = createUltraExecutionPreset({
16215
+ catalog: modelCatalog,
16216
+ resolveAgent: () => ctx.get?.("agents")?.currentInitiator?.(),
16217
+ defaultEffort: () => settings.get()[DEFAULT_REASONING_EFFORT_FIELD],
16218
+ record: appendUltraPolicy
16219
+ });
16220
+ ctx.effect(() => ultra.install(ctx), "codex-subscription: Ultra execution preset");
14384
16221
  const connection = createSubscriptionConnection({ resolveMode: () => settings.get().connectionMode });
14385
16222
  const defaultModel = createDefaultModelController({
14386
16223
  resolveService: () => ctx.get?.("agentDefaultModel"),
@@ -14409,6 +16246,7 @@ function apply(ctx, config = {}) {
14409
16246
  ctx.on("session/event", (session, event) => reasoning.sessionEvent(session, event));
14410
16247
  ctx.effect(() => () => connection.dispose());
14411
16248
  const provider = openaiCodexSubscriptionProvider({
16249
+ ultra,
14412
16250
  connection,
14413
16251
  compaction,
14414
16252
  reasoning,
@@ -14441,6 +16279,7 @@ function apply(ctx, config = {}) {
14441
16279
  connectionMode: settings.get().connectionMode ?? "sse",
14442
16280
  reviewModel: settings.get().reviewModel ?? "session",
14443
16281
  remoteControl: settings.get().remoteControl ?? "off",
16282
+ composerPredictions: settings.get().composerPredictions === "on" ? "on" : "off",
14444
16283
  otherModels: settings.get().otherModels === "off" ? "off" : "on",
14445
16284
  subagentBackend: settings.get().subagentBackend ?? "dsh",
14446
16285
  subagentBackendAvailable: subagentBackend !== void 0,
@@ -14471,6 +16310,7 @@ function apply(ctx, config = {}) {
14471
16310
  catalogStatus: modelCatalog.status(),
14472
16311
  verbosityModels: provider.getModels().filter((model) => modelCatalog.metadata(model.id)?.supportVerbosity ?? model.id !== "gpt-5.3-codex-spark").map((model) => model.id),
14473
16312
  ultrafastModels: provider.getModels().filter((model) => modelCatalog.metadata(model.id)?.supportsUltrafast === true).map((model) => model.id),
16313
+ ultraModels: provider.getModels().filter((model) => ultra.supported(model.id)).map((model) => model.id),
14474
16314
  fastModels: provider.getModels().filter((model) => modelCatalog.metadata(model.id)?.supportsFast ?? supportsCodexFastMode(model.id)).map((model) => model.id),
14475
16315
  writable: ctx.settings.writable
14476
16316
  };
@@ -14672,7 +16512,7 @@ function apply(ctx, config = {}) {
14672
16512
  }), "codex-subscription: default reasoning effort");
14673
16513
  ctx.effect(() => {
14674
16514
  const lifetime = new AbortController();
14675
- const defaults = withDefaultReasoningEffort(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(provider.wrapRetryAdapter(adapter))), provider), {
16515
+ const defaults = withDefaultReasoningEffort(ultra.wrapAdapter(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(provider.wrapRetryAdapter(adapter))), provider)), {
14676
16516
  preference: () => settings.get()[DEFAULT_REASONING_EFFORT_FIELD],
14677
16517
  modelDefault: (id) => modelCatalog.metadata(id)?.defaultReasoningEffort
14678
16518
  });
@@ -14689,7 +16529,7 @@ function apply(ctx, config = {}) {
14689
16529
  }, "codex-subscription: official model catalog");
14690
16530
  const currentAgent = () => ctx.get?.("agents")?.currentInitiator?.();
14691
16531
  const codexFetch = createCodexFetchProvider({
14692
- 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),
14693
16533
  getAuth: resolveAuth,
14694
16534
  readCredential: (options) => store.read(PROVIDER, options),
14695
16535
  resolveModel: () => {
@@ -14741,7 +16581,7 @@ function apply(ctx, config = {}) {
14741
16581
  const realSearchProviders = ctx.web.searchProviders;
14742
16582
  const resolveDshSearch = () => realSearchProviders?.get(searchProvider.dshProviderId());
14743
16583
  const gateSearch = (provider) => gateSearchProvider(provider, {
14744
- allowed: () => settings.get().otherModels !== "off" || currentAgent()?.session.requestContext?.()?.provider === PROVIDER,
16584
+ allowed: (llmProvider) => settings.get().otherModels !== "off" || (llmProvider ?? currentAgent()?.session.requestContext?.()?.provider) === PROVIDER,
14745
16585
  resolveDshProvider: resolveDshSearch
14746
16586
  });
14747
16587
  const codexSearch = createCodexSearchProvider({
@@ -14759,6 +16599,7 @@ function apply(ctx, config = {}) {
14759
16599
  const tracedCodexSearch = gateSearch({
14760
16600
  id: codexSearch.id,
14761
16601
  available: () => codexSearch.available(),
16602
+ ready: (llmProvider) => codexSearch.ready(llmProvider),
14762
16603
  async search(request, signal) {
14763
16604
  const result = await codexSearch.search(request, signal);
14764
16605
  searchTrace("answered by Codex subscription");
@@ -14851,6 +16692,8 @@ function apply(ctx, config = {}) {
14851
16692
  skills: () => ctx.get?.("skills"),
14852
16693
  commands: () => ctx.get?.("commands"),
14853
16694
  llm: () => ctx.llm,
16695
+ modelMetadata: (provider, model) => provider === PROVIDER ? modelCatalog.metadata(model) : void 0,
16696
+ historySource: createRemoteHistorySource({ query: () => ctx.get?.("sessionQuery") }),
14854
16697
  speed: {
14855
16698
  tiers: (provider, model) => provider === PROVIDER ? modelCatalog.metadata(model)?.serviceTiers ?? [] : [],
14856
16699
  current: () => settings.get()[SPEED_MODE_FIELD],
@@ -15029,6 +16872,46 @@ function apply(ctx, config = {}) {
15029
16872
  expirySkewMs: OAUTH_EXPIRY_SKEW_MS,
15030
16873
  activeReader: baseUsageReader
15031
16874
  });
16875
+ const desktopVoice = withEndCallTool(remoteBridge.desktopVoice, (tool) => ctx.tools.register(tool));
16876
+ const nativeVoice = createNativeVoiceHost({
16877
+ desktopVoice,
16878
+ log: diagnosticLog
16879
+ });
16880
+ ctx.effect(() => {
16881
+ const close = () => {
16882
+ nativeVoice.close().catch(() => diagnosticLog.warn("voice-native", "native call cleanup is waiting for a cancelled start"));
16883
+ };
16884
+ const sync = () => {
16885
+ if (settings.get().voiceCall !== "on") close();
16886
+ };
16887
+ const unwatch = settings.watch(sync);
16888
+ return () => {
16889
+ unwatch();
16890
+ close();
16891
+ };
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
+ }));
15032
16915
  const subscriptionHandler = createSubscriptionRpcHandler({
15033
16916
  authHandler: createCodexRpcHandler(coordinator, { openExternal: openCodexAuthUrl }),
15034
16917
  usageReader,
@@ -15040,18 +16923,15 @@ function apply(ctx, config = {}) {
15040
16923
  defaultModel,
15041
16924
  runtimeManagement,
15042
16925
  remoteControl,
15043
- desktopVoice: withEndCallTool(remoteBridge.desktopVoice, (tool) => ctx.tools.register(tool)),
15044
- voicePreview: createVoicePreview({
15045
- fetch: (input, init) => network.fetch("voice", input, init, { standardHttps: true }),
15046
- credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
15047
- ...options,
15048
- signal
15049
- }), signal),
15050
- userAgent: USER_AGENT
15051
- }),
16926
+ desktopVoice,
16927
+ nativeVoice,
16928
+ voicePreview,
16929
+ composerPredictions,
15052
16930
  onAccountChanged: () => {
15053
16931
  connectorsClient.clear();
15054
16932
  usageProfileReader.clear();
16933
+ voicePreview.clear();
16934
+ composerPredictions.clear();
15055
16935
  quotaRetryHandler.notifyAccountChanged();
15056
16936
  },
15057
16937
  diagnosticsReader: () => createSubscriptionDiagnostics({