dsh-codex-subscription 3.2.16 → 3.2.17

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.17";
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
  };
@@ -8676,6 +8706,109 @@ function withRemoteImageOutput(turn) {
8676
8706
  };
8677
8707
  }
8678
8708
  //#endregion
8709
+ //#region src/remote-image-uploads.js
8710
+ const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
8711
+ const MAX_STAGED_BYTES = 80 * 1024 * 1024;
8712
+ const MAX_STAGED_IMAGES = 32;
8713
+ const UPLOAD_TTL_MS = 5 * 6e4;
8714
+ function uploadPath(value) {
8715
+ if (typeof value !== "string" || value.length > 4096 || /[\x00-\x1f]/u.test(value)) return;
8716
+ const windows = /^[a-z]:[\\/]/iu.test(value);
8717
+ if ((windows ? value.split(/[\\/]/u) : value.split("/")).some((part) => part === "..")) return;
8718
+ if (windows) return win32.normalize(value).toLowerCase();
8719
+ if (value.startsWith("/")) return posix.normalize(value);
8720
+ }
8721
+ function mediaTypeOf(bytes) {
8722
+ if (bytes.length >= 24 && bytes.subarray(0, 8).toString("hex") === "89504e470d0a1a0a" && bytes.toString("ascii", 12, 16) === "IHDR") return "image/png";
8723
+ if (bytes.length >= 4 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 && bytes.at(-2) === 255 && bytes.at(-1) === 217) return "image/jpeg";
8724
+ if (bytes.length >= 14 && ["GIF87a", "GIF89a"].includes(bytes.toString("ascii", 0, 6))) return "image/gif";
8725
+ if (bytes.length >= 20 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP") return "image/webp";
8726
+ }
8727
+ function createRemoteImageUploads() {
8728
+ const uploads = /* @__PURE__ */ new Map();
8729
+ let totalBytes = 0;
8730
+ let timer;
8731
+ const discard = (key) => {
8732
+ const entry = uploads.get(key);
8733
+ if (!entry) return;
8734
+ totalBytes -= entry.data.length;
8735
+ uploads.delete(key);
8736
+ };
8737
+ const prune = () => {
8738
+ for (const [key, entry] of uploads) if (entry.expiresAt <= Date.now()) discard(key);
8739
+ if (uploads.size === 0) {
8740
+ clearInterval(timer);
8741
+ timer = void 0;
8742
+ }
8743
+ };
8744
+ const keyOf = (notify, path) => {
8745
+ const key = uploadPath(path);
8746
+ const client = notify?.clientId;
8747
+ if (typeof client !== "string" || !client || !key) return;
8748
+ return JSON.stringify([client, key]);
8749
+ };
8750
+ const get = (notify, path) => {
8751
+ prune();
8752
+ return uploads.get(keyOf(notify, path));
8753
+ };
8754
+ const requireImage = (notify, path) => {
8755
+ const entry = get(notify, path);
8756
+ if (!entry) throw invalidParams("The phone image upload is missing or expired. Attach it again.");
8757
+ return entry;
8758
+ };
8759
+ return {
8760
+ write(notify, { path, dataBase64 } = {}) {
8761
+ const key = keyOf(notify, path);
8762
+ if (!key) throw invalidParams("An absolute image upload path is required");
8763
+ 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");
8764
+ const data = Buffer.from(dataBase64, "base64");
8765
+ if (data.toString("base64") !== dataBase64 || data.length > MAX_IMAGE_BYTES) throw invalidParams("Invalid phone image encoding or size");
8766
+ const mediaType = mediaTypeOf(data);
8767
+ if (!mediaType) throw invalidParams("The phone image must be PNG, JPEG, GIF or WebP");
8768
+ prune();
8769
+ const previous = uploads.get(key);
8770
+ 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.");
8771
+ discard(key);
8772
+ const createdAt = Date.now();
8773
+ uploads.set(key, {
8774
+ data,
8775
+ mediaType,
8776
+ createdAt,
8777
+ expiresAt: createdAt + UPLOAD_TTL_MS
8778
+ });
8779
+ totalBytes += data.length;
8780
+ timer ??= setInterval(prune, 3e4).unref();
8781
+ return {};
8782
+ },
8783
+ read(notify, path) {
8784
+ return { dataBase64: requireImage(notify, path).data.toString("base64") };
8785
+ },
8786
+ image(notify, path) {
8787
+ const { data, mediaType } = requireImage(notify, path);
8788
+ return {
8789
+ type: "image",
8790
+ url: `data:${mediaType};base64,${data.toString("base64")}`
8791
+ };
8792
+ },
8793
+ metadata(notify, path) {
8794
+ const entry = get(notify, path);
8795
+ return entry && {
8796
+ isDirectory: false,
8797
+ isFile: true,
8798
+ isSymlink: false,
8799
+ createdAtMs: entry.createdAt,
8800
+ modifiedAtMs: entry.createdAt
8801
+ };
8802
+ },
8803
+ clear() {
8804
+ uploads.clear();
8805
+ totalBytes = 0;
8806
+ clearInterval(timer);
8807
+ timer = void 0;
8808
+ }
8809
+ };
8810
+ }
8811
+ //#endregion
8679
8812
  //#region src/remote-control-dsh.js
8680
8813
  const SESSION_EVENT_BATCH = 256;
8681
8814
  const RESUME_TURN_LIMIT = 5;
@@ -9217,6 +9350,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9217
9350
  const active = /* @__PURE__ */ new Map();
9218
9351
  const queues = /* @__PURE__ */ new Map();
9219
9352
  const starting = /* @__PURE__ */ new Map();
9353
+ const imageUploads = createRemoteImageUploads();
9220
9354
  let catalog;
9221
9355
  const service = () => {
9222
9356
  const value = controller();
@@ -9867,7 +10001,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9867
10001
  completedAt: null
9868
10002
  } };
9869
10003
  };
9870
- /** Message content for DSH from what the phone sent: its text plus any inline images (DSH admits and stores them itself). */
10004
+ /** Resolve previously uploaded paths before DSH admits and stores the images. */
10005
+ const resolveInput = (input, notify) => Array.isArray(input) ? input.map((part) => part?.type === "localImage" ? imageUploads.image(notify, part.path) : part) : input;
9871
10006
  const contentOf = (input) => {
9872
10007
  const text = [...skillGestures(input), inputText(input)].filter(Boolean).join(" ");
9873
10008
  const pictures = inputImages(input);
@@ -9921,7 +10056,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9921
10056
  }, notify, queued);
9922
10057
  }
9923
10058
  async function acceptTurn(params, notify, launch) {
9924
- const { text, pictures, content } = contentOf(params?.input);
10059
+ const { text, pictures, content } = contentOf(resolveInput(params?.input, notify));
9925
10060
  lastPrompt.text = text;
9926
10061
  const id = params?.threadId;
9927
10062
  const agent = await agentFor(id);
@@ -9961,6 +10096,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9961
10096
  turn,
9962
10097
  ended: void 0,
9963
10098
  userItem,
10099
+ queued: launch.queued,
9964
10100
  priorMessageIds: new Set(agent.session.deriveMessages().map((message) => message.id)),
9965
10101
  pendingImages: /* @__PURE__ */ new Set(),
9966
10102
  pendingSteers: /* @__PURE__ */ new Set(),
@@ -10349,7 +10485,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10349
10485
  marketplaces: []
10350
10486
  }),
10351
10487
  "fs/createDirectory": () => ({}),
10352
- "fs/getMetadata": (params) => realMetadata(params?.path) ?? {
10488
+ "fs/writeFile": (params, { notify, signal }) => {
10489
+ signal?.throwIfAborted();
10490
+ return imageUploads.write(notify, params ?? {});
10491
+ },
10492
+ "fs/readFile": (params, { notify }) => imageUploads.read(notify, params?.path),
10493
+ "fs/getMetadata": (params, { notify } = {}) => imageUploads.metadata(notify, params?.path) ?? realMetadata(params?.path) ?? {
10353
10494
  isDirectory: true,
10354
10495
  isFile: false,
10355
10496
  isSymlink: false,
@@ -10626,9 +10767,15 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10626
10767
  },
10627
10768
  "turn/start": (params, { notify }) => titles.has(params?.threadId) ? titleTurn(params, notify) : startTurn(params, notify),
10628
10769
  "turn/interrupt": (params) => {
10629
- active.get(params?.threadId)?.abort?.abort();
10630
- starting.get(params?.threadId)?.abort.abort();
10631
- service().cancel({ sessionId: params?.threadId });
10770
+ const id = params?.threadId;
10771
+ const running = active.get(id);
10772
+ const launch = starting.get(id);
10773
+ if (params?.turnId !== void 0 && params.turnId !== running?.turn.id) return {};
10774
+ if (running?.finishing || running?.ended || (running?.abort ?? launch?.abort)?.signal.aborted) return {};
10775
+ if (running) {
10776
+ running.abort.abort();
10777
+ service().cancel({ sessionId: id });
10778
+ } else launch?.abort.abort();
10632
10779
  return {};
10633
10780
  },
10634
10781
  "thread/compact/start": async (params, { notify }) => {
@@ -10640,11 +10787,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10640
10787
  subscribe(id, notify);
10641
10788
  const turn = emptyTurn();
10642
10789
  const abort = new AbortController();
10643
- active.set(id, {
10790
+ const running = {
10644
10791
  turn,
10645
10792
  ended: void 0,
10646
10793
  abort
10647
- });
10794
+ };
10795
+ active.set(id, running);
10648
10796
  emit(id, "turn/started", {
10649
10797
  threadId: id,
10650
10798
  turn
@@ -10658,7 +10806,10 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10658
10806
  });
10659
10807
  (async () => {
10660
10808
  try {
10661
- const result = (await registry.execute(agent, "/compact", [], abort.signal))?.result;
10809
+ const execution = await registry.execute(agent, "/compact", [], abort.signal);
10810
+ abort.signal.throwIfAborted();
10811
+ if (active.get(id) !== running) return;
10812
+ const result = execution?.result;
10662
10813
  if (result?.kind === "error") throw new Error(result.text || "Compaction failed");
10663
10814
  if (result?.sourceEventSeq !== void 0 && turn.items.length === 0) {
10664
10815
  const item = {
@@ -10681,6 +10832,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10681
10832
  }
10682
10833
  turn.status = "completed";
10683
10834
  } catch (error) {
10835
+ if (active.get(id) !== running) return;
10684
10836
  turn.status = abort.signal.aborted ? "interrupted" : "failed";
10685
10837
  if (turn.status === "failed") {
10686
10838
  turn.error = {
@@ -10716,12 +10868,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10716
10868
  })();
10717
10869
  return {};
10718
10870
  },
10719
- "turn/steer": async (params, { signal } = {}) => {
10871
+ "turn/steer": async (params, { signal, notify } = {}) => {
10720
10872
  const running = active.get(params?.threadId);
10721
10873
  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
10874
  signal?.throwIfAborted();
10723
10875
  if (!current()) throw invalidParams("The expected turn is not active");
10724
- const { content } = contentOf(params?.input);
10876
+ const { content } = contentOf(resolveInput(params?.input, notify));
10725
10877
  const operation = (async () => {
10726
10878
  if ((await service().prompt({
10727
10879
  requestId: randomUUID(),
@@ -10762,15 +10914,24 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10762
10914
  }),
10763
10915
  "thread/queue/add": async (params, { notify }) => {
10764
10916
  if (!Array.isArray(params?.input)) throw invalidParams("input is required");
10765
- contentOf(params.input);
10766
10917
  const id = params?.threadId;
10918
+ const clientUserMessageId = String(params.clientUserMessageId ?? randomUUID());
10919
+ const queue = queues.get(id) ?? [];
10920
+ const dispatched = active.get(id)?.queued;
10921
+ const existing = queue.find((entry) => entry.clientUserMessageId === clientUserMessageId) ?? (dispatched?.clientUserMessageId === clientUserMessageId ? dispatched : void 0);
10922
+ if (existing) {
10923
+ subscribe(id, notify);
10924
+ return { queuedSubmission: existing };
10925
+ }
10926
+ const input = resolveInput(params.input, notify);
10927
+ contentOf(input);
10767
10928
  const queued = {
10768
10929
  id: randomUUID(),
10769
- clientUserMessageId: String(params.clientUserMessageId ?? randomUUID()),
10770
- input: params.input
10930
+ clientUserMessageId,
10931
+ input
10771
10932
  };
10772
10933
  subscribe(id, notify);
10773
- queues.set(id, [...queues.get(id) ?? [], queued]);
10934
+ queues.set(id, [...queue, queued]);
10774
10935
  emit(id, "thread/queue/changed", { threadId: id });
10775
10936
  if (!active.has(id) && !starting.has(id)) await startQueuedTurn(id, notify, queued.id, {
10776
10937
  model: params.model,
@@ -11273,7 +11434,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
11273
11434
  onApproval,
11274
11435
  onQuestion,
11275
11436
  adopt,
11437
+ clearUploads: imageUploads.clear,
11276
11438
  close() {
11439
+ imageUploads.clear();
11277
11440
  realtimeVoice?.closeAll();
11278
11441
  },
11279
11442
  forget: (notify) => {
@@ -13431,6 +13594,7 @@ const DSH_SEARCH_PROVIDER_ID = "codex-subscription-dsh";
13431
13594
  function createDshSearchProvider({ resolveDshProvider, report }) {
13432
13595
  return Object.freeze({
13433
13596
  id: DSH_SEARCH_PROVIDER_ID,
13597
+ title: "DSH (Codex Subscription)",
13434
13598
  available: () => true,
13435
13599
  async ready(llmProvider) {
13436
13600
  const provider = resolveDshProvider?.();
@@ -13619,6 +13783,7 @@ function createCodexAutoSearchProvider(options) {
13619
13783
  const viaCodex = (request, signal) => options.codex.search(request, signal);
13620
13784
  return Object.freeze({
13621
13785
  id: CODEX_AUTO_SEARCH_PROVIDER_ID,
13786
+ title: "Codex Subscription (Auto)",
13622
13787
  available: () => true,
13623
13788
  async ready(llmProvider) {
13624
13789
  if (await options.codex.ready?.(llmProvider) ?? true) return true;
@@ -13660,6 +13825,7 @@ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
13660
13825
  };
13661
13826
  return Object.freeze({
13662
13827
  id: provider.id,
13828
+ title: provider.title,
13663
13829
  available: () => {
13664
13830
  try {
13665
13831
  return selected().available();
@@ -13689,9 +13855,14 @@ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
13689
13855
  *
13690
13856
  * @returns {Map|undefined} a stand-in for the web registry, or undefined when the registry is not a Map.
13691
13857
  */
13692
- function createSearchRouter({ registry, configuredId, mode, providers }) {
13858
+ function createSearchRouter({ registry, configuredId, mode, providers, enabled = () => true }) {
13693
13859
  if (!(registry instanceof Map)) return void 0;
13694
- const selected = () => {
13860
+ const selected = (id) => {
13861
+ if (!enabled()) {
13862
+ const provider = registry.get(id);
13863
+ if (!provider || !provider.available()) throw new WebError("The selected search provider is unavailable", "WEB_PROVIDER_UNAVAILABLE");
13864
+ return provider;
13865
+ }
13695
13866
  const source = mode();
13696
13867
  return source === "codex" ? providers.codex : source === "auto" ? providers.auto : providers.dsh;
13697
13868
  };
@@ -13701,10 +13872,10 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
13701
13872
  if (router === void 0) {
13702
13873
  router = Object.freeze({
13703
13874
  id,
13704
- available: () => true,
13705
- ready: (llmProvider) => selected().ready?.(llmProvider) ?? true,
13875
+ available: () => enabled() || registry.get(id)?.available() === true,
13876
+ ready: (llmProvider) => selected(id).ready?.(llmProvider) ?? true,
13706
13877
  search(request, signal) {
13707
- return selected().search(request, signal);
13878
+ return selected(id).search(request, signal);
13708
13879
  }
13709
13880
  });
13710
13881
  wrappers.set(id, router);
@@ -13714,7 +13885,7 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
13714
13885
  return new Proxy(registry, { get(target, property) {
13715
13886
  if (property === "get") return (id) => {
13716
13887
  const configured = configuredId();
13717
- return typeof id === "string" && id === configured && !OWN_IDS.has(id) ? routerFor(id) : target.get(id);
13888
+ return enabled() && typeof id === "string" && id === configured && !OWN_IDS.has(id) ? routerFor(id) : target.get(id);
13718
13889
  };
13719
13890
  const value = Reflect.get(target, property, target);
13720
13891
  return typeof value === "function" ? value.bind(target) : value;
@@ -13748,6 +13919,7 @@ function createCodexFetchProvider(options) {
13748
13919
  const fetchPage = options.fetch ?? fetch;
13749
13920
  return Object.freeze({
13750
13921
  id: CODEX_FETCH_PROVIDER_ID,
13922
+ title: "Codex Subscription",
13751
13923
  available: () => true,
13752
13924
  ready: (llmProvider) => options.allowed?.(llmProvider) === false ? false : subscriptionCredentialReady(options.readCredential),
13753
13925
  async fetch(request, signal) {
@@ -13890,6 +14062,75 @@ function configuredFetchProviderId(web, entries = [], ambient = process.env.DSH_
13890
14062
  return value ?? entry?.options?.config?.fetchProvider ?? environment;
13891
14063
  }
13892
14064
  //#endregion
14065
+ //#region src/web-provider-settings.js
14066
+ const WEB = "web";
14067
+ const subscriptionSearchIds = /* @__PURE__ */ new Set([
14068
+ CODEX_SEARCH_PROVIDER_ID,
14069
+ CODEX_AUTO_SEARCH_PROVIDER_ID,
14070
+ DSH_SEARCH_PROVIDER_ID
14071
+ ]);
14072
+ const isNativeSearch = (id) => typeof id === "string" && id !== "" && !subscriptionSearchIds.has(id);
14073
+ const isNativeFetch = (id) => typeof id === "string" && id !== "" && id !== "codex-subscription-fetch";
14074
+ function nativeDefaults(row, legacy) {
14075
+ const values = {};
14076
+ const search = row.user?.searchProvider ?? row.value?.searchProvider;
14077
+ const fetch = row.user?.fetchProvider ?? row.value?.fetchProvider;
14078
+ if (isNativeSearch(search) && search !== legacy.webSearchFallbackProvider) values.webSearchFallbackProvider = search;
14079
+ if (isNativeFetch(fetch) && fetch !== legacy.webFetchFallbackProvider) values.webFetchFallbackProvider = fetch;
14080
+ return values;
14081
+ }
14082
+ function createWebProviderSettings(ctx, settings) {
14083
+ const forms = ctx.settings;
14084
+ if (typeof ctx.web.listProviders !== "function" || typeof forms.describe !== "function") return void 0;
14085
+ const describe = () => forms.describe({ redactSecrets: true });
14086
+ const web = () => describe().find((row) => row.ns === WEB);
14087
+ const nativeSearch = () => {
14088
+ const { value, base } = web() ?? {};
14089
+ return [
14090
+ value?.searchProvider,
14091
+ settings.get().webSearchFallbackProvider,
14092
+ base?.searchProvider
14093
+ ].find(isNativeSearch);
14094
+ };
14095
+ const managed = () => settings.get().webProvidersManagedByDsh === true;
14096
+ async function remember() {
14097
+ if (!managed() || forms.writable !== true) return;
14098
+ const rows = describe();
14099
+ const web = rows.find((row) => row.ns === WEB);
14100
+ const plugin = rows.find((row) => row.ns === settings.id);
14101
+ if (!web || !plugin) return;
14102
+ const patch = nativeDefaults(web, settings.get());
14103
+ if (Object.keys(patch).length) await settings.update(patch, plugin.revision);
14104
+ }
14105
+ async function migrate() {
14106
+ if (managed() || forms.writable !== true) return;
14107
+ const rows = describe();
14108
+ const web = rows.find((row) => row.ns === WEB);
14109
+ const plugin = rows.find((row) => row.ns === settings.id);
14110
+ if (!web || !plugin) return;
14111
+ const currentSearch = web.value?.searchProvider;
14112
+ const currentFetch = web.value?.fetchProvider;
14113
+ const legacy = settings.get();
14114
+ const patch = {};
14115
+ if (Object.keys(plugin.user ?? {}).length && currentSearch && !subscriptionSearchIds.has(currentSearch)) {
14116
+ if (legacy.searchProvider === "codex") patch.searchProvider = CODEX_SEARCH_PROVIDER_ID;
14117
+ if (legacy.searchProvider === "auto") patch.searchProvider = CODEX_AUTO_SEARCH_PROVIDER_ID;
14118
+ }
14119
+ if (legacy.fetchProvider === "codex" && currentFetch !== "codex-subscription-fetch") patch.fetchProvider = CODEX_FETCH_PROVIDER_ID;
14120
+ const previous = nativeDefaults(web, legacy);
14121
+ if (Object.keys(previous).length) await settings.update(previous, plugin.revision);
14122
+ if (Object.keys(patch).length) await forms.update(WEB, patch, web.revision);
14123
+ const currentPlugin = describe().find((row) => row.ns === settings.id);
14124
+ if (currentPlugin) await settings.update({ webProvidersManagedByDsh: true }, currentPlugin.revision);
14125
+ }
14126
+ return {
14127
+ managed,
14128
+ migrate,
14129
+ nativeSearch,
14130
+ remember
14131
+ };
14132
+ }
14133
+ //#endregion
13893
14134
  //#region src/image-tool-registration.js
13894
14135
  /** Removing the tool also removes its schema from subsequent model requests. */
13895
14136
  function watchImageTool(settings, register) {
@@ -17998,6 +18239,9 @@ function createSearchProviderSwitcher(loader) {
17998
18239
  });
17999
18240
  }
18000
18241
  const settingsFields = {
18242
+ webProvidersManagedByDsh: z.boolean().default(false),
18243
+ webSearchFallbackProvider: z.string(),
18244
+ webFetchFallbackProvider: z.string(),
18001
18245
  [DISABLED_MODELS_FIELD]: z.transform(z.array(z.string()).max(100), normalizeDisabledModels).default([]),
18002
18246
  [AUTO_QUOTA_RETRY_FIELD]: z.boolean().default(false),
18003
18247
  subagentDefaultModel: z.transform(z.string().max(80), normalizeSubagentModel).default(""),
@@ -18025,6 +18269,8 @@ const Config = z.object(Object.fromEntries(Object.entries(settingsFields).map(([
18025
18269
  function apply(ctx, config = {}) {
18026
18270
  const settings = createSettingsAdapter(ctx, config);
18027
18271
  const searchProvider = createSearchProviderSwitcher(ctx.loader);
18272
+ const webSettings = createWebProviderSettings(ctx, settings);
18273
+ const nativeWebSettings = () => webSettings?.managed() === true;
18028
18274
  if (!process.env.NODE_TEST_CONTEXT) diagnosticLog.attach(dshHomePath("state", "codex-subscription", "diagnostic-log.jsonl"));
18029
18275
  diagnosticLog.info("plugin", `loaded ${PACKAGE_VERSION}`, `DSH ${hostDshVersion() ?? "unknown"}, node ${process.version}, ${process.platform}`);
18030
18276
  setAuthFailureLogger((message, detail) => diagnosticLog.error("auth", message, detail));
@@ -18176,6 +18422,11 @@ function apply(ctx, config = {}) {
18176
18422
  [QUICK_QUOTA_MODE_FIELD]: normalizeQuickQuotaMode(settings.get()[QUICK_QUOTA_MODE_FIELD], settings.get()[LEGACY_QUICK_QUOTA_FIELD]),
18177
18423
  [SEARCH_PROVIDER_FIELD]: settings.get()[SEARCH_PROVIDER_FIELD],
18178
18424
  [FETCH_PROVIDER_FIELD]: normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]),
18425
+ ...nativeWebSettings() ? {
18426
+ webProvidersManagedByDsh: true,
18427
+ webSearchFallbackProvider: settings.get().webSearchFallbackProvider,
18428
+ webFetchFallbackProvider: settings.get().webFetchFallbackProvider
18429
+ } : {},
18179
18430
  fetchRoutingAvailable: fetchRouted,
18180
18431
  [SPEED_MODE_FIELD]: settings.get()[SPEED_MODE_FIELD],
18181
18432
  [OUTPUT_VERBOSITY_FIELD]: normalizeOutputVerbosity(settings.get()[OUTPUT_VERBOSITY_FIELD]),
@@ -18205,6 +18456,7 @@ function apply(ctx, config = {}) {
18205
18456
  },
18206
18457
  update: async (patch) => {
18207
18458
  if (patch.subagentDefaultModel && !subagentDefaults.list().some((model) => model.id === patch.subagentDefaultModel)) throw new Error("Codex subtask model is unavailable or disallowed");
18459
+ if (nativeWebSettings() && (Object.hasOwn(patch, "searchProvider") || Object.hasOwn(patch, "fetchProvider"))) throw new Error("Select the provider in DSH Web Search and Fetch settings");
18208
18460
  if (patch["fetchProvider"] === "codex" && !fetchRouted) throw new Error("This DSH version does not support Codex webpage reading");
18209
18461
  if (Object.hasOwn(patch, "subagentBackend")) {
18210
18462
  if (!subagentBackend) throw new Error("DSH subagent services are unavailable");
@@ -18419,7 +18671,7 @@ function apply(ctx, config = {}) {
18419
18671
  }, "codex-subscription: official model catalog");
18420
18672
  const currentAgent = () => ctx.get?.("agents")?.currentInitiator?.();
18421
18673
  const codexFetch = createCodexFetchProvider({
18422
- allowed: (llmProvider) => fetchRouted && (settings.get().otherModels !== "off" || (llmProvider ?? currentAgent()?.session.requestContext?.()?.provider) === PROVIDER),
18674
+ allowed: (llmProvider) => (nativeWebSettings() || fetchRouted) && (settings.get().otherModels !== "off" || (llmProvider ?? currentAgent()?.session.requestContext?.()?.provider) === PROVIDER),
18423
18675
  getAuth: resolveAuth,
18424
18676
  readCredential: (options) => store.read(PROVIDER, options),
18425
18677
  resolveModel: () => {
@@ -18432,15 +18684,16 @@ function apply(ctx, config = {}) {
18432
18684
  const realFetchProviders = ctx.web.fetchProviders;
18433
18685
  ctx.web.registerFetchProvider?.({
18434
18686
  ...codexFetch,
18435
- available: () => fetchRouted && normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex"
18687
+ available: () => nativeWebSettings() ? configuredFetchProviderId(ctx.web, ctx.loader.entries()) === codexFetch.id : fetchRouted && normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex"
18436
18688
  });
18437
18689
  ctx.effect(() => {
18690
+ if (nativeWebSettings()) return void 0;
18438
18691
  const web = ctx.web;
18439
18692
  const configuredId = () => configuredFetchProviderId(web, ctx.loader.entries());
18440
18693
  const router = createCodexFetchRouter({
18441
18694
  registry: realFetchProviders,
18442
18695
  configuredId,
18443
- mode: () => fetchRouted ? normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]) : "dsh",
18696
+ mode: () => fetchRouted && !nativeWebSettings() ? normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]) : "dsh",
18444
18697
  codex: codexFetch
18445
18698
  });
18446
18699
  if (router !== void 0) {
@@ -18469,7 +18722,7 @@ function apply(ctx, config = {}) {
18469
18722
  return provider === void 0 || provider === PROVIDER;
18470
18723
  };
18471
18724
  const realSearchProviders = ctx.web.searchProviders;
18472
- const resolveDshSearch = () => realSearchProviders?.get(searchProvider.dshProviderId());
18725
+ const resolveDshSearch = () => realSearchProviders?.get(nativeWebSettings() ? webSettings.nativeSearch() ?? DSH_SEARCH_PROVIDER_FALLBACK : searchProvider.dshProviderId());
18473
18726
  const gateSearch = (provider) => gateSearchProvider(provider, {
18474
18727
  allowed: (llmProvider) => settings.get().otherModels !== "off" || (llmProvider ?? currentAgent()?.session.requestContext?.()?.provider) === PROVIDER,
18475
18728
  resolveDshProvider: resolveDshSearch
@@ -18488,6 +18741,7 @@ function apply(ctx, config = {}) {
18488
18741
  const searchTrace = (route) => diagnosticLog.info("search", `web search: ${route}`);
18489
18742
  const tracedCodexSearch = gateSearch({
18490
18743
  id: codexSearch.id,
18744
+ title: "Codex Subscription",
18491
18745
  available: () => codexSearch.available(),
18492
18746
  ready: (llmProvider) => codexSearch.ready(llmProvider),
18493
18747
  async search(request, signal) {
@@ -18510,11 +18764,13 @@ function apply(ctx, config = {}) {
18510
18764
  ctx.web.registerSearchProvider(autoSearch);
18511
18765
  let searchRouted = false;
18512
18766
  ctx.effect(() => {
18767
+ if (nativeWebSettings()) return void 0;
18513
18768
  const web = ctx.web;
18514
18769
  const router = createSearchRouter({
18515
18770
  registry: realSearchProviders,
18516
18771
  configuredId: () => searchProvider.current(),
18517
18772
  mode: () => settings.get()[SEARCH_PROVIDER_FIELD],
18773
+ enabled: () => !nativeWebSettings(),
18518
18774
  providers: {
18519
18775
  codex: tracedCodexSearch,
18520
18776
  auto: autoSearch,
@@ -18537,6 +18793,7 @@ function apply(ctx, config = {}) {
18537
18793
  }, "codex-subscription: search router");
18538
18794
  ctx.effect(() => {
18539
18795
  const select = async (value) => {
18796
+ if (nativeWebSettings()) return;
18540
18797
  if (searchRouted) {
18541
18798
  diagnosticLog.info("search", `web search source is ${value[SEARCH_PROVIDER_FIELD]}`);
18542
18799
  return;
@@ -18552,6 +18809,27 @@ function apply(ctx, config = {}) {
18552
18809
  select(settings.get());
18553
18810
  return settings.watch(select);
18554
18811
  }, "codex-subscription: search provider selection");
18812
+ if (webSettings) ctx.effect(() => {
18813
+ let timer;
18814
+ const sync = () => {
18815
+ clearTimeout(timer);
18816
+ timer = setTimeout(() => {
18817
+ (nativeWebSettings() ? webSettings.remember() : webSettings.migrate()).catch((error) => {
18818
+ ctx.logger?.warn?.("could not sync Web Search and Fetch settings: %s", error.message);
18819
+ });
18820
+ }, 75);
18821
+ };
18822
+ const documentPath = ctx.settings.documentPath;
18823
+ if (typeof documentPath === "string") watchFile(documentPath, {
18824
+ persistent: false,
18825
+ interval: 250
18826
+ }, sync);
18827
+ sync();
18828
+ return () => {
18829
+ clearTimeout(timer);
18830
+ if (typeof documentPath === "string") unwatchFile(documentPath, sync);
18831
+ };
18832
+ }, "codex-subscription: migrate web provider settings");
18555
18833
  const auth = createCodexAuthService(authModels, store, {
18556
18834
  runLogin: (operation) => network.run("login", operation),
18557
18835
  accountVault,
@@ -18626,7 +18904,8 @@ function apply(ctx, config = {}) {
18626
18904
  base: process.env.DSH_CODEX_REMOTE_BASE || void 0,
18627
18905
  methods: remoteBridge.methods,
18628
18906
  onActive: (_client, notify) => remoteBridge.adopt(notify),
18629
- onClose: (_client, notify) => remoteBridge.forget(notify)
18907
+ onClose: (_client, notify) => remoteBridge.forget(notify),
18908
+ onStop: remoteBridge.clearUploads
18630
18909
  });
18631
18910
  ctx.on("agent/assistant-stream", ({ agent, frame }) => {
18632
18911
  try {
@@ -18824,6 +19103,7 @@ function apply(ctx, config = {}) {
18824
19103
  voicePreview,
18825
19104
  composerPredictions,
18826
19105
  onAccountChanged: () => {
19106
+ remoteBridge.clearUploads();
18827
19107
  subagentCatalog.clear();
18828
19108
  connectorsClient.clear();
18829
19109
  usageProfileReader.clear();