dsh-codex-subscription 3.1.8 → 3.1.9

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;
@@ -1110,12 +1112,49 @@ function transportError(error, signal) {
1110
1112
  return Object.assign(new Error(`Network transport failure (${error.code}): ${error.message}`, { cause: error }), { code: error.code });
1111
1113
  }
1112
1114
  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;
1115
+ const iterator = response[Symbol.asyncIterator]();
1116
+ let finished = false, controller;
1117
+ const cleanup = () => signal?.removeEventListener("abort", abort);
1118
+ const fail = (error) => {
1119
+ if (finished) return;
1120
+ finished = true;
1121
+ cleanup();
1122
+ controller.error(transportError(error, signal));
1123
+ response.destroy();
1124
+ };
1125
+ const abort = () => fail(signal.reason);
1126
+ return new ReadableStream({
1127
+ start(value) {
1128
+ controller = value;
1129
+ response.on("error", fail);
1130
+ response.once("close", () => {
1131
+ if (!response.readableEnded) fail(Object.assign(/* @__PURE__ */ new Error("Response body closed before completion"), { code: "ERR_STREAM_PREMATURE_CLOSE" }));
1132
+ });
1133
+ signal?.addEventListener("abort", abort, { once: true });
1134
+ if (signal?.aborted) abort();
1135
+ },
1136
+ async pull() {
1137
+ try {
1138
+ const { value, done } = await iterator.next();
1139
+ if (finished) return;
1140
+ if (done) {
1141
+ finished = true;
1142
+ cleanup();
1143
+ controller.close();
1144
+ } else controller.enqueue(new Uint8Array(value));
1145
+ } catch (error) {
1146
+ fail(error);
1147
+ }
1148
+ },
1149
+ async cancel() {
1150
+ finished = true;
1151
+ cleanup();
1152
+ response.destroy();
1153
+ try {
1154
+ await iterator.return();
1155
+ } catch {}
1156
+ }
1157
+ });
1119
1158
  }
1120
1159
  function fetchThroughProxy(input, init, proxyUrl) {
1121
1160
  const target = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
@@ -1902,7 +1941,7 @@ function isDshAutoReview(context) {
1902
1941
  * persistence, headers, transport, and model behavior remain owned by the
1903
1942
  * original provider.
1904
1943
  */
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() } = {}) {
1944
+ 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
1945
  const provider = createOpenAICodexProvider();
1907
1946
  const retryBridge = createModelRetryBridge();
1908
1947
  const requestToken = Object.freeze({
@@ -1953,7 +1992,8 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1953
1992
  } },
1954
1993
  ...serviceTier === void 0 ? {} : { service_tier: serviceTier }
1955
1994
  };
1956
- return reasoning?.preparePayload(finalPayload, requestModel) ?? finalPayload;
1995
+ const reasoned = reasoning?.preparePayload(finalPayload, requestModel) ?? finalPayload;
1996
+ return ultra?.preparePayload(reasoned) ?? reasoned;
1957
1997
  }
1958
1998
  };
1959
1999
  };
@@ -2229,7 +2269,7 @@ const REASONING_LIMITS = Object.freeze({
2229
2269
  bytes: 16 * 1024 * 1024,
2230
2270
  updates: 128
2231
2271
  });
2232
- const record$8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2272
+ const record$9 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
2233
2273
  const efforts = /* @__PURE__ */ new Set([
2234
2274
  "low",
2235
2275
  "medium",
@@ -2243,13 +2283,13 @@ const reasoningDigest = (value) => {
2243
2283
  const text = boundedStringify(value, REASONING_LIMITS.bytes);
2244
2284
  return text === void 0 ? void 0 : reasoningHash(text);
2245
2285
  };
2246
- const boundary = (value, update = false) => record$8(value) && Object.keys(value).every((key) => [
2286
+ const boundary = (value, update = false) => record$9(value) && Object.keys(value).every((key) => [
2247
2287
  "offset",
2248
2288
  "hash",
2249
2289
  ...update ? ["effort"] : []
2250
2290
  ].includes(key)) && Number.isInteger(value.offset) && value.offset >= 0 && value.offset <= REASONING_LIMITS.items && isHash(value.hash);
2251
2291
  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) => ![
2292
+ 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
2293
  "version",
2254
2294
  "scope",
2255
2295
  "envelope",
@@ -2283,7 +2323,7 @@ function rewriteReasoning(payload, { model, scope, previous, fresh = false }) {
2283
2323
  payload,
2284
2324
  reason
2285
2325
  });
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");
2326
+ 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
2327
  if (payload.context_management !== void 0) return skip("cloud-compaction");
2288
2328
  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
2329
  "configuration_update",
@@ -2579,6 +2619,11 @@ const RPC_ENDPOINTS = Object.freeze([
2579
2619
  "voice/interrupt",
2580
2620
  "voice/preview",
2581
2621
  "voice/catalog",
2622
+ "voice/native/probe",
2623
+ "voice/native/start",
2624
+ "voice/native/status",
2625
+ "voice/native/control",
2626
+ "voice/native/stop",
2582
2627
  "remote/status",
2583
2628
  "remote/enable",
2584
2629
  "remote/disable",
@@ -2597,6 +2642,20 @@ const RPC_ENDPOINTS = Object.freeze([
2597
2642
  ]);
2598
2643
  //#endregion
2599
2644
  //#region src/subscription-transport.js
2645
+ const localNativeRequest = (request) => {
2646
+ try {
2647
+ const target = new URL(request.url);
2648
+ const origin = new URL(request.headers.get("origin"));
2649
+ const authority = request.headers.get("host") ?? target.host;
2650
+ return ["http:", "https:"].includes(origin.protocol) && !origin.username && !origin.password && [
2651
+ "localhost",
2652
+ "127.0.0.1",
2653
+ "[::1]"
2654
+ ].includes(origin.hostname) && authority === origin.host;
2655
+ } catch {
2656
+ return false;
2657
+ }
2658
+ };
2600
2659
  /** Exact routes stay inside DSH's authenticated /api bridge and body limit. */
2601
2660
  function registerSubscriptionTransport(connection, handler) {
2602
2661
  const disposers = [];
@@ -2608,6 +2667,7 @@ function registerSubscriptionTransport(connection, handler) {
2608
2667
  methods: ["POST"],
2609
2668
  requestBody: "buffered",
2610
2669
  async fetch(request) {
2670
+ if (endpoint.startsWith("voice/native/") && !localNativeRequest(request)) return new Response("native voice requires the local desktop", { status: 403 });
2611
2671
  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
2672
  let body;
2613
2673
  try {
@@ -3600,7 +3660,7 @@ function inheritedOriginalImageRef(session, assetId) {
3600
3660
  }
3601
3661
  //#endregion
3602
3662
  //#region src/version.js
3603
- const PACKAGE_VERSION = "3.1.8";
3663
+ const PACKAGE_VERSION = "3.1.9";
3604
3664
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
3605
3665
  //#endregion
3606
3666
  //#region src/codex-images.js
@@ -3628,7 +3688,7 @@ const FULL_ATTACHMENT_ID = /^sha256:[0-9a-f]{64}$/u;
3628
3688
  const BARE_ATTACHMENT_DIGEST = /^[0-9a-f]{64}$/iu;
3629
3689
  const PATH_LIKE_ATTACHMENT_ID = /[\\/]/u;
3630
3690
  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);
3691
+ const record$8 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
3632
3692
  const nonEmpty$2 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
3633
3693
  const NETWORK_REASONS = {
3634
3694
  UND_ERR_HEADERS_TIMEOUT: "the image service sent no response within 5 minutes",
@@ -3714,7 +3774,7 @@ function decodeCodexPng(value, maximumBytes) {
3714
3774
  return new Uint8Array(data);
3715
3775
  }
3716
3776
  function imageReference(value) {
3717
- const originalDimensions = record$7(value.originalDimensions) ? {
3777
+ const originalDimensions = record$8(value.originalDimensions) ? {
3718
3778
  width: value.originalDimensions.width,
3719
3779
  height: value.originalDimensions.height
3720
3780
  } : void 0;
@@ -3742,7 +3802,7 @@ function invalidAttachmentId(value) {
3742
3802
  function referenceOf(value, attachments) {
3743
3803
  const attachmentId = normalizeAttachmentId(value?.attachmentId);
3744
3804
  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");
3805
+ 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
3806
  return imageReference({
3747
3807
  ...value,
3748
3808
  attachmentId
@@ -3752,7 +3812,7 @@ function sessionImageReferences(messages) {
3752
3812
  const references = /* @__PURE__ */ new Map();
3753
3813
  const visit = (content) => {
3754
3814
  if (!Array.isArray(content)) return;
3755
- for (const block of content) if (block?.type === "image" && record$7(block.attachment)) {
3815
+ for (const block of content) if (block?.type === "image" && record$8(block.attachment)) {
3756
3816
  const id = normalizeAttachmentId(block.attachment.attachmentId);
3757
3817
  if (id !== void 0) references.set(id, block.attachment);
3758
3818
  } else if (block?.type === "tool-result") visit(block.content);
@@ -3917,7 +3977,7 @@ async function limitMessage(response, now = Date.now()) {
3917
3977
  } catch {
3918
3978
  return fallback;
3919
3979
  }
3920
- if (!record$7(error)) return fallback;
3980
+ if (!record$8(error)) return fallback;
3921
3981
  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
3982
  if (at === void 0) return fallback;
3923
3983
  const minutes = Math.max(1, Math.ceil((at - now) / 6e4));
@@ -3929,7 +3989,7 @@ async function refusalMessage(response, editing) {
3929
3989
  let reason;
3930
3990
  try {
3931
3991
  const value = JSON.parse(await readTextWithin(response, 16 * 1024));
3932
- const error = record$7(value?.error) ? value.error : void 0;
3992
+ const error = record$8(value?.error) ? value.error : void 0;
3933
3993
  reason = [
3934
3994
  error?.message,
3935
3995
  value?.detail,
@@ -3954,7 +4014,7 @@ async function readTextWithin(response, maximumBytes) {
3954
4014
  }
3955
4015
  function responseMetadata(value) {
3956
4016
  const data = Array.isArray(value?.data) ? value.data[0] : void 0;
3957
- const encoded = record$7(data) ? data.b64_json : void 0;
4017
+ const encoded = record$8(data) ? data.b64_json : void 0;
3958
4018
  if (typeof encoded !== "string") throw new Error("Codex returned no image data");
3959
4019
  return {
3960
4020
  encoded,
@@ -4435,6 +4495,16 @@ const FIELDS = /* @__PURE__ */ new Set([
4435
4495
  "event",
4436
4496
  "error"
4437
4497
  ]);
4498
+ for (const name of [
4499
+ "direction",
4500
+ "cursorDirection",
4501
+ "requestedView",
4502
+ "cursorView",
4503
+ "cursorThreadMatches",
4504
+ "cursorTurnScoped",
4505
+ "requestedTurnScoped",
4506
+ "cursorTurnMatches"
4507
+ ]) FIELDS.add(name);
4438
4508
  function phoneLog(event, details = {}, level = "info") {
4439
4509
  const fields = {};
4440
4510
  for (const [name, value] of Object.entries(details)) {
@@ -6447,6 +6517,7 @@ function createRealtimeVoice(options) {
6447
6517
  ws,
6448
6518
  notify,
6449
6519
  ended: false,
6520
+ inputReady: false,
6450
6521
  chain: Promise.resolve(),
6451
6522
  tail: [],
6452
6523
  lines: [],
@@ -6510,6 +6581,7 @@ function createRealtimeVoice(options) {
6510
6581
  ws.on("message", (data) => {
6511
6582
  try {
6512
6583
  const value = JSON.parse(String(data));
6584
+ if (!session.ended && value.type === "session.input_audio.append" && typeof value.audio === "string" && value.audio.length > 0) session.inputReady = true;
6513
6585
  const id = value.client_event_id ?? value.error?.event_id;
6514
6586
  if (id && session.controls.delete(id)) {
6515
6587
  if (value.type === "error") log.warn("voice", "the voice service refused an interruption command", String(value.error?.message ?? "").slice(0, 200));
@@ -6656,6 +6728,7 @@ function createRealtimeVoice(options) {
6656
6728
  const session = sessions.get(threadId);
6657
6729
  return session ? {
6658
6730
  active: true,
6731
+ inputReady: session.inputReady,
6659
6732
  working: session.working > 0,
6660
6733
  closing: session.closing === true,
6661
6734
  lines: session.lines.slice(-6)
@@ -6672,6 +6745,195 @@ function createRealtimeVoice(options) {
6672
6745
  };
6673
6746
  }
6674
6747
  //#endregion
6748
+ //#region src/remote-control-capabilities.js
6749
+ const record$7 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
6750
+ const decimal$1 = (value) => typeof value === "string" && /^-?\d+(?:\.\d+)?$/u.test(value) ? value : null;
6751
+ const integer = (value) => Number.isSafeInteger(value) && value >= 0;
6752
+ const percentage = (value) => Number.isFinite(value) && value >= 0 && value <= 100;
6753
+ const plans = /* @__PURE__ */ new Set([
6754
+ "free",
6755
+ "go",
6756
+ "plus",
6757
+ "pro",
6758
+ "prolite",
6759
+ "promax",
6760
+ "team",
6761
+ "self_serve_business_prolite",
6762
+ "self_serve_business_usage_based",
6763
+ "business",
6764
+ "ent26",
6765
+ "enterprise_cbp_automation",
6766
+ "enterprise_cbp_usage_based",
6767
+ "enterprise",
6768
+ "edu",
6769
+ "edu_plus",
6770
+ "edu_pro",
6771
+ "unknown"
6772
+ ]);
6773
+ const reachedTypes = /* @__PURE__ */ new Set([
6774
+ "rate_limit_reached",
6775
+ "workspace_owner_credits_depleted",
6776
+ "workspace_member_credits_depleted",
6777
+ "workspace_owner_usage_limit_reached",
6778
+ "workspace_member_usage_limit_reached"
6779
+ ]);
6780
+ function creditsOf$1(value) {
6781
+ if (!record$7(value) || typeof value.unlimited !== "boolean") return null;
6782
+ return {
6783
+ hasCredits: true,
6784
+ unlimited: value.unlimited,
6785
+ balance: decimal$1(value.balance)
6786
+ };
6787
+ }
6788
+ function individualOf$1(value) {
6789
+ if (!record$7(value) || decimal$1(value.limit) === null || decimal$1(value.used) === null || !percentage(value.remainingPercent) || !integer(value.resetsAt)) return null;
6790
+ return {
6791
+ limit: value.limit,
6792
+ used: value.used,
6793
+ remainingPercent: Math.round(value.remainingPercent),
6794
+ resetsAt: value.resetsAt
6795
+ };
6796
+ }
6797
+ const windowOf$1 = (value) => record$7(value) && percentage(value.usedPercent) ? {
6798
+ usedPercent: Math.round(value.usedPercent),
6799
+ windowDurationMins: Number.isFinite(value.windowSeconds) && value.windowSeconds > 0 ? Math.round(value.windowSeconds / 60) : null,
6800
+ resetsAt: integer(value.resetsAt) ? value.resetsAt : null
6801
+ } : null;
6802
+ /** Project the existing safe usage reading into the app-server account snapshot. */
6803
+ function phoneRateLimits(read) {
6804
+ const limits = Array.isArray(read?.rateLimits) ? read.rateLimits : [];
6805
+ const main = limits.find((limit) => limit.id === "codex") ?? limits[0];
6806
+ const accountBucket = (limit) => limit === main && (limit === void 0 || limit.id === "codex");
6807
+ const snapshot = (limit) => ({
6808
+ limitId: limit?.id ?? "codex",
6809
+ limitName: limit?.name ?? null,
6810
+ normalModelSlug: null,
6811
+ primary: windowOf$1(limit?.windows?.[0]),
6812
+ secondary: windowOf$1(limit?.windows?.[1]),
6813
+ credits: accountBucket(limit) ? creditsOf$1(read?.credits) : null,
6814
+ individualLimit: accountBucket(limit) ? individualOf$1(read?.individualLimit) : null,
6815
+ spendControlReached: typeof read?.spendControlReached === "boolean" ? read.spendControlReached : null,
6816
+ planType: read?.planType == null ? null : plans.has(read.planType) ? read.planType : "unknown",
6817
+ rateLimitReachedType: reachedTypes.has(read?.rateLimitReachedType) ? read.rateLimitReachedType : null
6818
+ });
6819
+ const resets = read?.resetCredits;
6820
+ return {
6821
+ ordinaryUsageAllowed: null,
6822
+ rateLimits: snapshot(main),
6823
+ rateLimitsByLimitId: read ? Object.fromEntries(limits.map((limit) => [limit.id, snapshot(limit)])) : null,
6824
+ rateLimitResetCredits: record$7(resets) && integer(resets.availableCount) ? {
6825
+ availableCount: resets.availableCount,
6826
+ credits: null
6827
+ } : null,
6828
+ accountId: null,
6829
+ rateLimitUpsell: null
6830
+ };
6831
+ }
6832
+ /** Migration hints use the same provider/model identity as the phone model picker. */
6833
+ function phoneModelUpgrade(metadata, encodeModel) {
6834
+ const target = metadata?.upgradeTo ?? metadata?.retirement?.upgradeTo;
6835
+ if (typeof target !== "string" || !target.trim() || target.length > 256 || /[\u0000-\u001f\u007f]/u.test(target)) return {
6836
+ upgrade: null,
6837
+ upgradeInfo: null
6838
+ };
6839
+ const model = encodeModel(target);
6840
+ const at = metadata?.retirement?.at;
6841
+ return {
6842
+ upgrade: model,
6843
+ upgradeInfo: {
6844
+ model,
6845
+ retirementAt: integer(at) && at > 0 ? Math.floor(at / 1e3) : null,
6846
+ upgradeCopy: null,
6847
+ modelLink: null,
6848
+ migrationMarkdown: null
6849
+ }
6850
+ };
6851
+ }
6852
+ //#endregion
6853
+ //#region src/remote-history-page.js
6854
+ const PREFIX = "history1:";
6855
+ const encode = (value) => PREFIX + Buffer.from(JSON.stringify(value)).toString("base64url");
6856
+ const decode = (cursor) => {
6857
+ if (typeof cursor !== "string" || cursor.length > 4096 || !cursor.startsWith(PREFIX)) throw invalidParams("Invalid history cursor");
6858
+ try {
6859
+ const value = JSON.parse(Buffer.from(cursor.slice(9), "base64url").toString());
6860
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalidParams("Invalid history cursor");
6861
+ return value;
6862
+ } catch {
6863
+ throw invalidParams("Invalid history cursor");
6864
+ }
6865
+ };
6866
+ const scopeParts = (scope) => {
6867
+ try {
6868
+ const value = JSON.parse(scope);
6869
+ return Array.isArray(value) ? value : [];
6870
+ } catch {
6871
+ return [];
6872
+ }
6873
+ };
6874
+ const scopeKey = (scope) => {
6875
+ const parts = scopeParts(scope);
6876
+ return parts[1] === "items" ? JSON.stringify(parts.slice(0, 2)) : scope;
6877
+ };
6878
+ const anchorCursor = (id, scope, direction, inclusive) => encode({
6879
+ v: 2,
6880
+ s: scopeKey(scope),
6881
+ d: direction,
6882
+ a: id,
6883
+ i: inclusive
6884
+ });
6885
+ function initialHistoryCursor(list, scope) {
6886
+ const anchor = list.at(-1)?.id;
6887
+ return anchor === void 0 ? null : anchorCursor(anchor, scope, "desc", true);
6888
+ }
6889
+ function historyPage(list, params, scope, defaultDirection = "desc", accept = () => true) {
6890
+ const cursor = params?.cursor;
6891
+ const legacyOffset = typeof cursor === "string" && /^\d+$/u.test(cursor);
6892
+ const saved = cursor == null || legacyOffset ? void 0 : decode(cursor);
6893
+ const direction = params?.sortDirection ?? saved?.d ?? defaultDirection;
6894
+ if (!["asc", "desc"].includes(direction)) throw invalidParams("Invalid history sort direction");
6895
+ const limit = params?.limit ?? 50;
6896
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw invalidParams("History page limit must be between 1 and 100");
6897
+ if (saved && (![1, 2].includes(saved.v) || scopeKey(saved.s) !== scopeKey(scope) || typeof saved.a !== "string" || saved.v === 2 && typeof saved.i !== "boolean")) {
6898
+ const currentScope = scopeParts(scope), cursorScope = scopeParts(saved.s);
6899
+ const view = (value) => ["turns", "items"].includes(value) ? value : "unknown";
6900
+ phoneLog("history cursor rejected", {
6901
+ direction,
6902
+ cursorDirection: ["asc", "desc"].includes(saved.d) ? saved.d : "unknown",
6903
+ requestedView: view(currentScope[1]),
6904
+ cursorView: view(cursorScope[1]),
6905
+ cursorThreadMatches: currentScope[0] === cursorScope[0],
6906
+ cursorTurnScoped: !!cursorScope[2],
6907
+ requestedTurnScoped: !!currentScope[2],
6908
+ cursorTurnMatches: currentScope[2] === cursorScope[2]
6909
+ }, "warn");
6910
+ throw invalidParams("History cursor belongs to another view");
6911
+ }
6912
+ const ordered = direction === "asc" ? list : list.toReversed();
6913
+ const start = legacyOffset ? Number(cursor) : saved ? ordered.findIndex((item) => item.id === saved.a) : 0;
6914
+ if (!Number.isSafeInteger(start) || start < 0) throw invalidParams("History cursor is no longer available");
6915
+ const candidates = legacyOffset ? ordered.filter(accept).slice(start) : ordered.slice(start + (saved?.v === 2 && !saved.i ? 1 : 0)).filter(accept);
6916
+ const data = candidates.slice(0, limit);
6917
+ return {
6918
+ data,
6919
+ nextCursor: candidates.length > data.length ? anchorCursor(data.at(-1).id, scope, direction, false) : null,
6920
+ backwardsCursor: data.length ? anchorCursor(data[0].id, scope, direction === "asc" ? "desc" : "asc", true) : null
6921
+ };
6922
+ }
6923
+ function historyIndex(messages, turns) {
6924
+ const positions = new Map(messages.map((message, index) => [message.id, index]));
6925
+ const ranges = turns.map((turn) => ({
6926
+ ...turn,
6927
+ items: turn.items.map((item) => item.type === "userMessage" ? item : {
6928
+ id: item.id,
6929
+ type: item.type
6930
+ }),
6931
+ from: positions.get(turn.id) ?? 0
6932
+ }));
6933
+ for (let i = 0; i < ranges.length; i++) ranges[i].to = ranges[i + 1]?.from ?? messages.length;
6934
+ return ranges;
6935
+ }
6936
+ //#endregion
6675
6937
  //#region src/remote-control-image-output.js
6676
6938
  const images = /* @__PURE__ */ new WeakMap();
6677
6939
  const renderedSources = /* @__PURE__ */ new WeakMap();
@@ -6822,33 +7084,6 @@ function page(list, params) {
6822
7084
  };
6823
7085
  }
6824
7086
  /** 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
7087
  /** First place `term` appears in `text`: a short passage around it and the match's UTF-16 range inside that passage. */
6853
7088
  function occurrence(text, term, radius = 60) {
6854
7089
  const at = String(text).toLocaleLowerCase().indexOf(String(term).toLocaleLowerCase());
@@ -7044,7 +7279,7 @@ const toolOutput = (message, imageUrls, imageAssets) => [{
7044
7279
  /** Images the person attached to a message of their own. */
7045
7280
  const typedImages = (message) => message.role === "user" && (message.source === void 0 || message.source?.kind === "user") ? (message.content ?? []).filter((block) => block?.type === "image" && block.attachment) : [];
7046
7281
  /** `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()) {
7282
+ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new Map(), cwd = void 0, imageAssets = /* @__PURE__ */ new Map(), indexOnly = false) {
7048
7283
  const turns = [];
7049
7284
  let turn;
7050
7285
  const calls = /* @__PURE__ */ new Map();
@@ -7059,7 +7294,7 @@ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new
7059
7294
  for (const message of messages) if (message.role === "user") {
7060
7295
  const text = typedText(message);
7061
7296
  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;
7297
+ if (text === "" && pictures.length === 0 && !(indexOnly && typedImages(message).length)) continue;
7063
7298
  close();
7064
7299
  turn = {
7065
7300
  ...emptyTurn(),
@@ -7082,6 +7317,7 @@ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new
7082
7317
  } else if (message.role === "assistant") {
7083
7318
  turn ??= {
7084
7319
  ...emptyTurn(),
7320
+ id: message.id,
7085
7321
  startedAt: seconds(at)
7086
7322
  };
7087
7323
  for (const [index, block] of message.content.entries()) {
@@ -7237,7 +7473,7 @@ function createPhoneConfig(file) {
7237
7473
  }
7238
7474
  };
7239
7475
  }
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 }) {
7476
+ 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
7477
  const subscribers = /* @__PURE__ */ new Map();
7242
7478
  const threadSources = /* @__PURE__ */ new Map();
7243
7479
  const active = /* @__PURE__ */ new Map();
@@ -7431,7 +7667,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7431
7667
  await Promise.all(wanted.map(async (block) => {
7432
7668
  const started = Date.now();
7433
7669
  try {
7434
- const stored = await store.readImage(block.attachment, AbortSignal.timeout(1e4));
7670
+ const timeout = AbortSignal.timeout(1e4);
7671
+ const stored = await store.readImage(block.attachment, parentSignal ? AbortSignal.any([parentSignal, timeout]) : timeout);
7435
7672
  urls.set(block.attachment.attachmentId, `data:${stored.ref.mediaType};base64,${Buffer.from(stored.data).toString("base64")}`);
7436
7673
  phoneLog("image read completed", {
7437
7674
  attachmentId: block.attachment.attachmentId,
@@ -7569,6 +7806,127 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7569
7806
  });
7570
7807
  return result;
7571
7808
  };
7809
+ const historyIndexes = /* @__PURE__ */ new WeakMap();
7810
+ const historySnapshot = async (id, signal) => {
7811
+ signal?.throwIfAborted();
7812
+ let source;
7813
+ try {
7814
+ source = await historySource?.read(id, { signal });
7815
+ } catch (error) {
7816
+ if (error?.code === "SESSION_QUERY_SESSION_NOT_FOUND") throw notFound(id);
7817
+ throw error;
7818
+ }
7819
+ const session = (source ? void 0 : await agentFor(id))?.session;
7820
+ const messages = source?.messages ?? session.deriveMessages();
7821
+ const meta = source?.meta ?? session.meta;
7822
+ const events = source?.events;
7823
+ const cwd = directoryOf(events ? {
7824
+ meta,
7825
+ snapshotEvents: () => events
7826
+ } : session);
7827
+ const owner = events && Object.isFrozen(events) ? events : session ?? messages;
7828
+ const revision = source?.cursor ?? session?.seq ?? messages;
7829
+ let cached = historyIndexes.get(owner);
7830
+ if (!cached || cached.revision !== revision) {
7831
+ cached = {
7832
+ revision,
7833
+ ranges: historyIndex(messages, projectTurns(messages, meta?.createdAt, /* @__PURE__ */ new Map(), cwd, /* @__PURE__ */ new Map(), true))
7834
+ };
7835
+ historyIndexes.set(owner, cached);
7836
+ }
7837
+ const live = active.get(id);
7838
+ if (live?.userItem) for (const message of messages) reconcileUser(id, live, message);
7839
+ const outline = withLiveTurn(id, cached.ranges);
7840
+ return {
7841
+ meta,
7842
+ messages,
7843
+ cwd,
7844
+ ranges: cached.ranges,
7845
+ outline
7846
+ };
7847
+ };
7848
+ const renderHistory = async (id, snapshot, selected, signal) => {
7849
+ signal?.throwIfAborted();
7850
+ const wanted = new Set(selected.map((turn) => turn.id));
7851
+ const ranges = snapshot.ranges.filter((range) => wanted.has(turnAliases.get(`${id}\0${range.id}`) ?? range.id));
7852
+ const messages = ranges.flatMap((range) => snapshot.messages.slice(range.from, range.to));
7853
+ const { urls, assets } = await imageUrlsOf(messages, signal);
7854
+ signal?.throwIfAborted();
7855
+ const turns = ranges.flatMap((range) => projectTurns(snapshot.messages.slice(range.from, range.to), snapshot.meta?.createdAt, urls, snapshot.cwd, assets, true));
7856
+ const visible = wanted.has(active.get(id)?.turn.id) ? withLiveTurn(id, turns) : withShownIds(id, turns);
7857
+ const byId = new Map(visible.map((turn) => [turn.id, turn]));
7858
+ return selected.map((turn) => byId.get(turn.id)).filter(Boolean);
7859
+ };
7860
+ const listHistoryTurns = async (params, signal) => {
7861
+ if (params?.itemsView != null && ![
7862
+ "full",
7863
+ "summary",
7864
+ "notLoaded"
7865
+ ].includes(params.itemsView)) throw invalidParams("Invalid turn items view");
7866
+ const id = params?.threadId;
7867
+ const snapshot = await historySnapshot(id, signal);
7868
+ const result = historyPage(snapshot.outline, params, JSON.stringify([id, "turns"]));
7869
+ const full = params?.itemsView == null || params.itemsView === "full";
7870
+ const data = (full ? await renderHistory(id, snapshot, result.data, signal) : result.data.map((turn) => ({
7871
+ ...turn,
7872
+ items: [],
7873
+ itemsView: "notLoaded"
7874
+ }))).map(({ from, to, ...turn }) => turn);
7875
+ phoneLog("history page completed", {
7876
+ threadId: id,
7877
+ type: full ? "full" : "notLoaded",
7878
+ turns: data.length
7879
+ });
7880
+ return {
7881
+ ...result,
7882
+ data
7883
+ };
7884
+ };
7885
+ const listHistoryItems = async (params, signal) => {
7886
+ const id = params?.threadId;
7887
+ if (params?.turnId != null && (typeof params.turnId !== "string" || params.turnId === "")) throw invalidParams("turnId must be nonempty");
7888
+ const snapshot = await historySnapshot(id, signal);
7889
+ const turns = snapshot.outline;
7890
+ if (params?.turnId && !turns.some((turn) => turn.id === params.turnId)) throw invalidParams("Turn not found");
7891
+ let items = turns.flatMap((turn) => turn.items.map((item) => ({
7892
+ id: JSON.stringify([turn.id, item.id]),
7893
+ turnId: turn.id,
7894
+ itemId: item.id
7895
+ })));
7896
+ let cursor = params?.cursor;
7897
+ if (cursor && typeof cursor === "object") {
7898
+ if (cursor.type !== "item" || typeof cursor.itemId !== "string" || !cursor.itemId || !params.turnId) throw invalidParams("An item anchor requires a turnId and itemId");
7899
+ const at = items.findIndex((item) => item.itemId === cursor.itemId && item.turnId === params.turnId);
7900
+ if (at < 0) throw invalidParams("Item anchor not found in this turn");
7901
+ items = params?.sortDirection === "desc" ? items.slice(0, at) : items.slice(at + 1);
7902
+ cursor = void 0;
7903
+ }
7904
+ phoneLog("history items page requested", {
7905
+ threadId: id,
7906
+ turnId: params?.turnId,
7907
+ direction: ["asc", "desc"].includes(params?.sortDirection) ? params.sortDirection : "default",
7908
+ type: params?.cursor && typeof params.cursor === "object" ? "itemAnchor" : params?.cursor ? "opaqueCursor" : "firstPage"
7909
+ });
7910
+ const result = historyPage(items, {
7911
+ ...params,
7912
+ cursor
7913
+ }, JSON.stringify([id, "items"]), "asc", (item) => !params?.turnId || item.turnId === params.turnId);
7914
+ const wanted = new Set(result.data.map((item) => item.turnId));
7915
+ const rendered = await renderHistory(id, snapshot, turns.filter((turn) => wanted.has(turn.id)), signal);
7916
+ const byTurn = new Map(rendered.map((turn) => [turn.id, new Map(turn.items.map((item) => [item.id, item]))]));
7917
+ return {
7918
+ ...result,
7919
+ data: result.data.flatMap((entry) => {
7920
+ const item = byTurn.get(entry.turnId)?.get(entry.itemId);
7921
+ return item ? [{
7922
+ turnId: entry.turnId,
7923
+ item,
7924
+ startedAt: null,
7925
+ completedAt: null
7926
+ }] : [];
7927
+ })
7928
+ };
7929
+ };
7572
7930
  /** Apply a model or effort the phone picked; DSH validates it against its own catalog. */
7573
7931
  const TIER_OF = {
7574
7932
  fast: "priority",
@@ -7978,6 +8336,19 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7978
8336
  snippets
7979
8337
  };
7980
8338
  };
8339
+ const readThreadMetadata = async (id, signal) => {
8340
+ const entry = (await service().list({}, signal)).items?.find((item) => item.sessionId === id && item.origin !== "subagent");
8341
+ if (!entry) throw notFound(id);
8342
+ return thread({
8343
+ id,
8344
+ cwd: entry.cwd,
8345
+ createdAt: entry.createdAt ?? entry.updatedAt,
8346
+ updatedAt: entry.updatedAt,
8347
+ running: entry.running,
8348
+ projectId: projectIdOf(id),
8349
+ title: entry.projections?.values?.title ?? null
8350
+ });
8351
+ };
7981
8352
  const matches = (entry, term, snippets) => {
7982
8353
  const needle = typeof term === "string" ? term.trim().toLocaleLowerCase() : "";
7983
8354
  return needle === "" || snippets.has(entry.id) || `${entry.name ?? ""} ${entry.preview}`.toLocaleLowerCase().includes(needle);
@@ -8087,8 +8458,10 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8087
8458
  inputModalities: modalities.get(model.id)?.length ? modalities.get(model.id) : ["text"],
8088
8459
  supportsPersonality: false,
8089
8460
  additionalSpeedTiers: tiersOf(group.id, model.id).map((tier) => tier.id),
8090
- upgrade: null,
8091
- upgradeInfo: null,
8461
+ ...phoneModelUpgrade(modelMetadata(group.id, model.id), (target) => modelKey({
8462
+ provider: group.id,
8463
+ model: target
8464
+ })),
8092
8465
  availabilityNux: null,
8093
8466
  serviceTiers: tiersOf(group.id, model.id),
8094
8467
  defaultServiceTier: null
@@ -8292,15 +8665,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8292
8665
  };
8293
8666
  },
8294
8667
  "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
- },
8668
+ "account/rateLimits/read": async () => phoneRateLimits(await usage()?.read?.().catch(() => void 0)),
8669
+ "thread/turns/list": (params, { signal } = {}) => listHistoryTurns(params, signal),
8670
+ "thread/items/list": (params, { signal } = {}) => listHistoryItems(params, signal),
8304
8671
  "thread/fork": async (params, { notify }) => {
8305
8672
  const forked = await service().fork({ sessionId: params?.threadId });
8306
8673
  const agent = await agentFor(forked.sessionId);
@@ -8396,8 +8763,28 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8396
8763
  await registry.unarchiveSession(params?.threadId);
8397
8764
  return { thread: (await openThread(params?.threadId)).thread };
8398
8765
  },
8399
- "thread/read": async (params, { signal } = {}) => ({ thread: (await openThread(params?.threadId, void 0, signal)).thread }),
8766
+ "thread/read": async (params, { signal } = {}) => ({ thread: params?.includeTurns === false ? {
8767
+ ...await readThreadMetadata(params?.threadId, signal),
8768
+ historyMode: "paginated"
8769
+ } : (await openThread(params?.threadId, void 0, signal)).thread }),
8400
8770
  "thread/resume": async (params, { notify, signal }) => {
8771
+ if (params?.excludeTurns === true) {
8772
+ const value = {
8773
+ ...await readThreadMetadata(params?.threadId, signal),
8774
+ historyMode: "paginated"
8775
+ };
8776
+ const snapshot = await historySnapshot(params.threadId, signal);
8777
+ const agent = await agentFor(params.threadId);
8778
+ if (notify) subscribe(params.threadId, notify);
8779
+ await (catalog ? void 0 : loadCatalog().catch(() => void 0));
8780
+ const itemAnchors = snapshot.outline.flatMap((turn) => turn.items.map((item) => ({ id: JSON.stringify([turn.id, item.id]) })));
8781
+ return {
8782
+ ...settings(agent, value.cwd),
8783
+ thread: value,
8784
+ turnsBackwardsCursor: initialHistoryCursor(snapshot.outline, JSON.stringify([params.threadId, "turns"])),
8785
+ itemsBackwardsCursor: initialHistoryCursor(itemAnchors, JSON.stringify([params.threadId, "items"]))
8786
+ };
8787
+ }
8401
8788
  const { agent, thread: value } = await openThread(params?.threadId, notify, signal);
8402
8789
  return {
8403
8790
  ...settings(agent, value.cwd),
@@ -9057,6 +9444,289 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9057
9444
  };
9058
9445
  }
9059
9446
  //#endregion
9447
+ //#region src/remote-history-source.js
9448
+ 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");
9449
+ const failure$2 = (code, message) => Object.assign(new Error(message), { code });
9450
+ /** Read a detached native observation. No agent attachment or private log reader. */
9451
+ function createRemoteHistorySource({ query, loadModule = createRequire(import.meta.url) }) {
9452
+ const derived = /* @__PURE__ */ new WeakMap();
9453
+ let sdk;
9454
+ const modules = () => {
9455
+ if (sdk) return sdk;
9456
+ const load = (id) => {
9457
+ try {
9458
+ return loadModule(id);
9459
+ } catch (error) {
9460
+ if (!unavailableModule(error, id)) throw error;
9461
+ }
9462
+ };
9463
+ const session = load("@deepseek-ai/dsh-session");
9464
+ if (!session) return void 0;
9465
+ const catalog = load("@deepseek-ai/dsh-session-format-catalog/message-projections");
9466
+ if (typeof session.foldSurface !== "function" || typeof session.deriveEventMessage !== "function" || !Array.isArray(catalog?.currentSessionMessageProjections)) return void 0;
9467
+ sdk = {
9468
+ ...session,
9469
+ projections: catalog.currentSessionMessageProjections
9470
+ };
9471
+ return sdk;
9472
+ };
9473
+ return Object.freeze({ async read(id, { signal } = {}) {
9474
+ signal?.throwIfAborted();
9475
+ const service = query();
9476
+ if (typeof service?.observeSession !== "function") return void 0;
9477
+ const native = modules();
9478
+ if (!native) return void 0;
9479
+ const source = await service.observeSession(id, {
9480
+ signal,
9481
+ projectionMode: "none"
9482
+ });
9483
+ try {
9484
+ signal?.throwIfAborted();
9485
+ const header = source?.header;
9486
+ if (header?.id !== id) throw failure$2("SESSION_QUERY_SOURCE_CONFLICT", "Session observation identity does not match the thread");
9487
+ if (header.origin === "subagent" || typeof header.cwd !== "string" || header.cwd.trim() === "") throw failure$2("SESSION_QUERY_SESSION_NOT_FOUND", "Thread is not available");
9488
+ const events = source.events;
9489
+ if (!Array.isArray(events)) throw failure$2("SESSION_QUERY_CORRUPT_SESSION", "Session observation has no event array");
9490
+ let messages = derived.get(events);
9491
+ if (!messages) {
9492
+ const surface = native.foldSurface(events, native.projections);
9493
+ messages = Object.freeze(surface.nodes.map((seq) => native.deriveEventMessage(events[seq], surface.projectedMessages)).filter(Boolean));
9494
+ if (Object.isFrozen(events)) derived.set(events, messages);
9495
+ }
9496
+ signal?.throwIfAborted();
9497
+ return {
9498
+ meta: header,
9499
+ messages,
9500
+ events,
9501
+ cursor: source.cursor,
9502
+ source: source.source,
9503
+ revision: source.revision,
9504
+ inheritedEventCount: source.inheritedEventCount
9505
+ };
9506
+ } finally {
9507
+ source?.[Symbol.dispose]?.();
9508
+ }
9509
+ } });
9510
+ }
9511
+ //#endregion
9512
+ //#region src/ultra-execution.js
9513
+ const ULTRA_POLICY_RECORD = "plugin:dsh-codex-subscription/ultra-policy";
9514
+ const providerId = "openai-codex";
9515
+ const unavailable$1 = (message) => new LlmError(message, "UNSUPPORTED_OPTION");
9516
+ const scopedTools = (agent) => agent?.ctx?.get?.("tools") ?? (Object.hasOwn(agent?.ctx ?? {}, "tools") ? agent.ctx.tools : void 0);
9517
+ /** Native DSH tools/providers only; never install a provider or change a preset. */
9518
+ function nativeDelegations(ctx, agent) {
9519
+ const tools = scopedTools(agent) ?? ctx.get?.("tools");
9520
+ const subagents = ctx.get?.("subagents");
9521
+ return presetEntries(ctx).flatMap((entry) => {
9522
+ const config = entry.fiber?.config ?? entry.options?.config;
9523
+ if (entry.options?.name !== "@deepseek-ai/dsh-tool-subagent" || !["spawn", "codex-subscription-subagent"].includes(config?.provider) || !subagents?.getProvider?.(config.provider)) return [];
9524
+ const name = config.toolName ?? "subagent";
9525
+ const definition = tools?.get?.(name, agent);
9526
+ return agent && !definition ? [] : [{
9527
+ name,
9528
+ definition
9529
+ }];
9530
+ });
9531
+ }
9532
+ /**
9533
+ * Ultra keeps its user-visible selection in Harness headers. Only the inner
9534
+ * adapter receives the model's native effort. DSH owns child scheduling,
9535
+ * sandbox/approval decisions, concurrency/depth budgets and cancellation.
9536
+ */
9537
+ function createUltraExecutionPreset({ catalog, resolveAgent = () => void 0, defaultEffort = () => void 0, delegations = nativeDelegations, record } = {}) {
9538
+ const scope = new AsyncLocalStorage(), bindings = /* @__PURE__ */ new Map();
9539
+ let context, installed = false;
9540
+ const metadata = (id) => catalog?.metadata?.(id)?.ultra;
9541
+ const available = () => installed && typeof record === "function" && typeof context?.get?.("tools")?.guard === "function" && delegations(context).length > 0;
9542
+ const supported = (id) => available() && metadata(id) !== void 0;
9543
+ const deactivate = (binding) => {
9544
+ binding.removeAbort?.();
9545
+ binding.removeAbort = void 0;
9546
+ if (binding.state) binding.state.active = false;
9547
+ };
9548
+ const disposeAgent = (agent) => {
9549
+ const binding = bindings.get(agent);
9550
+ if (!binding) return;
9551
+ deactivate(binding);
9552
+ binding.disposeGuard();
9553
+ bindings.delete(agent);
9554
+ };
9555
+ const bind = (agent) => {
9556
+ let binding = bindings.get(agent);
9557
+ if (binding) return binding;
9558
+ const tools = scopedTools(agent);
9559
+ if (typeof tools?.guard !== "function") throw unavailable$1("Ultra requires the native DSH agent tool policy service");
9560
+ binding = { state: void 0 };
9561
+ binding.disposeGuard = tools.guard((exec) => {
9562
+ const state = binding.state;
9563
+ if (!state || !state.tools.some((tool) => tool.name === exec.name)) return;
9564
+ if (!state.active || state.signal.aborted || exec.agent !== agent) return "Ultra delegation belongs to an inactive or cancelled request";
9565
+ const tool = state.tools.find((tool) => tool.name === exec.name);
9566
+ if (tools.get(exec.name, agent) !== tool.definition) return "Ultra delegation tool changed after request preparation; retry the request";
9567
+ });
9568
+ bindings.set(agent, binding);
9569
+ return binding;
9570
+ };
9571
+ const request = (agent, config, signal, turn) => {
9572
+ const existing = bindings.get(agent);
9573
+ if (existing) deactivate(existing);
9574
+ const implicitUltra = config.reasoningEffort === void 0 && defaultEffort(config.model) === "ultra" && supported(config.model) && delegations(context, agent).length > 0 && typeof scopedTools(agent)?.guard === "function";
9575
+ const selected = config.reasoningEffort ?? (implicitUltra ? "ultra" : void 0);
9576
+ if (config.provider !== providerId || selected !== "ultra") {
9577
+ const binding = bindings.get(agent);
9578
+ if (binding) {
9579
+ deactivate(binding);
9580
+ binding.state = void 0;
9581
+ }
9582
+ return;
9583
+ }
9584
+ signal.throwIfAborted();
9585
+ const preset = metadata(config.model);
9586
+ if (!supported(config.model) || !preset) throw unavailable$1("This account/model does not advertise an available DSH Ultra execution preset");
9587
+ const tools = [...new Map(delegations(context, agent).map((tool) => [tool.name, tool])).values()];
9588
+ if (!tools.length) throw unavailable$1("Ultra requires an independent subagent tool in the selected Agent preset");
9589
+ const binding = bind(agent);
9590
+ const previous = binding.state;
9591
+ deactivate(binding);
9592
+ const policy = Object.freeze({
9593
+ version: 1,
9594
+ provider: config.provider,
9595
+ model: config.model,
9596
+ requestedEffort: "ultra",
9597
+ effectiveEffort: preset.effectiveEffort,
9598
+ delegationPolicy: "proactive",
9599
+ tools: Object.freeze(tools.map((tool) => tool.name)),
9600
+ turn
9601
+ });
9602
+ const state = {
9603
+ policy,
9604
+ tools,
9605
+ signal,
9606
+ active: true,
9607
+ preset: { ...preset }
9608
+ };
9609
+ binding.state = state;
9610
+ const abort = () => {
9611
+ state.active = false;
9612
+ };
9613
+ signal.addEventListener("abort", abort, { once: true });
9614
+ binding.removeAbort = () => signal.removeEventListener("abort", abort);
9615
+ try {
9616
+ if (JSON.stringify(previous?.policy) !== JSON.stringify(policy)) record(agent.session, ULTRA_POLICY_RECORD, policy);
9617
+ } catch (error) {
9618
+ deactivate(binding);
9619
+ throw error;
9620
+ }
9621
+ };
9622
+ const describe = (info) => !info?.reasoning || !supported(info.id) || resolveAgent() && (!delegations(context, resolveAgent()).length || typeof scopedTools(resolveAgent())?.guard !== "function") ? info : {
9623
+ ...info,
9624
+ reasoning: {
9625
+ ...info.reasoning,
9626
+ efforts: [...info.reasoning.efforts.filter((effort) => effort.id !== "ultra"), {
9627
+ id: "ultra",
9628
+ name: `Ultra (DSH parallel · ${metadata(info.id).effectiveEffort})`
9629
+ }]
9630
+ }
9631
+ };
9632
+ const stream = (factory, options, captured) => (async function* () {
9633
+ const auxiliary = ["session-title", "compaction"].includes(options.purpose) || isDshAutoReview(options);
9634
+ let state;
9635
+ let input = options;
9636
+ if (options.provider === providerId && options.reasoningEffort === "ultra") {
9637
+ if (!captured) throw unavailable$1("This account/model does not advertise Ultra");
9638
+ const agent = resolveAgent();
9639
+ if (!auxiliary) {
9640
+ state = bindings.get(agent)?.state;
9641
+ 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");
9642
+ }
9643
+ input = {
9644
+ ...options,
9645
+ reasoningEffort: captured.effectiveEffort === "none" ? "off" : captured.effectiveEffort
9646
+ };
9647
+ }
9648
+ const iterator = scope.run(state, () => factory(input)[Symbol.asyncIterator]());
9649
+ try {
9650
+ for (;;) {
9651
+ const next = await scope.run(state, () => iterator.next());
9652
+ if (next.done) return next.value;
9653
+ yield next.value;
9654
+ }
9655
+ } finally {
9656
+ await scope.run(state, () => iterator.return?.());
9657
+ }
9658
+ })();
9659
+ return {
9660
+ available,
9661
+ supported,
9662
+ snapshot: (agent) => {
9663
+ const state = bindings.get(agent)?.state;
9664
+ return state ? {
9665
+ ...state.policy,
9666
+ tools: [...state.policy.tools],
9667
+ active: state.active && !state.signal.aborted
9668
+ } : void 0;
9669
+ },
9670
+ install(ctx) {
9671
+ if (installed) throw new Error("Ultra execution preset is already installed");
9672
+ context = ctx;
9673
+ installed = true;
9674
+ const disposeRequest = ctx.on("agent/request", async ({ agent, signal, turn }, next) => {
9675
+ const config = await next();
9676
+ request(agent, config, signal, turn);
9677
+ return config;
9678
+ });
9679
+ const disposeAgentListener = ctx.on("agent/disposed", ({ agent }) => disposeAgent(agent));
9680
+ const disposeEnd = ctx.on("session/event", (session, event) => {
9681
+ if (event.type !== "turn/end") return;
9682
+ for (const [agent, binding] of bindings) if (agent.session === session && binding.state?.policy.turn === event.data.turn) deactivate(binding);
9683
+ });
9684
+ return () => {
9685
+ installed = false;
9686
+ disposeRequest();
9687
+ disposeAgentListener();
9688
+ disposeEnd();
9689
+ for (const agent of [...bindings.keys()]) disposeAgent(agent);
9690
+ context = void 0;
9691
+ };
9692
+ },
9693
+ wrapAdapter(adapter) {
9694
+ return new Proxy(adapter, { get(target, property) {
9695
+ const value = Reflect.get(target, property, target);
9696
+ if (property === "resolveModel" && typeof value === "function") return async (...args) => args[0] === providerId ? describe(await value.apply(target, args)) : value.apply(target, args);
9697
+ if (property === "prepareCall" && typeof value === "function") return async (...args) => {
9698
+ const call = await value.apply(target, args);
9699
+ if (args[0] !== providerId) return call;
9700
+ const captured = supported(args[1]) ? { ...metadata(args[1]) } : void 0;
9701
+ return {
9702
+ ...call,
9703
+ model: describe(call.model),
9704
+ stream: (options) => stream((input) => call.stream(input), options, captured)
9705
+ };
9706
+ };
9707
+ if (property === "stream" && typeof value === "function") return (options) => stream((input) => value.call(target, input), options, supported(options.model) ? { ...metadata(options.model) } : void 0);
9708
+ return typeof value === "function" ? value.bind(target) : value;
9709
+ } });
9710
+ },
9711
+ preparePayload(payload) {
9712
+ const state = scope.getStore();
9713
+ if (!state) return payload;
9714
+ if (!state.active || state.signal.aborted || payload.model !== state.policy.model) throw unavailable$1("Ultra request policy is no longer active");
9715
+ 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");
9716
+ if (payload.instructions != null && typeof payload.instructions !== "string") throw unavailable$1("Ultra requires the native Codex instructions contract");
9717
+ 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.`;
9718
+ return {
9719
+ ...payload,
9720
+ ...state.policy.effectiveEffort === "none" ? { reasoning: {
9721
+ ...payload.reasoning,
9722
+ effort: "none"
9723
+ } } : {},
9724
+ instructions: `${payload.instructions ?? ""}\n\n<multi_agent_mode>\n${guidance}\n</multi_agent_mode>`
9725
+ };
9726
+ }
9727
+ };
9728
+ }
9729
+ //#endregion
9060
9730
  //#region src/remote-image-assets.js
9061
9731
  const BASE$1 = "https://chatgpt.com/backend-api/";
9062
9732
  const FILE_ID = /^file[-_][A-Za-z0-9_-]{1,200}$/u;
@@ -10334,6 +11004,24 @@ function isRecord(value) {
10334
11004
  return value !== null && typeof value === "object" && !Array.isArray(value);
10335
11005
  }
10336
11006
  //#endregion
11007
+ //#region src/ultra-effort.js
11008
+ const NATIVE_CODEX_EFFORTS = Object.freeze([
11009
+ "none",
11010
+ "minimal",
11011
+ "low",
11012
+ "medium",
11013
+ "high",
11014
+ "xhigh",
11015
+ "max"
11016
+ ]);
11017
+ function ultraCatalogPreset(value) {
11018
+ const supported = (Array.isArray(value?.supported_reasoning_levels) ? value.supported_reasoning_levels : []).map((item) => item?.effort).filter((effort) => typeof effort === "string");
11019
+ if (!supported.includes("ultra")) return void 0;
11020
+ const override = value.multi_agent_reasoning_effort;
11021
+ const effectiveEffort = override !== "ultra" && supported.includes(override) ? override : supported.includes("max") ? "max" : supported.findLast((effort) => effort !== "ultra") ?? "medium";
11022
+ return NATIVE_CODEX_EFFORTS.includes(effectiveEffort) ? Object.freeze({ effectiveEffort }) : void 0;
11023
+ }
11024
+ //#endregion
10337
11025
  //#region src/model-catalog.js
10338
11026
  const CODEX_MODELS_URL = `https://chatgpt.com/backend-api/codex/models?client_version=${encodeURIComponent(PACKAGE_VERSION)}`;
10339
11027
  const LEVELS = [
@@ -10350,7 +11038,8 @@ const record$6 = (value) => value !== null && typeof value === "object" && !Arra
10350
11038
  const nonEmpty$1 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
10351
11039
  const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0 ? value : void 0;
10352
11040
  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);
11041
+ const modelId = (value) => typeof value === "string" && /^[a-z][a-z0-9._-]{0,79}$/u.test(value) ? value : void 0;
11042
+ 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
11043
  }
10355
11044
  function retirementMillis(value) {
10356
11045
  for (const source of [
@@ -10414,7 +11103,11 @@ function serviceTierEntries(value) {
10414
11103
  return found;
10415
11104
  }
10416
11105
  function unsupportedCapabilities(value) {
10417
- const reasoning = capabilityNames((value.supported_reasoning_levels ?? []).map((item) => item?.effort)).filter((level) => !["none", ...LEVELS.slice(1)].includes(level));
11106
+ const reasoning = capabilityNames((value.supported_reasoning_levels ?? []).map((item) => item?.effort)).filter((level) => ![
11107
+ "none",
11108
+ ...LEVELS.slice(1),
11109
+ ...ultraCatalogPreset(value) ? ["ultra"] : []
11110
+ ].includes(level));
10418
11111
  const inputs = capabilityNames(Array.isArray(value.input_modalities) ? value.input_modalities : []).filter((input) => !["text", "image"].includes(input));
10419
11112
  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
11113
  "auto",
@@ -10457,12 +11150,14 @@ function visibleModel(value, displayNames, now) {
10457
11150
  at: retirement.at,
10458
11151
  upgradeTo: retirement.upgradeTo
10459
11152
  } },
11153
+ ...upgradeTo === void 0 ? {} : { upgradeTo },
10460
11154
  priority: Number.isFinite(value.priority) ? value.priority : 0,
10461
11155
  input: input.length > 0 ? input : ["text"],
10462
11156
  contextWindow: positiveInteger(value.context_window) ?? positiveInteger(value.max_context_window),
10463
11157
  ...positiveInteger(value.max_context_window) === void 0 ? {} : { maxContextWindow: value.max_context_window },
10464
11158
  reasoning: supported.length > 0,
10465
11159
  supportsReasoningEffortUpdates: value.supports_reasoning_effort_updates === true,
11160
+ ...ultraCatalogPreset(value) === void 0 ? {} : { ultra: ultraCatalogPreset(value) },
10466
11161
  thinkingLevelMap,
10467
11162
  ...defaultReasoningEffort === void 0 ? {} : { defaultReasoningEffort },
10468
11163
  supportVerbosity: value.support_verbosity === true,
@@ -12445,8 +13140,8 @@ function createReportReader({ url, parse, label, getAuth, readCredential, fetch:
12445
13140
  return Object.freeze({
12446
13141
  read({ force = false, signal } = {}) {
12447
13142
  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
13143
  if (inFlight !== void 0) return inFlight.then(structuredClone);
13144
+ if (!force && cached !== void 0 && now() - cached.fetchedAt < ttlMs) return Promise.resolve(structuredClone(cached));
12450
13145
  const current = generation;
12451
13146
  const run = load(signal).then((value) => {
12452
13147
  if (generation === current) {
@@ -13750,8 +14445,58 @@ async function settlesLive(preferences, patch, signal, { attempts = 8, delayMs =
13750
14445
  }
13751
14446
  return live();
13752
14447
  }
13753
- function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageReader, planHistoryReader, usageProfileReader, resetCreditService, preferences, defaultModel, runtimeManagement, remoteControl, desktopVoice, voicePreview, diagnosticsReader, modelCatalog, originalImages, resolveInheritedOriginal, closeConnections, onAccountChanged, onCleanupFailure }) {
14448
+ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageReader, planHistoryReader, usageProfileReader, resetCreditService, preferences, defaultModel, runtimeManagement, remoteControl, desktopVoice, nativeVoice, voicePreview, diagnosticsReader, modelCatalog, originalImages, resolveInheritedOriginal, closeConnections, onAccountChanged, onCleanupFailure }) {
13754
14449
  return async (endpoint, payload, signal) => {
14450
+ if (endpoint.startsWith("voice/native/")) try {
14451
+ signal.throwIfAborted();
14452
+ if (!nativeVoice) return publicError("voice-native-unavailable", "Native voice is unavailable");
14453
+ const action = endpoint.slice(13);
14454
+ if (action === "probe") return {
14455
+ ok: true,
14456
+ value: await nativeVoice.probe(signal)
14457
+ };
14458
+ const sessionId = payload?.sessionId;
14459
+ if (typeof sessionId !== "string" || !sessionId || sessionId.length > 512) return publicError("invalid-input", "Invalid voice request");
14460
+ if (action === "start") {
14461
+ const current = preferences?.status?.() ?? {};
14462
+ if (current.voiceCall !== "on") return publicError("unavailable", "Voice is turned off");
14463
+ if (payload.captureAllowed !== true) return publicError("invalid-input", "Microphone permission is required");
14464
+ return {
14465
+ ok: true,
14466
+ value: await nativeVoice.start({
14467
+ sessionId,
14468
+ captureAllowed: true,
14469
+ voice: current.voiceVoice,
14470
+ language: current.voiceLanguage
14471
+ }, signal)
14472
+ };
14473
+ }
14474
+ const leaseToken = payload?.leaseToken;
14475
+ if (typeof leaseToken !== "string" || leaseToken.length < 16 || leaseToken.length > 128) return publicError("invalid-input", "Invalid voice owner");
14476
+ if (action === "status") return {
14477
+ ok: true,
14478
+ value: nativeVoice.status(sessionId, leaseToken)
14479
+ };
14480
+ if (action === "stop") return {
14481
+ ok: true,
14482
+ value: await nativeVoice.stop({
14483
+ sessionId,
14484
+ leaseToken
14485
+ })
14486
+ };
14487
+ if (action === "control" && ["mute", "outputMute"].includes(payload.action) && typeof payload.muted === "boolean") return {
14488
+ ok: true,
14489
+ value: await nativeVoice[payload.action]({
14490
+ sessionId,
14491
+ leaseToken,
14492
+ muted: payload.muted
14493
+ })
14494
+ };
14495
+ return publicError("invalid-input", "Invalid voice request");
14496
+ } catch (error) {
14497
+ if (signal.aborted) throw error;
14498
+ return publicError(error?.code === "voice-native-unavailable" ? "voice-native-unavailable" : "operation-error", "Could not use native voice");
14499
+ }
13755
14500
  if (endpoint === "default-model/status" || endpoint === "default-model/select") try {
13756
14501
  signal.throwIfAborted();
13757
14502
  if (!defaultModel) return publicError("unavailable", "The default model is unavailable");
@@ -13800,6 +14545,8 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13800
14545
  }
13801
14546
  const current = preferences?.status?.() ?? {};
13802
14547
  if (current.voiceCall !== "on") return publicError("unavailable", "Voice is turned off");
14548
+ await nativeVoice?.close();
14549
+ signal.throwIfAborted();
13803
14550
  return {
13804
14551
  ok: true,
13805
14552
  value: await desktopVoice.start({
@@ -13924,6 +14671,7 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13924
14671
  verbosityModels: Array.isArray(value?.verbosityModels) ? value.verbosityModels : [],
13925
14672
  fastModels: Array.isArray(value?.fastModels) ? value.fastModels : [],
13926
14673
  ultrafastModels: Array.isArray(value?.ultrafastModels) ? value.ultrafastModels : [],
14674
+ ultraModels: Array.isArray(value?.ultraModels) ? value.ultraModels : [],
13927
14675
  catalogStatus: value?.catalogStatus
13928
14676
  }
13929
14677
  };
@@ -14106,7 +14854,7 @@ const BASE = "https://chatgpt.com/backend-api";
14106
14854
  const CATALOG_TTL_MS = 10 * 6e4;
14107
14855
  const MAX_CLIP_BYTES = 2 * 1024 * 1024;
14108
14856
  const PREVIEW_HOSTS = /^https:\/\/[a-z0-9.-]*oaistatic\.com\//u;
14109
- const failure = (code, message) => Object.assign(new Error(message), { code });
14857
+ const failure$1 = (code, message) => Object.assign(new Error(message), { code });
14110
14858
  function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, base = BASE }) {
14111
14859
  const catalogs = /* @__PURE__ */ new Map();
14112
14860
  const clips = /* @__PURE__ */ new Map();
@@ -14121,7 +14869,7 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
14121
14869
  let value;
14122
14870
  try {
14123
14871
  const { access, accountId } = await credentials(signal);
14124
- if (!access || !accountId) throw failure("voice-auth", "ChatGPT sign-in is required");
14872
+ if (!access || !accountId) throw failure$1("voice-auth", "ChatGPT sign-in is required");
14125
14873
  const response = await fetch(`${base}/settings/voices?spoken_language=${language}`, {
14126
14874
  headers: {
14127
14875
  authorization: `Bearer ${access}`,
@@ -14131,15 +14879,15 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
14131
14879
  },
14132
14880
  signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3)
14133
14881
  });
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}`);
14882
+ if (response.status === 401) throw failure$1("voice-auth", "ChatGPT sign-in needs renewal");
14883
+ if (!response.ok) throw failure$1("voice-catalog", `voice catalog HTTP ${response.status}`);
14136
14884
  value = await response.json();
14137
- if (!Array.isArray(value?.voices)) throw failure("voice-catalog", "Invalid voice catalog");
14885
+ if (!Array.isArray(value?.voices)) throw failure$1("voice-catalog", "Invalid voice catalog");
14138
14886
  signal?.throwIfAborted();
14139
14887
  } catch (error) {
14140
14888
  signal?.throwIfAborted();
14141
14889
  if (error?.code === "voice-auth" || error?.code === "voice-catalog") throw error;
14142
- throw failure("voice-catalog", "Could not load the voice catalog");
14890
+ throw failure$1("voice-catalog", "Could not load the voice catalog");
14143
14891
  }
14144
14892
  const voices = (Array.isArray(value?.voices) ? value.voices : []).filter((entry) => typeof entry?.name === "string" && typeof entry?.preview_url === "string" && PREVIEW_HOSTS.test(entry.preview_url));
14145
14893
  catalogs.set(language, {
@@ -14165,13 +14913,13 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
14165
14913
  let bytes;
14166
14914
  try {
14167
14915
  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}`);
14916
+ if (!response.ok) throw failure$1("voice-download", `voice sample HTTP ${response.status}`);
14169
14917
  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");
14918
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_CLIP_BYTES) throw failure$1("voice-download", "voice sample has an unexpected size");
14171
14919
  signal?.throwIfAborted();
14172
14920
  } catch {
14173
14921
  signal?.throwIfAborted();
14174
- throw failure("voice-download", "Could not download the voice sample");
14922
+ throw failure$1("voice-download", "Could not download the voice sample");
14175
14923
  }
14176
14924
  const type = /\.mp3(?:$|\?)/u.test(entry.preview_url) ? "audio/mpeg" : "audio/mp4";
14177
14925
  const result = {
@@ -14254,6 +15002,628 @@ function withEndCallTool(desktopVoice, register) {
14254
15002
  });
14255
15003
  }
14256
15004
  //#endregion
15005
+ //#region src/voice-barge-in.js
15006
+ /** Mute playback promptly, and restore it only after interrupted audio has drained. */
15007
+ function createBargeInGate({ interrupt, changed, speechMs = 120, silenceMs = 400, outputTailMs = 0 }) {
15008
+ let speakingAt, quietAt, outputQuietAt, suppressed = false, drained = false;
15009
+ let outputActiveAt;
15010
+ return { sample({ mic, output, now }) {
15011
+ if (mic > .12) {
15012
+ speakingAt ??= now;
15013
+ quietAt = void 0;
15014
+ } else {
15015
+ speakingAt = void 0;
15016
+ quietAt ??= now;
15017
+ }
15018
+ if (output < .025) outputQuietAt ??= now;
15019
+ else outputQuietAt = void 0;
15020
+ if (output > .025) outputActiveAt = now;
15021
+ const recentOutput = outputTailMs > 0 && outputActiveAt !== void 0 && now - outputActiveAt <= outputTailMs;
15022
+ if (!suppressed && speakingAt !== void 0 && now - speakingAt >= speechMs && (output > .025 || recentOutput)) {
15023
+ suppressed = true;
15024
+ drained = false;
15025
+ changed(true);
15026
+ interrupt();
15027
+ }
15028
+ if (suppressed && outputQuietAt !== void 0 && now - outputQuietAt >= 250) drained = true;
15029
+ if (suppressed && drained && quietAt !== void 0 && now - quietAt >= silenceMs) {
15030
+ suppressed = false;
15031
+ speakingAt = void 0;
15032
+ changed(false);
15033
+ }
15034
+ } };
15035
+ }
15036
+ //#endregion
15037
+ //#region src/voice-native-host.js
15038
+ const MAX_LINE = 128 * 1024;
15039
+ const START_TIMEOUT = 3e4;
15040
+ const LEASE_TIMEOUT = 1e4;
15041
+ const helperFile = fileURLToPath(new URL("../native/linux-voice-helper.py", import.meta.url));
15042
+ const failure = (code, message = "Native voice is unavailable") => Object.assign(new Error(message), { code });
15043
+ const aborted = () => Object.assign(/* @__PURE__ */ new Error("Native voice was cancelled"), {
15044
+ name: "AbortError",
15045
+ code: "ABORT_ERR"
15046
+ });
15047
+ function withAbort(promise, signal) {
15048
+ if (signal.aborted) {
15049
+ Promise.resolve(promise).catch(() => {});
15050
+ return Promise.reject(aborted());
15051
+ }
15052
+ let cancel;
15053
+ const cancellation = new Promise((_, reject) => {
15054
+ cancel = () => reject(aborted());
15055
+ signal.addEventListener("abort", cancel, { once: true });
15056
+ });
15057
+ return Promise.race([promise, cancellation]).finally(() => signal.removeEventListener("abort", cancel));
15058
+ }
15059
+ /** Fixed JSON-lines transport. Stderr and SDP are never forwarded to diagnostics. */
15060
+ function helperPort(spawn, python, path, onEvent, onFailure) {
15061
+ const env = {};
15062
+ for (const key of [
15063
+ "PATH",
15064
+ "HOME",
15065
+ "LANG",
15066
+ "LC_ALL",
15067
+ "LC_CTYPE",
15068
+ "XDG_RUNTIME_DIR",
15069
+ "XDG_CONFIG_HOME",
15070
+ "XDG_DATA_HOME",
15071
+ "DBUS_SESSION_BUS_ADDRESS",
15072
+ "PULSE_SERVER",
15073
+ "PULSE_COOKIE",
15074
+ "GI_TYPELIB_PATH",
15075
+ "GST_PLUGIN_PATH",
15076
+ "LD_LIBRARY_PATH"
15077
+ ]) if (process.env[key] !== void 0) env[key] = process.env[key];
15078
+ env.PYTHONUNBUFFERED = "1";
15079
+ const child = spawn(python, [path], {
15080
+ shell: false,
15081
+ stdio: [
15082
+ "pipe",
15083
+ "pipe",
15084
+ "pipe"
15085
+ ],
15086
+ env
15087
+ });
15088
+ const pending = /* @__PURE__ */ new Map(), waiting = /* @__PURE__ */ new Map(), events = /* @__PURE__ */ new Map();
15089
+ let buffer = Buffer.alloc(0), sequence = 0, broken, closing = false, exited = false, shutdown;
15090
+ let finished;
15091
+ const exit = new Promise((resolve) => {
15092
+ finished = resolve;
15093
+ });
15094
+ const fail = (code) => {
15095
+ if (broken || closing) return;
15096
+ broken = failure(code);
15097
+ for (const value of pending.values()) value.reject(broken);
15098
+ for (const values of waiting.values()) for (const value of values) value.reject(broken);
15099
+ pending.clear();
15100
+ waiting.clear();
15101
+ onFailure?.(broken);
15102
+ };
15103
+ const receive = (message) => {
15104
+ if (!message || typeof message !== "object" || Array.isArray(message)) {
15105
+ fail("native-protocol");
15106
+ return;
15107
+ }
15108
+ if (Object.hasOwn(message, "id")) {
15109
+ const entry = pending.get(message.id);
15110
+ if (!entry) return;
15111
+ pending.delete(message.id);
15112
+ if (message.ok === true) entry.resolve(message);
15113
+ else entry.reject(failure("native-command"));
15114
+ return;
15115
+ }
15116
+ if (message.event === "error") {
15117
+ fail("native-helper");
15118
+ return;
15119
+ }
15120
+ if (message.event === "closed" || message.event === "state" && [
15121
+ "failed",
15122
+ "closed",
15123
+ "disconnected"
15124
+ ].includes(message.state)) {
15125
+ fail("native-disconnected");
15126
+ return;
15127
+ }
15128
+ const key = message.event === "state" ? "state:" + message.state : message.event;
15129
+ if (key === "offer" || key === "state:connected") {
15130
+ events.set(key, message);
15131
+ for (const waiter of waiting.get(key) ?? []) waiter.resolve(message);
15132
+ waiting.delete(key);
15133
+ }
15134
+ onEvent?.(message);
15135
+ };
15136
+ child.stdout.on("data", (chunk) => {
15137
+ if (broken || closing) return;
15138
+ const incoming = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
15139
+ let offset = 0;
15140
+ while (offset < incoming.length) {
15141
+ const newline = incoming.indexOf(10, offset);
15142
+ const end = newline === -1 ? incoming.length : newline;
15143
+ const part = incoming.subarray(offset, end);
15144
+ if (buffer.length + part.length + (newline === -1 ? 0 : 1) > MAX_LINE) {
15145
+ fail("native-protocol-size");
15146
+ return;
15147
+ }
15148
+ if (newline === -1) {
15149
+ if (buffer.length + part.length >= MAX_LINE) {
15150
+ fail("native-protocol-size");
15151
+ return;
15152
+ }
15153
+ buffer = buffer.length ? Buffer.concat([buffer, part]) : Buffer.from(part);
15154
+ return;
15155
+ }
15156
+ const line = buffer.length ? Buffer.concat([buffer, part]) : part;
15157
+ buffer = Buffer.alloc(0);
15158
+ try {
15159
+ receive(JSON.parse(line.toString("utf8")));
15160
+ } catch {
15161
+ fail("native-protocol");
15162
+ return;
15163
+ }
15164
+ if (broken || closing) return;
15165
+ offset = end + 1;
15166
+ }
15167
+ });
15168
+ child.stdout.on("end", () => fail("native-eof"));
15169
+ child.stdout.on("error", () => fail("native-io"));
15170
+ child.stdin.on("error", () => fail("native-io"));
15171
+ child.stderr?.on("error", () => {});
15172
+ child.stderr?.resume();
15173
+ child.on("error", () => {
15174
+ fail("native-spawn");
15175
+ if (!child.pid) {
15176
+ exited = true;
15177
+ finished();
15178
+ }
15179
+ });
15180
+ child.on("exit", () => fail("native-exit"));
15181
+ child.on("close", () => {
15182
+ exited = true;
15183
+ finished();
15184
+ fail("native-exit");
15185
+ });
15186
+ const request = (type, fields = {}, timeout = 5e3) => {
15187
+ if (broken || closing) return Promise.reject(broken ?? failure("native-closed"));
15188
+ const id = ++sequence;
15189
+ const data = JSON.stringify({
15190
+ ...fields,
15191
+ id,
15192
+ type
15193
+ }) + "\n";
15194
+ if (Buffer.byteLength(data) > MAX_LINE) return Promise.reject(failure("native-protocol-size"));
15195
+ return new Promise((resolve, reject) => {
15196
+ const timer = setTimeout(() => {
15197
+ pending.delete(id);
15198
+ reject(failure("native-command-timeout"));
15199
+ }, timeout);
15200
+ pending.set(id, {
15201
+ resolve: (value) => {
15202
+ clearTimeout(timer);
15203
+ resolve(value);
15204
+ },
15205
+ reject: (error) => {
15206
+ clearTimeout(timer);
15207
+ reject(error);
15208
+ }
15209
+ });
15210
+ try {
15211
+ child.stdin.write(data);
15212
+ } catch {
15213
+ pending.get(id)?.reject(failure("native-io"));
15214
+ pending.delete(id);
15215
+ }
15216
+ });
15217
+ };
15218
+ return {
15219
+ request,
15220
+ closed: exit,
15221
+ wait(key) {
15222
+ if (broken || closing) return Promise.reject(broken ?? failure("native-closed"));
15223
+ if (events.has(key)) return Promise.resolve(events.get(key));
15224
+ return new Promise((resolve, reject) => {
15225
+ const values = waiting.get(key) ?? [];
15226
+ values.push({
15227
+ resolve,
15228
+ reject
15229
+ });
15230
+ waiting.set(key, values);
15231
+ });
15232
+ },
15233
+ close() {
15234
+ if (shutdown) return shutdown;
15235
+ closing = true;
15236
+ for (const entry of pending.values()) entry.reject(failure("native-closed"));
15237
+ for (const values of waiting.values()) for (const entry of values) entry.reject(failure("native-closed"));
15238
+ pending.clear();
15239
+ waiting.clear();
15240
+ events.clear();
15241
+ buffer = Buffer.alloc(0);
15242
+ shutdown = (async () => {
15243
+ try {
15244
+ child.stdin.end();
15245
+ } catch {}
15246
+ const wait = async (ms) => {
15247
+ let timer;
15248
+ await Promise.race([exit, new Promise((resolve) => {
15249
+ timer = setTimeout(resolve, ms);
15250
+ })]);
15251
+ clearTimeout(timer);
15252
+ };
15253
+ if (!exited) await wait(750);
15254
+ if (!exited) {
15255
+ try {
15256
+ child.kill("SIGTERM");
15257
+ } catch {}
15258
+ await wait(500);
15259
+ }
15260
+ if (!exited) {
15261
+ try {
15262
+ child.kill("SIGKILL");
15263
+ } catch {}
15264
+ await wait(500);
15265
+ }
15266
+ if (!exited) throw failure("native-helper-cleanup", "The native audio process has not exited");
15267
+ })();
15268
+ return shutdown;
15269
+ }
15270
+ };
15271
+ }
15272
+ /** One native device lease, backed by the existing authenticated desktop call service. */
15273
+ function createNativeVoiceHost({ desktopVoice, spawn: spawn$1 = spawn, platform = process.platform, helperPath = helperFile, python = "python3", log } = {}) {
15274
+ let current, last, closing, probing = false;
15275
+ const probes = /* @__PURE__ */ new Set(), remotePending = /* @__PURE__ */ new Map();
15276
+ const owns = (call, sessionId, leaseToken) => call && call.sessionId === sessionId && call.leaseToken === leaseToken;
15277
+ const safeLog = (code) => {
15278
+ try {
15279
+ log?.warn?.("voice-native", code);
15280
+ } catch {}
15281
+ };
15282
+ const info = (code) => {
15283
+ try {
15284
+ log?.info?.("voice-native", code);
15285
+ } catch {}
15286
+ };
15287
+ const stopRemote = (call) => {
15288
+ if (!call.remoteRequested) return;
15289
+ try {
15290
+ Promise.resolve(desktopVoice.stop(call.sessionId)).catch(() => safeLog("native-remote-cleanup"));
15291
+ } catch {
15292
+ safeLog("native-remote-cleanup");
15293
+ }
15294
+ };
15295
+ const closeCall = (call, code) => {
15296
+ if (call.closing) return call.closing;
15297
+ call.ended = true;
15298
+ call.state = "closed";
15299
+ info(code);
15300
+ clearTimeout(call.deadline);
15301
+ clearInterval(call.heartbeat);
15302
+ call.removeAbort?.();
15303
+ call.controller.abort();
15304
+ stopRemote(call);
15305
+ last = {
15306
+ sessionId: call.sessionId,
15307
+ leaseToken: call.leaseToken,
15308
+ code
15309
+ };
15310
+ const released = () => {
15311
+ if (current === call) current = void 0;
15312
+ };
15313
+ call.port?.closed.then(released);
15314
+ call.closing = Promise.resolve(call.port?.close()).then(released);
15315
+ call.closing.catch(() => safeLog("native-helper-cleanup"));
15316
+ return call.closing;
15317
+ };
15318
+ const owner = (params) => {
15319
+ if (!owns(current, params?.sessionId, params?.leaseToken) || current.ended) throw failure("native-voice-owner", "This window does not own the native voice call");
15320
+ return current;
15321
+ };
15322
+ const inactive = (code) => ({
15323
+ active: false,
15324
+ native: true,
15325
+ nativeState: "closed",
15326
+ leaseValid: false,
15327
+ levels: {
15328
+ mic: 0,
15329
+ assistant: 0
15330
+ },
15331
+ ...code ? { code } : {}
15332
+ });
15333
+ return Object.freeze({
15334
+ async probe(signal) {
15335
+ if (platform !== "linux") return {
15336
+ available: false,
15337
+ platform,
15338
+ code: "native-unsupported"
15339
+ };
15340
+ if (signal?.aborted) throw aborted();
15341
+ if (probing || closing) return {
15342
+ available: false,
15343
+ platform,
15344
+ code: "native-voice-busy"
15345
+ };
15346
+ probing = true;
15347
+ const controller = new AbortController();
15348
+ const cancel = () => controller.abort();
15349
+ signal?.addEventListener("abort", cancel, { once: true });
15350
+ let port;
15351
+ const timer = setTimeout(cancel, 5e3);
15352
+ try {
15353
+ port = helperPort(spawn$1, python, helperPath, void 0, cancel);
15354
+ probes.add(port);
15355
+ port.closed.then(() => {
15356
+ probes.delete(port);
15357
+ probing = false;
15358
+ });
15359
+ const response = await withAbort(port.request("probe"), controller.signal);
15360
+ const missing = Array.isArray(response.missing) ? response.missing.filter((x) => typeof x === "string" && /^[a-z0-9_-]{1,48}$/i.test(x)).slice(0, 32) : [];
15361
+ return {
15362
+ available: response.available === true,
15363
+ platform,
15364
+ missing
15365
+ };
15366
+ } catch (error) {
15367
+ if (signal?.aborted) throw aborted();
15368
+ return {
15369
+ available: false,
15370
+ platform,
15371
+ code: "native-unavailable"
15372
+ };
15373
+ } finally {
15374
+ clearTimeout(timer);
15375
+ signal?.removeEventListener("abort", cancel);
15376
+ if (port) {
15377
+ await port.close();
15378
+ probes.delete(port);
15379
+ } else probing = false;
15380
+ }
15381
+ },
15382
+ async start({ sessionId, captureAllowed, voice, language } = {}, signal) {
15383
+ if (platform !== "linux" || typeof desktopVoice?.start !== "function" || typeof desktopVoice?.stop !== "function" || typeof desktopVoice?.status !== "function") throw failure("native-unsupported");
15384
+ if (captureAllowed !== true) throw failure("native-capture-permission", "Microphone capture requires confirmation");
15385
+ if (typeof sessionId !== "string" || !sessionId || sessionId.length > 512) throw failure("native-session");
15386
+ if (signal?.aborted) throw aborted();
15387
+ if (closing || current || remotePending.has(sessionId)) throw failure("native-voice-busy", "Native voice is already in use");
15388
+ if (desktopVoice.status(sessionId)?.active === true) throw failure("native-voice-busy", "This conversation already has a voice call");
15389
+ const call = {
15390
+ sessionId,
15391
+ leaseToken: randomUUID(),
15392
+ controller: new AbortController(),
15393
+ state: "starting",
15394
+ levels: {
15395
+ mic: 0,
15396
+ assistant: 0
15397
+ },
15398
+ muted: false,
15399
+ outputMuted: false,
15400
+ interrupted: false,
15401
+ interruptions: 0
15402
+ };
15403
+ info("native-starting");
15404
+ current = call;
15405
+ const cancel = () => {
15406
+ closeCall(call, "native-cancelled");
15407
+ };
15408
+ signal?.addEventListener("abort", cancel, { once: true });
15409
+ call.removeAbort = () => signal?.removeEventListener("abort", cancel);
15410
+ if (signal?.aborted) {
15411
+ await closeCall(call, "native-cancelled");
15412
+ throw aborted();
15413
+ }
15414
+ call.deadline = setTimeout(() => {
15415
+ closeCall(call, "native-start-timeout");
15416
+ }, START_TIMEOUT);
15417
+ const control = (type) => {
15418
+ if (call.ended) return;
15419
+ call.port.request(type).catch(() => {
15420
+ closeCall(call, "native-control");
15421
+ });
15422
+ };
15423
+ const gate = createBargeInGate({
15424
+ outputTailMs: 500,
15425
+ silenceMs: 700,
15426
+ changed(value) {
15427
+ call.interrupted = value;
15428
+ if (value) call.interruptions++;
15429
+ info(value ? "native-speech-interrupt" : "native-speech-resume");
15430
+ control(value ? "interrupt" : "resume");
15431
+ },
15432
+ interrupt() {
15433
+ try {
15434
+ Promise.resolve(desktopVoice.interrupt(sessionId)).catch(() => {
15435
+ closeCall(call, "native-interrupt");
15436
+ });
15437
+ } catch {
15438
+ closeCall(call, "native-interrupt");
15439
+ }
15440
+ }
15441
+ });
15442
+ try {
15443
+ call.port = helperPort(spawn$1, python, helperPath, (event) => {
15444
+ if (call.ended || event.event !== "level") return;
15445
+ if (![event.mic, event.assistant].every((x) => typeof x === "number" && Number.isFinite(x) && x >= 0 && x <= 1)) return;
15446
+ call.levels = {
15447
+ mic: call.muted ? 0 : Math.min(1, event.mic * 3.2),
15448
+ assistant: Math.min(1, event.assistant * 3.2)
15449
+ };
15450
+ if (call.state === "connected") gate.sample({
15451
+ mic: call.levels.mic,
15452
+ output: call.levels.assistant,
15453
+ now: performance.now()
15454
+ });
15455
+ }, (error) => {
15456
+ closeCall(call, error.code);
15457
+ });
15458
+ if (call.ended) {
15459
+ await call.port.close();
15460
+ throw aborted();
15461
+ }
15462
+ await withAbort(call.port.request("start", { captureAllowed: true }), call.controller.signal);
15463
+ const { sdp } = await withAbort(call.port.wait("offer"), call.controller.signal);
15464
+ if (typeof sdp !== "string" || !sdp.startsWith("v=0") || Buffer.byteLength(sdp) > 64 * 1024) throw failure("native-offer");
15465
+ call.remoteRequested = true;
15466
+ const remote = Promise.resolve().then(() => {
15467
+ call.controller.signal.throwIfAborted();
15468
+ return desktopVoice.start({
15469
+ sessionId,
15470
+ sdp,
15471
+ voice,
15472
+ language,
15473
+ signal: call.controller.signal
15474
+ });
15475
+ }).finally(() => {
15476
+ if (call.ended) stopRemote(call);
15477
+ if (remotePending.get(sessionId) === remote) remotePending.delete(sessionId);
15478
+ });
15479
+ remotePending.set(sessionId, remote);
15480
+ const result = await withAbort(remote, call.controller.signal);
15481
+ if (typeof result?.answer !== "string" || !result.answer.startsWith("v=0") || Buffer.byteLength(result.answer) >= 100 * 1024) throw failure("native-answer");
15482
+ await withAbort(call.port.request("remote", {
15483
+ descriptionType: "answer",
15484
+ sdp: result.answer
15485
+ }), call.controller.signal);
15486
+ await withAbort(call.port.wait("state:connected"), call.controller.signal);
15487
+ let readyTimer;
15488
+ try {
15489
+ await withAbort(new Promise((resolve, reject) => {
15490
+ const check = () => {
15491
+ try {
15492
+ const status = desktopVoice.status(sessionId);
15493
+ if (status?.active === false) {
15494
+ reject(failure("native-remote-ended"));
15495
+ return;
15496
+ }
15497
+ if (status?.inputReady !== false) {
15498
+ resolve();
15499
+ return;
15500
+ }
15501
+ readyTimer = setTimeout(check, 50);
15502
+ } catch {
15503
+ reject(failure("native-remote-status"));
15504
+ }
15505
+ };
15506
+ check();
15507
+ }), call.controller.signal);
15508
+ } finally {
15509
+ clearTimeout(readyTimer);
15510
+ }
15511
+ call.state = "connected";
15512
+ call.renewed = performance.now();
15513
+ info("native-connected");
15514
+ clearTimeout(call.deadline);
15515
+ call.removeAbort?.();
15516
+ call.removeAbort = void 0;
15517
+ call.heartbeat = setInterval(() => {
15518
+ if (performance.now() - call.renewed >= LEASE_TIMEOUT) {
15519
+ closeCall(call, "native-lease-expired");
15520
+ return;
15521
+ }
15522
+ try {
15523
+ if (desktopVoice.status(sessionId)?.active === false) closeCall(call, "native-remote-ended");
15524
+ } catch {
15525
+ closeCall(call, "native-remote-status");
15526
+ }
15527
+ }, 1e3);
15528
+ call.heartbeat.unref?.();
15529
+ return {
15530
+ sessionId,
15531
+ leaseToken: call.leaseToken,
15532
+ native: true,
15533
+ nativeState: "connected"
15534
+ };
15535
+ } catch (error) {
15536
+ const code = last?.leaseToken === call.leaseToken && last.code || (typeof error?.code === "string" && error.code.startsWith("native-") ? error.code : "native-start-failed");
15537
+ await closeCall(call, code);
15538
+ if (signal?.aborted) throw aborted();
15539
+ throw failure(code);
15540
+ }
15541
+ },
15542
+ status(sessionId, leaseToken) {
15543
+ if (!owns(current, sessionId, leaseToken) || current.ended) return inactive(owns(last, sessionId, leaseToken) ? last.code : "native-voice-owner");
15544
+ const call = current;
15545
+ call.renewed = performance.now();
15546
+ let remote;
15547
+ try {
15548
+ remote = desktopVoice.status(sessionId);
15549
+ } catch {
15550
+ closeCall(call, "native-remote-status");
15551
+ return inactive("native-remote-status");
15552
+ }
15553
+ if (remote?.active === false) {
15554
+ closeCall(call, "native-remote-ended");
15555
+ return inactive("native-remote-ended");
15556
+ }
15557
+ return {
15558
+ ...remote,
15559
+ active: call.state === "connected",
15560
+ native: true,
15561
+ nativeState: call.state,
15562
+ leaseValid: true,
15563
+ levels: { ...call.levels },
15564
+ muted: call.muted,
15565
+ outputMuted: call.outputMuted,
15566
+ interrupted: call.interrupted,
15567
+ interruptions: call.interruptions
15568
+ };
15569
+ },
15570
+ async mute(params) {
15571
+ const call = owner(params);
15572
+ if (typeof params.muted !== "boolean") throw failure("native-control");
15573
+ try {
15574
+ await call.port.request("mute", { muted: params.muted });
15575
+ call.muted = params.muted;
15576
+ if (call.muted) call.levels.mic = 0;
15577
+ } catch {
15578
+ await closeCall(call, "native-control");
15579
+ throw failure("native-control");
15580
+ }
15581
+ return { muted: call.muted };
15582
+ },
15583
+ async outputMute(params) {
15584
+ const call = owner(params);
15585
+ if (typeof params.muted !== "boolean") throw failure("native-control");
15586
+ try {
15587
+ await call.port.request("outputMute", { muted: params.muted });
15588
+ call.outputMuted = params.muted;
15589
+ } catch {
15590
+ await closeCall(call, "native-control");
15591
+ throw failure("native-control");
15592
+ }
15593
+ return { outputMuted: call.outputMuted };
15594
+ },
15595
+ async stop(params) {
15596
+ if (!owns(current, params?.sessionId, params?.leaseToken)) return { stopped: false };
15597
+ await closeCall(current, "native-stopped");
15598
+ return { stopped: true };
15599
+ },
15600
+ close(signal) {
15601
+ if (closing) return closing;
15602
+ closing = (async () => {
15603
+ await Promise.all([current && closeCall(current, "native-disposed"), ...[...probes].map((port) => port.close())]);
15604
+ if (remotePending.size) {
15605
+ const controller = new AbortController();
15606
+ const cancel = () => controller.abort();
15607
+ const timer = setTimeout(cancel, 5e3);
15608
+ signal?.addEventListener("abort", cancel, { once: true });
15609
+ if (signal?.aborted) cancel();
15610
+ try {
15611
+ await withAbort(Promise.allSettled([...remotePending.values()]), controller.signal);
15612
+ } catch {
15613
+ throw signal?.aborted ? aborted() : failure("native-voice-busy", "The previous voice call is still closing");
15614
+ } finally {
15615
+ clearTimeout(timer);
15616
+ signal?.removeEventListener("abort", cancel);
15617
+ }
15618
+ }
15619
+ })().finally(() => {
15620
+ closing = void 0;
15621
+ });
15622
+ return closing;
15623
+ }
15624
+ });
15625
+ }
15626
+ //#endregion
14257
15627
  //#region src/index.js
14258
15628
  const z = createRequire(import.meta.resolve("@deepseek-ai/dsh-settings"))("@deepseek-ai/schemastery");
14259
15629
  const name = "codex-subscription";
@@ -14381,6 +15751,19 @@ function apply(ctx, config = {}) {
14381
15751
  3e5
14382
15752
  ]
14383
15753
  });
15754
+ let appendUltraPolicy;
15755
+ try {
15756
+ appendUltraPolicy = createRequire(import.meta.url)("@deepseek-ai/dsh-session").appendPluginRecord;
15757
+ } catch (error) {
15758
+ if (!(error?.code === "MODULE_NOT_FOUND" && error.message?.startsWith("Cannot find module '@deepseek-ai/dsh-session'"))) throw error;
15759
+ }
15760
+ const ultra = createUltraExecutionPreset({
15761
+ catalog: modelCatalog,
15762
+ resolveAgent: () => ctx.get?.("agents")?.currentInitiator?.(),
15763
+ defaultEffort: () => settings.get()[DEFAULT_REASONING_EFFORT_FIELD],
15764
+ record: appendUltraPolicy
15765
+ });
15766
+ ctx.effect(() => ultra.install(ctx), "codex-subscription: Ultra execution preset");
14384
15767
  const connection = createSubscriptionConnection({ resolveMode: () => settings.get().connectionMode });
14385
15768
  const defaultModel = createDefaultModelController({
14386
15769
  resolveService: () => ctx.get?.("agentDefaultModel"),
@@ -14409,6 +15792,7 @@ function apply(ctx, config = {}) {
14409
15792
  ctx.on("session/event", (session, event) => reasoning.sessionEvent(session, event));
14410
15793
  ctx.effect(() => () => connection.dispose());
14411
15794
  const provider = openaiCodexSubscriptionProvider({
15795
+ ultra,
14412
15796
  connection,
14413
15797
  compaction,
14414
15798
  reasoning,
@@ -14471,6 +15855,7 @@ function apply(ctx, config = {}) {
14471
15855
  catalogStatus: modelCatalog.status(),
14472
15856
  verbosityModels: provider.getModels().filter((model) => modelCatalog.metadata(model.id)?.supportVerbosity ?? model.id !== "gpt-5.3-codex-spark").map((model) => model.id),
14473
15857
  ultrafastModels: provider.getModels().filter((model) => modelCatalog.metadata(model.id)?.supportsUltrafast === true).map((model) => model.id),
15858
+ ultraModels: provider.getModels().filter((model) => ultra.supported(model.id)).map((model) => model.id),
14474
15859
  fastModels: provider.getModels().filter((model) => modelCatalog.metadata(model.id)?.supportsFast ?? supportsCodexFastMode(model.id)).map((model) => model.id),
14475
15860
  writable: ctx.settings.writable
14476
15861
  };
@@ -14672,7 +16057,7 @@ function apply(ctx, config = {}) {
14672
16057
  }), "codex-subscription: default reasoning effort");
14673
16058
  ctx.effect(() => {
14674
16059
  const lifetime = new AbortController();
14675
- const defaults = withDefaultReasoningEffort(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(provider.wrapRetryAdapter(adapter))), provider), {
16060
+ const defaults = withDefaultReasoningEffort(ultra.wrapAdapter(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(provider.wrapRetryAdapter(adapter))), provider)), {
14676
16061
  preference: () => settings.get()[DEFAULT_REASONING_EFFORT_FIELD],
14677
16062
  modelDefault: (id) => modelCatalog.metadata(id)?.defaultReasoningEffort
14678
16063
  });
@@ -14851,6 +16236,8 @@ function apply(ctx, config = {}) {
14851
16236
  skills: () => ctx.get?.("skills"),
14852
16237
  commands: () => ctx.get?.("commands"),
14853
16238
  llm: () => ctx.llm,
16239
+ modelMetadata: (provider, model) => provider === PROVIDER ? modelCatalog.metadata(model) : void 0,
16240
+ historySource: createRemoteHistorySource({ query: () => ctx.get?.("sessionQuery") }),
14854
16241
  speed: {
14855
16242
  tiers: (provider, model) => provider === PROVIDER ? modelCatalog.metadata(model)?.serviceTiers ?? [] : [],
14856
16243
  current: () => settings.get()[SPEED_MODE_FIELD],
@@ -15029,6 +16416,24 @@ function apply(ctx, config = {}) {
15029
16416
  expirySkewMs: OAUTH_EXPIRY_SKEW_MS,
15030
16417
  activeReader: baseUsageReader
15031
16418
  });
16419
+ const desktopVoice = withEndCallTool(remoteBridge.desktopVoice, (tool) => ctx.tools.register(tool));
16420
+ const nativeVoice = createNativeVoiceHost({
16421
+ desktopVoice,
16422
+ log: diagnosticLog
16423
+ });
16424
+ ctx.effect(() => {
16425
+ const close = () => {
16426
+ nativeVoice.close().catch(() => diagnosticLog.warn("voice-native", "native call cleanup is waiting for a cancelled start"));
16427
+ };
16428
+ const sync = () => {
16429
+ if (settings.get().voiceCall !== "on") close();
16430
+ };
16431
+ const unwatch = settings.watch(sync);
16432
+ return () => {
16433
+ unwatch();
16434
+ close();
16435
+ };
16436
+ });
15032
16437
  const subscriptionHandler = createSubscriptionRpcHandler({
15033
16438
  authHandler: createCodexRpcHandler(coordinator, { openExternal: openCodexAuthUrl }),
15034
16439
  usageReader,
@@ -15040,7 +16445,8 @@ function apply(ctx, config = {}) {
15040
16445
  defaultModel,
15041
16446
  runtimeManagement,
15042
16447
  remoteControl,
15043
- desktopVoice: withEndCallTool(remoteBridge.desktopVoice, (tool) => ctx.tools.register(tool)),
16448
+ desktopVoice,
16449
+ nativeVoice,
15044
16450
  voicePreview: createVoicePreview({
15045
16451
  fetch: (input, init) => network.fetch("voice", input, init, { standardHttps: true }),
15046
16452
  credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {