dsh-codex-subscription 3.1.7 → 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");
@@ -461,6 +462,20 @@ const VOICE_LANGUAGES = Object.freeze([
461
462
  const normalizeVoiceCall = (value) => value === "on" ? "on" : "off";
462
463
  const normalizeVoiceVoice = (value) => VOICE_VOICES.includes(value) ? value : "cove";
463
464
  const normalizeVoiceLanguage = (value) => VOICE_LANGUAGES.includes(value) ? value : "auto";
465
+ const DEFAULT_REASONING_EFFORT_FIELD = "defaultReasoningEffort";
466
+ const DEFAULT_REASONING_EFFORTS = Object.freeze([
467
+ "auto",
468
+ "off",
469
+ "minimal",
470
+ "low",
471
+ "medium",
472
+ "high",
473
+ "xhigh",
474
+ "max",
475
+ "ultra"
476
+ ]);
477
+ const DEFAULT_REASONING_EFFORT = "auto";
478
+ const normalizeDefaultReasoningEffort = (value) => DEFAULT_REASONING_EFFORTS.includes(value) ? value : DEFAULT_REASONING_EFFORT;
464
479
  const REASONING_SUMMARY_FIELD = "reasoningSummary";
465
480
  const REASONING_SUMMARIES = Object.freeze([
466
481
  "auto",
@@ -604,6 +619,73 @@ const normalizeQuickQuotaMode = (value, legacyVisible = false) => [
604
619
  ].includes(value) ? value : legacyVisible === true ? QUICK_QUOTA_MODE_PERCENT : "off";
605
620
  const supportsCodexFastMode = (modelId) => typeof modelId === "string" && (/^gpt-5\.(?:5|6)(?:$|-)/u.test(modelId) || modelId === "gpt-5.4" || modelId === "gpt-6-astra");
606
621
  //#endregion
622
+ //#region src/default-reasoning-effort.js
623
+ function modelInfo(info, preference, modelDefault) {
624
+ const efforts = info?.reasoning?.efforts;
625
+ if (!Array.isArray(efforts)) return info;
626
+ const supported = (effort) => efforts.some((value) => value.id === effort);
627
+ const fallback = supported(modelDefault) ? modelDefault : info.reasoning.defaultEffort;
628
+ const selected = preference !== "auto" && supported(preference) ? preference : fallback;
629
+ return supported(selected) ? {
630
+ ...info,
631
+ reasoning: {
632
+ ...info.reasoning,
633
+ defaultEffort: selected
634
+ }
635
+ } : info;
636
+ }
637
+ function withDefaultReasoningEffort(adapter, { provider = "openai-codex", preference, modelDefault } = {}) {
638
+ const snapshot = (model) => ({
639
+ choice: normalizeDefaultReasoningEffort(preference?.()),
640
+ fallback: modelDefault?.(model)
641
+ });
642
+ const optionsFor = (options, info) => options.reasoningEffort !== void 0 || options.provider !== provider || options.model !== info.id || info.reasoning?.defaultEffort === void 0 ? options : {
643
+ ...options,
644
+ reasoningEffort: info.reasoning.defaultEffort
645
+ };
646
+ const prepare = async (target, args, captured) => {
647
+ const call = await target.prepareCall(...args);
648
+ const info = modelInfo(call.model, captured.choice, captured.fallback);
649
+ return {
650
+ ...call,
651
+ model: info,
652
+ stream: (options) => call.stream(optionsFor(options, info))
653
+ };
654
+ };
655
+ return new Proxy(adapter, { get(target, property) {
656
+ const value = Reflect.get(target, property, target);
657
+ if (property === "resolveModel" && typeof value === "function") return async (...args) => {
658
+ if (args[0] !== provider) return value.apply(target, args);
659
+ const captured = snapshot(args[1]);
660
+ return modelInfo(await value.apply(target, args), captured.choice, captured.fallback);
661
+ };
662
+ if (property === "prepareCall" && typeof value === "function") return (...args) => args[0] === provider ? prepare(target, args, snapshot(args[1])) : value.apply(target, args);
663
+ if (property === "stream" && typeof value === "function") return (options) => {
664
+ if (options.provider !== provider) return value.call(target, options);
665
+ const captured = snapshot(options.model);
666
+ return (async function* () {
667
+ let call;
668
+ try {
669
+ if (typeof target.prepareCall === "function") call = await prepare(target, [
670
+ options.provider,
671
+ options.model,
672
+ options.signal
673
+ ], captured);
674
+ else {
675
+ const info = modelInfo(await target.resolveModel(options.provider, options.model, options.signal), captured.choice, captured.fallback);
676
+ call = { stream: (input) => value.call(target, optionsFor(input, info)) };
677
+ }
678
+ } catch {
679
+ yield* value.call(target, options);
680
+ return;
681
+ }
682
+ yield* call.stream(options);
683
+ })();
684
+ };
685
+ return typeof value === "function" ? value.bind(target) : value;
686
+ } });
687
+ }
688
+ //#endregion
607
689
  //#region src/preference-fields.js
608
690
  const PREFERENCE_FIELDS = Object.freeze({
609
691
  compactionMode: {
@@ -620,6 +702,11 @@ const PREFERENCE_FIELDS = Object.freeze({
620
702
  default: "on",
621
703
  error: "Invalid reasoning cache preference"
622
704
  },
705
+ [DEFAULT_REASONING_EFFORT_FIELD]: {
706
+ choices: DEFAULT_REASONING_EFFORTS,
707
+ default: DEFAULT_REASONING_EFFORT,
708
+ error: "Invalid default reasoning effort"
709
+ },
623
710
  connectionMode: {
624
711
  choices: ["sse", "websocket"],
625
712
  default: "sse",
@@ -950,7 +1037,9 @@ async function windowsSystemProxy(options = {}) {
950
1037
  "ProxyEnable"
951
1038
  ], {
952
1039
  windowsHide: true,
953
- encoding: "utf8"
1040
+ encoding: "utf8",
1041
+ timeout: 1e4,
1042
+ signal: options.signal
954
1043
  });
955
1044
  if (!/REG_DWORD\s+0x1\b/iu.test(enabled.stdout)) return void 0;
956
1045
  const configured = await run(reg, [
@@ -960,7 +1049,9 @@ async function windowsSystemProxy(options = {}) {
960
1049
  "ProxyServer"
961
1050
  ], {
962
1051
  windowsHide: true,
963
- encoding: "utf8"
1052
+ encoding: "utf8",
1053
+ timeout: 1e4,
1054
+ signal: options.signal
964
1055
  });
965
1056
  return selectWindowsProxy(/^\s*ProxyServer\s+REG_\w+\s+(.+)$/imu.exec(configured.stdout)?.[1]);
966
1057
  } catch {
@@ -970,7 +1061,11 @@ async function windowsSystemProxy(options = {}) {
970
1061
  async function macSystemProxy(options = {}) {
971
1062
  const run = options.execFile ?? execFileAsync;
972
1063
  try {
973
- const result = await run("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8" });
1064
+ const result = await run("/usr/sbin/scutil", ["--proxy"], {
1065
+ encoding: "utf8",
1066
+ timeout: 1e4,
1067
+ signal: options.signal
1068
+ });
974
1069
  if (!/^\s*HTTPSEnable\s*:\s*1\s*$/imu.test(result.stdout)) return void 0;
975
1070
  const host = /^\s*HTTPSProxy\s*:\s*(\S+)\s*$/imu.exec(result.stdout)?.[1];
976
1071
  const port = /^\s*HTTPSPort\s*:\s*(\d+)\s*$/imu.exec(result.stdout)?.[1];
@@ -1017,12 +1112,49 @@ function transportError(error, signal) {
1017
1112
  return Object.assign(new Error(`Network transport failure (${error.code}): ${error.message}`, { cause: error }), { code: error.code });
1018
1113
  }
1019
1114
  function transportResponseBody(response, signal) {
1020
- const body = new PassThrough();
1021
- response.on("error", (error) => body.destroy(transportError(error, signal)));
1022
- body.on("close", () => response.destroy());
1023
- const stream = Readable.toWeb(body);
1024
- response.pipe(body);
1025
- 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
+ });
1026
1158
  }
1027
1159
  function fetchThroughProxy(input, init, proxyUrl) {
1028
1160
  const target = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
@@ -1809,7 +1941,7 @@ function isDshAutoReview(context) {
1809
1941
  * persistence, headers, transport, and model behavior remain owned by the
1810
1942
  * original provider.
1811
1943
  */
1812
- function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, resolveOutputVerbosity = () => OUTPUT_VERBOSITY_DEFAULT, resolveInputImageDetail = () => void 0, resolveReasoningSummary = () => void 0, resolveContextMode = () => void 0, resolveCustomContextWindow = () => void 0, resolveReviewModel = () => REVIEW_MODEL_SESSION, catalog, connection, compaction, reasoning, runNetwork = (_area, operation) => operation() } = {}) {
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() } = {}) {
1813
1945
  const provider = createOpenAICodexProvider();
1814
1946
  const retryBridge = createModelRetryBridge();
1815
1947
  const requestToken = Object.freeze({
@@ -1860,7 +1992,8 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
1860
1992
  } },
1861
1993
  ...serviceTier === void 0 ? {} : { service_tier: serviceTier }
1862
1994
  };
1863
- return reasoning?.preparePayload(finalPayload, requestModel) ?? finalPayload;
1995
+ const reasoned = reasoning?.preparePayload(finalPayload, requestModel) ?? finalPayload;
1996
+ return ultra?.preparePayload(reasoned) ?? reasoned;
1864
1997
  }
1865
1998
  };
1866
1999
  };
@@ -2136,7 +2269,7 @@ const REASONING_LIMITS = Object.freeze({
2136
2269
  bytes: 16 * 1024 * 1024,
2137
2270
  updates: 128
2138
2271
  });
2139
- 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);
2140
2273
  const efforts = /* @__PURE__ */ new Set([
2141
2274
  "low",
2142
2275
  "medium",
@@ -2150,13 +2283,13 @@ const reasoningDigest = (value) => {
2150
2283
  const text = boundedStringify(value, REASONING_LIMITS.bytes);
2151
2284
  return text === void 0 ? void 0 : reasoningHash(text);
2152
2285
  };
2153
- 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) => [
2154
2287
  "offset",
2155
2288
  "hash",
2156
2289
  ...update ? ["effort"] : []
2157
2290
  ].includes(key)) && Number.isInteger(value.offset) && value.offset >= 0 && value.offset <= REASONING_LIMITS.items && isHash(value.hash);
2158
2291
  function isReasoningState(value) {
2159
- if (!record$8(value) || value.version !== 1 || !isHash(value.scope) || !isHash(value.envelope) || !efforts.has(value.baseline) || !boundary(value.last) || !Array.isArray(value.updates) || value.updates.length > REASONING_LIMITS.updates || Object.keys(value).some((key) => ![
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) => ![
2160
2293
  "version",
2161
2294
  "scope",
2162
2295
  "envelope",
@@ -2190,7 +2323,7 @@ function rewriteReasoning(payload, { model, scope, previous, fresh = false }) {
2190
2323
  payload,
2191
2324
  reason
2192
2325
  });
2193
- if (!supportsReasoningUpdates(model) || !record$8(payload) || payload.model !== model.id || !Array.isArray(payload.input) || !record$8(payload.reasoning) || !efforts.has(payload.reasoning.effort)) return skip("unsupported-request");
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");
2194
2327
  if (payload.context_management !== void 0) return skip("cloud-compaction");
2195
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) => [
2196
2329
  "configuration_update",
@@ -2486,6 +2619,11 @@ const RPC_ENDPOINTS = Object.freeze([
2486
2619
  "voice/interrupt",
2487
2620
  "voice/preview",
2488
2621
  "voice/catalog",
2622
+ "voice/native/probe",
2623
+ "voice/native/start",
2624
+ "voice/native/status",
2625
+ "voice/native/control",
2626
+ "voice/native/stop",
2489
2627
  "remote/status",
2490
2628
  "remote/enable",
2491
2629
  "remote/disable",
@@ -2504,6 +2642,20 @@ const RPC_ENDPOINTS = Object.freeze([
2504
2642
  ]);
2505
2643
  //#endregion
2506
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
+ };
2507
2659
  /** Exact routes stay inside DSH's authenticated /api bridge and body limit. */
2508
2660
  function registerSubscriptionTransport(connection, handler) {
2509
2661
  const disposers = [];
@@ -2515,6 +2667,7 @@ function registerSubscriptionTransport(connection, handler) {
2515
2667
  methods: ["POST"],
2516
2668
  requestBody: "buffered",
2517
2669
  async fetch(request) {
2670
+ if (endpoint.startsWith("voice/native/") && !localNativeRequest(request)) return new Response("native voice requires the local desktop", { status: 403 });
2518
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 });
2519
2672
  let body;
2520
2673
  try {
@@ -2696,7 +2849,8 @@ const SUPPORTED_RUNTIME_VERSIONS = Object.freeze([
2696
2849
  "0.2.1-alpha.5",
2697
2850
  "0.2.1-rc.1",
2698
2851
  "0.2.1-rc.2",
2699
- "0.2.1-rc.3"
2852
+ "0.2.1-rc.3",
2853
+ "0.2.1-rc.4"
2700
2854
  ]);
2701
2855
  const require = createRequire(import.meta.url);
2702
2856
  const execute = promisify(execFile);
@@ -3506,7 +3660,7 @@ function inheritedOriginalImageRef(session, assetId) {
3506
3660
  }
3507
3661
  //#endregion
3508
3662
  //#region src/version.js
3509
- const PACKAGE_VERSION = "3.1.7";
3663
+ const PACKAGE_VERSION = "3.1.9";
3510
3664
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
3511
3665
  //#endregion
3512
3666
  //#region src/codex-images.js
@@ -3534,7 +3688,7 @@ const FULL_ATTACHMENT_ID = /^sha256:[0-9a-f]{64}$/u;
3534
3688
  const BARE_ATTACHMENT_DIGEST = /^[0-9a-f]{64}$/iu;
3535
3689
  const PATH_LIKE_ATTACHMENT_ID = /[\\/]/u;
3536
3690
  const FILE_NAME_ATTACHMENT_ID = /\.[A-Za-z0-9]{1,16}$/u;
3537
- 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);
3538
3692
  const nonEmpty$2 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
3539
3693
  const NETWORK_REASONS = {
3540
3694
  UND_ERR_HEADERS_TIMEOUT: "the image service sent no response within 5 minutes",
@@ -3620,7 +3774,7 @@ function decodeCodexPng(value, maximumBytes) {
3620
3774
  return new Uint8Array(data);
3621
3775
  }
3622
3776
  function imageReference(value) {
3623
- const originalDimensions = record$7(value.originalDimensions) ? {
3777
+ const originalDimensions = record$8(value.originalDimensions) ? {
3624
3778
  width: value.originalDimensions.width,
3625
3779
  height: value.originalDimensions.height
3626
3780
  } : void 0;
@@ -3648,7 +3802,7 @@ function invalidAttachmentId(value) {
3648
3802
  function referenceOf(value, attachments) {
3649
3803
  const attachmentId = normalizeAttachmentId(value?.attachmentId);
3650
3804
  if (attachmentId === void 0) invalidAttachmentId(value);
3651
- if (!record$7(value) || !attachments.imageLimits.mediaTypes.includes(value.mediaType) || !Number.isSafeInteger(value.bytes) || value.bytes <= 0 || !Number.isSafeInteger(value.width) || value.width <= 0 || !Number.isSafeInteger(value.height) || value.height <= 0 || value.name !== void 0 && (typeof value.name !== "string" || value.name.length > 256) || value.originalDimensions !== void 0 && (!record$7(value.originalDimensions) || !Number.isSafeInteger(value.originalDimensions.width) || value.originalDimensions.width <= 0 || !Number.isSafeInteger(value.originalDimensions.height) || value.originalDimensions.height <= 0)) throw new Error("referenceImages contains an invalid image reference");
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");
3652
3806
  return imageReference({
3653
3807
  ...value,
3654
3808
  attachmentId
@@ -3658,7 +3812,7 @@ function sessionImageReferences(messages) {
3658
3812
  const references = /* @__PURE__ */ new Map();
3659
3813
  const visit = (content) => {
3660
3814
  if (!Array.isArray(content)) return;
3661
- 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)) {
3662
3816
  const id = normalizeAttachmentId(block.attachment.attachmentId);
3663
3817
  if (id !== void 0) references.set(id, block.attachment);
3664
3818
  } else if (block?.type === "tool-result") visit(block.content);
@@ -3823,7 +3977,7 @@ async function limitMessage(response, now = Date.now()) {
3823
3977
  } catch {
3824
3978
  return fallback;
3825
3979
  }
3826
- if (!record$7(error)) return fallback;
3980
+ if (!record$8(error)) return fallback;
3827
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;
3828
3982
  if (at === void 0) return fallback;
3829
3983
  const minutes = Math.max(1, Math.ceil((at - now) / 6e4));
@@ -3835,7 +3989,7 @@ async function refusalMessage(response, editing) {
3835
3989
  let reason;
3836
3990
  try {
3837
3991
  const value = JSON.parse(await readTextWithin(response, 16 * 1024));
3838
- const error = record$7(value?.error) ? value.error : void 0;
3992
+ const error = record$8(value?.error) ? value.error : void 0;
3839
3993
  reason = [
3840
3994
  error?.message,
3841
3995
  value?.detail,
@@ -3860,7 +4014,7 @@ async function readTextWithin(response, maximumBytes) {
3860
4014
  }
3861
4015
  function responseMetadata(value) {
3862
4016
  const data = Array.isArray(value?.data) ? value.data[0] : void 0;
3863
- const encoded = record$7(data) ? data.b64_json : void 0;
4017
+ const encoded = record$8(data) ? data.b64_json : void 0;
3864
4018
  if (typeof encoded !== "string") throw new Error("Codex returned no image data");
3865
4019
  return {
3866
4020
  encoded,
@@ -4341,6 +4495,16 @@ const FIELDS = /* @__PURE__ */ new Set([
4341
4495
  "event",
4342
4496
  "error"
4343
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);
4344
4508
  function phoneLog(event, details = {}, level = "info") {
4345
4509
  const fields = {};
4346
4510
  for (const [name, value] of Object.entries(details)) {
@@ -4691,6 +4855,7 @@ function enrollment(value) {
4691
4855
  * credentials: (signal?: AbortSignal) => Promise<{ access?: string, accountId?: string }>,
4692
4856
  * fetch?: typeof fetch,
4693
4857
  * WebSocket: new (url: string, options: object) => any,
4858
+ * resolveProxy?: (options: { target: URL, signal: AbortSignal }) => Promise<string | undefined>,
4694
4859
  * installationId: string,
4695
4860
  * hostName: string,
4696
4861
  * userAgent: string,
@@ -5057,22 +5222,53 @@ function createRemoteControlRelay(options) {
5057
5222
  };
5058
5223
  const connectOnce = async (signal) => {
5059
5224
  const current = await ensureEnrollment(signal);
5225
+ if (signal.aborted) return;
5226
+ const proxy = endpoints.websocket.protocol === "wss:" ? await new Promise((resolve, reject) => {
5227
+ const lookup = AbortSignal.any([signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
5228
+ const abort = () => reject(signal.aborted ? signal.reason : new RemoteControlError("timeout", "Proxy resolution timed out"));
5229
+ lookup.addEventListener("abort", abort, { once: true });
5230
+ Promise.resolve().then(() => {
5231
+ lookup.throwIfAborted();
5232
+ return (options.resolveProxy ?? resolveCodexOAuthProxy)({
5233
+ target: endpoints.websocket,
5234
+ signal: lookup
5235
+ });
5236
+ }).then(resolve, reject).finally(() => lookup.removeEventListener("abort", abort));
5237
+ if (lookup.aborted) abort();
5238
+ }) : void 0;
5239
+ if (signal.aborted) return;
5060
5240
  await new Promise((resolve, reject) => {
5061
- const ws = new options.WebSocket(endpoints.websocket.toString(), { headers: {
5062
- authorization: `Bearer ${current.token}`,
5063
- "user-agent": options.userAgent,
5064
- "x-codex-installation-id": installation,
5065
- "x-codex-name": Buffer.from(options.hostName).toString("base64"),
5066
- "x-codex-protocol-version": PROTOCOL_VERSION,
5067
- "x-codex-server-id": current.serverId,
5068
- ...subscribeCursor === void 0 ? {} : { "x-codex-subscribe-cursor": subscribeCursor }
5069
- } });
5241
+ const connecting = new AbortController();
5242
+ const agent = proxy ? new HttpsProxyAgent(proxy, { signal: connecting.signal }) : void 0;
5243
+ const ws = new options.WebSocket(endpoints.websocket.toString(), {
5244
+ handshakeTimeout: REQUEST_TIMEOUT_MS,
5245
+ ...agent ? { agent } : {},
5246
+ headers: {
5247
+ authorization: `Bearer ${current.token}`,
5248
+ "user-agent": options.userAgent,
5249
+ "x-codex-installation-id": installation,
5250
+ "x-codex-name": Buffer.from(options.hostName).toString("base64"),
5251
+ "x-codex-protocol-version": PROTOCOL_VERSION,
5252
+ "x-codex-server-id": current.serverId,
5253
+ ...subscribeCursor === void 0 ? {} : { "x-codex-subscribe-cursor": subscribeCursor }
5254
+ }
5255
+ });
5070
5256
  socket = ws;
5071
5257
  let queue = Promise.resolve();
5072
- const onAbort = () => ws.close();
5258
+ const onAbort = () => {
5259
+ stopBeat();
5260
+ ws.close();
5261
+ };
5073
5262
  signal.addEventListener("abort", onAbort, { once: true });
5074
5263
  let ping;
5075
5264
  let silent;
5265
+ const handshake = setTimeout(() => {
5266
+ stopBeat();
5267
+ try {
5268
+ (ws.terminate ?? ws.close).call(ws);
5269
+ } catch {}
5270
+ reject(new RemoteControlError("timeout", "Remote Control connection timed out"));
5271
+ }, REQUEST_TIMEOUT_MS);
5076
5272
  const hearFrom = () => {
5077
5273
  clearTimeout(silent);
5078
5274
  silent = setTimeout(() => {
@@ -5083,10 +5279,14 @@ function createRemoteControlRelay(options) {
5083
5279
  }, options.pongTimeoutMs ?? PONG_TIMEOUT_MS);
5084
5280
  };
5085
5281
  const stopBeat = () => {
5282
+ clearTimeout(handshake);
5086
5283
  clearInterval(ping);
5087
5284
  clearTimeout(silent);
5285
+ connecting.abort();
5286
+ agent?.destroy();
5088
5287
  };
5089
5288
  ws.on("open", () => {
5289
+ clearTimeout(handshake);
5090
5290
  state.status = "connected";
5091
5291
  state.connectedAt = now();
5092
5292
  state.lastError = void 0;
@@ -5131,6 +5331,7 @@ function createRemoteControlRelay(options) {
5131
5331
  signal.removeEventListener("abort", onAbort);
5132
5332
  resolve();
5133
5333
  });
5334
+ if (signal.aborted) onAbort();
5134
5335
  });
5135
5336
  assemblies.clear();
5136
5337
  socket = void 0;
@@ -5147,6 +5348,7 @@ function createRemoteControlRelay(options) {
5147
5348
  await connectOnce(signal);
5148
5349
  if (state.connectedAt !== void 0 && now() - state.connectedAt >= STABLE_MS) delay = INITIAL_RECONNECT_MS;
5149
5350
  } catch (error) {
5351
+ if (signal.aborted) break;
5150
5352
  asked = error?.retryAfterMs;
5151
5353
  state.lastError = error?.code ?? "network";
5152
5354
  if (options.debug) state.detail = String(error?.message ?? error).slice(0, 160);
@@ -6315,6 +6517,7 @@ function createRealtimeVoice(options) {
6315
6517
  ws,
6316
6518
  notify,
6317
6519
  ended: false,
6520
+ inputReady: false,
6318
6521
  chain: Promise.resolve(),
6319
6522
  tail: [],
6320
6523
  lines: [],
@@ -6378,6 +6581,7 @@ function createRealtimeVoice(options) {
6378
6581
  ws.on("message", (data) => {
6379
6582
  try {
6380
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;
6381
6585
  const id = value.client_event_id ?? value.error?.event_id;
6382
6586
  if (id && session.controls.delete(id)) {
6383
6587
  if (value.type === "error") log.warn("voice", "the voice service refused an interruption command", String(value.error?.message ?? "").slice(0, 200));
@@ -6524,6 +6728,7 @@ function createRealtimeVoice(options) {
6524
6728
  const session = sessions.get(threadId);
6525
6729
  return session ? {
6526
6730
  active: true,
6731
+ inputReady: session.inputReady,
6527
6732
  working: session.working > 0,
6528
6733
  closing: session.closing === true,
6529
6734
  lines: session.lines.slice(-6)
@@ -6540,6 +6745,195 @@ function createRealtimeVoice(options) {
6540
6745
  };
6541
6746
  }
6542
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
6543
6937
  //#region src/remote-control-image-output.js
6544
6938
  const images = /* @__PURE__ */ new WeakMap();
6545
6939
  const renderedSources = /* @__PURE__ */ new WeakMap();
@@ -6690,33 +7084,6 @@ function page(list, params) {
6690
7084
  };
6691
7085
  }
6692
7086
  /** Codex usage as the phone's rate-limit snapshot (primary and secondary windows of the main limit). */
6693
- function rateLimits(read) {
6694
- const toWindow = (entry) => entry && {
6695
- usedPercent: Math.round(entry.usedPercent),
6696
- windowDurationMins: Math.round(entry.windowSeconds / 60),
6697
- resetsAt: entry.resetsAt ?? null
6698
- };
6699
- const snapshot = (limit) => ({
6700
- limitId: limit?.id ?? "codex",
6701
- limitName: limit?.name ?? null,
6702
- normalModelSlug: null,
6703
- primary: toWindow(limit?.windows?.[0]) ?? null,
6704
- secondary: toWindow(limit?.windows?.[1]) ?? null,
6705
- credits: null,
6706
- individualLimit: null,
6707
- spendControlReached: read?.spendControlReached ?? null,
6708
- planType: read?.planType ?? null,
6709
- rateLimitReachedType: read?.rateLimitReachedType ?? null
6710
- });
6711
- return {
6712
- ordinaryUsageAllowed: null,
6713
- rateLimits: snapshot(read?.rateLimits?.find((limit) => limit.id === "codex") ?? read?.rateLimits?.[0]),
6714
- rateLimitsByLimitId: read ? Object.fromEntries((read.rateLimits ?? []).map((limit) => [limit.id, snapshot(limit)])) : null,
6715
- rateLimitResetCredits: null,
6716
- accountId: null,
6717
- rateLimitUpsell: null
6718
- };
6719
- }
6720
7087
  /** First place `term` appears in `text`: a short passage around it and the match's UTF-16 range inside that passage. */
6721
7088
  function occurrence(text, term, radius = 60) {
6722
7089
  const at = String(text).toLocaleLowerCase().indexOf(String(term).toLocaleLowerCase());
@@ -6912,7 +7279,7 @@ const toolOutput = (message, imageUrls, imageAssets) => [{
6912
7279
  /** Images the person attached to a message of their own. */
6913
7280
  const typedImages = (message) => message.role === "user" && (message.source === void 0 || message.source?.kind === "user") ? (message.content ?? []).filter((block) => block?.type === "image" && block.attachment) : [];
6914
7281
  /** `imageUrls` maps an attachment id to a data URL the phone can show; images without one are left out. */
6915
- 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) {
6916
7283
  const turns = [];
6917
7284
  let turn;
6918
7285
  const calls = /* @__PURE__ */ new Map();
@@ -6927,7 +7294,7 @@ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new
6927
7294
  for (const message of messages) if (message.role === "user") {
6928
7295
  const text = typedText(message);
6929
7296
  const pictures = typedImages(message).map((block) => imageAssets.get(block.attachment.attachmentId)?.downloadUrl ?? imageUrls.get(block.attachment.attachmentId)).filter(Boolean);
6930
- if (text === "" && pictures.length === 0) continue;
7297
+ if (text === "" && pictures.length === 0 && !(indexOnly && typedImages(message).length)) continue;
6931
7298
  close();
6932
7299
  turn = {
6933
7300
  ...emptyTurn(),
@@ -6950,6 +7317,7 @@ function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new
6950
7317
  } else if (message.role === "assistant") {
6951
7318
  turn ??= {
6952
7319
  ...emptyTurn(),
7320
+ id: message.id,
6953
7321
  startedAt: seconds(at)
6954
7322
  };
6955
7323
  for (const [index, block] of message.content.entries()) {
@@ -7105,7 +7473,7 @@ function createPhoneConfig(file) {
7105
7473
  }
7106
7474
  };
7107
7475
  }
7108
- function createDshRemoteControl({ controller, agents, permissions = () => void 0, workspaces = () => void 0, attachments = () => void 0, remoteImages = void 0, imagePublishMs = 2e4, usage = () => void 0, usageProfile = () => void 0, projections = () => void 0, skills = () => void 0, commands = () => void 0, llm = () => void 0, speed = void 0, trace = () => {}, phoneReturnMs = PHONE_RETURN_MS, userAgent, appServerUserAgent = userAgent, configFile = void 0, voice = void 0 }) {
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 }) {
7109
7477
  const subscribers = /* @__PURE__ */ new Map();
7110
7478
  const threadSources = /* @__PURE__ */ new Map();
7111
7479
  const active = /* @__PURE__ */ new Map();
@@ -7299,7 +7667,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7299
7667
  await Promise.all(wanted.map(async (block) => {
7300
7668
  const started = Date.now();
7301
7669
  try {
7302
- 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);
7303
7672
  urls.set(block.attachment.attachmentId, `data:${stored.ref.mediaType};base64,${Buffer.from(stored.data).toString("base64")}`);
7304
7673
  phoneLog("image read completed", {
7305
7674
  attachmentId: block.attachment.attachmentId,
@@ -7437,6 +7806,127 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7437
7806
  });
7438
7807
  return result;
7439
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
+ };
7440
7930
  /** Apply a model or effort the phone picked; DSH validates it against its own catalog. */
7441
7931
  const TIER_OF = {
7442
7932
  fast: "priority",
@@ -7846,6 +8336,19 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7846
8336
  snippets
7847
8337
  };
7848
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
+ };
7849
8352
  const matches = (entry, term, snippets) => {
7850
8353
  const needle = typeof term === "string" ? term.trim().toLocaleLowerCase() : "";
7851
8354
  return needle === "" || snippets.has(entry.id) || `${entry.name ?? ""} ${entry.preview}`.toLocaleLowerCase().includes(needle);
@@ -7955,8 +8458,10 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
7955
8458
  inputModalities: modalities.get(model.id)?.length ? modalities.get(model.id) : ["text"],
7956
8459
  supportsPersonality: false,
7957
8460
  additionalSpeedTiers: tiersOf(group.id, model.id).map((tier) => tier.id),
7958
- upgrade: null,
7959
- upgradeInfo: null,
8461
+ ...phoneModelUpgrade(modelMetadata(group.id, model.id), (target) => modelKey({
8462
+ provider: group.id,
8463
+ model: target
8464
+ })),
7960
8465
  availabilityNux: null,
7961
8466
  serviceTiers: tiersOf(group.id, model.id),
7962
8467
  defaultServiceTier: null
@@ -8160,15 +8665,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8160
8665
  };
8161
8666
  },
8162
8667
  "currentTime/read": () => ({ currentTimeAt: seconds(Date.now()) }),
8163
- "account/rateLimits/read": async () => rateLimits(await usage()?.read?.().catch(() => void 0)),
8164
- "thread/turns/list": async (params) => {
8165
- const { thread: value } = await openThread(params?.threadId);
8166
- const ordered = params?.sortDirection === "asc" ? value.turns : value.turns.toReversed();
8167
- return {
8168
- ...page(ordered, params),
8169
- backwardsCursor: ordered.length ? String(0) : null
8170
- };
8171
- },
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),
8172
8671
  "thread/fork": async (params, { notify }) => {
8173
8672
  const forked = await service().fork({ sessionId: params?.threadId });
8174
8673
  const agent = await agentFor(forked.sessionId);
@@ -8264,8 +8763,28 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8264
8763
  await registry.unarchiveSession(params?.threadId);
8265
8764
  return { thread: (await openThread(params?.threadId)).thread };
8266
8765
  },
8267
- "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 }),
8268
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
+ }
8269
8788
  const { agent, thread: value } = await openThread(params?.threadId, notify, signal);
8270
8789
  return {
8271
8790
  ...settings(agent, value.cwd),
@@ -8925,6 +9444,289 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
8925
9444
  };
8926
9445
  }
8927
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
8928
9730
  //#region src/remote-image-assets.js
8929
9731
  const BASE$1 = "https://chatgpt.com/backend-api/";
8930
9732
  const FILE_ID = /^file[-_][A-Za-z0-9_-]{1,200}$/u;
@@ -10202,6 +11004,24 @@ function isRecord(value) {
10202
11004
  return value !== null && typeof value === "object" && !Array.isArray(value);
10203
11005
  }
10204
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
10205
11025
  //#region src/model-catalog.js
10206
11026
  const CODEX_MODELS_URL = `https://chatgpt.com/backend-api/codex/models?client_version=${encodeURIComponent(PACKAGE_VERSION)}`;
10207
11027
  const LEVELS = [
@@ -10218,7 +11038,8 @@ const record$6 = (value) => value !== null && typeof value === "object" && !Arra
10218
11038
  const nonEmpty$1 = (value) => typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
10219
11039
  const positiveInteger = (value) => Number.isSafeInteger(value) && value > 0 ? value : void 0;
10220
11040
  function upgradeModelId(value) {
10221
- return (typeof value.upgrade === "string" ? nonEmpty$1(value.upgrade) : record$6(value.upgrade) ? nonEmpty$1(value.upgrade.model) : void 0) ?? (record$6(value.upgrade_info) ? nonEmpty$1(value.upgrade_info.model) : void 0) ?? (record$6(value.upgradeInfo) ? nonEmpty$1(value.upgradeInfo.model) : void 0);
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);
10222
11043
  }
10223
11044
  function retirementMillis(value) {
10224
11045
  for (const source of [
@@ -10282,7 +11103,11 @@ function serviceTierEntries(value) {
10282
11103
  return found;
10283
11104
  }
10284
11105
  function unsupportedCapabilities(value) {
10285
- 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));
10286
11111
  const inputs = capabilityNames(Array.isArray(value.input_modalities) ? value.input_modalities : []).filter((input) => !["text", "image"].includes(input));
10287
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) => ![
10288
11113
  "auto",
@@ -10304,6 +11129,9 @@ function visibleModel(value, displayNames, now) {
10304
11129
  const reserve = id === "gpt-reserve" && ["list", "hide"].includes(value.visibility);
10305
11130
  if (id === void 0 || value.visibility !== "list" && !reserve) return void 0;
10306
11131
  const supported = Array.isArray(value.supported_reasoning_levels) ? value.supported_reasoning_levels : [];
11132
+ const thinkingLevelMap = reasoningMap(supported);
11133
+ const defaultEffort = value.default_reasoning_level === "none" ? "off" : value.default_reasoning_level;
11134
+ const defaultReasoningEffort = LEVELS.includes(defaultEffort) && thinkingLevelMap[defaultEffort] != null ? defaultEffort : void 0;
10307
11135
  const input = Array.isArray(value.input_modalities) ? value.input_modalities.filter((item) => ["text", "image"].includes(item)) : ["text", "image"];
10308
11136
  const unsupported = unsupportedCapabilities({
10309
11137
  ...value,
@@ -10322,13 +11150,16 @@ function visibleModel(value, displayNames, now) {
10322
11150
  at: retirement.at,
10323
11151
  upgradeTo: retirement.upgradeTo
10324
11152
  } },
11153
+ ...upgradeTo === void 0 ? {} : { upgradeTo },
10325
11154
  priority: Number.isFinite(value.priority) ? value.priority : 0,
10326
11155
  input: input.length > 0 ? input : ["text"],
10327
11156
  contextWindow: positiveInteger(value.context_window) ?? positiveInteger(value.max_context_window),
10328
11157
  ...positiveInteger(value.max_context_window) === void 0 ? {} : { maxContextWindow: value.max_context_window },
10329
11158
  reasoning: supported.length > 0,
10330
11159
  supportsReasoningEffortUpdates: value.supports_reasoning_effort_updates === true,
10331
- thinkingLevelMap: reasoningMap(supported),
11160
+ ...ultraCatalogPreset(value) === void 0 ? {} : { ultra: ultraCatalogPreset(value) },
11161
+ thinkingLevelMap,
11162
+ ...defaultReasoningEffort === void 0 ? {} : { defaultReasoningEffort },
10332
11163
  supportVerbosity: value.support_verbosity === true,
10333
11164
  defaultVerbosity: [
10334
11165
  "low",
@@ -10381,6 +11212,7 @@ function mergeModel(baseModels, remote) {
10381
11212
  reasoning: remote.reasoning,
10382
11213
  supportsReasoningEffortUpdates: remote.supportsReasoningEffortUpdates,
10383
11214
  thinkingLevelMap: remote.thinkingLevelMap,
11215
+ ...remote.defaultReasoningEffort === void 0 ? {} : { defaultReasoningEffort: remote.defaultReasoningEffort },
10384
11216
  ...remote.contextWindow === void 0 ? {} : { contextWindow: remote.contextWindow },
10385
11217
  ...remote.maxContextWindow === void 0 ? {} : { maxContextWindow: remote.maxContextWindow },
10386
11218
  ...base.id === remote.id ? {} : { cost: {
@@ -10701,6 +11533,12 @@ const CODEX_SEARCH_URL = "https://chatgpt.com/backend-api/codex/alpha/search";
10701
11533
  const DEFAULT_MODEL = "gpt-5.6-luna";
10702
11534
  const MAX_OUTPUT_TOKENS = 4096;
10703
11535
  const MAX_SOURCE_DATE = 64;
11536
+ const RETRYABLE_STATUSES = /* @__PURE__ */ new Set([
11537
+ 500,
11538
+ 502,
11539
+ 503,
11540
+ 504
11541
+ ]);
10704
11542
  const record$5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
10705
11543
  const nonEmpty = (value) => typeof value === "string" && value.length > 0 ? value : void 0;
10706
11544
  const displayText = (value) => {
@@ -10765,7 +11603,7 @@ function createCodexSearchProvider(options) {
10765
11603
  const id = nonEmpty(options.resolveSessionId?.()) ?? randomUUID();
10766
11604
  let response;
10767
11605
  try {
10768
- response = await fetchSearch(CODEX_SEARCH_URL, {
11606
+ const init = {
10769
11607
  method: "POST",
10770
11608
  redirect: "error",
10771
11609
  headers: {
@@ -10791,19 +11629,35 @@ function createCodexSearchProvider(options) {
10791
11629
  max_output_tokens: MAX_OUTPUT_TOKENS
10792
11630
  }),
10793
11631
  signal
10794
- });
11632
+ };
11633
+ for (let attempt = 0; attempt < 2; attempt++) {
11634
+ response = await fetchSearch(CODEX_SEARCH_URL, init);
11635
+ signal?.throwIfAborted();
11636
+ const requestId = response.headers?.get?.("x-request-id") ?? response.headers?.get?.("cf-ray");
11637
+ const detail = `model=${model}, mode=${preferences.searchMode}, attempt=${attempt + 1}${typeof requestId === "string" && /^[a-zA-Z0-9._:-]{1,128}$/u.test(requestId) ? `, requestId=${requestId}` : ""}`;
11638
+ const retry = attempt === 0 && RETRYABLE_STATUSES.has(response.status);
11639
+ diagnosticLog.log(response.ok ? "info" : "warn", "search", `Codex search HTTP ${response.status}${retry ? "; retrying once on the same source" : ""}`, detail);
11640
+ if (!retry) break;
11641
+ try {
11642
+ response.body?.cancel().catch(() => {});
11643
+ } catch {}
11644
+ await setTimeout$1(300, void 0, { signal });
11645
+ }
10795
11646
  } catch (error) {
10796
11647
  if (signal?.aborted || error?.name === "AbortError") throw new WebError("Codex search aborted", "WEB_ABORTED", { cause: error });
10797
11648
  throw new WebError("Codex search request failed", "WEB_PROVIDER_ERROR", { cause: error });
10798
11649
  }
10799
11650
  if (!response.ok) {
10800
11651
  const authFailure = await authFailureMessage(response);
11652
+ if (signal?.aborted) throw new WebError("Codex search aborted", "WEB_ABORTED", { cause: signal.reason });
10801
11653
  throw authFailure === "ChatGPT sign-in needs to be renewed" ? new WebError(authFailure, "WEB_PROVIDER_CREDENTIAL_MISSING") : authFailure !== void 0 ? new WebError(authFailure, "WEB_PROVIDER_ERROR") : new WebError(`Codex search request failed (HTTP ${response.status})`, "WEB_PROVIDER_ERROR");
10802
11654
  }
10803
11655
  let value;
10804
11656
  try {
10805
11657
  value = await response.json();
11658
+ signal?.throwIfAborted();
10806
11659
  } catch (error) {
11660
+ if (signal?.aborted || error?.name === "AbortError") throw new WebError("Codex search aborted", "WEB_ABORTED", { cause: error });
10807
11661
  throw new WebError("Codex returned an unreadable search response", "WEB_PROVIDER_ERROR", { cause: error });
10808
11662
  }
10809
11663
  try {
@@ -12286,8 +13140,8 @@ function createReportReader({ url, parse, label, getAuth, readCredential, fetch:
12286
13140
  return Object.freeze({
12287
13141
  read({ force = false, signal } = {}) {
12288
13142
  if (failed !== void 0 && now() < failed.retryAt) return Promise.reject(new Error(failed.message));
12289
- if (!force && cached !== void 0 && now() - cached.fetchedAt < ttlMs) return Promise.resolve(structuredClone(cached));
12290
13143
  if (inFlight !== void 0) return inFlight.then(structuredClone);
13144
+ if (!force && cached !== void 0 && now() - cached.fetchedAt < ttlMs) return Promise.resolve(structuredClone(cached));
12291
13145
  const current = generation;
12292
13146
  const run = load(signal).then((value) => {
12293
13147
  if (generation === current) {
@@ -13591,8 +14445,58 @@ async function settlesLive(preferences, patch, signal, { attempts = 8, delayMs =
13591
14445
  }
13592
14446
  return live();
13593
14447
  }
13594
- 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 }) {
13595
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
+ }
13596
14500
  if (endpoint === "default-model/status" || endpoint === "default-model/select") try {
13597
14501
  signal.throwIfAborted();
13598
14502
  if (!defaultModel) return publicError("unavailable", "The default model is unavailable");
@@ -13641,6 +14545,8 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13641
14545
  }
13642
14546
  const current = preferences?.status?.() ?? {};
13643
14547
  if (current.voiceCall !== "on") return publicError("unavailable", "Voice is turned off");
14548
+ await nativeVoice?.close();
14549
+ signal.throwIfAborted();
13644
14550
  return {
13645
14551
  ok: true,
13646
14552
  value: await desktopVoice.start({
@@ -13765,6 +14671,7 @@ function createSubscriptionRpcHandler({ authHandler, usageReader, accountUsageRe
13765
14671
  verbosityModels: Array.isArray(value?.verbosityModels) ? value.verbosityModels : [],
13766
14672
  fastModels: Array.isArray(value?.fastModels) ? value.fastModels : [],
13767
14673
  ultrafastModels: Array.isArray(value?.ultrafastModels) ? value.ultrafastModels : [],
14674
+ ultraModels: Array.isArray(value?.ultraModels) ? value.ultraModels : [],
13768
14675
  catalogStatus: value?.catalogStatus
13769
14676
  }
13770
14677
  };
@@ -13947,7 +14854,7 @@ const BASE = "https://chatgpt.com/backend-api";
13947
14854
  const CATALOG_TTL_MS = 10 * 6e4;
13948
14855
  const MAX_CLIP_BYTES = 2 * 1024 * 1024;
13949
14856
  const PREVIEW_HOSTS = /^https:\/\/[a-z0-9.-]*oaistatic\.com\//u;
13950
- const failure = (code, message) => Object.assign(new Error(message), { code });
14857
+ const failure$1 = (code, message) => Object.assign(new Error(message), { code });
13951
14858
  function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, base = BASE }) {
13952
14859
  const catalogs = /* @__PURE__ */ new Map();
13953
14860
  const clips = /* @__PURE__ */ new Map();
@@ -13962,7 +14869,7 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
13962
14869
  let value;
13963
14870
  try {
13964
14871
  const { access, accountId } = await credentials(signal);
13965
- 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");
13966
14873
  const response = await fetch(`${base}/settings/voices?spoken_language=${language}`, {
13967
14874
  headers: {
13968
14875
  authorization: `Bearer ${access}`,
@@ -13972,15 +14879,15 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
13972
14879
  },
13973
14880
  signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3)
13974
14881
  });
13975
- if (response.status === 401) throw failure("voice-auth", "ChatGPT sign-in needs renewal");
13976
- if (!response.ok) throw failure("voice-catalog", `voice catalog HTTP ${response.status}`);
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}`);
13977
14884
  value = await response.json();
13978
- 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");
13979
14886
  signal?.throwIfAborted();
13980
14887
  } catch (error) {
13981
14888
  signal?.throwIfAborted();
13982
14889
  if (error?.code === "voice-auth" || error?.code === "voice-catalog") throw error;
13983
- throw failure("voice-catalog", "Could not load the voice catalog");
14890
+ throw failure$1("voice-catalog", "Could not load the voice catalog");
13984
14891
  }
13985
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));
13986
14893
  catalogs.set(language, {
@@ -14006,13 +14913,13 @@ function createVoicePreview({ fetch, credentials, userAgent, now = Date.now, bas
14006
14913
  let bytes;
14007
14914
  try {
14008
14915
  const response = await fetch(entry.preview_url, { signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3) });
14009
- if (!response.ok) throw failure("voice-download", `voice sample HTTP ${response.status}`);
14916
+ if (!response.ok) throw failure$1("voice-download", `voice sample HTTP ${response.status}`);
14010
14917
  bytes = Buffer.from(await response.arrayBuffer());
14011
- if (bytes.byteLength === 0 || bytes.byteLength > MAX_CLIP_BYTES) throw failure("voice-download", "voice sample has an unexpected size");
14918
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_CLIP_BYTES) throw failure$1("voice-download", "voice sample has an unexpected size");
14012
14919
  signal?.throwIfAborted();
14013
14920
  } catch {
14014
14921
  signal?.throwIfAborted();
14015
- throw failure("voice-download", "Could not download the voice sample");
14922
+ throw failure$1("voice-download", "Could not download the voice sample");
14016
14923
  }
14017
14924
  const type = /\.mp3(?:$|\?)/u.test(entry.preview_url) ? "audio/mpeg" : "audio/mp4";
14018
14925
  const result = {
@@ -14095,6 +15002,628 @@ function withEndCallTool(desktopVoice, register) {
14095
15002
  });
14096
15003
  }
14097
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
14098
15627
  //#region src/index.js
14099
15628
  const z = createRequire(import.meta.resolve("@deepseek-ai/dsh-settings"))("@deepseek-ai/schemastery");
14100
15629
  const name = "codex-subscription";
@@ -14222,6 +15751,19 @@ function apply(ctx, config = {}) {
14222
15751
  3e5
14223
15752
  ]
14224
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");
14225
15767
  const connection = createSubscriptionConnection({ resolveMode: () => settings.get().connectionMode });
14226
15768
  const defaultModel = createDefaultModelController({
14227
15769
  resolveService: () => ctx.get?.("agentDefaultModel"),
@@ -14250,6 +15792,7 @@ function apply(ctx, config = {}) {
14250
15792
  ctx.on("session/event", (session, event) => reasoning.sessionEvent(session, event));
14251
15793
  ctx.effect(() => () => connection.dispose());
14252
15794
  const provider = openaiCodexSubscriptionProvider({
15795
+ ultra,
14253
15796
  connection,
14254
15797
  compaction,
14255
15798
  reasoning,
@@ -14278,6 +15821,7 @@ function apply(ctx, config = {}) {
14278
15821
  [AUTO_QUOTA_RETRY_FIELD]: normalizeAutoQuotaRetry(settings.get()[AUTO_QUOTA_RETRY_FIELD]),
14279
15822
  compactionMode: settings.get().compactionMode ?? "dsh",
14280
15823
  reasoningCache: normalizeReasoningCache(settings.get().reasoningCache),
15824
+ [DEFAULT_REASONING_EFFORT_FIELD]: normalizeDefaultReasoningEffort(settings.get()[DEFAULT_REASONING_EFFORT_FIELD]),
14281
15825
  connectionMode: settings.get().connectionMode ?? "sse",
14282
15826
  reviewModel: settings.get().reviewModel ?? "session",
14283
15827
  remoteControl: settings.get().remoteControl ?? "off",
@@ -14311,6 +15855,7 @@ function apply(ctx, config = {}) {
14311
15855
  catalogStatus: modelCatalog.status(),
14312
15856
  verbosityModels: provider.getModels().filter((model) => modelCatalog.metadata(model.id)?.supportVerbosity ?? model.id !== "gpt-5.3-codex-spark").map((model) => model.id),
14313
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),
14314
15859
  fastModels: provider.getModels().filter((model) => modelCatalog.metadata(model.id)?.supportsFast ?? supportsCodexFastMode(model.id)).map((model) => model.id),
14315
15860
  writable: ctx.settings.writable
14316
15861
  };
@@ -14507,9 +16052,16 @@ function apply(ctx, config = {}) {
14507
16052
  ctx.effect(() => ctx.on?.("session/event", (_session, event) => {
14508
16053
  if (event?.type === "request/context") hiddenDirectory.dependenciesChanged();
14509
16054
  }), "codex-subscription: hidden model dependencies");
16055
+ ctx.effect(() => settings.watch((value, previous) => {
16056
+ if (normalizeDefaultReasoningEffort(value["defaultReasoningEffort"]) !== normalizeDefaultReasoningEffort(previous["defaultReasoningEffort"])) ctx.llm.emitAdaptersUpdated?.();
16057
+ }), "codex-subscription: default reasoning effort");
14510
16058
  ctx.effect(() => {
14511
16059
  const lifetime = new AbortController();
14512
- const readyAdapter = withModelCatalogReady(hiddenDirectory.wrap(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(provider.wrapRetryAdapter(adapter))), provider)), modelCatalog, { signal: lifetime.signal });
16060
+ const defaults = withDefaultReasoningEffort(ultra.wrapAdapter(observeAdapter(reasoning.wrapAdapter(compaction.wrapAdapter(provider.wrapRetryAdapter(adapter))), provider)), {
16061
+ preference: () => settings.get()[DEFAULT_REASONING_EFFORT_FIELD],
16062
+ modelDefault: (id) => modelCatalog.metadata(id)?.defaultReasoningEffort
16063
+ });
16064
+ const readyAdapter = withModelCatalogReady(hiddenDirectory.wrap(defaults), modelCatalog, { signal: lifetime.signal });
14513
16065
  const disposeAdapter = ctx.llm.registerAdapter([PROVIDER], readyAdapter);
14514
16066
  Promise.resolve().then(() => modelCatalog.refresh({ signal: lifetime.signal })).catch((error) => {
14515
16067
  if (!lifetime.signal.aborted) ctx.logger?.debug?.("could not refresh Codex model catalog (%s)", error?.code ?? error?.name ?? "unknown error");
@@ -14684,6 +16236,8 @@ function apply(ctx, config = {}) {
14684
16236
  skills: () => ctx.get?.("skills"),
14685
16237
  commands: () => ctx.get?.("commands"),
14686
16238
  llm: () => ctx.llm,
16239
+ modelMetadata: (provider, model) => provider === PROVIDER ? modelCatalog.metadata(model) : void 0,
16240
+ historySource: createRemoteHistorySource({ query: () => ctx.get?.("sessionQuery") }),
14687
16241
  speed: {
14688
16242
  tiers: (provider, model) => provider === PROVIDER ? modelCatalog.metadata(model)?.serviceTiers ?? [] : [],
14689
16243
  current: () => settings.get()[SPEED_MODE_FIELD],
@@ -14862,6 +16416,24 @@ function apply(ctx, config = {}) {
14862
16416
  expirySkewMs: OAUTH_EXPIRY_SKEW_MS,
14863
16417
  activeReader: baseUsageReader
14864
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
+ });
14865
16437
  const subscriptionHandler = createSubscriptionRpcHandler({
14866
16438
  authHandler: createCodexRpcHandler(coordinator, { openExternal: openCodexAuthUrl }),
14867
16439
  usageReader,
@@ -14873,7 +16445,8 @@ function apply(ctx, config = {}) {
14873
16445
  defaultModel,
14874
16446
  runtimeManagement,
14875
16447
  remoteControl,
14876
- desktopVoice: withEndCallTool(remoteBridge.desktopVoice, (tool) => ctx.tools.register(tool)),
16448
+ desktopVoice,
16449
+ nativeVoice,
14877
16450
  voicePreview: createVoicePreview({
14878
16451
  fetch: (input, init) => network.fetch("voice", input, init, { standardHttps: true }),
14879
16452
  credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {