dsh-codex-subscription 3.2.15 → 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
  }
@@ -4828,6 +4845,7 @@ async function readSubscriptionCredentials(getAuth, readCredential, signal) {
4828
4845
  const ORIGINAL_IMAGE_CHUNK_BYTES = 4 * 1024 * 1024;
4829
4846
  const ORIGINAL_IMAGE_ID_PATTERN = /^img_[0-9a-f]{32}$/u;
4830
4847
  const GENERATED_IMAGE_MEDIA_TYPES = Object.freeze(["image/png", "image/gif"]);
4848
+ const FORK_EVENT_BATCH = 256;
4831
4849
  const positiveInteger$1 = (value) => Number.isSafeInteger(value) && value > 0;
4832
4850
  function decodeOriginalImageRef(value) {
4833
4851
  if (value === null || typeof value !== "object" || Array.isArray(value) || typeof value.assetId !== "string" || !ORIGINAL_IMAGE_ID_PATTERN.test(value.assetId) || !GENERATED_IMAGE_MEDIA_TYPES.includes(value.mediaType) || !positiveInteger$1(value.bytes) || value.bytes > 48 * 1024 * 1024 || !positiveInteger$1(value.width) || !positiveInteger$1(value.height) || typeof value.name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(value.name) || typeof value.sha256 !== "string" || !/^[0-9a-f]{64}$/u.test(value.sha256)) return void 0;
@@ -4858,22 +4876,20 @@ function inheritedOriginalImageRef(session, assetId) {
4858
4876
  const seedLength = session?.inheritedEventCount;
4859
4877
  if (!forked || !Number.isSafeInteger(seedLength) || seedLength < 0 || !ORIGINAL_IMAGE_ID_PATTERN.test(assetId)) return void 0;
4860
4878
  if (typeof session?.snapshotEvents !== "function") return void 0;
4861
- let events;
4862
4879
  try {
4863
- events = session.snapshotEvents();
4864
- } catch {
4865
- return;
4866
- }
4867
- if (!Array.isArray(events)) return void 0;
4868
- for (const event of events) {
4869
- if (!Number.isSafeInteger(event?.seq) || event.seq < 0 || event.seq >= seedLength || event.type !== "tool/result") continue;
4870
- const original = decodeImagePresentation(event.data?.meta)?.original;
4871
- if (original?.assetId === assetId) return original;
4872
- }
4880
+ for (let from = 0; from < seedLength; from += FORK_EVENT_BATCH) {
4881
+ const end = Math.min(from + FORK_EVENT_BATCH, seedLength);
4882
+ for (const event of session.snapshotEvents(from, end)) {
4883
+ if (!Number.isSafeInteger(event?.seq) || event.seq < from || event.seq >= end || event.type !== "tool/result" || event.data?.meta?.original?.assetId !== assetId) continue;
4884
+ const original = decodeImagePresentation(event.data.meta)?.original;
4885
+ if (original) return original;
4886
+ }
4887
+ }
4888
+ } catch {}
4873
4889
  }
4874
4890
  //#endregion
4875
4891
  //#region src/version.js
4876
- const PACKAGE_VERSION = "3.2.15";
4892
+ const PACKAGE_VERSION = "3.2.17";
4877
4893
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
4878
4894
  //#endregion
4879
4895
  //#region src/image-original-store.js
@@ -5586,12 +5602,13 @@ function createCodexImageTool(options) {
5586
5602
  const mediaType = animated ? "image/gif" : "image/png";
5587
5603
  if (animated) {
5588
5604
  if (editing) throw new Error("Animated GIF editing is not supported on the Codex subscription route");
5589
- const { frameCount = 6, frameDurationMs = 150 } = args.gif ?? {};
5590
- 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");
5591
5608
  imageOptions.animation = {
5592
5609
  output_format: "gif",
5593
- frame_count: frameCount,
5594
- frame_duration_ms: frameDurationMs
5610
+ ...frameCount === void 0 ? {} : { frame_count: frameCount },
5611
+ ...frameDurationMs === void 0 ? {} : { frame_duration_ms: frameDurationMs }
5595
5612
  };
5596
5613
  }
5597
5614
  const { access, accountId } = await readSubscriptionCredentials(options.getAuth, options.readCredential, exec.signal);
@@ -5982,6 +5999,8 @@ const MAX_SEEN = 128;
5982
5999
  const STREAMING = /delta$|outputDelta|tokenUsage|summaryPartAdded/u;
5983
6000
  const QUIET$1 = /* @__PURE__ */ new Set([
5984
6001
  "command/exec",
6002
+ "fs/writeFile",
6003
+ "fs/readFile",
5985
6004
  "thread/attachment/list",
5986
6005
  "thread/list",
5987
6006
  "thread/queue/list",
@@ -6117,6 +6136,12 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
6117
6136
  ask
6118
6137
  };
6119
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
+ };
6120
6145
  const reply = async (id, result) => {
6121
6146
  await client.send({
6122
6147
  id,
@@ -6145,7 +6170,10 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
6145
6170
  const { id, method, params } = message;
6146
6171
  if (id === void 0) {
6147
6172
  note("notify", method);
6148
- if (method === "initialized") initialized = true;
6173
+ if (method === "initialized") {
6174
+ initialized = true;
6175
+ markActive();
6176
+ }
6149
6177
  notifications[method]?.(params, {
6150
6178
  ...context,
6151
6179
  signal: new AbortController().signal
@@ -6164,10 +6192,7 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
6164
6192
  ...logged,
6165
6193
  hasClientId: typeof params?.clientUserMessageId === "string"
6166
6194
  });
6167
- if (!active && method !== "initialize") {
6168
- active = true;
6169
- onActive?.(client, notify);
6170
- }
6195
+ if (method !== "initialize") markActive();
6171
6196
  if (debug && !QUIET$1.has(method)) record({
6172
6197
  method: `request:${method}`,
6173
6198
  params: JSON.stringify(params ?? null).slice(0, /realtime/u.test(method) ? 8e3 : 700)
@@ -6178,7 +6203,7 @@ function createRemoteControlHost({ methods, notifications = {}, onConnection, on
6178
6203
  ...logged,
6179
6204
  code: METHOD_NOT_FOUND
6180
6205
  }, "warn");
6181
- record({
6206
+ if (!QUIET$1.has(method)) record({
6182
6207
  method,
6183
6208
  missing: true,
6184
6209
  params: JSON.stringify(params ?? null).slice(0, /realtime/u.test(method) ? 8e3 : 600)
@@ -6950,13 +6975,13 @@ async function writeInstallation(filename, state) {
6950
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
6951
6976
  */
6952
6977
  function createRemoteControl(options) {
6953
- const phones = /* @__PURE__ */ new Set();
6978
+ const phones = /* @__PURE__ */ new Map();
6954
6979
  const host = createRemoteControlHost({
6955
6980
  methods: options.methods,
6956
6981
  notifications: options.notifications,
6957
6982
  onConnection: options.onConnection,
6958
6983
  onActive: (client, notify) => {
6959
- phones.add(client.id);
6984
+ phones.set(client.id, client.clientId ?? client.id);
6960
6985
  options.onActive?.(client, notify);
6961
6986
  },
6962
6987
  onClose: (client, notify) => {
@@ -7015,7 +7040,11 @@ function createRemoteControl(options) {
7015
7040
  },
7016
7041
  async disable() {
7017
7042
  enabled = false;
7018
- if (relay) await relay.stop();
7043
+ try {
7044
+ if (relay) await relay.stop();
7045
+ } finally {
7046
+ options.onStop?.();
7047
+ }
7019
7048
  return this.status();
7020
7049
  },
7021
7050
  async pair(signal) {
@@ -7039,7 +7068,7 @@ function createRemoteControl(options) {
7039
7068
  clients: 0,
7040
7069
  reconnects: 0
7041
7070
  },
7042
- phones: phones.size,
7071
+ phones: new Set(phones.values()).size,
7043
7072
  methods: host.seen(),
7044
7073
  trace: host.trace()
7045
7074
  };
@@ -8677,7 +8706,129 @@ function withRemoteImageOutput(turn) {
8677
8706
  };
8678
8707
  }
8679
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
8680
8812
  //#region src/remote-control-dsh.js
8813
+ const SESSION_EVENT_BATCH = 256;
8814
+ const RESUME_TURN_LIMIT = 5;
8815
+ function latestDirectory(events) {
8816
+ for (let i = events.length - 1; i >= 0; i--) {
8817
+ const event = events[i];
8818
+ if (event?.type === "working-directory/change" && typeof event.data?.cwd === "string" && event.data.cwd) return event.data.cwd;
8819
+ }
8820
+ }
8821
+ function foldSessionDetails(details, events) {
8822
+ for (const event of events) {
8823
+ const data = event?.data;
8824
+ if (event?.type === "model/selection" && data?.provider && data?.model) details.model = {
8825
+ provider: data.provider,
8826
+ model: data.model,
8827
+ reasoningEffort: data.reasoningEffort
8828
+ };
8829
+ if (event?.type === "working-directory/change" && typeof data?.cwd === "string" && data.cwd) details.cwd = data.cwd;
8830
+ }
8831
+ }
8681
8832
  /** A folder the phone named, only when it is an existing absolute folder on this machine. */
8682
8833
  function localFolder(value) {
8683
8834
  if (typeof value !== "string" || value === "" || !isAbsolute(value)) return void 0;
@@ -8974,6 +9125,30 @@ const toolOutput = (message, imageUrls, imageAssets) => [{
8974
9125
  /** One user message starts a turn; assistant blocks and tool results fill it. */
8975
9126
  /** Images the person attached to a message of their own. */
8976
9127
  const typedImages = (message) => message.role === "user" && (message.source === void 0 || message.source?.kind === "user") ? (message.content ?? []).filter((block) => block?.type === "image" && block.attachment) : [];
9128
+ function recentTurnMessages(session, limit) {
9129
+ const nodes = session.surface?.nodes;
9130
+ const useSurface = Array.isArray(nodes) && typeof session.deriveEventMessage === "function" && typeof session.snapshotEvents === "function";
9131
+ const list = useSurface ? nodes : session.deriveMessages();
9132
+ const recent = [];
9133
+ let turns = 0;
9134
+ let oldestStart = 0;
9135
+ for (let index = list.length - 1; index >= 0; index--) {
9136
+ const entry = list[index];
9137
+ const event = useSurface ? session.snapshotEvents(entry, entry + 1)[0] : void 0;
9138
+ const message = useSurface ? event && session.deriveEventMessage(event) : entry;
9139
+ if (!message) continue;
9140
+ if (typedText(message) !== "" || typedImages(message).length > 0) {
9141
+ turns++;
9142
+ if (turns > limit) {
9143
+ recent.length = oldestStart;
9144
+ break;
9145
+ }
9146
+ oldestStart = recent.length + 1;
9147
+ }
9148
+ recent.push(message);
9149
+ }
9150
+ return recent.reverse();
9151
+ }
8977
9152
  /** `imageUrls` maps an attachment id to a data URL the phone can show; images without one are left out. */
8978
9153
  function projectTurns(messages, at = Date.now(), imageUrls = /* @__PURE__ */ new Map(), cwd = void 0, imageAssets = /* @__PURE__ */ new Map(), indexOnly = false) {
8979
9154
  const turns = [];
@@ -9175,6 +9350,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9175
9350
  const active = /* @__PURE__ */ new Map();
9176
9351
  const queues = /* @__PURE__ */ new Map();
9177
9352
  const starting = /* @__PURE__ */ new Map();
9353
+ const imageUploads = createRemoteImageUploads();
9178
9354
  let catalog;
9179
9355
  const service = () => {
9180
9356
  const value = controller();
@@ -9233,35 +9409,40 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9233
9409
  return catalog;
9234
9410
  };
9235
9411
  const pickedBy = /* @__PURE__ */ new Map();
9236
- const recorded = (agent) => {
9412
+ const detailsBySession = /* @__PURE__ */ new WeakMap();
9413
+ const sessionDetails = (session) => {
9414
+ if (!session) return void 0;
9415
+ const end = session.seq;
9237
9416
  try {
9238
- const session = agent?.session;
9239
- const events = typeof session?.snapshotEvents === "function" ? session.snapshotEvents() : session?.eventsSnapshot;
9240
- for (let index = (events?.length ?? 0) - 1; index >= 0; index -= 1) {
9241
- const data = events[index]?.type === "model/selection" ? events[index].data : void 0;
9242
- if (data?.provider && data?.model) return {
9243
- provider: data.provider,
9244
- model: data.model,
9245
- reasoningEffort: data.reasoningEffort
9246
- };
9417
+ if (typeof session.snapshotEvents !== "function" || !Number.isSafeInteger(end) || end < 0) {
9418
+ const details = {};
9419
+ foldSessionDetails(details, session.eventsSnapshot ?? []);
9420
+ return details;
9247
9421
  }
9248
- } catch {}
9422
+ const prior = detailsBySession.get(session);
9423
+ if (prior?.end === end) return prior;
9424
+ const details = { ...prior?.end < end ? prior : { end: 0 } };
9425
+ while (details.end < end) {
9426
+ const next = Math.min(details.end + SESSION_EVENT_BATCH, end);
9427
+ foldSessionDetails(details, session.snapshotEvents(details.end, next));
9428
+ details.end = next;
9429
+ }
9430
+ detailsBySession.set(session, details);
9431
+ return details;
9432
+ } catch {
9433
+ return;
9434
+ }
9435
+ };
9436
+ const recorded = (agent) => {
9437
+ const model = sessionDetails(agent?.session)?.model;
9438
+ if (model) return model;
9249
9439
  return agent?.options?.provider && agent?.options?.model ? {
9250
9440
  provider: agent.options.provider,
9251
9441
  model: agent.options.model,
9252
9442
  reasoningEffort: agent.options.reasoningEffort
9253
9443
  } : void 0;
9254
9444
  };
9255
- const directoryOf = (session) => {
9256
- try {
9257
- const events = typeof session?.snapshotEvents === "function" ? session.snapshotEvents() : session?.eventsSnapshot;
9258
- for (let index = (events?.length ?? 0) - 1; index >= 0; index -= 1) {
9259
- const cwd = events[index]?.type === "working-directory/change" ? events[index].data?.cwd : void 0;
9260
- if (typeof cwd === "string" && cwd !== "") return cwd;
9261
- }
9262
- } catch {}
9263
- return session?.meta?.cwd;
9264
- };
9445
+ const directoryOf = (session) => sessionDetails(session)?.cwd ?? session?.meta?.cwd;
9265
9446
  const sameSelection = (a, b) => a?.provider === b?.provider && a?.model === b?.model && a?.reasoningEffort === b?.reasoningEffort;
9266
9447
  const selection = (agent) => {
9267
9448
  const saved = recorded(agent);
@@ -9452,12 +9633,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9452
9633
  text: writing.text
9453
9634
  }] : [];
9454
9635
  const last = turns.at(-1);
9455
- const ours = last?.items[0]?.type === "userMessage" && (last.items[0].id === live.userItem.id || !live.priorMessageIds.has(last.items[0].id) && typed(last.items[0]) === typed(live.userItem));
9636
+ const ours = live.userItem && last?.items[0]?.type === "userMessage" && (last.items[0].id === live.userItem.id || !live.priorMessageIds.has(last.items[0].id) && typed(last.items[0]) === typed(live.userItem));
9456
9637
  const items = ours ? [
9457
9638
  live.userItem,
9458
9639
  ...last.items.slice(1),
9459
9640
  ...tail
9460
- ] : [live.userItem, ...tail];
9641
+ ] : [...live.userItem ? [live.userItem] : live.turn.items, ...tail];
9461
9642
  return [...ours ? turns.slice(0, -1) : turns, {
9462
9643
  ...live.turn,
9463
9644
  items,
@@ -9516,10 +9697,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9516
9697
  const messages = source?.messages ?? session.deriveMessages();
9517
9698
  const meta = source?.meta ?? session.meta;
9518
9699
  const events = source?.events;
9519
- const cwd = directoryOf(events ? {
9520
- meta,
9521
- snapshotEvents: () => events
9522
- } : session);
9700
+ const cwd = events ? latestDirectory(events) ?? meta?.cwd : directoryOf(session);
9523
9701
  const owner = events && Object.isFrozen(events) ? events : session ?? messages;
9524
9702
  const revision = source?.cursor ?? session?.seq ?? messages;
9525
9703
  let cached = historyIndexes.get(owner);
@@ -9559,8 +9737,10 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9559
9737
  "summary",
9560
9738
  "notLoaded"
9561
9739
  ].includes(params.itemsView)) throw invalidParams("Invalid turn items view");
9562
- const id = params?.threadId;
9563
- const snapshot = await historySnapshot(id, signal);
9740
+ return renderTurnPage(params, await historySnapshot(params?.threadId, signal), signal);
9741
+ };
9742
+ const renderTurnPage = async (params, snapshot, signal) => {
9743
+ const id = params.threadId;
9564
9744
  const result = historyPage(snapshot.outline, params, JSON.stringify([id, "turns"]));
9565
9745
  const full = params?.itemsView == null || params.itemsView === "full";
9566
9746
  const data = (full ? await renderHistory(id, snapshot, result.data, signal) : result.data.map((turn) => ({
@@ -9578,6 +9758,66 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9578
9758
  data
9579
9759
  };
9580
9760
  };
9761
+ const resumePageOptions = (value) => {
9762
+ if (value == null) return void 0;
9763
+ if (typeof value !== "object" || Array.isArray(value)) throw invalidParams("Invalid initial turns page");
9764
+ const limit = value.limit ?? RESUME_TURN_LIMIT;
9765
+ const sortDirection = value.sortDirection ?? "desc";
9766
+ const itemsView = value.itemsView ?? "summary";
9767
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw invalidParams("History page limit must be between 1 and 100");
9768
+ if (!["asc", "desc"].includes(sortDirection)) throw invalidParams("Invalid history sort direction");
9769
+ if (![
9770
+ "full",
9771
+ "summary",
9772
+ "notLoaded"
9773
+ ].includes(itemsView)) throw invalidParams("Invalid turn items view");
9774
+ return {
9775
+ limit: Math.min(limit, RESUME_TURN_LIMIT),
9776
+ sortDirection,
9777
+ itemsView
9778
+ };
9779
+ };
9780
+ const resumePaginated = async (id, options, notify, signal) => {
9781
+ const value = {
9782
+ ...await readThreadMetadata(id, signal),
9783
+ historyMode: "paginated"
9784
+ };
9785
+ const agent = await agentFor(id);
9786
+ if (notify) subscribe(id, notify);
9787
+ await (catalog ? void 0 : loadCatalog().catch(() => void 0));
9788
+ signal?.throwIfAborted();
9789
+ const session = agent.session;
9790
+ const cwd = directoryOf(session) ?? value.cwd;
9791
+ const meta = session.meta;
9792
+ const messages = recentTurnMessages(session, (options?.limit ?? 1) + 1);
9793
+ const live = active.get(id);
9794
+ if (live?.userItem) for (const message of messages) reconcileUser(id, live, message);
9795
+ const ranges = historyIndex(messages, projectTurns(messages, meta?.createdAt, /* @__PURE__ */ new Map(), cwd, /* @__PURE__ */ new Map(), true));
9796
+ const outline = withLiveTurn(id, ranges);
9797
+ const last = outline.at(-1);
9798
+ const lastItem = last?.items.at(-1);
9799
+ const itemAnchors = lastItem ? [{ id: JSON.stringify([last.id, lastItem.id]) }] : [];
9800
+ const initialTurnsPage = options ? await renderTurnPage({
9801
+ ...options,
9802
+ threadId: id
9803
+ }, options.sortDirection === "asc" ? await historySnapshot(id, signal) : {
9804
+ meta,
9805
+ messages,
9806
+ cwd,
9807
+ ranges,
9808
+ outline
9809
+ }, signal) : null;
9810
+ return {
9811
+ ...settings(agent, cwd),
9812
+ thread: {
9813
+ ...value,
9814
+ cwd
9815
+ },
9816
+ initialTurnsPage,
9817
+ turnsBackwardsCursor: initialHistoryCursor(outline, JSON.stringify([id, "turns"])),
9818
+ itemsBackwardsCursor: initialHistoryCursor(itemAnchors, JSON.stringify([id, "items"]))
9819
+ };
9820
+ };
9581
9821
  const listHistoryItems = async (params, signal) => {
9582
9822
  const id = params?.threadId;
9583
9823
  if (params?.turnId != null && (typeof params.turnId !== "string" || params.turnId === "")) throw invalidParams("turnId must be nonempty");
@@ -9761,7 +10001,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9761
10001
  completedAt: null
9762
10002
  } };
9763
10003
  };
9764
- /** 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;
9765
10006
  const contentOf = (input) => {
9766
10007
  const text = [...skillGestures(input), inputText(input)].filter(Boolean).join(" ");
9767
10008
  const pictures = inputImages(input);
@@ -9815,7 +10056,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9815
10056
  }, notify, queued);
9816
10057
  }
9817
10058
  async function acceptTurn(params, notify, launch) {
9818
- const { text, pictures, content } = contentOf(params?.input);
10059
+ const { text, pictures, content } = contentOf(resolveInput(params?.input, notify));
9819
10060
  lastPrompt.text = text;
9820
10061
  const id = params?.threadId;
9821
10062
  const agent = await agentFor(id);
@@ -9855,6 +10096,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9855
10096
  turn,
9856
10097
  ended: void 0,
9857
10098
  userItem,
10099
+ queued: launch.queued,
9858
10100
  priorMessageIds: new Set(agent.session.deriveMessages().map((message) => message.id)),
9859
10101
  pendingImages: /* @__PURE__ */ new Set(),
9860
10102
  pendingSteers: /* @__PURE__ */ new Set(),
@@ -10243,7 +10485,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10243
10485
  marketplaces: []
10244
10486
  }),
10245
10487
  "fs/createDirectory": () => ({}),
10246
- "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) ?? {
10247
10494
  isDirectory: true,
10248
10495
  isFile: false,
10249
10496
  isSymlink: false,
@@ -10481,23 +10728,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10481
10728
  historyMode: "paginated"
10482
10729
  } : (await openThread(params?.threadId, void 0, signal)).thread }),
10483
10730
  "thread/resume": async (params, { notify, signal }) => {
10484
- if (params?.excludeTurns === true) {
10485
- const value = {
10486
- ...await readThreadMetadata(params?.threadId, signal),
10487
- historyMode: "paginated"
10488
- };
10489
- const snapshot = await historySnapshot(params.threadId, signal);
10490
- const agent = await agentFor(params.threadId);
10491
- if (notify) subscribe(params.threadId, notify);
10492
- await (catalog ? void 0 : loadCatalog().catch(() => void 0));
10493
- const itemAnchors = snapshot.outline.flatMap((turn) => turn.items.map((item) => ({ id: JSON.stringify([turn.id, item.id]) })));
10494
- return {
10495
- ...settings(agent, value.cwd),
10496
- thread: value,
10497
- turnsBackwardsCursor: initialHistoryCursor(snapshot.outline, JSON.stringify([params.threadId, "turns"])),
10498
- itemsBackwardsCursor: initialHistoryCursor(itemAnchors, JSON.stringify([params.threadId, "items"]))
10499
- };
10500
- }
10731
+ const options = resumePageOptions(params?.initialTurnsPage);
10732
+ if (options || params?.excludeTurns === true) return resumePaginated(params?.threadId, options, notify, signal);
10501
10733
  const { agent, thread: value } = await openThread(params?.threadId, notify, signal);
10502
10734
  return {
10503
10735
  ...settings(agent, value.cwd),
@@ -10535,9 +10767,15 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10535
10767
  },
10536
10768
  "turn/start": (params, { notify }) => titles.has(params?.threadId) ? titleTurn(params, notify) : startTurn(params, notify),
10537
10769
  "turn/interrupt": (params) => {
10538
- active.get(params?.threadId)?.abort?.abort();
10539
- starting.get(params?.threadId)?.abort.abort();
10540
- 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();
10541
10779
  return {};
10542
10780
  },
10543
10781
  "thread/compact/start": async (params, { notify }) => {
@@ -10549,11 +10787,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10549
10787
  subscribe(id, notify);
10550
10788
  const turn = emptyTurn();
10551
10789
  const abort = new AbortController();
10552
- active.set(id, {
10790
+ const running = {
10553
10791
  turn,
10554
10792
  ended: void 0,
10555
10793
  abort
10556
- });
10794
+ };
10795
+ active.set(id, running);
10557
10796
  emit(id, "turn/started", {
10558
10797
  threadId: id,
10559
10798
  turn
@@ -10567,7 +10806,10 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10567
10806
  });
10568
10807
  (async () => {
10569
10808
  try {
10570
- 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;
10571
10813
  if (result?.kind === "error") throw new Error(result.text || "Compaction failed");
10572
10814
  if (result?.sourceEventSeq !== void 0 && turn.items.length === 0) {
10573
10815
  const item = {
@@ -10590,6 +10832,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10590
10832
  }
10591
10833
  turn.status = "completed";
10592
10834
  } catch (error) {
10835
+ if (active.get(id) !== running) return;
10593
10836
  turn.status = abort.signal.aborted ? "interrupted" : "failed";
10594
10837
  if (turn.status === "failed") {
10595
10838
  turn.error = {
@@ -10625,12 +10868,12 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10625
10868
  })();
10626
10869
  return {};
10627
10870
  },
10628
- "turn/steer": async (params, { signal } = {}) => {
10871
+ "turn/steer": async (params, { signal, notify } = {}) => {
10629
10872
  const running = active.get(params?.threadId);
10630
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;
10631
10874
  signal?.throwIfAborted();
10632
10875
  if (!current()) throw invalidParams("The expected turn is not active");
10633
- const { content } = contentOf(params?.input);
10876
+ const { content } = contentOf(resolveInput(params?.input, notify));
10634
10877
  const operation = (async () => {
10635
10878
  if ((await service().prompt({
10636
10879
  requestId: randomUUID(),
@@ -10671,15 +10914,24 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10671
10914
  }),
10672
10915
  "thread/queue/add": async (params, { notify }) => {
10673
10916
  if (!Array.isArray(params?.input)) throw invalidParams("input is required");
10674
- contentOf(params.input);
10675
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);
10676
10928
  const queued = {
10677
10929
  id: randomUUID(),
10678
- clientUserMessageId: String(params.clientUserMessageId ?? randomUUID()),
10679
- input: params.input
10930
+ clientUserMessageId,
10931
+ input
10680
10932
  };
10681
10933
  subscribe(id, notify);
10682
- queues.set(id, [...queues.get(id) ?? [], queued]);
10934
+ queues.set(id, [...queue, queued]);
10683
10935
  emit(id, "thread/queue/changed", { threadId: id });
10684
10936
  if (!active.has(id) && !starting.has(id)) await startQueuedTurn(id, notify, queued.id, {
10685
10937
  model: params.model,
@@ -11182,7 +11434,9 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
11182
11434
  onApproval,
11183
11435
  onQuestion,
11184
11436
  adopt,
11437
+ clearUploads: imageUploads.clear,
11185
11438
  close() {
11439
+ imageUploads.clear();
11186
11440
  realtimeVoice?.closeAll();
11187
11441
  },
11188
11442
  forget: (notify) => {
@@ -13340,6 +13594,7 @@ const DSH_SEARCH_PROVIDER_ID = "codex-subscription-dsh";
13340
13594
  function createDshSearchProvider({ resolveDshProvider, report }) {
13341
13595
  return Object.freeze({
13342
13596
  id: DSH_SEARCH_PROVIDER_ID,
13597
+ title: "DSH (Codex Subscription)",
13343
13598
  available: () => true,
13344
13599
  async ready(llmProvider) {
13345
13600
  const provider = resolveDshProvider?.();
@@ -13528,6 +13783,7 @@ function createCodexAutoSearchProvider(options) {
13528
13783
  const viaCodex = (request, signal) => options.codex.search(request, signal);
13529
13784
  return Object.freeze({
13530
13785
  id: CODEX_AUTO_SEARCH_PROVIDER_ID,
13786
+ title: "Codex Subscription (Auto)",
13531
13787
  available: () => true,
13532
13788
  async ready(llmProvider) {
13533
13789
  if (await options.codex.ready?.(llmProvider) ?? true) return true;
@@ -13569,6 +13825,7 @@ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
13569
13825
  };
13570
13826
  return Object.freeze({
13571
13827
  id: provider.id,
13828
+ title: provider.title,
13572
13829
  available: () => {
13573
13830
  try {
13574
13831
  return selected().available();
@@ -13598,9 +13855,14 @@ function gateSearchProvider(provider, { allowed, resolveDshProvider }) {
13598
13855
  *
13599
13856
  * @returns {Map|undefined} a stand-in for the web registry, or undefined when the registry is not a Map.
13600
13857
  */
13601
- function createSearchRouter({ registry, configuredId, mode, providers }) {
13858
+ function createSearchRouter({ registry, configuredId, mode, providers, enabled = () => true }) {
13602
13859
  if (!(registry instanceof Map)) return void 0;
13603
- 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
+ }
13604
13866
  const source = mode();
13605
13867
  return source === "codex" ? providers.codex : source === "auto" ? providers.auto : providers.dsh;
13606
13868
  };
@@ -13610,10 +13872,10 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
13610
13872
  if (router === void 0) {
13611
13873
  router = Object.freeze({
13612
13874
  id,
13613
- available: () => true,
13614
- ready: (llmProvider) => selected().ready?.(llmProvider) ?? true,
13875
+ available: () => enabled() || registry.get(id)?.available() === true,
13876
+ ready: (llmProvider) => selected(id).ready?.(llmProvider) ?? true,
13615
13877
  search(request, signal) {
13616
- return selected().search(request, signal);
13878
+ return selected(id).search(request, signal);
13617
13879
  }
13618
13880
  });
13619
13881
  wrappers.set(id, router);
@@ -13623,7 +13885,7 @@ function createSearchRouter({ registry, configuredId, mode, providers }) {
13623
13885
  return new Proxy(registry, { get(target, property) {
13624
13886
  if (property === "get") return (id) => {
13625
13887
  const configured = configuredId();
13626
- 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);
13627
13889
  };
13628
13890
  const value = Reflect.get(target, property, target);
13629
13891
  return typeof value === "function" ? value.bind(target) : value;
@@ -13647,11 +13909,17 @@ const httpUrl = (value) => {
13647
13909
  return;
13648
13910
  }
13649
13911
  };
13912
+ function markdownFormatHint(url) {
13913
+ const parsed = new URL(url);
13914
+ const values = parsed.searchParams.getAll("accept");
13915
+ return parsed.hostname === "learn.microsoft.com" && values.length === 1 && values[0] === "text/markdown" ? "Codex could not open the Microsoft Learn Markdown URL. Remove only the accept=text/markdown parameter and try again." : void 0;
13916
+ }
13650
13917
  /** Read public page text through Codex commands.open; never call another provider. */
13651
13918
  function createCodexFetchProvider(options) {
13652
13919
  const fetchPage = options.fetch ?? fetch;
13653
13920
  return Object.freeze({
13654
13921
  id: CODEX_FETCH_PROVIDER_ID,
13922
+ title: "Codex Subscription",
13655
13923
  available: () => true,
13656
13924
  ready: (llmProvider) => options.allowed?.(llmProvider) === false ? false : subscriptionCredentialReady(options.readCredential),
13657
13925
  async fetch(request, signal) {
@@ -13710,8 +13978,12 @@ function createCodexFetchProvider(options) {
13710
13978
  }
13711
13979
  throw new WebError(authFailure ?? `Codex webpage request failed (HTTP ${response.status})`, authFailure === "ChatGPT sign-in needs to be renewed" ? "WEB_PROVIDER_CREDENTIAL_MISSING" : "WEB_PROVIDER_ERROR");
13712
13980
  }
13713
- const value = await response.json();
13981
+ const value = await response.json().catch(() => void 0);
13714
13982
  activeSignal.throwIfAborted();
13983
+ if (value === void 0) {
13984
+ diagnosticLog.warn("fetch", "Codex webpage response could not be parsed", "invalid-response");
13985
+ throw new WebError("Codex returned an unreadable webpage response", "WEB_PROVIDER_ERROR");
13986
+ }
13715
13987
  const source = Array.isArray(value?.results) ? value.results.find((item) => httpUrl(item?.url) !== void 0 && item?.type !== "error" && item?.title !== "Internal Error") : void 0;
13716
13988
  const output = typeof value?.output === "string" ? value.output : "";
13717
13989
  const heading = output.split(/\r?\n/u, 1)[0].trim();
@@ -13726,8 +13998,11 @@ function createCodexFetchProvider(options) {
13726
13998
  continue;
13727
13999
  }
13728
14000
  const upstreamTimeout = internalError && /(?:^|\n)Failed to fetch [^\n]*:\s*\(\d+\)\s*Timeout fetching/iu.test(output);
13729
- diagnosticLog.warn("fetch", "Codex webpage text unavailable", upstreamTimeout ? "upstream-timeout" : internalError ? "upstream-error" : !pageUrl ? "missing-source" : "empty-output");
14001
+ const inaccessible = internalError && /^URL(?: https?:\/\/\S+)? is not accessible via this tool\./imu.test(output);
14002
+ diagnosticLog.warn("fetch", "Codex webpage text unavailable", upstreamTimeout ? "upstream-timeout" : inaccessible ? "upstream-inaccessible" : internalError ? "upstream-error" : !output.trim() ? "empty-output" : headingUrl ? "invalid-source-metadata" : "missing-source");
13730
14003
  if (upstreamTimeout) throw new WebError("Codex webpage service timed out fetching this page. Try another page, or change the webpage provider in settings.", "WEB_FETCH_TIMEOUT");
14004
+ const hint = inaccessible && !/not safe|blocked|robots|forbidden|access denied/iu.test(output) ? markdownFormatHint(url) : void 0;
14005
+ if (hint) throw new WebError(hint, "WEB_PROVIDER_ERROR");
13731
14006
  throw new WebError("Codex could not read this webpage. Try another page, or change the webpage provider in settings.", "WEB_PROVIDER_ERROR");
13732
14007
  }
13733
14008
  const lineCount = Number(metadata.match(/Total lines: (\d+)/u)?.[1]);
@@ -13787,6 +14062,75 @@ function configuredFetchProviderId(web, entries = [], ambient = process.env.DSH_
13787
14062
  return value ?? entry?.options?.config?.fetchProvider ?? environment;
13788
14063
  }
13789
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
13790
14134
  //#region src/image-tool-registration.js
13791
14135
  /** Removing the tool also removes its schema from subsequent model requests. */
13792
14136
  function watchImageTool(settings, register) {
@@ -17895,6 +18239,9 @@ function createSearchProviderSwitcher(loader) {
17895
18239
  });
17896
18240
  }
17897
18241
  const settingsFields = {
18242
+ webProvidersManagedByDsh: z.boolean().default(false),
18243
+ webSearchFallbackProvider: z.string(),
18244
+ webFetchFallbackProvider: z.string(),
17898
18245
  [DISABLED_MODELS_FIELD]: z.transform(z.array(z.string()).max(100), normalizeDisabledModels).default([]),
17899
18246
  [AUTO_QUOTA_RETRY_FIELD]: z.boolean().default(false),
17900
18247
  subagentDefaultModel: z.transform(z.string().max(80), normalizeSubagentModel).default(""),
@@ -17922,6 +18269,8 @@ const Config = z.object(Object.fromEntries(Object.entries(settingsFields).map(([
17922
18269
  function apply(ctx, config = {}) {
17923
18270
  const settings = createSettingsAdapter(ctx, config);
17924
18271
  const searchProvider = createSearchProviderSwitcher(ctx.loader);
18272
+ const webSettings = createWebProviderSettings(ctx, settings);
18273
+ const nativeWebSettings = () => webSettings?.managed() === true;
17925
18274
  if (!process.env.NODE_TEST_CONTEXT) diagnosticLog.attach(dshHomePath("state", "codex-subscription", "diagnostic-log.jsonl"));
17926
18275
  diagnosticLog.info("plugin", `loaded ${PACKAGE_VERSION}`, `DSH ${hostDshVersion() ?? "unknown"}, node ${process.version}, ${process.platform}`);
17927
18276
  setAuthFailureLogger((message, detail) => diagnosticLog.error("auth", message, detail));
@@ -18073,6 +18422,11 @@ function apply(ctx, config = {}) {
18073
18422
  [QUICK_QUOTA_MODE_FIELD]: normalizeQuickQuotaMode(settings.get()[QUICK_QUOTA_MODE_FIELD], settings.get()[LEGACY_QUICK_QUOTA_FIELD]),
18074
18423
  [SEARCH_PROVIDER_FIELD]: settings.get()[SEARCH_PROVIDER_FIELD],
18075
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
+ } : {},
18076
18430
  fetchRoutingAvailable: fetchRouted,
18077
18431
  [SPEED_MODE_FIELD]: settings.get()[SPEED_MODE_FIELD],
18078
18432
  [OUTPUT_VERBOSITY_FIELD]: normalizeOutputVerbosity(settings.get()[OUTPUT_VERBOSITY_FIELD]),
@@ -18102,6 +18456,7 @@ function apply(ctx, config = {}) {
18102
18456
  },
18103
18457
  update: async (patch) => {
18104
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");
18105
18460
  if (patch["fetchProvider"] === "codex" && !fetchRouted) throw new Error("This DSH version does not support Codex webpage reading");
18106
18461
  if (Object.hasOwn(patch, "subagentBackend")) {
18107
18462
  if (!subagentBackend) throw new Error("DSH subagent services are unavailable");
@@ -18316,7 +18671,7 @@ function apply(ctx, config = {}) {
18316
18671
  }, "codex-subscription: official model catalog");
18317
18672
  const currentAgent = () => ctx.get?.("agents")?.currentInitiator?.();
18318
18673
  const codexFetch = createCodexFetchProvider({
18319
- 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),
18320
18675
  getAuth: resolveAuth,
18321
18676
  readCredential: (options) => store.read(PROVIDER, options),
18322
18677
  resolveModel: () => {
@@ -18329,15 +18684,16 @@ function apply(ctx, config = {}) {
18329
18684
  const realFetchProviders = ctx.web.fetchProviders;
18330
18685
  ctx.web.registerFetchProvider?.({
18331
18686
  ...codexFetch,
18332
- available: () => fetchRouted && normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex"
18687
+ available: () => nativeWebSettings() ? configuredFetchProviderId(ctx.web, ctx.loader.entries()) === codexFetch.id : fetchRouted && normalizeFetchProvider(settings.get()["fetchProvider"]) === "codex"
18333
18688
  });
18334
18689
  ctx.effect(() => {
18690
+ if (nativeWebSettings()) return void 0;
18335
18691
  const web = ctx.web;
18336
18692
  const configuredId = () => configuredFetchProviderId(web, ctx.loader.entries());
18337
18693
  const router = createCodexFetchRouter({
18338
18694
  registry: realFetchProviders,
18339
18695
  configuredId,
18340
- mode: () => fetchRouted ? normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]) : "dsh",
18696
+ mode: () => fetchRouted && !nativeWebSettings() ? normalizeFetchProvider(settings.get()[FETCH_PROVIDER_FIELD]) : "dsh",
18341
18697
  codex: codexFetch
18342
18698
  });
18343
18699
  if (router !== void 0) {
@@ -18366,7 +18722,7 @@ function apply(ctx, config = {}) {
18366
18722
  return provider === void 0 || provider === PROVIDER;
18367
18723
  };
18368
18724
  const realSearchProviders = ctx.web.searchProviders;
18369
- const resolveDshSearch = () => realSearchProviders?.get(searchProvider.dshProviderId());
18725
+ const resolveDshSearch = () => realSearchProviders?.get(nativeWebSettings() ? webSettings.nativeSearch() ?? DSH_SEARCH_PROVIDER_FALLBACK : searchProvider.dshProviderId());
18370
18726
  const gateSearch = (provider) => gateSearchProvider(provider, {
18371
18727
  allowed: (llmProvider) => settings.get().otherModels !== "off" || (llmProvider ?? currentAgent()?.session.requestContext?.()?.provider) === PROVIDER,
18372
18728
  resolveDshProvider: resolveDshSearch
@@ -18385,6 +18741,7 @@ function apply(ctx, config = {}) {
18385
18741
  const searchTrace = (route) => diagnosticLog.info("search", `web search: ${route}`);
18386
18742
  const tracedCodexSearch = gateSearch({
18387
18743
  id: codexSearch.id,
18744
+ title: "Codex Subscription",
18388
18745
  available: () => codexSearch.available(),
18389
18746
  ready: (llmProvider) => codexSearch.ready(llmProvider),
18390
18747
  async search(request, signal) {
@@ -18407,11 +18764,13 @@ function apply(ctx, config = {}) {
18407
18764
  ctx.web.registerSearchProvider(autoSearch);
18408
18765
  let searchRouted = false;
18409
18766
  ctx.effect(() => {
18767
+ if (nativeWebSettings()) return void 0;
18410
18768
  const web = ctx.web;
18411
18769
  const router = createSearchRouter({
18412
18770
  registry: realSearchProviders,
18413
18771
  configuredId: () => searchProvider.current(),
18414
18772
  mode: () => settings.get()[SEARCH_PROVIDER_FIELD],
18773
+ enabled: () => !nativeWebSettings(),
18415
18774
  providers: {
18416
18775
  codex: tracedCodexSearch,
18417
18776
  auto: autoSearch,
@@ -18434,6 +18793,7 @@ function apply(ctx, config = {}) {
18434
18793
  }, "codex-subscription: search router");
18435
18794
  ctx.effect(() => {
18436
18795
  const select = async (value) => {
18796
+ if (nativeWebSettings()) return;
18437
18797
  if (searchRouted) {
18438
18798
  diagnosticLog.info("search", `web search source is ${value[SEARCH_PROVIDER_FIELD]}`);
18439
18799
  return;
@@ -18449,6 +18809,27 @@ function apply(ctx, config = {}) {
18449
18809
  select(settings.get());
18450
18810
  return settings.watch(select);
18451
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");
18452
18833
  const auth = createCodexAuthService(authModels, store, {
18453
18834
  runLogin: (operation) => network.run("login", operation),
18454
18835
  accountVault,
@@ -18523,7 +18904,8 @@ function apply(ctx, config = {}) {
18523
18904
  base: process.env.DSH_CODEX_REMOTE_BASE || void 0,
18524
18905
  methods: remoteBridge.methods,
18525
18906
  onActive: (_client, notify) => remoteBridge.adopt(notify),
18526
- onClose: (_client, notify) => remoteBridge.forget(notify)
18907
+ onClose: (_client, notify) => remoteBridge.forget(notify),
18908
+ onStop: remoteBridge.clearUploads
18527
18909
  });
18528
18910
  ctx.on("agent/assistant-stream", ({ agent, frame }) => {
18529
18911
  try {
@@ -18721,6 +19103,7 @@ function apply(ctx, config = {}) {
18721
19103
  voicePreview,
18722
19104
  composerPredictions,
18723
19105
  onAccountChanged: () => {
19106
+ remoteBridge.clearUploads();
18724
19107
  subagentCatalog.clear();
18725
19108
  connectorsClient.clear();
18726
19109
  usageProfileReader.clear();