dsh-codex-subscription 3.2.16 → 3.2.18

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
@@ -3,8 +3,8 @@ import { defineTool } from "@deepseek-ai/dsh-tools";
3
3
  import { createHash, randomBytes, randomUUID } from "node:crypto";
4
4
  import { closeOpenAICodexWebSocketSessions, getOpenAICodexWebSocketDebugStats, resetOpenAICodexWebSocketDebugStats } from "@earendil-works/pi-ai/api/openai-codex-responses";
5
5
  import { execFile, spawn } from "node:child_process";
6
- import { appendFileSync, constants, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
7
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
6
+ import { appendFileSync, constants, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, unwatchFile, watchFile, writeFileSync } from "node:fs";
7
+ import { basename, dirname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
8
8
  import { request } from "node:https";
9
9
  import { AsyncLocalStorage } from "node:async_hooks";
10
10
  import { promisify } from "node:util";
@@ -44,8 +44,9 @@ function createSettingsAdapter(ctx, config) {
44
44
  };
45
45
  const get = () => Object.fromEntries(Object.entries(liveConfig()).map(([key, value]) => [key, typeof value?.get === "function" ? value.get() : value]));
46
46
  return {
47
+ id,
47
48
  get,
48
- update: (patch) => ctx.settings.update(id, patch),
49
+ update: (patch, ...revision) => ctx.settings.update(id, patch, ...revision),
49
50
  watch(listener) {
50
51
  let previous = get();
51
52
  return ctx.on("loader/volatile-update", () => {
@@ -1487,6 +1488,8 @@ const execFileAsync = promisify(execFile);
1487
1488
  const CODEX_AUTH_HOST = "auth.openai.com";
1488
1489
  const CODEX_SUBSCRIPTION_HOST = "chatgpt.com";
1489
1490
  const CODEX_MODEL_SSE_PATH = "/backend-api/codex/responses";
1491
+ const CODEX_WEBSOCKET_LIMIT_HEADER = "x-codex-websocket-max-message-bytes";
1492
+ const CODEX_WEBSOCKET_MESSAGE_TOO_LARGE = "WebSocket request exceeds the advertised message size limit";
1490
1493
  const MODEL_SSE_PROXY_ENV = "DSH_CODEX_SSE_PROXY";
1491
1494
  const CODEX_HOSTS = /* @__PURE__ */ new Set([CODEX_AUTH_HOST, CODEX_SUBSCRIPTION_HOST]);
1492
1495
  const OAUTH_HOSTS = /* @__PURE__ */ new Set([CODEX_AUTH_HOST]);
@@ -1787,8 +1790,17 @@ async function withCodexNetwork(run, options = {}) {
1787
1790
  ...args[1],
1788
1791
  ...proxy ? { agent: new HttpsProxyAgent(proxy) } : {}
1789
1792
  });
1793
+ let maxMessageBytes;
1794
+ if (url.pathname === CODEX_MODEL_SSE_PATH) socket.once?.("upgrade", (response) => {
1795
+ const header = response.headers?.[CODEX_WEBSOCKET_LIMIT_HEADER];
1796
+ if (typeof header !== "string" || !/^\d+$/u.test(header)) return;
1797
+ const limit = Number(header);
1798
+ if (Number.isSafeInteger(limit)) maxMessageBytes = limit;
1799
+ });
1790
1800
  const send = socket.send;
1791
1801
  socket.send = function(...values) {
1802
+ const message = values[0];
1803
+ if (maxMessageBytes !== void 0 && typeof message === "string" && Buffer.byteLength(message) > maxMessageBytes) throw new Error(CODEX_WEBSOCKET_MESSAGE_TOO_LARGE);
1792
1804
  observe();
1793
1805
  return Reflect.apply(send, this, values);
1794
1806
  };
@@ -1980,7 +1992,7 @@ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy
1980
1992
  totals[key] = Math.min(Number.MAX_SAFE_INTEGER, totals[key] + Math.max(0, count - entry.seen[key]));
1981
1993
  entry.seen[key] = count;
1982
1994
  }
1983
- if (!entry.retired && stats.websocketFallbackActive === true && (!entry.cooling || failures > 0)) {
1995
+ if (!entry.retired && stats.websocketFallbackActive === true && stats.lastWebSocketError !== "WebSocket request exceeds the advertised message size limit" && (!entry.cooling || failures > 0)) {
1984
1996
  entry.streak = Math.min(20, entry.streak + Math.max(1, failures));
1985
1997
  entry.cooling = true;
1986
1998
  entry.retryAt = now() + delay(entry.streak);
@@ -2134,6 +2146,11 @@ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy
2134
2146
  const stats = observe(entry);
2135
2147
  entry.active--;
2136
2148
  entry.used = now();
2149
+ const skippedForSize = stats.lastWebSocketError === CODEX_WEBSOCKET_MESSAGE_TOO_LARGE;
2150
+ if (skippedForSize && !entry.active && !entry.retired) {
2151
+ sdk.reset(entry.key);
2152
+ entry.seen = zero();
2153
+ }
2137
2154
  if (probe) {
2138
2155
  probes.delete(group);
2139
2156
  entry.probe = false;
@@ -2142,7 +2159,7 @@ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy
2142
2159
  entry.retryAt = 0;
2143
2160
  entry.cooling = false;
2144
2161
  recovery.recoverySuccesses++;
2145
- } else if (!entry.retired && !entry.cooling) {
2162
+ } else if (!skippedForSize && !entry.retired && !entry.cooling) {
2146
2163
  entry.cooling = true;
2147
2164
  entry.retryAt = now() + delay(entry.streak);
2148
2165
  }
@@ -4872,7 +4889,7 @@ function inheritedOriginalImageRef(session, assetId) {
4872
4889
  }
4873
4890
  //#endregion
4874
4891
  //#region src/version.js
4875
- const PACKAGE_VERSION = "3.2.16";
4892
+ const PACKAGE_VERSION = "3.2.18";
4876
4893
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
4877
4894
  //#endregion
4878
4895
  //#region src/image-original-store.js
@@ -5585,12 +5602,13 @@ function createCodexImageTool(options) {
5585
5602
  const mediaType = animated ? "image/gif" : "image/png";
5586
5603
  if (animated) {
5587
5604
  if (editing) throw new Error("Animated GIF editing is not supported on the Codex subscription route");
5588
- const { frameCount = 6, frameDurationMs = 150 } = args.gif ?? {};
5589
- if (!record$8(args.gif) || !Number.isInteger(frameCount) || frameCount < 2 || frameCount > 16 || !Number.isInteger(frameDurationMs) || frameDurationMs < 20 || frameDurationMs > 655350) throw new Error("Invalid animated GIF options");
5605
+ if (!record$8(args.gif)) throw new Error("Invalid animated GIF options");
5606
+ const { frameCount, frameDurationMs } = args.gif;
5607
+ if (frameCount !== void 0 && (!Number.isInteger(frameCount) || frameCount < 2 || frameCount > 16) || frameDurationMs !== void 0 && (!Number.isInteger(frameDurationMs) || frameDurationMs < 20 || frameDurationMs > 655350)) throw new Error("Invalid animated GIF options");
5590
5608
  imageOptions.animation = {
5591
5609
  output_format: "gif",
5592
- frame_count: frameCount,
5593
- frame_duration_ms: frameDurationMs
5610
+ ...frameCount === void 0 ? {} : { frame_count: frameCount },
5611
+ ...frameDurationMs === void 0 ? {} : { frame_duration_ms: frameDurationMs }
5594
5612
  };
5595
5613
  }
5596
5614
  const { access, accountId } = await readSubscriptionCredentials(options.getAuth, options.readCredential, exec.signal);
@@ -5981,6 +5999,8 @@ const MAX_SEEN = 128;
5981
5999
  const STREAMING = /delta$|outputDelta|tokenUsage|summaryPartAdded/u;
5982
6000
  const QUIET$1 = /* @__PURE__ */ new Set([
5983
6001
  "command/exec",
6002
+ "fs/writeFile",
6003
+ "fs/readFile",
5984
6004
  "thread/attachment/list",
5985
6005
  "thread/list",
5986
6006
  "thread/queue/list",
@@ -6116,6 +6136,12 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
6116
6136
  ask
6117
6137
  };
6118
6138
  onConnection?.(client);
6139
+ const markActive = () => {
6140
+ if (active) return;
6141
+ active = true;
6142
+ phoneLog("client handshake confirmed", { clientId: client.clientId });
6143
+ onActive?.(client, notify);
6144
+ };
6119
6145
  const reply = async (id, result) => {
6120
6146
  await client.send({
6121
6147
  id,
@@ -6144,7 +6170,10 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
6144
6170
  const { id, method, params } = message;
6145
6171
  if (id === void 0) {
6146
6172
  note("notify", method);
6147
- if (method === "initialized") initialized = true;
6173
+ if (method === "initialized") {
6174
+ initialized = true;
6175
+ markActive();
6176
+ }
6148
6177
  notifications[method]?.(params, {
6149
6178
  ...context,
6150
6179
  signal: new AbortController().signal
@@ -6163,10 +6192,7 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
6163
6192
  ...logged,
6164
6193
  hasClientId: typeof params?.clientUserMessageId === "string"
6165
6194
  });
6166
- if (!active && method !== "initialize") {
6167
- active = true;
6168
- onActive?.(client, notify);
6169
- }
6195
+ if (method !== "initialize") markActive();
6170
6196
  if (debug && !QUIET$1.has(method)) record({
6171
6197
  method: `request:${method}`,
6172
6198
  params: JSON.stringify(params ?? null).slice(0, /realtime/u.test(method) ? 8e3 : 700)
@@ -6177,7 +6203,7 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
6177
6203
  ...logged,
6178
6204
  code: METHOD_NOT_FOUND
6179
6205
  }, "warn");
6180
- record({
6206
+ if (!QUIET$1.has(method)) record({
6181
6207
  method,
6182
6208
  missing: true,
6183
6209
  params: JSON.stringify(params ?? null).slice(0, /realtime/u.test(method) ? 8e3 : 600)
@@ -6949,13 +6975,13 @@ async function writeInstallation(filename, state) {
6949
6975
  * @param {{ credentials: Function, WebSocket: Function, fetch?: Function, stateFile: string, hostName: string, userAgent: string, methods: object, notifications?: object, onConnection?: Function, onClose?: Function, base?: string }} options
6950
6976
  */
6951
6977
  function createRemoteControl(options) {
6952
- const phones = /* @__PURE__ */ new Set();
6978
+ const phones = /* @__PURE__ */ new Map();
6953
6979
  const host = createRemoteControlHost({
6954
6980
  methods: options.methods,
6955
6981
  notifications: options.notifications,
6956
6982
  onConnection: options.onConnection,
6957
6983
  onActive: (client, notify) => {
6958
- phones.add(client.id);
6984
+ phones.set(client.id, client.clientId ?? client.id);
6959
6985
  options.onActive?.(client, notify);
6960
6986
  },
6961
6987
  onClose: (client, notify) => {
@@ -7014,7 +7040,11 @@ function createRemoteControl(options) {
7014
7040
  },
7015
7041
  async disable() {
7016
7042
  enabled = false;
7017
- if (relay) await relay.stop();
7043
+ try {
7044
+ if (relay) await relay.stop();
7045
+ } finally {
7046
+ options.onStop?.();
7047
+ }
7018
7048
  return this.status();
7019
7049
  },
7020
7050
  async pair(signal) {
@@ -7038,7 +7068,7 @@ function createRemoteControl(options) {
7038
7068
  clients: 0,
7039
7069
  reconnects: 0
7040
7070
  },
7041
- phones: phones.size,
7071
+ phones: new Set(phones.values()).size,
7042
7072
  methods: host.seen(),
7043
7073
  trace: host.trace()
7044
7074
  };
@@ -7586,6 +7616,69 @@ function createVoiceQuestions({ speak, now = Date.now, deliveryMs = 15e3 }) {
7586
7616
  };
7587
7617
  return questions;
7588
7618
  }
7619
+ const validId = (value) => typeof value === "string" && /^[a-f0-9-]{36}$/u.test(value);
7620
+ const valid = (value) => validId(value?.id) && Array.isArray(value.entries) && value.entries.length <= 200 && value.entries.every((entry) => validId(entry?.callId) && ["user", "assistant"].includes(entry.role) && typeof entry.text === "string" && entry.text.length <= 4096);
7621
+ /** Temporary recovery data, removed once the native session has durably recorded it. */
7622
+ function createVoiceTranscriptRecovery(directory) {
7623
+ const pending = /* @__PURE__ */ new Map();
7624
+ const filename = (id) => join(directory, createHash("sha256").update(id).digest("hex") + ".json");
7625
+ const read = async (threadId) => {
7626
+ try {
7627
+ const value = JSON.parse(await readFile(filename(threadId), "utf8"));
7628
+ return valid(value) ? value : void 0;
7629
+ } catch (error) {
7630
+ if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
7631
+ }
7632
+ };
7633
+ const enqueue = (threadId, operation) => {
7634
+ const next = (pending.get(threadId) ?? Promise.resolve()).catch(() => {}).then(operation);
7635
+ pending.set(threadId, next);
7636
+ const forget = () => {
7637
+ if (pending.get(threadId) === next) pending.delete(threadId);
7638
+ };
7639
+ next.then(forget, forget);
7640
+ return next;
7641
+ };
7642
+ return {
7643
+ async load(threadId) {
7644
+ await pending.get(threadId)?.catch(() => {});
7645
+ return read(threadId);
7646
+ },
7647
+ save(threadId, checkpoint) {
7648
+ return enqueue(threadId, async () => {
7649
+ await mkdir(directory, {
7650
+ recursive: true,
7651
+ mode: 448
7652
+ });
7653
+ const file = filename(threadId);
7654
+ const temporary = `${file}.${randomUUID()}.tmp`;
7655
+ try {
7656
+ await writeFile(temporary, JSON.stringify(checkpoint), {
7657
+ flag: "wx",
7658
+ mode: 384,
7659
+ flush: true
7660
+ });
7661
+ await rename(temporary, file);
7662
+ if (process.platform !== "win32") {
7663
+ const handle = await open(directory, "r");
7664
+ try {
7665
+ await handle.sync();
7666
+ } finally {
7667
+ await handle.close();
7668
+ }
7669
+ }
7670
+ } finally {
7671
+ await rm(temporary, { force: true });
7672
+ }
7673
+ });
7674
+ },
7675
+ remove(threadId, checkpointId) {
7676
+ return enqueue(threadId, async () => {
7677
+ if ((await read(threadId))?.id === checkpointId) await rm(filename(threadId), { force: true });
7678
+ });
7679
+ }
7680
+ };
7681
+ }
7589
7682
  //#endregion
7590
7683
  //#region src/remote-control-realtime.js
7591
7684
  const SIDEBAND_BASES = ["wss://api.openai.com/v1/live", "wss://realtime.chatgpt.com/v1/live"];
@@ -7615,6 +7708,8 @@ function callNote(transcript) {
7615
7708
  return VOICE_NOTE_PREFIX + dialogue(transcript);
7616
7709
  }
7617
7710
  const VOICE_NOTE_PREFIX = "Part of the voice call that was not handed over as a request:\n";
7711
+ const VOICE_NOTE_SOURCE = "codex-subscription-voice";
7712
+ const recentCallNote = (entries) => callNote(entries.slice(-6));
7618
7713
  /** Which side channel an agent message belongs on: progress is commentary, an answer is spoken. */
7619
7714
  function channelOf(text, prefixes = CHANNEL_PREFIXES) {
7620
7715
  for (const [name, list] of Object.entries(prefixes)) if (Array.isArray(list) && list.some((prefix) => prefix !== "" && text.startsWith(prefix))) return name === "final" ? "speakable" : name === "analysis" ? void 0 : "commentary";
@@ -7863,27 +7958,44 @@ function createRealtimeVoice(options) {
7863
7958
  }
7864
7959
  throw last ?? /* @__PURE__ */ new Error("no voice endpoint answered");
7865
7960
  }
7961
+ const pendingTranscript = async (threadId, checkpoint) => {
7962
+ const ids = new Set(checkpoint.entries.map((entry) => entry.callId));
7963
+ const recorded = await options.recordedIds?.(threadId, ids);
7964
+ return checkpoint.entries.filter((entry) => !recorded?.has(entry.callId));
7965
+ };
7866
7966
  const flushTail = (threadId, session) => {
7867
- if (!session.flushTail || session.tail.length === 0) return;
7967
+ if (!session.flushTail || session.tail.length === 0 && !session.recovered) return;
7868
7968
  const transcript = session.tail.splice(0);
7969
+ const restored = session.recovered;
7970
+ const combined = [...restored?.entries ?? [], ...transcript].slice(-200);
7869
7971
  const note = session.silent && options.record ? callNote(transcript) : void 0;
7870
7972
  const notes = note ? savingNotes.get(threadId) ?? /* @__PURE__ */ new Set() : void 0;
7871
- const latest = note ? { text: callNote(transcript.slice(-6).map((entry) => ({
7872
- ...entry,
7873
- text: entry.text.slice(-350)
7874
- }))) } : void 0;
7973
+ const latest = note ? { text: recentCallNote(combined) } : void 0;
7875
7974
  if (notes) {
7876
7975
  notes.add(latest);
7877
7976
  if (notes.size > 2) notes.delete(notes.values().next().value);
7878
7977
  savingNotes.set(threadId, notes);
7879
7978
  }
7880
- const save = note ? () => options.record(threadId, note) : () => options.delegate(threadId, callRecord(transcript), () => {});
7881
- session.chain = (note ? session.admission : session.chain).then(save).catch((error) => log.warn("voice", "could not save the voice transcript to the conversation", String(error?.message ?? error))).finally(() => {
7979
+ const save = session.checkpointId ? async () => {
7980
+ const prior = restored ? await pendingTranscript(threadId, restored) : [];
7981
+ const calls = Map.groupBy([...prior, ...transcript].slice(-200), (entry) => entry.callId);
7982
+ for (const [recordId, entries] of calls) if (!await options.record(threadId, callNote(entries), recordId)) return;
7983
+ await options.recovery.remove(threadId, session.checkpointId);
7984
+ if (restored) await options.recovery.remove(threadId, restored.id);
7985
+ } : note ? () => options.record(threadId, note) : () => options.delegate(threadId, callRecord(transcript), () => {});
7986
+ session.chain = Promise.all([note ? session.admission : session.chain, session.transcriptWrite]).then(save).catch(() => log.warn("voice", "could not save the voice transcript to the conversation")).finally(() => {
7882
7987
  if (!notes) return;
7883
7988
  notes.delete(latest);
7884
7989
  if (notes.size === 0 && savingNotes.get(threadId) === notes) savingNotes.delete(threadId);
7885
7990
  });
7886
7991
  };
7992
+ const announceClosed = (threadId, session, reason) => {
7993
+ const announce = () => session.notify("thread/realtime/closed", {
7994
+ threadId,
7995
+ reason
7996
+ });
7997
+ (session.transcriptWrite ? session.transcriptWrite.then(announce) : announce()).catch(() => {});
7998
+ };
7887
7999
  const stop = (threadId, reason = "requested") => {
7888
8000
  const pending = starts.get(threadId);
7889
8001
  starts.delete(threadId);
@@ -7905,10 +8017,7 @@ function createRealtimeVoice(options) {
7905
8017
  try {
7906
8018
  session.ws.close();
7907
8019
  } catch {}
7908
- session.notify("thread/realtime/closed", {
7909
- threadId,
7910
- reason
7911
- }).catch(() => {});
8020
+ announceClosed(threadId, session, reason);
7912
8021
  return true;
7913
8022
  };
7914
8023
  /** Give the client time to finish speaking before it stops the call. */
@@ -7928,9 +8037,23 @@ function createRealtimeVoice(options) {
7928
8037
  const pending = new AbortController();
7929
8038
  starts.set(threadId, pending);
7930
8039
  const lifetime = signal ? AbortSignal.any([signal, pending.signal]) : pending.signal;
7931
- let credential, ws;
8040
+ let credential, ws, recovered;
8041
+ const recoverable = desktop && params.silentTailRecord === true && params.flushTranscriptTailOnSessionEnd !== false && options.recovery && options.record;
7932
8042
  try {
7933
8043
  lifetime.throwIfAborted();
8044
+ if (recoverable) try {
8045
+ const checkpoint = await options.recovery.load(threadId);
8046
+ if (checkpoint) {
8047
+ const entries = await pendingTranscript(threadId, checkpoint);
8048
+ if (entries.length > 0) recovered = {
8049
+ ...checkpoint,
8050
+ entries
8051
+ };
8052
+ else await options.recovery.remove(threadId, checkpoint.id);
8053
+ }
8054
+ } catch {
8055
+ log.warn("voice", "could not read the voice recovery checkpoint");
8056
+ }
7934
8057
  credential = await options.credentials(lifetime);
7935
8058
  lifetime.throwIfAborted();
7936
8059
  } catch (error) {
@@ -7978,6 +8101,10 @@ function createRealtimeVoice(options) {
7978
8101
  silent: params.silentTailRecord === true,
7979
8102
  hangUp: params.hangUpOnGoodbye === true
7980
8103
  };
8104
+ if (recoverable) {
8105
+ session.checkpointId = crypto.randomUUID();
8106
+ session.recovered = recovered;
8107
+ }
7981
8108
  session.flowId = crypto.randomUUID().slice(0, 8);
7982
8109
  session.openedAt = performance.now();
7983
8110
  session.desktop = desktop;
@@ -8215,7 +8342,11 @@ function createRealtimeVoice(options) {
8215
8342
  if (event.text.trim()) session.awaitingVoiceReply = true;
8216
8343
  }
8217
8344
  if (event.text.trim() !== "") {
8218
- session.tail.push({
8345
+ session.tail.push(session.checkpointId ? {
8346
+ callId: session.checkpointId,
8347
+ role: event.role,
8348
+ text: bounded(event.text)
8349
+ } : {
8219
8350
  role: event.role,
8220
8351
  text: event.text
8221
8352
  });
@@ -8226,11 +8357,25 @@ function createRealtimeVoice(options) {
8226
8357
  });
8227
8358
  if (session.lines.length > 12) session.lines.shift();
8228
8359
  }
8229
- notify("thread/realtime/transcript/done", {
8360
+ const complete = () => notify("thread/realtime/transcript/done", {
8230
8361
  threadId,
8231
8362
  role: event.role,
8232
8363
  text: event.text
8233
- }).catch(() => {});
8364
+ });
8365
+ if (session.checkpointId && event.text.trim() !== "") {
8366
+ const entries = [...session.recovered?.entries ?? [], ...session.tail].slice(-200);
8367
+ const save = options.recovery.save(threadId, {
8368
+ id: session.checkpointId,
8369
+ entries
8370
+ });
8371
+ session.transcriptWrite = save.catch(() => {
8372
+ log.warn("voice", "could not save the voice recovery checkpoint");
8373
+ });
8374
+ save.then(complete, () => notify("thread/realtime/error", {
8375
+ threadId,
8376
+ message: "The voice transcript could not be saved."
8377
+ })).catch(() => {});
8378
+ } else complete().catch(() => {});
8234
8379
  const spoken = event.text.trim();
8235
8380
  const said = Date.now();
8236
8381
  const endsCall = event.role === "user" && classifySpokenHangup ? checkFinalSpeech(spoken, said) : void 0;
@@ -8297,14 +8442,13 @@ function createRealtimeVoice(options) {
8297
8442
  session.questions.close();
8298
8443
  flushTail(threadId, session);
8299
8444
  log.warn("voice", "the voice call closed");
8300
- notify("thread/realtime/closed", {
8301
- threadId,
8302
- reason: "transportClosed"
8303
- }).catch(() => {});
8445
+ announceClosed(threadId, session, "transportClosed");
8304
8446
  });
8305
8447
  ws.on("error", (error) => log.warn("voice", "the voice connection failed", String(error?.message ?? error)));
8306
8448
  if (startupContext) try {
8307
- const context = startupContext([...savingNotes.get(threadId) ?? []].map((note) => note.text));
8449
+ const notes = [...savingNotes.get(threadId) ?? []].map((note) => note.text);
8450
+ if (recovered?.entries.length) notes.push(recentCallNote(recovered.entries));
8451
+ const context = startupContext(notes);
8308
8452
  if (context) {
8309
8453
  for (const piece of appendChunks(context)) if (!send(outbound.sessionAppend(piece, "commentary"))) break;
8310
8454
  }
@@ -8676,6 +8820,109 @@ function withRemoteImageOutput(turn) {
8676
8820
  };
8677
8821
  }
8678
8822
  //#endregion
8823
+ //#region src/remote-image-uploads.js
8824
+ const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
8825
+ const MAX_STAGED_BYTES = 80 * 1024 * 1024;
8826
+ const MAX_STAGED_IMAGES = 32;
8827
+ const UPLOAD_TTL_MS = 5 * 6e4;
8828
+ function uploadPath(value) {
8829
+ if (typeof value !== "string" || value.length > 4096 || /[\x00-\x1f]/u.test(value)) return;
8830
+ const windows = /^[a-z]:[\\/]/iu.test(value);
8831
+ if ((windows ? value.split(/[\\/]/u) : value.split("/")).some((part) => part === "..")) return;
8832
+ if (windows) return win32.normalize(value).toLowerCase();
8833
+ if (value.startsWith("/")) return posix.normalize(value);
8834
+ }
8835
+ function mediaTypeOf(bytes) {
8836
+ if (bytes.length >= 24 && bytes.subarray(0, 8).toString("hex") === "89504e470d0a1a0a" && bytes.toString("ascii", 12, 16) === "IHDR") return "image/png";
8837
+ if (bytes.length >= 4 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 && bytes.at(-2) === 255 && bytes.at(-1) === 217) return "image/jpeg";
8838
+ if (bytes.length >= 14 && ["GIF87a", "GIF89a"].includes(bytes.toString("ascii", 0, 6))) return "image/gif";
8839
+ if (bytes.length >= 20 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP") return "image/webp";
8840
+ }
8841
+ function createRemoteImageUploads() {
8842
+ const uploads = /* @__PURE__ */ new Map();
8843
+ let totalBytes = 0;
8844
+ let timer;
8845
+ const discard = (key) => {
8846
+ const entry = uploads.get(key);
8847
+ if (!entry) return;
8848
+ totalBytes -= entry.data.length;
8849
+ uploads.delete(key);
8850
+ };
8851
+ const prune = () => {
8852
+ for (const [key, entry] of uploads) if (entry.expiresAt <= Date.now()) discard(key);
8853
+ if (uploads.size === 0) {
8854
+ clearInterval(timer);
8855
+ timer = void 0;
8856
+ }
8857
+ };
8858
+ const keyOf = (notify, path) => {
8859
+ const key = uploadPath(path);
8860
+ const client = notify?.clientId;
8861
+ if (typeof client !== "string" || !client || !key) return;
8862
+ return JSON.stringify([client, key]);
8863
+ };
8864
+ const get = (notify, path) => {
8865
+ prune();
8866
+ return uploads.get(keyOf(notify, path));
8867
+ };
8868
+ const requireImage = (notify, path) => {
8869
+ const entry = get(notify, path);
8870
+ if (!entry) throw invalidParams("The phone image upload is missing or expired. Attach it again.");
8871
+ return entry;
8872
+ };
8873
+ return {
8874
+ write(notify, { path, dataBase64 } = {}) {
8875
+ const key = keyOf(notify, path);
8876
+ if (!key) throw invalidParams("An absolute image upload path is required");
8877
+ if (typeof dataBase64 !== "string" || !dataBase64 || dataBase64.length > Math.ceil(MAX_IMAGE_BYTES / 3) * 4 || dataBase64.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/u.test(dataBase64)) throw invalidParams("The phone image must contain valid base64 and be at most 20 MiB");
8878
+ const data = Buffer.from(dataBase64, "base64");
8879
+ if (data.toString("base64") !== dataBase64 || data.length > MAX_IMAGE_BYTES) throw invalidParams("Invalid phone image encoding or size");
8880
+ const mediaType = mediaTypeOf(data);
8881
+ if (!mediaType) throw invalidParams("The phone image must be PNG, JPEG, GIF or WebP");
8882
+ prune();
8883
+ const previous = uploads.get(key);
8884
+ if (!previous && uploads.size >= MAX_STAGED_IMAGES || totalBytes - (previous?.data.length ?? 0) + data.length > MAX_STAGED_BYTES) throw invalidParams("Too many images are waiting for upload. Try again after the previous uploads expire.");
8885
+ discard(key);
8886
+ const createdAt = Date.now();
8887
+ uploads.set(key, {
8888
+ data,
8889
+ mediaType,
8890
+ createdAt,
8891
+ expiresAt: createdAt + UPLOAD_TTL_MS
8892
+ });
8893
+ totalBytes += data.length;
8894
+ timer ??= setInterval(prune, 3e4).unref();
8895
+ return {};
8896
+ },
8897
+ read(notify, path) {
8898
+ return { dataBase64: requireImage(notify, path).data.toString("base64") };
8899
+ },
8900
+ image(notify, path) {
8901
+ const { data, mediaType } = requireImage(notify, path);
8902
+ return {
8903
+ type: "image",
8904
+ url: `data:${mediaType};base64,${data.toString("base64")}`
8905
+ };
8906
+ },
8907
+ metadata(notify, path) {
8908
+ const entry = get(notify, path);
8909
+ return entry && {
8910
+ isDirectory: false,
8911
+ isFile: true,
8912
+ isSymlink: false,
8913
+ createdAtMs: entry.createdAt,
8914
+ modifiedAtMs: entry.createdAt
8915
+ };
8916
+ },
8917
+ clear() {
8918
+ uploads.clear();
8919
+ totalBytes = 0;
8920
+ clearInterval(timer);
8921
+ timer = void 0;
8922
+ }
8923
+ };
8924
+ }
8925
+ //#endregion
8679
8926
  //#region src/remote-control-dsh.js
8680
8927
  const SESSION_EVENT_BATCH = 256;
8681
8928
  const RESUME_TURN_LIMIT = 5;
@@ -8833,7 +9080,7 @@ function voiceStartupContext(agent, saving) {
8833
9080
  const entries = [];
8834
9081
  const notes = /* @__PURE__ */ new Set();
8835
9082
  const addNote = (text) => {
8836
- const excerpt = appendChunks(text.trim(), 1050)[0];
9083
+ const excerpt = appendChunks(VOICE_NOTE_PREFIX + text.slice(62).trim().split("\n").slice(-6).reverse().map((line) => line.replace(/^(You: |Voice: )(.*)$/u, (_, role, speech) => role + speech.slice(-350))).join("\n"), 1050)[0];
8837
9084
  if (excerpt && !notes.has(excerpt)) {
8838
9085
  notes.add(excerpt);
8839
9086
  entries.push(excerpt);
@@ -8848,7 +9095,7 @@ function voiceStartupContext(agent, saving) {
8848
9095
  }
8849
9096
  for (let i = messages.length - 1; i >= 0 && entries.length < 8; i--) {
8850
9097
  const message = messages[i];
8851
- const text = message.role === "assistant" ? visibleText(message.content) : typedText(message);
9098
+ const text = message.role === "assistant" || message.source?.kind === "codex-subscription-voice" ? visibleText(message.content) : typedText(message);
8852
9099
  if (text.startsWith("Part of the voice call that was not handed over as a request:\n")) addNote(text);
8853
9100
  else if (text) entries.push(`${message.role === "user" ? "User" : "Assistant"}: ${appendChunks(text, 420)[0]}`);
8854
9101
  }
@@ -9217,6 +9464,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9217
9464
  const active = /* @__PURE__ */ new Map();
9218
9465
  const queues = /* @__PURE__ */ new Map();
9219
9466
  const starting = /* @__PURE__ */ new Map();
9467
+ const imageUploads = createRemoteImageUploads();
9220
9468
  let catalog;
9221
9469
  const service = () => {
9222
9470
  const value = controller();
@@ -9867,7 +10115,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9867
10115
  completedAt: null
9868
10116
  } };
9869
10117
  };
9870
- /** Message content for DSH from what the phone sent: its text plus any inline images (DSH admits and stores them itself). */
10118
+ /** Resolve previously uploaded paths before DSH admits and stores the images. */
10119
+ const resolveInput = (input, notify) => Array.isArray(input) ? input.map((part) => part?.type === "localImage" ? imageUploads.image(notify, part.path) : part) : input;
9871
10120
  const contentOf = (input) => {
9872
10121
  const text = [...skillGestures(input), inputText(input)].filter(Boolean).join(" ");
9873
10122
  const pictures = inputImages(input);
@@ -9921,7 +10170,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9921
10170
  }, notify, queued);
9922
10171
  }
9923
10172
  async function acceptTurn(params, notify, launch) {
9924
- const { text, pictures, content } = contentOf(params?.input);
10173
+ const { text, pictures, content } = contentOf(resolveInput(params?.input, notify));
9925
10174
  lastPrompt.text = text;
9926
10175
  const id = params?.threadId;
9927
10176
  const agent = await agentFor(id);
@@ -9961,6 +10210,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9961
10210
  turn,
9962
10211
  ended: void 0,
9963
10212
  userItem,
10213
+ queued: launch.queued,
9964
10214
  priorMessageIds: new Set(agent.session.deriveMessages().map((message) => message.id)),
9965
10215
  pendingImages: /* @__PURE__ */ new Set(),
9966
10216
  pendingSteers: /* @__PURE__ */ new Set(),
@@ -10197,8 +10447,29 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10197
10447
  }, AbortSignal.timeout(3e4)))?.accepted === false) throw new Error("DSH rejected the message");
10198
10448
  };
10199
10449
  /** Leave text in the conversation's context for its next message, without starting a turn. */
10200
- const recordToAgent = async (threadId, text) => {
10450
+ const recordedIds = async (threadId, ids) => {
10451
+ if (typeof voice?.flushSession !== "function") return;
10452
+ const { session } = await agentFor(threadId);
10453
+ const found = session.deriveMessages().filter((message) => ids.has(message.id) && message.source?.kind === "codex-subscription-voice");
10454
+ if (!found.length || !await voice.flushSession(session)) return;
10455
+ return new Set(found.map((message) => message.id));
10456
+ };
10457
+ const recordToAgent = async (threadId, text, checkpointId) => {
10201
10458
  const agent = await agentFor(threadId);
10459
+ if (checkpointId && typeof voice?.flushSession === "function" && typeof agent.session.append === "function") {
10460
+ while (agent.status === "running" && typeof agent.whenIdle === "function") await agent.whenIdle();
10461
+ if (agent.status === "running") return false;
10462
+ if (!agent.session.deriveMessages().some((message) => message.id === checkpointId && message.source?.kind === "codex-subscription-voice")) agent.session.append("user/message", {
10463
+ id: checkpointId,
10464
+ role: "user",
10465
+ content: [{
10466
+ type: "text",
10467
+ text
10468
+ }],
10469
+ source: { kind: VOICE_NOTE_SOURCE }
10470
+ }, { surfaceOp: "append" });
10471
+ return await voice.flushSession(agent.session) === true;
10472
+ }
10202
10473
  if (typeof agent.inject !== "function") return;
10203
10474
  if (agent.status === "running") await agent.whenIdle?.();
10204
10475
  agent.inject({
@@ -10217,7 +10488,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10217
10488
  log: diagnosticLog,
10218
10489
  delegate: delegateToAgent,
10219
10490
  queue: queueVoiceWork,
10220
- record: recordToAgent
10491
+ record: recordToAgent,
10492
+ recordedIds
10221
10493
  }) : void 0;
10222
10494
  const phoneConfig = createPhoneConfig(configFile);
10223
10495
  const methods = {
@@ -10349,7 +10621,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10349
10621
  marketplaces: []
10350
10622
  }),
10351
10623
  "fs/createDirectory": () => ({}),
10352
- "fs/getMetadata": (params) => realMetadata(params?.path) ?? {
10624
+ "fs/writeFile": (params, { notify, signal }) => {
10625
+ signal?.throwIfAborted();
10626
+ return imageUploads.write(notify, params ?? {});
10627
+ },
10628
+ "fs/readFile": (params, { notify }) => imageUploads.read(notify, params?.path),
10629
+ "fs/getMetadata": (params, { notify } = {}) => imageUploads.metadata(notify, params?.path) ?? realMetadata(params?.path) ?? {
10353
10630
  isDirectory: true,
10354
10631
  isFile: false,
10355
10632
  isSymlink: false,
@@ -10626,9 +10903,15 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10626
10903
  },
10627
10904
  "turn/start": (params, { notify }) => titles.has(params?.threadId) ? titleTurn(params, notify) : startTurn(params, notify),
10628
10905
  "turn/interrupt": (params) => {
10629
- active.get(params?.threadId)?.abort?.abort();
10630
- starting.get(params?.threadId)?.abort.abort();
10631
- service().cancel({ sessionId: params?.threadId });
10906
+ const id = params?.threadId;
10907
+ const running = active.get(id);
10908
+ const launch = starting.get(id);
10909
+ if (params?.turnId !== void 0 && params.turnId !== running?.turn.id) return {};
10910
+ if (running?.finishing || running?.ended || (running?.abort ?? launch?.abort)?.signal.aborted) return {};
10911
+ if (running) {
10912
+ running.abort.abort();
10913
+ service().cancel({ sessionId: id });
10914
+ } else launch?.abort.abort();
10632
10915
  return {};
10633
10916
  },
10634
10917
  "thread/compact/start": async (params, { notify }) => {
@@ -10640,11 +10923,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10640
10923
  subscribe(id, notify);
10641
10924
  const turn = emptyTurn();
10642
10925
  const abort = new AbortController();
10643
- active.set(id, {
10926
+ const running = {
10644
10927
  turn,
10645
10928
  ended: void 0,
10646
10929
  abort
10647
- });
10930
+ };
10931
+ active.set(id, running);
10648
10932
  emit(id, "turn/started", {
10649
10933
  threadId: id,
10650
10934
  turn
@@ -10658,7 +10942,10 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10658
10942
  });
10659
10943
  (async () => {
10660
10944
  try {
10661
- const result = (await registry.execute(agent, "/compact", [], abort.signal))?.result;
10945
+ const execution = await registry.execute(agent, "/compact", [], abort.signal);
10946
+ abort.signal.throwIfAborted();
10947
+ if (active.get(id) !== running) return;
10948
+ const result = execution?.result;
10662
10949
  if (result?.kind === "error") throw new Error(result.text || "Compaction failed");
10663
10950
  if (result?.sourceEventSeq !== void 0 && turn.items.length === 0) {
10664
10951
  const item = {
@@ -10681,6 +10968,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10681
10968
  }
10682
10969
  turn.status = "completed";
10683
10970
  } catch (error) {
10971
+ if (active.get(id) !== running) return;
10684
10972
  turn.status = abort.signal.aborted ? "interrupted" : "failed";
10685
10973
  if (turn.status === "failed") {
10686
10974
  turn.error = {
@@ -10716,12 +11004,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10716
11004
  })();
10717
11005
  return {};
10718
11006
  },
10719
- "turn/steer": async (params, { signal } = {}) => {
11007
+ "turn/steer": async (params, { signal, notify } = {}) => {
10720
11008
  const running = active.get(params?.threadId);
10721
11009
  const current = () => running && active.get(params?.threadId) === running && running.userItem && !running.finishing && !running.ended && !running.abort.signal.aborted && !starting.has(params?.threadId) && params?.expectedTurnId === running.turn.id;
10722
11010
  signal?.throwIfAborted();
10723
11011
  if (!current()) throw invalidParams("The expected turn is not active");
10724
- const { content } = contentOf(params?.input);
11012
+ const { content } = contentOf(resolveInput(params?.input, notify));
10725
11013
  const operation = (async () => {
10726
11014
  if ((await service().prompt({
10727
11015
  requestId: randomUUID(),
@@ -10762,15 +11050,24 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10762
11050
  }),
10763
11051
  "thread/queue/add": async (params, { notify }) => {
10764
11052
  if (!Array.isArray(params?.input)) throw invalidParams("input is required");
10765
- contentOf(params.input);
10766
11053
  const id = params?.threadId;
11054
+ const clientUserMessageId = String(params.clientUserMessageId ?? randomUUID());
11055
+ const queue = queues.get(id) ?? [];
11056
+ const dispatched = active.get(id)?.queued;
11057
+ const existing = queue.find((entry) => entry.clientUserMessageId === clientUserMessageId) ?? (dispatched?.clientUserMessageId === clientUserMessageId ? dispatched : void 0);
11058
+ if (existing) {
11059
+ subscribe(id, notify);
11060
+ return { queuedSubmission: existing };
11061
+ }
11062
+ const input = resolveInput(params.input, notify);
11063
+ contentOf(input);
10767
11064
  const queued = {
10768
11065
  id: randomUUID(),
10769
- clientUserMessageId: String(params.clientUserMessageId ?? randomUUID()),
10770
- input: params.input
11066
+ clientUserMessageId,
11067
+ input
10771
11068
  };
10772
11069
  subscribe(id, notify);
10773
- queues.set(id, [...queues.get(id) ?? [], queued]);
11070
+ queues.set(id, [...queue, queued]);
10774
11071
  emit(id, "thread/queue/changed", { threadId: id });
10775
11072
  if (!active.has(id) && !starting.has(id)) await startQueuedTurn(id, notify, queued.id, {
10776
11073
  model: params.model,
@@ -11273,7 +11570,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
11273
11570
  onApproval,
11274
11571
  onQuestion,
11275
11572
  adopt,
11573
+ clearUploads: imageUploads.clear,
11276
11574
  close() {
11575
+ imageUploads.clear();
11277
11576
  realtimeVoice?.closeAll();
11278
11577
  },
11279
11578
  forget: (notify) => {
@@ -13431,6 +13730,7 @@ const DSH_SEARCH_PROVIDER_ID = "codex-subscription-dsh";
13431
13730
  function createDshSearchProvider({ resolveDshProvider, report }) {
13432
13731
  return Object.freeze({
13433
13732
  id: DSH_SEARCH_PROVIDER_ID,
13733
+ title: "DSH (Codex Subscription)",
13434
13734
  available: () => true,
13435
13735
  async ready(llmProvider) {
13436
13736
  const provider = resolveDshProvider?.();
@@ -13619,6 +13919,7 @@ function createCodexAutoSearchProvider(options) {
13619
13919
  const viaCodex = (request, signal) => options.codex.search(request, signal);
13620
13920
  return Object.freeze({
13621
13921
  id: CODEX_AUTO_SEARCH_PROVIDER_ID,
13922
+ title: "Codex Subscription (Auto)",
13622
13923
  available: () => true,
13623
13924
  async ready(llmProvider) {
13624
13925
  if (await options.codex.ready?.(llmProvider) ?? true) return true;
@@ -13660,6 +13961,7 @@ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
13660
13961
  };
13661
13962
  return Object.freeze({
13662
13963
  id: provider.id,
13964
+ title: provider.title,
13663
13965
  available: () => {
13664
13966
  try {
13665
13967
  return selected().available();
@@ -13689,9 +13991,14 @@ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
13689
13991
  *
13690
13992
  * @returns {Map|undefined} a stand-in for the web registry, or undefined when the registry is not a Map.
13691
13993
  */
13692
- function createSearchRouter({ registry, configuredId, mode, providers }) {
13994
+ function createSearchRouter({ registry, configuredId, mode, providers, enabled = () => true }) {
13693
13995
  if (!(registry instanceof Map)) return void 0;
13694
- const selected = () => {
13996
+ const selected = (id) => {
13997
+ if (!enabled()) {
13998
+ const provider = registry.get(id);
13999
+ if (!provider || !provider.available()) throw new WebError("The selected search provider is unavailable", "WEB_PROVIDER_UNAVAILABLE");
14000
+ return provider;
14001
+ }
13695
14002
  const source = mode();
13696
14003
  return source === "codex" ? providers.codex : source === "auto" ? providers.auto : providers.dsh;
13697
14004
  };
@@ -13701,10 +14008,10 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
13701
14008
  if (router === void 0) {
13702
14009
  router = Object.freeze({
13703
14010
  id,
13704
- available: () => true,
13705
- ready: (llmProvider) => selected().ready?.(llmProvider) ?? true,
14011
+ available: () => enabled() || registry.get(id)?.available() === true,
14012
+ ready: (llmProvider) => selected(id).ready?.(llmProvider) ?? true,
13706
14013
  search(request, signal) {
13707
- return selected().search(request, signal);
14014
+ return selected(id).search(request, signal);
13708
14015
  }
13709
14016
  });
13710
14017
  wrappers.set(id, router);
@@ -13714,7 +14021,7 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
13714
14021
  return new Proxy(registry, { get(target, property) {
13715
14022
  if (property === "get") return (id) => {
13716
14023
  const configured = configuredId();
13717
- return typeof id === "string" && id === configured && !OWN_IDS.has(id) ? routerFor(id) : target.get(id);
14024
+ return enabled() && typeof id === "string" && id === configured && !OWN_IDS.has(id) ? routerFor(id) : target.get(id);
13718
14025
  };
13719
14026
  const value = Reflect.get(target, property, target);
13720
14027
  return typeof value === "function" ? value.bind(target) : value;
@@ -13748,6 +14055,7 @@ function createCodexFetchProvider(options) {
13748
14055
  const fetchPage = options.fetch ?? fetch;
13749
14056
  return Object.freeze({
13750
14057
  id: CODEX_FETCH_PROVIDER_ID,
14058
+ title: "Codex Subscription",
13751
14059
  available: () => true,
13752
14060
  ready: (llmProvider) => options.allowed?.(llmProvider) === false ? false : subscriptionCredentialReady(options.readCredential),
13753
14061
  async fetch(request, signal) {
@@ -13890,6 +14198,75 @@ function configuredFetchProviderId(web, entries = [], ambient = process.env.DSH_
13890
14198
  return value ?? entry?.options?.config?.fetchProvider ?? environment;
13891
14199
  }
13892
14200
  //#endregion
14201
+ //#region src/web-provider-settings.js
14202
+ const WEB = "web";
14203
+ const subscriptionSearchIds = /* @__PURE__ */ new Set([
14204
+ CODEX_SEARCH_PROVIDER_ID,
14205
+ CODEX_AUTO_SEARCH_PROVIDER_ID,
14206
+ DSH_SEARCH_PROVIDER_ID
14207
+ ]);
14208
+ const isNativeSearch = (id) => typeof id === "string" && id !== "" && !subscriptionSearchIds.has(id);
14209
+ const isNativeFetch = (id) => typeof id === "string" && id !== "" && id !== "codex-subscription-fetch";
14210
+ function nativeDefaults(row, legacy) {
14211
+ const values = {};
14212
+ const search = row.user?.searchProvider ?? row.value?.searchProvider;
14213
+ const fetch = row.user?.fetchProvider ?? row.value?.fetchProvider;
14214
+ if (isNativeSearch(search) && search !== legacy.webSearchFallbackProvider) values.webSearchFallbackProvider = search;
14215
+ if (isNativeFetch(fetch) && fetch !== legacy.webFetchFallbackProvider) values.webFetchFallbackProvider = fetch;
14216
+ return values;
14217
+ }
14218
+ function createWebProviderSettings(ctx, settings) {
14219
+ const forms = ctx.settings;
14220
+ if (typeof ctx.web.listProviders !== "function" || typeof forms.describe !== "function") return void 0;
14221
+ const describe = () => forms.describe({ redactSecrets: true });
14222
+ const web = () => describe().find((row) => row.ns === WEB);
14223
+ const nativeSearch = () => {
14224
+ const { value, base } = web() ?? {};
14225
+ return [
14226
+ value?.searchProvider,
14227
+ settings.get().webSearchFallbackProvider,
14228
+ base?.searchProvider
14229
+ ].find(isNativeSearch);
14230
+ };
14231
+ const managed = () => settings.get().webProvidersManagedByDsh === true;
14232
+ async function remember() {
14233
+ if (!managed() || forms.writable !== true) return;
14234
+ const rows = describe();
14235
+ const web = rows.find((row) => row.ns === WEB);
14236
+ const plugin = rows.find((row) => row.ns === settings.id);
14237
+ if (!web || !plugin) return;
14238
+ const patch = nativeDefaults(web, settings.get());
14239
+ if (Object.keys(patch).length) await settings.update(patch, plugin.revision);
14240
+ }
14241
+ async function migrate() {
14242
+ if (managed() || forms.writable !== true) return;
14243
+ const rows = describe();
14244
+ const web = rows.find((row) => row.ns === WEB);
14245
+ const plugin = rows.find((row) => row.ns === settings.id);
14246
+ if (!web || !plugin) return;
14247
+ const currentSearch = web.value?.searchProvider;
14248
+ const currentFetch = web.value?.fetchProvider;
14249
+ const legacy = settings.get();
14250
+ const patch = {};
14251
+ if (Object.keys(plugin.user ?? {}).length && currentSearch && !subscriptionSearchIds.has(currentSearch)) {
14252
+ if (legacy.searchProvider === "codex") patch.searchProvider = CODEX_SEARCH_PROVIDER_ID;
14253
+ if (legacy.searchProvider === "auto") patch.searchProvider = CODEX_AUTO_SEARCH_PROVIDER_ID;
14254
+ }
14255
+ if (legacy.fetchProvider === "codex" && currentFetch !== "codex-subscription-fetch") patch.fetchProvider = CODEX_FETCH_PROVIDER_ID;
14256
+ const previous = nativeDefaults(web, legacy);
14257
+ if (Object.keys(previous).length) await settings.update(previous, plugin.revision);
14258
+ if (Object.keys(patch).length) await forms.update(WEB, patch, web.revision);
14259
+ const currentPlugin = describe().find((row) => row.ns === settings.id);
14260
+ if (currentPlugin) await settings.update({ webProvidersManagedByDsh: true }, currentPlugin.revision);
14261
+ }
14262
+ return {
14263
+ managed,
14264
+ migrate,
14265
+ nativeSearch,
14266
+ remember
14267
+ };
14268
+ }
14269
+ //#endregion
13893
14270
  //#region src/image-tool-registration.js
13894
14271
  /** Removing the tool also removes its schema from subsequent model requests. */
13895
14272
  function watchImageTool(settings, register) {
@@ -17998,6 +18375,9 @@ function createSearchProviderSwitcher(loader) {
17998
18375
  });
17999
18376
  }
18000
18377
  const settingsFields = {
18378
+ webProvidersManagedByDsh: z.boolean().default(false),
18379
+ webSearchFallbackProvider: z.string(),
18380
+ webFetchFallbackProvider: z.string(),
18001
18381
  [DISABLED_MODELS_FIELD]: z.transform(z.array(z.string()).max(100), normalizeDisabledModels).default([]),
18002
18382
  [AUTO_QUOTA_RETRY_FIELD]: z.boolean().default(false),
18003
18383
  subagentDefaultModel: z.transform(z.string().max(80), normalizeSubagentModel).default(""),
@@ -18025,6 +18405,8 @@ const Config = z.object(Object.fromEntries(Object.entries(settingsFields).map(([
18025
18405
  function apply(ctx, config = {}) {
18026
18406
  const settings = createSettingsAdapter(ctx, config);
18027
18407
  const searchProvider = createSearchProviderSwitcher(ctx.loader);
18408
+ const webSettings = createWebProviderSettings(ctx, settings);
18409
+ const nativeWebSettings = () => webSettings?.managed() === true;
18028
18410
  if (!process.env.NODE_TEST_CONTEXT) diagnosticLog.attach(dshHomePath("state", "codex-subscription", "diagnostic-log.jsonl"));
18029
18411
  diagnosticLog.info("plugin", `loaded ${PACKAGE_VERSION}`, `DSH ${hostDshVersion() ?? "unknown"}, node ${process.version}, ${process.platform}`);
18030
18412
  setAuthFailureLogger((message, detail) => diagnosticLog.error("auth", message, detail));
@@ -18176,6 +18558,11 @@ function apply(ctx, config = {}) {
18176
18558
  [QUICK_QUOTA_MODE_FIELD]: normalizeQuickQuotaMode(settings.get()[QUICK_QUOTA_MODE_FIELD], settings.get()[LEGACY_QUICK_QUOTA_FIELD]),
18177
18559
  [SEARCH_PROVIDER_FIELD]: settings.get()[SEARCH_PROVIDER_FIELD],
18178
18560
  [FETCH_PROVIDER_FIELD]: normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]),
18561
+ ...nativeWebSettings() ? {
18562
+ webProvidersManagedByDsh: true,
18563
+ webSearchFallbackProvider: settings.get().webSearchFallbackProvider,
18564
+ webFetchFallbackProvider: settings.get().webFetchFallbackProvider
18565
+ } : {},
18179
18566
  fetchRoutingAvailable: fetchRouted,
18180
18567
  [SPEED_MODE_FIELD]: settings.get()[SPEED_MODE_FIELD],
18181
18568
  [OUTPUT_VERBOSITY_FIELD]: normalizeOutputVerbosity(settings.get()[OUTPUT_VERBOSITY_FIELD]),
@@ -18205,6 +18592,7 @@ function apply(ctx, config = {}) {
18205
18592
  },
18206
18593
  update: async (patch) => {
18207
18594
  if (patch.subagentDefaultModel && !subagentDefaults.list().some((model) => model.id === patch.subagentDefaultModel)) throw new Error("Codex subtask model is unavailable or disallowed");
18595
+ if (nativeWebSettings() && (Object.hasOwn(patch, "searchProvider") || Object.hasOwn(patch, "fetchProvider"))) throw new Error("Select the provider in DSH Web Search and Fetch settings");
18208
18596
  if (patch["fetchProvider"] === "codex" && !fetchRouted) throw new Error("This DSH version does not support Codex webpage reading");
18209
18597
  if (Object.hasOwn(patch, "subagentBackend")) {
18210
18598
  if (!subagentBackend) throw new Error("DSH subagent services are unavailable");
@@ -18419,7 +18807,7 @@ function apply(ctx, config = {}) {
18419
18807
  }, "codex-subscription: official model catalog");
18420
18808
  const currentAgent = () => ctx.get?.("agents")?.currentInitiator?.();
18421
18809
  const codexFetch = createCodexFetchProvider({
18422
- allowed: (llmProvider) => fetchRouted && (settings.get().otherModels !== "off" || (llmProvider ?? currentAgent()?.session.requestContext?.()?.provider) === PROVIDER),
18810
+ allowed: (llmProvider) => (nativeWebSettings() || fetchRouted) && (settings.get().otherModels !== "off" || (llmProvider ?? currentAgent()?.session.requestContext?.()?.provider) === PROVIDER),
18423
18811
  getAuth: resolveAuth,
18424
18812
  readCredential: (options) => store.read(PROVIDER, options),
18425
18813
  resolveModel: () => {
@@ -18432,15 +18820,16 @@ function apply(ctx, config = {}) {
18432
18820
  const realFetchProviders = ctx.web.fetchProviders;
18433
18821
  ctx.web.registerFetchProvider?.({
18434
18822
  ...codexFetch,
18435
- available: () => fetchRouted && normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex"
18823
+ available: () => nativeWebSettings() ? configuredFetchProviderId(ctx.web, ctx.loader.entries()) === codexFetch.id : fetchRouted && normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex"
18436
18824
  });
18437
18825
  ctx.effect(() => {
18826
+ if (nativeWebSettings()) return void 0;
18438
18827
  const web = ctx.web;
18439
18828
  const configuredId = () => configuredFetchProviderId(web, ctx.loader.entries());
18440
18829
  const router = createCodexFetchRouter({
18441
18830
  registry: realFetchProviders,
18442
18831
  configuredId,
18443
- mode: () => fetchRouted ? normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]) : "dsh",
18832
+ mode: () => fetchRouted && !nativeWebSettings() ? normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]) : "dsh",
18444
18833
  codex: codexFetch
18445
18834
  });
18446
18835
  if (router !== void 0) {
@@ -18469,7 +18858,7 @@ function apply(ctx, config = {}) {
18469
18858
  return provider === void 0 || provider === PROVIDER;
18470
18859
  };
18471
18860
  const realSearchProviders = ctx.web.searchProviders;
18472
- const resolveDshSearch = () => realSearchProviders?.get(searchProvider.dshProviderId());
18861
+ const resolveDshSearch = () => realSearchProviders?.get(nativeWebSettings() ? webSettings.nativeSearch() ?? DSH_SEARCH_PROVIDER_FALLBACK : searchProvider.dshProviderId());
18473
18862
  const gateSearch = (provider) => gateSearchProvider(provider, {
18474
18863
  allowed: (llmProvider) => settings.get().otherModels !== "off" || (llmProvider ?? currentAgent()?.session.requestContext?.()?.provider) === PROVIDER,
18475
18864
  resolveDshProvider: resolveDshSearch
@@ -18488,6 +18877,7 @@ function apply(ctx, config = {}) {
18488
18877
  const searchTrace = (route) => diagnosticLog.info("search", `web search: ${route}`);
18489
18878
  const tracedCodexSearch = gateSearch({
18490
18879
  id: codexSearch.id,
18880
+ title: "Codex Subscription",
18491
18881
  available: () => codexSearch.available(),
18492
18882
  ready: (llmProvider) => codexSearch.ready(llmProvider),
18493
18883
  async search(request, signal) {
@@ -18510,11 +18900,13 @@ function apply(ctx, config = {}) {
18510
18900
  ctx.web.registerSearchProvider(autoSearch);
18511
18901
  let searchRouted = false;
18512
18902
  ctx.effect(() => {
18903
+ if (nativeWebSettings()) return void 0;
18513
18904
  const web = ctx.web;
18514
18905
  const router = createSearchRouter({
18515
18906
  registry: realSearchProviders,
18516
18907
  configuredId: () => searchProvider.current(),
18517
18908
  mode: () => settings.get()[SEARCH_PROVIDER_FIELD],
18909
+ enabled: () => !nativeWebSettings(),
18518
18910
  providers: {
18519
18911
  codex: tracedCodexSearch,
18520
18912
  auto: autoSearch,
@@ -18537,6 +18929,7 @@ function apply(ctx, config = {}) {
18537
18929
  }, "codex-subscription: search router");
18538
18930
  ctx.effect(() => {
18539
18931
  const select = async (value) => {
18932
+ if (nativeWebSettings()) return;
18540
18933
  if (searchRouted) {
18541
18934
  diagnosticLog.info("search", `web search source is ${value[SEARCH_PROVIDER_FIELD]}`);
18542
18935
  return;
@@ -18552,6 +18945,27 @@ function apply(ctx, config = {}) {
18552
18945
  select(settings.get());
18553
18946
  return settings.watch(select);
18554
18947
  }, "codex-subscription: search provider selection");
18948
+ if (webSettings) ctx.effect(() => {
18949
+ let timer;
18950
+ const sync = () => {
18951
+ clearTimeout(timer);
18952
+ timer = setTimeout(() => {
18953
+ (nativeWebSettings() ? webSettings.remember() : webSettings.migrate()).catch((error) => {
18954
+ ctx.logger?.warn?.("could not sync Web Search and Fetch settings: %s", error.message);
18955
+ });
18956
+ }, 75);
18957
+ };
18958
+ const documentPath = ctx.settings.documentPath;
18959
+ if (typeof documentPath === "string") watchFile(documentPath, {
18960
+ persistent: false,
18961
+ interval: 250
18962
+ }, sync);
18963
+ sync();
18964
+ return () => {
18965
+ clearTimeout(timer);
18966
+ if (typeof documentPath === "string") unwatchFile(documentPath, sync);
18967
+ };
18968
+ }, "codex-subscription: migrate web provider settings");
18555
18969
  const auth = createCodexAuthService(authModels, store, {
18556
18970
  runLogin: (operation) => network.run("login", operation),
18557
18971
  accountVault,
@@ -18598,6 +19012,8 @@ function apply(ctx, config = {}) {
18598
19012
  configFile: dshHomePath("state", "codex-subscription", "remote-config.json"),
18599
19013
  voice: {
18600
19014
  WebSocket,
19015
+ recovery: createVoiceTranscriptRecovery(dshHomePath("state", "codex-subscription", "voice-transcript-recovery")),
19016
+ flushSession: (session) => ctx.get?.("sessions")?.flush?.(session),
18601
19017
  resolveProxy: resolveCodexOAuthProxy,
18602
19018
  fetch: (input, init) => network.fetch("voice", input, init),
18603
19019
  credentials: (signal) => readSubscriptionCredentials(resolveAuth, (options) => store.read(PROVIDER, {
@@ -18626,7 +19042,8 @@ function apply(ctx, config = {}) {
18626
19042
  base: process.env.DSH_CODEX_REMOTE_BASE || void 0,
18627
19043
  methods: remoteBridge.methods,
18628
19044
  onActive: (_client, notify) => remoteBridge.adopt(notify),
18629
- onClose: (_client, notify) => remoteBridge.forget(notify)
19045
+ onClose: (_client, notify) => remoteBridge.forget(notify),
19046
+ onStop: remoteBridge.clearUploads
18630
19047
  });
18631
19048
  ctx.on("agent/assistant-stream", ({ agent, frame }) => {
18632
19049
  try {
@@ -18824,6 +19241,7 @@ function apply(ctx, config = {}) {
18824
19241
  voicePreview,
18825
19242
  composerPredictions,
18826
19243
  onAccountChanged: () => {
19244
+ remoteBridge.clearUploads();
18827
19245
  subagentCatalog.clear();
18828
19246
  connectorsClient.clear();
18829
19247
  usageProfileReader.clear();