dsh-codex-subscription 3.2.13 → 3.2.15

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
@@ -10,18 +10,20 @@ import { AsyncLocalStorage } from "node:async_hooks";
10
10
  import { promisify } from "node:util";
11
11
  import { HttpsProxyAgent } from "https-proxy-agent";
12
12
  import WebSocket from "ws";
13
+ import { ProxyAgent, getGlobalDispatcher } from "undici";
13
14
  import * as dshLlm from "@deepseek-ai/dsh-llm";
14
15
  import { LlmError, createUserMessage } from "@deepseek-ai/dsh-llm";
15
16
  import { fileURLToPath, pathToFileURL } from "node:url";
16
17
  import { openaiCodexProvider as createOpenAICodexProvider } from "@earendil-works/pi-ai/providers/openai-codex";
18
+ import { isContextOverflow } from "@earendil-works/pi-ai/utils/overflow";
17
19
  import { createModels } from "@earendil-works/pi-ai";
18
20
  import { clientRequestSchema } from "@deepseek-ai/dsh-client-connection";
19
21
  import { lstat, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
20
22
  import { PassThrough } from "node:stream";
23
+ import { dshHomePath, resolveDshHome } from "@deepseek-ai/dsh-home-paths";
21
24
  import * as dshCredentials from "@deepseek-ai/dsh-credentials";
22
25
  import { homedir, hostname } from "node:os";
23
26
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
24
- import { dshHomePath, resolveDshHome } from "@deepseek-ai/dsh-home-paths";
25
27
  import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
26
28
  import { WebError } from "@deepseek-ai/dsh-web";
27
29
  import { performance as performance$1 } from "node:perf_hooks";
@@ -277,6 +279,14 @@ function createDefaultModelController({ resolveService, resolveEditor, listModel
277
279
  //#endregion
278
280
  //#region src/image-models.js
279
281
  const DEFAULT_IMAGE_MODEL = "gpt-image-2";
282
+ const experimentalQuality = Object.freeze([
283
+ "auto",
284
+ "low",
285
+ "medium",
286
+ "high",
287
+ "xhigh",
288
+ "max"
289
+ ]);
280
290
  const IMAGE_MODELS = Object.freeze({
281
291
  "gpt-image-2": Object.freeze([
282
292
  "auto",
@@ -284,22 +294,10 @@ const IMAGE_MODELS = Object.freeze({
284
294
  "medium",
285
295
  "high"
286
296
  ]),
287
- "gpt-image-2.5-flare": Object.freeze([
288
- "auto",
289
- "low",
290
- "medium",
291
- "high",
292
- "xhigh",
293
- "max"
294
- ]),
295
- "gpt-image-2.5-sunburst": Object.freeze([
296
- "auto",
297
- "low",
298
- "medium",
299
- "high",
300
- "xhigh",
301
- "max"
302
- ])
297
+ "gpt-image-2.5-flare": experimentalQuality,
298
+ "gpt-image-2.5-sunburst": experimentalQuality,
299
+ "gpt-image-2.6-flare": experimentalQuality,
300
+ "gpt-image-2.6-sunburst": experimentalQuality
303
301
  });
304
302
  function resolveImageModel(model = DEFAULT_IMAGE_MODEL) {
305
303
  if (typeof model !== "string" || !Object.hasOwn(IMAGE_MODELS, model)) throw new Error("Unknown image model");
@@ -1162,6 +1160,7 @@ const choices = /* @__PURE__ */ new Set([
1162
1160
  "unknown"
1163
1161
  ]);
1164
1162
  const routes$1 = /* @__PURE__ */ new Set([
1163
+ "host",
1165
1164
  "direct",
1166
1165
  "environment",
1167
1166
  "system",
@@ -1176,6 +1175,7 @@ const phases = /* @__PURE__ */ new Set([
1176
1175
  "payload",
1177
1176
  "stream"
1178
1177
  ]);
1178
+ const fetchPaths = /* @__PURE__ */ new Set(["host-fetch", "dedicated-proxy"]);
1179
1179
  const elapsedBuckets$1 = /* @__PURE__ */ new Set([
1180
1180
  "under-1s",
1181
1181
  "1-5s",
@@ -1198,6 +1198,12 @@ function safeAttempt(value = {}) {
1198
1198
  ...typeof value.attemptId === "string" && /^[a-f0-9-]{36}$/.test(value.attemptId) ? { attemptId: value.attemptId } : {},
1199
1199
  ...choices.has(value.preference) ? { preference: value.preference } : {},
1200
1200
  ...choices.has(value.requestedTransport) ? { requestedTransport: value.requestedTransport } : {},
1201
+ ...typeof value.model === "string" && /^gpt-[a-z0-9][a-z0-9.-]{0,63}$/u.test(value.model) ? { model: value.model } : {},
1202
+ ...fetchPaths.has(value.fetchPath) ? { fetchPath: value.fetchPath } : {},
1203
+ ...value.failure === "context-overflow" ? { failure: value.failure } : {},
1204
+ ...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {},
1205
+ ...typeof value.cloudCompactionRequested === "boolean" ? { cloudCompactionRequested: value.cloudCompactionRequested } : {},
1206
+ ...typeof value.checkpointInPayload === "boolean" ? { checkpointInPayload: value.checkpointInPayload } : {},
1201
1207
  ...Array.isArray(value.transports) ? { transports: value.transports.filter((item) => transports.has(item)).slice(0, 8) } : {},
1202
1208
  ...typeof value.headersReceived === "boolean" ? { headersReceived: value.headersReceived } : {},
1203
1209
  ...typeof value.eventDelivered === "boolean" ? { eventDelivered: value.eventDelivered } : {},
@@ -1226,8 +1232,11 @@ function createModelAttempt({ now = Date.now, publish = () => {} } = {}) {
1226
1232
  transport(value) {
1227
1233
  if (!finished && transports.has(value) && data.transports.at(-1) !== value && data.transports.length < 8) data.transports.push(value);
1228
1234
  },
1229
- response() {
1230
- if (!finished) data.headersReceived = true;
1235
+ response(status) {
1236
+ if (!finished) {
1237
+ data.headersReceived = true;
1238
+ if (Number.isInteger(status)) data.httpStatus = status;
1239
+ }
1231
1240
  },
1232
1241
  fetchFailure(error) {
1233
1242
  if (!finished) data.networkFailure = safeFetchFailure(error);
@@ -1276,6 +1285,7 @@ const areas$1 = /* @__PURE__ */ new Set([
1276
1285
  "predictions"
1277
1286
  ]);
1278
1287
  const isNetworkDiagnosticArea = (area) => areas$1.has(area);
1288
+ const NETWORK_FAILURE_LIMIT = areas$1.size;
1279
1289
  const codes$1 = /* @__PURE__ */ new Set([
1280
1290
  "timeout",
1281
1291
  "dns",
@@ -1285,6 +1295,7 @@ const codes$1 = /* @__PURE__ */ new Set([
1285
1295
  "http-error"
1286
1296
  ]);
1287
1297
  const routes = /* @__PURE__ */ new Set([
1298
+ "host",
1288
1299
  "direct",
1289
1300
  "environment",
1290
1301
  "system",
@@ -1306,6 +1317,7 @@ const safeNetworkTiming = ({ route, elapsed }) => ({
1306
1317
  /** Process-local bounded evidence. No bodies, URLs, exception strings or identities. */
1307
1318
  function createDiagnosticEvents({ limit = 32, now = Date.now } = {}) {
1308
1319
  const events = [];
1320
+ const lastFailure = /* @__PURE__ */ new Map();
1309
1321
  const capacity = Math.max(1, Math.min(128, Number.isInteger(limit) ? limit : 32));
1310
1322
  let dropped = 0, sequence = 0;
1311
1323
  return {
@@ -1321,17 +1333,26 @@ function createDiagnosticEvents({ limit = 32, now = Date.now } = {}) {
1321
1333
  ...codes$1.has(value.code) ? { code: value.code } : {},
1322
1334
  ...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {}
1323
1335
  });
1336
+ if (value.status === "failed") {
1337
+ const previous = lastFailure.get(area);
1338
+ if (previous && previous.sequence < events[0].sequence) dropped++;
1339
+ lastFailure.set(area, events.at(-1));
1340
+ }
1324
1341
  if (events.length > capacity) {
1325
- events.shift();
1326
- dropped++;
1342
+ const oldest = events.shift();
1343
+ if (lastFailure.get(oldest.area) !== oldest) dropped++;
1327
1344
  }
1328
1345
  },
1329
- snapshot: () => ({
1330
- scope: "plugin-process",
1331
- capacity,
1332
- dropped,
1333
- events: events.map((value) => ({ ...value }))
1334
- })
1346
+ snapshot() {
1347
+ const oldest = events[0]?.sequence ?? Infinity;
1348
+ const retained = [...lastFailure.values()].filter((event) => event.sequence < oldest);
1349
+ return {
1350
+ scope: "plugin-process",
1351
+ capacity,
1352
+ dropped,
1353
+ events: [...retained, ...events].sort((a, b) => a.sequence - b.sequence).map((value) => ({ ...value }))
1354
+ };
1355
+ }
1335
1356
  };
1336
1357
  }
1337
1358
  //#endregion
@@ -1643,7 +1664,7 @@ function transportResponseBody(response, signal) {
1643
1664
  }
1644
1665
  });
1645
1666
  }
1646
- function fetchThroughProxy(input, init, proxyUrl) {
1667
+ function fetchThroughProxy(input, init, proxyUrl, tls = {}) {
1647
1668
  const target = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
1648
1669
  const body = bodyBytes(init?.body);
1649
1670
  const headers = new Headers(init?.headers);
@@ -1653,7 +1674,8 @@ function fetchThroughProxy(input, init, proxyUrl) {
1653
1674
  method: init?.method ?? "GET",
1654
1675
  headers: Object.fromEntries(headers.entries()),
1655
1676
  agent: proxyUrl ? new HttpsProxyAgent(proxyUrl, { signal: init?.signal }) : void 0,
1656
- signal: init?.signal
1677
+ signal: init?.signal,
1678
+ ...tls.ca ? { ca: tls.ca } : {}
1657
1679
  }, (response) => {
1658
1680
  const responseHeaders = new Headers();
1659
1681
  for (const [name, value] of Object.entries(response.headers)) if (Array.isArray(value)) value.forEach((item) => responseHeaders.append(name, item));
@@ -1699,20 +1721,48 @@ async function fetchInCodexScope(scope, fetchBeforeScope, input, init) {
1699
1721
  }
1700
1722
  route = await proxy;
1701
1723
  }
1702
- scopedOptions.onRoute?.(route.source);
1724
+ const hostModelFetch = scopedOptions.requestFetch && target.origin === `https://${CODEX_SUBSCRIPTION_HOST}` && target.pathname === CODEX_MODEL_SSE_PATH && !dedicatedProxy;
1725
+ if (hostModelFetch || dedicatedProxy) scopedOptions.onModelFetchPath?.(hostModelFetch ? "host-fetch" : "dedicated-proxy");
1726
+ scopedOptions.onRoute?.(hostModelFetch ? "host" : route.source);
1703
1727
  try {
1704
1728
  scopedOptions.onTransport?.("sse");
1705
1729
  } catch {}
1706
1730
  let response;
1707
1731
  try {
1708
1732
  if (dedicatedProxy && !route.url) throw new TypeError("Invalid DSH_CODEX_SSE_PROXY. Use an HTTP or HTTPS CONNECT proxy.");
1709
- response = await (route.url === void 0 && !scopedOptions.standardHttps ? fetchBeforeScope(input, init) : proxyFetch(input, init, route.url));
1733
+ if (hostModelFetch) if (!route.url || init?.dispatcher) response = await fetchBeforeScope(input, init);
1734
+ else {
1735
+ const proxy = new ProxyAgent(route.url);
1736
+ const signal = init?.signal ?? input?.signal;
1737
+ const abort = () => {
1738
+ proxy.destroy(signal.reason).catch(() => {});
1739
+ };
1740
+ signal?.addEventListener("abort", abort, { once: true });
1741
+ if (signal?.aborted) abort();
1742
+ const fallback = getGlobalDispatcher();
1743
+ const dispatcher = { dispatch(options, handler) {
1744
+ if (String(options.origin) !== target.origin) return fallback.dispatch(options, handler);
1745
+ scopedOptions.onRoute?.(route.source);
1746
+ return proxy.dispatch(options, handler);
1747
+ } };
1748
+ try {
1749
+ response = await fetchBeforeScope(input, {
1750
+ ...init,
1751
+ dispatcher
1752
+ });
1753
+ } finally {
1754
+ signal?.removeEventListener("abort", abort);
1755
+ proxy.close().catch(() => {});
1756
+ }
1757
+ }
1758
+ else response = await (route.url === void 0 && !scopedOptions.standardHttps ? fetchBeforeScope(input, init) : proxyFetch(input, init, route.url, dedicatedProxy ? { ca: scopedOptions.modelSseCa } : {}));
1710
1759
  } catch (error) {
1711
1760
  try {
1712
1761
  scopedOptions.onFetchFailure?.(error);
1713
1762
  } catch {}
1714
1763
  throw error;
1715
1764
  }
1765
+ if (hostModelFetch || dedicatedProxy) scopedOptions.onModelHttpStatus?.(response.status);
1716
1766
  return scopedOptions.transformResponse?.(response, target) ?? response;
1717
1767
  }
1718
1768
  async function withCodexNetwork(run, options = {}) {
@@ -1809,9 +1859,10 @@ function createCodexNetworkTransport(options = {}) {
1809
1859
  ...options,
1810
1860
  ...connection
1811
1861
  };
1862
+ const explicitProxy = area === "model" && connection.requestFetch === true ? (scoped.env ?? process.env)[MODEL_SSE_PROXY_ENV]?.trim() : void 0;
1812
1863
  const value = await withCodexNetwork(operation, {
1813
1864
  ...scoped,
1814
- modelSseProxy: area === "model" && connection.requestFetch === true ? (scoped.env ?? process.env)[MODEL_SSE_PROXY_ENV]?.trim() : void 0,
1865
+ modelSseProxy: explicitProxy,
1815
1866
  onRoute: (source) => {
1816
1867
  route = source;
1817
1868
  routed = true;
@@ -2159,6 +2210,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
2159
2210
  const scope = new AsyncLocalStorage();
2160
2211
  const stats = {
2161
2212
  requests: 0,
2213
+ checkpointsReceived: 0,
2162
2214
  checkpointsSaved: 0,
2163
2215
  checkpointsReused: 0
2164
2216
  };
@@ -2310,7 +2362,10 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
2310
2362
  oversized = true;
2311
2363
  }
2312
2364
  }
2313
- if (event.type === "response.completed" && event.response?.status === "completed") state.completed = !oversized;
2365
+ if (event.type === "response.completed" && event.response?.status === "completed") {
2366
+ if (!state.completed && !oversized && state.captured?.length) stats.checkpointsReceived = Math.min(Number.MAX_SAFE_INTEGER, stats.checkpointsReceived + 1);
2367
+ state.completed = !oversized;
2368
+ }
2314
2369
  };
2315
2370
  const stream = response.body.pipeThrough(new TransformStream({
2316
2371
  transform(bytes, controller) {
@@ -2960,7 +3015,13 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
2960
3015
  const settle = (status, error, healthError = error) => {
2961
3016
  if (attempt.snapshot().status) return;
2962
3017
  health?.finish(status === "ok" ? "completed" : status === "abandoned" ? "cancelled" : status, healthError);
2963
- if (status === "failed") noteStreamFailure(stage, error, effectiveSource, networkFailure, attempt.snapshot().attemptId);
3018
+ if (status === "failed") {
3019
+ if (isContextOverflow({
3020
+ stopReason: "error",
3021
+ errorMessage: healthError?.errorMessage ?? error?.message ?? ""
3022
+ })) attempt.configure({ failure: "context-overflow" });
3023
+ noteStreamFailure(stage, error, effectiveSource, networkFailure, attempt.snapshot().attemptId);
3024
+ }
2964
3025
  attempt.finish(status, stage);
2965
3026
  };
2966
3027
  const finish = () => {
@@ -2988,7 +3049,8 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
2988
3049
  };
2989
3050
  attempt.configure({
2990
3051
  preference: request.diagnostic?.preference ?? request.options?.transport ?? "auto",
2991
- requestedTransport: next.transport ?? "auto"
3052
+ requestedTransport: next.transport ?? "auto",
3053
+ model: source?.model?.id
2992
3054
  });
2993
3055
  effectiveSource = {
2994
3056
  ...source,
@@ -3010,6 +3072,12 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3010
3072
  attempt.route(route);
3011
3073
  scopedNetwork?.onRoute?.(route);
3012
3074
  },
3075
+ onModelFetchPath(fetchPath) {
3076
+ attempt.configure({ fetchPath });
3077
+ },
3078
+ onModelHttpStatus(status) {
3079
+ attempt.response(status);
3080
+ },
3013
3081
  onTransport(transport) {
3014
3082
  attempt.transport(transport);
3015
3083
  scopedNetwork?.onTransport?.(transport);
@@ -3042,7 +3110,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3042
3110
  ...fetch === void 0 ? {} : { fetch },
3043
3111
  async onResponse(info, requestModel) {
3044
3112
  health.response(info);
3045
- attempt.response();
3113
+ attempt.response(info?.status);
3046
3114
  retryHint?.onResponse(info);
3047
3115
  return next.onResponse?.(info, requestModel);
3048
3116
  },
@@ -3054,6 +3122,12 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3054
3122
  stage = "payload";
3055
3123
  signal.throwIfAborted();
3056
3124
  const body = await next.onPayload?.(payload, requestModel);
3125
+ const outgoing = body ?? payload;
3126
+ attempt.configure({
3127
+ model: requestModel?.id,
3128
+ cloudCompactionRequested: Array.isArray(outgoing?.context_management) && outgoing.context_management.some((item) => item?.type === "compaction"),
3129
+ checkpointInPayload: Array.isArray(outgoing?.input) && outgoing.input.some((item) => item?.type === "compaction")
3130
+ });
3057
3131
  signal.throwIfAborted();
3058
3132
  stage = "request";
3059
3133
  return body;
@@ -4753,9 +4827,10 @@ async function readSubscriptionCredentials(getAuth, readCredential, signal) {
4753
4827
  }
4754
4828
  const ORIGINAL_IMAGE_CHUNK_BYTES = 4 * 1024 * 1024;
4755
4829
  const ORIGINAL_IMAGE_ID_PATTERN = /^img_[0-9a-f]{32}$/u;
4830
+ const GENERATED_IMAGE_MEDIA_TYPES = Object.freeze(["image/png", "image/gif"]);
4756
4831
  const positiveInteger$1 = (value) => Number.isSafeInteger(value) && value > 0;
4757
4832
  function decodeOriginalImageRef(value) {
4758
- if (value === null || typeof value !== "object" || Array.isArray(value) || typeof value.assetId !== "string" || !ORIGINAL_IMAGE_ID_PATTERN.test(value.assetId) || value.mediaType !== "image/png" || !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;
4833
+ 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;
4759
4834
  return {
4760
4835
  assetId: value.assetId,
4761
4836
  mediaType: value.mediaType,
@@ -4798,9 +4873,185 @@ function inheritedOriginalImageRef(session, assetId) {
4798
4873
  }
4799
4874
  //#endregion
4800
4875
  //#region src/version.js
4801
- const PACKAGE_VERSION = "3.2.13";
4876
+ const PACKAGE_VERSION = "3.2.15";
4802
4877
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
4803
4878
  //#endregion
4879
+ //#region src/image-original-store.js
4880
+ const ORIGINAL_IMAGE_DIRECTORY = "dsh-codex-subscription/images/v1";
4881
+ const METADATA_VERSION = 1;
4882
+ const digest = (data) => createHash("sha256").update(data).digest("hex");
4883
+ const validSessionId = (value) => typeof value === "string" && value.length > 0 && value.length <= 512;
4884
+ function pngDimensions(data) {
4885
+ if (!(data instanceof Uint8Array) || data.byteLength < 24 || Buffer.from(data.subarray(0, 8)).toString("hex") !== "89504e470d0a1a0a" || Buffer.from(data.subarray(12, 16)).toString("ascii") !== "IHDR") throw new TypeError("invalid PNG dimensions");
4886
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
4887
+ const width = view.getUint32(16, false);
4888
+ const height = view.getUint32(20, false);
4889
+ if (width === 0 || height === 0) throw new TypeError("invalid PNG dimensions");
4890
+ return {
4891
+ width,
4892
+ height
4893
+ };
4894
+ }
4895
+ function gifDimensions(data) {
4896
+ if (!(data instanceof Uint8Array) || data.byteLength < 13 || !/^GIF8[79]a$/u.test(Buffer.from(data.subarray(0, 6)).toString("ascii"))) throw new TypeError("invalid GIF dimensions");
4897
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
4898
+ const width = view.getUint16(6, true);
4899
+ const height = view.getUint16(8, true);
4900
+ if (width === 0 || height === 0) throw new TypeError("invalid GIF dimensions");
4901
+ return {
4902
+ width,
4903
+ height
4904
+ };
4905
+ }
4906
+ const imageDimensions = (data, mediaType) => mediaType === "image/gif" ? gifDimensions(data) : pngDimensions(data);
4907
+ async function writeExclusive(filename, data) {
4908
+ await mkdir(dirname(filename), {
4909
+ recursive: true,
4910
+ mode: 448
4911
+ });
4912
+ const handle = await open(filename, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 384);
4913
+ try {
4914
+ await handle.writeFile(data);
4915
+ await handle.sync();
4916
+ } finally {
4917
+ await handle.close();
4918
+ }
4919
+ }
4920
+ async function assertPrivateFile(filename) {
4921
+ const stat = await lstat(filename);
4922
+ if (!stat.isFile()) throw new Error("not a regular file");
4923
+ if (process.platform !== "win32" && (stat.mode & 63) !== 0) throw new Error("file is not owner-only");
4924
+ }
4925
+ function parseMetadata(text) {
4926
+ let value;
4927
+ try {
4928
+ value = JSON.parse(text);
4929
+ } catch {
4930
+ return;
4931
+ }
4932
+ if (value?.version !== METADATA_VERSION || !validSessionId(value.sessionId)) return void 0;
4933
+ const image = decodeOriginalImageRef(value.image);
4934
+ return image === void 0 ? void 0 : {
4935
+ sessionId: value.sessionId,
4936
+ image
4937
+ };
4938
+ }
4939
+ var OriginalImageStore = class {
4940
+ constructor(dshHome) {
4941
+ this.root = resolve(join(resolveDshHome(dshHome), ORIGINAL_IMAGE_DIRECTORY));
4942
+ }
4943
+ directory(assetId) {
4944
+ if (!ORIGINAL_IMAGE_ID_PATTERN.test(assetId)) throw new TypeError("invalid original image asset id");
4945
+ return join(this.root, assetId.slice(4, 6), assetId);
4946
+ }
4947
+ originalPath(assetId) {
4948
+ return join(this.directory(assetId), "original");
4949
+ }
4950
+ async save(sessionId, data, name = "codex-generated-original.png", mediaType = "image/png") {
4951
+ if (!validSessionId(sessionId) || !(data instanceof Uint8Array) || data.byteLength === 0 || data.byteLength > 48 * 1024 * 1024) throw new TypeError("invalid original image input");
4952
+ const { width, height } = imageDimensions(data, mediaType);
4953
+ const assetId = `img_${randomBytes(16).toString("hex")}`;
4954
+ const directory = this.directory(assetId);
4955
+ const ref = {
4956
+ assetId,
4957
+ mediaType,
4958
+ bytes: data.byteLength,
4959
+ width,
4960
+ height,
4961
+ name,
4962
+ sha256: digest(data)
4963
+ };
4964
+ try {
4965
+ await mkdir(dirname(directory), {
4966
+ recursive: true,
4967
+ mode: 448
4968
+ });
4969
+ await mkdir(directory, {
4970
+ recursive: false,
4971
+ mode: 448
4972
+ });
4973
+ await writeExclusive(join(directory, "original"), data);
4974
+ const temporary = join(directory, `metadata.${randomBytes(8).toString("hex")}.tmp`);
4975
+ await writeExclusive(temporary, Buffer.from(`${JSON.stringify({
4976
+ version: METADATA_VERSION,
4977
+ sessionId,
4978
+ image: ref
4979
+ }, null, 2)}\n`));
4980
+ await rename(temporary, join(directory, "metadata.json"));
4981
+ return ref;
4982
+ } catch (error) {
4983
+ await rm(directory, {
4984
+ recursive: true,
4985
+ force: true
4986
+ }).catch(() => void 0);
4987
+ throw error;
4988
+ }
4989
+ }
4990
+ async remove(ref) {
4991
+ if (ref !== void 0 && ORIGINAL_IMAGE_ID_PATTERN.test(ref.assetId)) await rm(this.directory(ref.assetId), {
4992
+ recursive: true,
4993
+ force: true
4994
+ }).catch(() => void 0);
4995
+ }
4996
+ async read(sessionId, assetId, inherited) {
4997
+ if (!validSessionId(sessionId) || !ORIGINAL_IMAGE_ID_PATTERN.test(assetId)) return void 0;
4998
+ try {
4999
+ const directory = this.directory(assetId);
5000
+ const metadataFile = join(directory, "metadata.json");
5001
+ const originalFile = join(directory, "original");
5002
+ await Promise.all([assertPrivateFile(metadataFile), assertPrivateFile(originalFile)]);
5003
+ const metadata = parseMetadata(await readFile(metadataFile, "utf8"));
5004
+ if (metadata === void 0 || metadata.image.assetId !== assetId || metadata.sessionId !== sessionId && !originalImageRefsEqual(metadata.image, inherited)) return void 0;
5005
+ const buffer = await readFile(originalFile);
5006
+ const data = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
5007
+ const dimensions = imageDimensions(data, metadata.image.mediaType);
5008
+ if (data.byteLength !== metadata.image.bytes || digest(data) !== metadata.image.sha256 || dimensions.width !== metadata.image.width || dimensions.height !== metadata.image.height) return void 0;
5009
+ return {
5010
+ ref: metadata.image,
5011
+ data
5012
+ };
5013
+ } catch {
5014
+ return;
5015
+ }
5016
+ }
5017
+ async chunk(sessionId, assetId, offset, inherited) {
5018
+ if (!validSessionId(sessionId) || !ORIGINAL_IMAGE_ID_PATTERN.test(assetId) || !Number.isSafeInteger(offset) || offset < 0 || offset % 4194304 !== 0) return void 0;
5019
+ let handle;
5020
+ try {
5021
+ const metadataFile = join(this.directory(assetId), "metadata.json");
5022
+ const originalFile = this.originalPath(assetId);
5023
+ await Promise.all([assertPrivateFile(metadataFile), assertPrivateFile(originalFile)]);
5024
+ const metadata = parseMetadata(await readFile(metadataFile, "utf8"));
5025
+ if (!metadata || metadata.image.assetId !== assetId || metadata.sessionId !== sessionId && !originalImageRefsEqual(metadata.image, inherited)) return void 0;
5026
+ handle = await open(originalFile, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
5027
+ const stat = await handle.stat();
5028
+ if (!stat.isFile() || stat.size !== metadata.image.bytes || offset >= stat.size || process.platform !== "win32" && (stat.mode & 63) !== 0) return void 0;
5029
+ const header = Buffer.alloc(metadata.image.mediaType === "image/gif" ? 13 : 24);
5030
+ if ((await handle.read(header, 0, header.length, 0)).bytesRead !== header.length) return void 0;
5031
+ const dimensions = imageDimensions(header, metadata.image.mediaType);
5032
+ if (dimensions.width !== metadata.image.width || dimensions.height !== metadata.image.height) return void 0;
5033
+ const length = Math.min(ORIGINAL_IMAGE_CHUNK_BYTES, stat.size - offset);
5034
+ const chunk = Buffer.alloc(length);
5035
+ let read = 0;
5036
+ while (read < length) {
5037
+ const result = await handle.read(chunk, read, length - read, offset + read);
5038
+ if (!result.bytesRead) return void 0;
5039
+ read += result.bytesRead;
5040
+ }
5041
+ return {
5042
+ ref: metadata.image,
5043
+ offset,
5044
+ encoded: chunk.toString("base64"),
5045
+ done: offset + length === stat.size
5046
+ };
5047
+ } catch {
5048
+ return;
5049
+ } finally {
5050
+ await handle?.close();
5051
+ }
5052
+ }
5053
+ };
5054
+ //#endregion
4804
5055
  //#region src/codex-images.js
4805
5056
  const CODEX_IMAGE_TOOL_NAME = "codex_image_generate";
4806
5057
  const CODEX_IMAGE_GENERATION_URL = "https://chatgpt.com/backend-api/codex/images/generations";
@@ -4901,16 +5152,44 @@ async function readJsonWithin(response, maximumBytes) {
4901
5152
  }
4902
5153
  }
4903
5154
  /** Strictly decode one PNG returned by the subscription backend. */
4904
- function decodeCodexPng(value, maximumBytes) {
5155
+ function decodeImageBytes(value, maximumBytes, format) {
4905
5156
  const encoded = nonEmpty$2(value);
4906
5157
  const padding = encoded?.endsWith("==") ? 2 : encoded?.endsWith("=") ? 1 : 0;
4907
- if (encoded === void 0 || encoded.length % 4 !== 0 || !validBase64Body(encoded, encoded.length - padding)) throw new Error("Codex returned an invalid base64 PNG");
5158
+ if (encoded === void 0 || encoded.length % 4 !== 0 || !validBase64Body(encoded, encoded.length - padding)) throw new Error(`Codex returned an invalid base64 ${format}`);
4908
5159
  const decodedBytes = encoded.length / 4 * 3 - padding;
4909
5160
  if (decodedBytes > maximumBytes) throw new Error("Codex image exceeds the image size limit");
4910
5161
  const data = Buffer.from(encoded, "base64");
4911
- if (data.length !== decodedBytes || data.length < PNG_SIGNATURE.length || !data.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) throw new Error("Codex returned an invalid PNG");
5162
+ if (data.length !== decodedBytes) throw new Error(`Codex returned an invalid ${format}`);
5163
+ return data;
5164
+ }
5165
+ function decodeCodexPng(value, maximumBytes) {
5166
+ const data = decodeImageBytes(value, maximumBytes, "PNG");
5167
+ if (!data.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE)) throw new Error("Codex returned an invalid PNG");
4912
5168
  return new Uint8Array(data);
4913
5169
  }
5170
+ function decodeAnimatedGif(value, maximumBytes) {
5171
+ const data = decodeImageBytes(value, maximumBytes, "GIF");
5172
+ const { width, height } = gifDimensions(data);
5173
+ if (width * height > 8294400) throw new Error("Codex GIF exceeds the image pixel limit");
5174
+ let offset = 13 + (data[10] & 128 ? 3 * (2 << (data[10] & 7)) : 0);
5175
+ let frames = 0;
5176
+ while (offset < data.length) {
5177
+ const kind = data[offset++];
5178
+ if (kind === 59 && offset === data.length && frames > 1) return data;
5179
+ if (kind === 33) offset++;
5180
+ else if (kind === 44 && offset + 9 < data.length) {
5181
+ const frameWidth = data.readUInt16LE(offset + 4);
5182
+ const frameHeight = data.readUInt16LE(offset + 6);
5183
+ if (frameWidth === 0 || frameHeight === 0 || frameWidth > width || frameHeight > height) break;
5184
+ const flags = data[offset + 8];
5185
+ offset += 10 + (flags & 128 ? 3 * (2 << (flags & 7)) : 0);
5186
+ if (++frames > 16) break;
5187
+ } else break;
5188
+ while (offset < data.length && data[offset] !== 0) offset += 1 + data[offset];
5189
+ offset++;
5190
+ }
5191
+ throw new Error("Codex did not return a valid animated GIF");
5192
+ }
4914
5193
  function imageReference(value) {
4915
5194
  const originalDimensions = record$8(value.originalDimensions) ? {
4916
5195
  width: value.originalDimensions.width,
@@ -4996,7 +5275,7 @@ function imageContent(value) {
4996
5275
  const label = typeof value.size === "string" && value.size.length > 0 ? `Generated a ${value.size} image.` : "Generated an image.";
4997
5276
  return [{
4998
5277
  type: "text",
4999
- text: value.localPath === void 0 ? label : `${label}\nOriginal PNG saved on the DSH host at: ${JSON.stringify(value.localPath)}. Read this file or copy it to the workspace with a .png extension; this host path is not a browser URL. The image is already shown to the user, so do not embed it again; copy it rather than move it, and leave the original in place unless the user asks you to delete it.`
5278
+ text: value.localPath === void 0 ? label : `${label}\nOriginal ${value.original?.mediaType === "image/gif" ? "GIF" : "PNG"} saved on the DSH host at: ${JSON.stringify(value.localPath)}. Read this file or copy it to the workspace with the matching extension; this host path is not a browser URL. The image is already shown to the user, so do not embed it again; copy it rather than move it, and leave the original in place unless the user asks you to delete it.`
5000
5279
  }, {
5001
5280
  type: "image",
5002
5281
  attachment: imageReference(value.image)
@@ -5018,7 +5297,12 @@ function imageOutputSchema() {
5018
5297
  },
5019
5298
  mediaType: {
5020
5299
  type: "string",
5021
- enum: ["image/png"],
5300
+ enum: [
5301
+ "image/png",
5302
+ "image/jpeg",
5303
+ "image/webp",
5304
+ "image/gif"
5305
+ ],
5022
5306
  required: true
5023
5307
  },
5024
5308
  bytes: {
@@ -5061,7 +5345,7 @@ function imageOutputSchema() {
5061
5345
  },
5062
5346
  mediaType: {
5063
5347
  type: "string",
5064
- enum: ["image/png"],
5348
+ enum: GENERATED_IMAGE_MEDIA_TYPES,
5065
5349
  required: true
5066
5350
  },
5067
5351
  bytes: {
@@ -5093,7 +5377,7 @@ function imageOutputSchema() {
5093
5377
  localPath: {
5094
5378
  type: "string",
5095
5379
  required: true,
5096
- description: "Absolute path to the original PNG on the DSH host."
5380
+ description: "Absolute path to the original image on the DSH host."
5097
5381
  },
5098
5382
  quality: { type: "string" },
5099
5383
  size: { type: "string" }
@@ -5173,7 +5457,7 @@ function createCodexImageTool(options) {
5173
5457
  model: {
5174
5458
  type: "string",
5175
5459
  enum: Object.keys(IMAGE_MODELS),
5176
- description: "Optional image engine, independent of the conversation model. When omitted, uses the user image setting (initially gpt-image-2). The 2.5 identifiers are experimental subscription candidates; override only when explicitly requested. Never silently retry with another model."
5460
+ description: "Optional image engine, independent of the conversation model. Defaults to the user image setting. Flare and Sunburst are experimental request options; override only when explicitly requested. Never silently retry with another model."
5177
5461
  },
5178
5462
  prompt: {
5179
5463
  type: "string",
@@ -5205,6 +5489,21 @@ function createCodexImageTool(options) {
5205
5489
  ],
5206
5490
  description: "Optional background mode. Request transparent only when the user needs transparency."
5207
5491
  },
5492
+ gif: {
5493
+ type: "object",
5494
+ additionalProperties: false,
5495
+ description: "Only for an explicit request for a new animated GIF. Availability depends on the subscription service. Never replace an unavailable GIF with a static image.",
5496
+ properties: {
5497
+ frameCount: {
5498
+ type: "integer",
5499
+ description: "2–16 frames, defaults to 6."
5500
+ },
5501
+ frameDurationMs: {
5502
+ type: "integer",
5503
+ description: "20–655350 milliseconds, defaults to 150."
5504
+ }
5505
+ }
5506
+ },
5208
5507
  referenceImages: {
5209
5508
  type: "array",
5210
5509
  description: "Optional references to 1-5 selected images. For session images provide only attachmentId; the host resolves trusted metadata. Omit only for a new image; never drop an invalid reference to bypass editing.",
@@ -5282,11 +5581,23 @@ function createCodexImageTool(options) {
5282
5581
  const prompt = nonEmpty$2(args.prompt);
5283
5582
  if (prompt === void 0) throw new Error("prompt must be a non-empty string");
5284
5583
  const imageOptions = normalizeImageOptions(args);
5584
+ const editing = args.referenceImages !== void 0;
5585
+ const animated = args.gif !== void 0;
5586
+ const mediaType = animated ? "image/gif" : "image/png";
5587
+ if (animated) {
5588
+ 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");
5591
+ imageOptions.animation = {
5592
+ output_format: "gif",
5593
+ frame_count: frameCount,
5594
+ frame_duration_ms: frameDurationMs
5595
+ };
5596
+ }
5285
5597
  const { access, accountId } = await readSubscriptionCredentials(options.getAuth, options.readCredential, exec.signal);
5286
5598
  if (typeof access !== "string" || access.length === 0 || typeof accountId !== "string" || accountId.length === 0) throw new Error("ChatGPT subscription is not signed in");
5287
- if (!attachments.imageLimits.mediaTypes.includes("image/png")) throw new Error("This DSH installation does not accept PNG image attachments");
5599
+ if (!attachments.imageLimits.mediaTypes.includes(mediaType)) throw new Error(`This DSH installation does not accept ${animated ? "GIF" : "PNG"} image attachments`);
5288
5600
  const maximumBytes = Math.min(attachments.imageLimits.maxImageBytes, attachments.imageLimits.maxMessageImageBytes);
5289
- const editing = args.referenceImages !== void 0;
5290
5601
  const sessionMessages = editing && typeof options.getSessionMessages === "function" ? await options.getSessionMessages(exec.agent?.id) : void 0;
5291
5602
  const images = editing ? await editImages(args.referenceImages, attachments, exec.signal, sessionMessages ?? (options.getSessionMessages ? [] : void 0)) : void 0;
5292
5603
  let response;
@@ -5310,7 +5621,8 @@ function createCodexImageTool(options) {
5310
5621
  background: imageOptions.background,
5311
5622
  model: resolveImageModel(args.model),
5312
5623
  quality: imageOptions.quality,
5313
- size: imageOptions.size
5624
+ size: imageOptions.size,
5625
+ ...imageOptions.animation
5314
5626
  }),
5315
5627
  signal: exec.signal
5316
5628
  });
@@ -5324,19 +5636,24 @@ function createCodexImageTool(options) {
5324
5636
  if (response.status === 403 && authFailure === "ChatGPT denied this request (HTTP 403). Check account access or contact OpenAI Support; signing in again may not resolve it.") throw new Error(`${await refusalMessage(response, editing)}${requestId}`);
5325
5637
  if (authFailure !== void 0) throw new Error(authFailure);
5326
5638
  if (response.status === 429) throw new Error(`${await limitMessage(response)}${requestId}`);
5639
+ if (animated && response.status === 400) {
5640
+ const body = await readTextWithin(response, 16 * 1024);
5641
+ if (/GIF output is not enabled for this request/iu.test(body)) throw new Error(`GIF generation is not yet available through this Codex subscription connection. Try ChatGPT Images in the browser.${requestId}`);
5642
+ }
5327
5643
  throw new Error(`Codex image ${editing ? "edit" : "generation"} failed (HTTP ${response.status})${requestId}`);
5328
5644
  }
5329
5645
  const metadata = responseMetadata(await readJsonWithin(response, encodedLimit(maximumBytes) + RESPONSE_ENVELOPE_BYTES));
5330
- const data = decodeCodexPng(metadata.encoded, maximumBytes);
5646
+ const data = animated ? decodeAnimatedGif(metadata.encoded, maximumBytes) : decodeCodexPng(metadata.encoded, maximumBytes);
5331
5647
  const sessionId = exec.agent?.id;
5332
5648
  if (sessionId === void 0) throw new Error("Codex image generation requires a session-owned tool call");
5333
- const original = await options.originalImages.save(String(sessionId), data);
5649
+ const extension = animated ? "gif" : "png";
5650
+ const original = await options.originalImages.save(String(sessionId), data, `codex-generated-original.${extension}`, mediaType);
5334
5651
  let ref;
5335
5652
  try {
5336
5653
  ref = await attachments.saveImage({
5337
5654
  data,
5338
- mediaType: "image/png",
5339
- name: "codex-generated.png"
5655
+ mediaType,
5656
+ name: `codex-generated.${extension}`
5340
5657
  });
5341
5658
  } catch (error) {
5342
5659
  await options.originalImages.remove(original);
@@ -13491,170 +13808,6 @@ function watchImageTool(settings, register) {
13491
13808
  };
13492
13809
  }
13493
13810
  //#endregion
13494
- //#region src/image-original-store.js
13495
- const ORIGINAL_IMAGE_DIRECTORY = "dsh-codex-subscription/images/v1";
13496
- const METADATA_VERSION = 1;
13497
- const digest = (data) => createHash("sha256").update(data).digest("hex");
13498
- const validSessionId = (value) => typeof value === "string" && value.length > 0 && value.length <= 512;
13499
- function pngDimensions(data) {
13500
- if (!(data instanceof Uint8Array) || data.byteLength < 24 || Buffer.from(data.subarray(0, 8)).toString("hex") !== "89504e470d0a1a0a" || Buffer.from(data.subarray(12, 16)).toString("ascii") !== "IHDR") throw new TypeError("invalid PNG dimensions");
13501
- const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
13502
- const width = view.getUint32(16, false);
13503
- const height = view.getUint32(20, false);
13504
- if (width === 0 || height === 0) throw new TypeError("invalid PNG dimensions");
13505
- return {
13506
- width,
13507
- height
13508
- };
13509
- }
13510
- async function writeExclusive(filename, data) {
13511
- await mkdir(dirname(filename), {
13512
- recursive: true,
13513
- mode: 448
13514
- });
13515
- const handle = await open(filename, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 384);
13516
- try {
13517
- await handle.writeFile(data);
13518
- await handle.sync();
13519
- } finally {
13520
- await handle.close();
13521
- }
13522
- }
13523
- async function assertPrivateFile(filename) {
13524
- const stat = await lstat(filename);
13525
- if (!stat.isFile()) throw new Error("not a regular file");
13526
- if (process.platform !== "win32" && (stat.mode & 63) !== 0) throw new Error("file is not owner-only");
13527
- }
13528
- function parseMetadata(text) {
13529
- let value;
13530
- try {
13531
- value = JSON.parse(text);
13532
- } catch {
13533
- return;
13534
- }
13535
- if (value?.version !== METADATA_VERSION || !validSessionId(value.sessionId)) return void 0;
13536
- const image = decodeOriginalImageRef(value.image);
13537
- return image === void 0 ? void 0 : {
13538
- sessionId: value.sessionId,
13539
- image
13540
- };
13541
- }
13542
- var OriginalImageStore = class {
13543
- constructor(dshHome) {
13544
- this.root = resolve(join(resolveDshHome(dshHome), ORIGINAL_IMAGE_DIRECTORY));
13545
- }
13546
- directory(assetId) {
13547
- if (!ORIGINAL_IMAGE_ID_PATTERN.test(assetId)) throw new TypeError("invalid original image asset id");
13548
- return join(this.root, assetId.slice(4, 6), assetId);
13549
- }
13550
- originalPath(assetId) {
13551
- return join(this.directory(assetId), "original");
13552
- }
13553
- async save(sessionId, data, name = "codex-generated-original.png") {
13554
- if (!validSessionId(sessionId) || !(data instanceof Uint8Array) || data.byteLength === 0 || data.byteLength > 48 * 1024 * 1024) throw new TypeError("invalid original image input");
13555
- const { width, height } = pngDimensions(data);
13556
- const assetId = `img_${randomBytes(16).toString("hex")}`;
13557
- const directory = this.directory(assetId);
13558
- const ref = {
13559
- assetId,
13560
- mediaType: "image/png",
13561
- bytes: data.byteLength,
13562
- width,
13563
- height,
13564
- name,
13565
- sha256: digest(data)
13566
- };
13567
- try {
13568
- await mkdir(dirname(directory), {
13569
- recursive: true,
13570
- mode: 448
13571
- });
13572
- await mkdir(directory, {
13573
- recursive: false,
13574
- mode: 448
13575
- });
13576
- await writeExclusive(join(directory, "original"), data);
13577
- const temporary = join(directory, `metadata.${randomBytes(8).toString("hex")}.tmp`);
13578
- await writeExclusive(temporary, Buffer.from(`${JSON.stringify({
13579
- version: METADATA_VERSION,
13580
- sessionId,
13581
- image: ref
13582
- }, null, 2)}\n`));
13583
- await rename(temporary, join(directory, "metadata.json"));
13584
- return ref;
13585
- } catch (error) {
13586
- await rm(directory, {
13587
- recursive: true,
13588
- force: true
13589
- }).catch(() => void 0);
13590
- throw error;
13591
- }
13592
- }
13593
- async remove(ref) {
13594
- if (ref !== void 0 && ORIGINAL_IMAGE_ID_PATTERN.test(ref.assetId)) await rm(this.directory(ref.assetId), {
13595
- recursive: true,
13596
- force: true
13597
- }).catch(() => void 0);
13598
- }
13599
- async read(sessionId, assetId, inherited) {
13600
- if (!validSessionId(sessionId) || !ORIGINAL_IMAGE_ID_PATTERN.test(assetId)) return void 0;
13601
- try {
13602
- const directory = this.directory(assetId);
13603
- const metadataFile = join(directory, "metadata.json");
13604
- const originalFile = join(directory, "original");
13605
- await Promise.all([assertPrivateFile(metadataFile), assertPrivateFile(originalFile)]);
13606
- const metadata = parseMetadata(await readFile(metadataFile, "utf8"));
13607
- if (metadata === void 0 || metadata.image.assetId !== assetId || metadata.sessionId !== sessionId && !originalImageRefsEqual(metadata.image, inherited)) return void 0;
13608
- const buffer = await readFile(originalFile);
13609
- const data = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
13610
- const dimensions = pngDimensions(data);
13611
- if (data.byteLength !== metadata.image.bytes || digest(data) !== metadata.image.sha256 || dimensions.width !== metadata.image.width || dimensions.height !== metadata.image.height) return void 0;
13612
- return {
13613
- ref: metadata.image,
13614
- data
13615
- };
13616
- } catch {
13617
- return;
13618
- }
13619
- }
13620
- async chunk(sessionId, assetId, offset, inherited) {
13621
- if (!validSessionId(sessionId) || !ORIGINAL_IMAGE_ID_PATTERN.test(assetId) || !Number.isSafeInteger(offset) || offset < 0 || offset % 4194304 !== 0) return void 0;
13622
- let handle;
13623
- try {
13624
- const metadataFile = join(this.directory(assetId), "metadata.json");
13625
- const originalFile = this.originalPath(assetId);
13626
- await Promise.all([assertPrivateFile(metadataFile), assertPrivateFile(originalFile)]);
13627
- const metadata = parseMetadata(await readFile(metadataFile, "utf8"));
13628
- if (!metadata || metadata.image.assetId !== assetId || metadata.sessionId !== sessionId && !originalImageRefsEqual(metadata.image, inherited)) return void 0;
13629
- handle = await open(originalFile, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
13630
- const stat = await handle.stat();
13631
- if (!stat.isFile() || stat.size !== metadata.image.bytes || offset >= stat.size || process.platform !== "win32" && (stat.mode & 63) !== 0) return void 0;
13632
- const header = Buffer.alloc(24);
13633
- if ((await handle.read(header, 0, 24, 0)).bytesRead !== 24) return void 0;
13634
- const dimensions = pngDimensions(header);
13635
- if (dimensions.width !== metadata.image.width || dimensions.height !== metadata.image.height) return void 0;
13636
- const length = Math.min(ORIGINAL_IMAGE_CHUNK_BYTES, stat.size - offset);
13637
- const chunk = Buffer.alloc(length);
13638
- let read = 0;
13639
- while (read < length) {
13640
- const result = await handle.read(chunk, read, length - read, offset + read);
13641
- if (!result.bytesRead) return void 0;
13642
- read += result.bytesRead;
13643
- }
13644
- return {
13645
- ref: metadata.image,
13646
- offset,
13647
- encoded: chunk.toString("base64"),
13648
- done: offset + length === stat.size
13649
- };
13650
- } catch {
13651
- return;
13652
- } finally {
13653
- await handle?.close();
13654
- }
13655
- }
13656
- };
13657
- //#endregion
13658
13811
  //#region src/diagnostic-checks.js
13659
13812
  const states = /* @__PURE__ */ new Set([
13660
13813
  "pass",
@@ -13851,6 +14004,13 @@ const actions = Object.freeze({
13851
14004
  "runtime/install": "subagents",
13852
14005
  "runtime/remove": "subagents",
13853
14006
  "runtime/cancel": "subagents",
14007
+ "voice/start": "transport",
14008
+ "voice/stop": "transport",
14009
+ "voice/native/start": "transport",
14010
+ "voice/native/stop": "transport",
14011
+ "remote/enable": "transport",
14012
+ "remote/pair": "transport",
14013
+ "remote/disable": "transport",
13854
14014
  codex_image_generate: "images",
13855
14015
  codex_sketch: "sketch"
13856
14016
  });
@@ -13860,6 +14020,14 @@ const QUIET = /* @__PURE__ */ new Set([
13860
14020
  "preferences/models",
13861
14021
  "predictions/generate"
13862
14022
  ]);
14023
+ const RPC_FAILURES = /* @__PURE__ */ new Set([
14024
+ "internal",
14025
+ "invalid-input",
14026
+ "not-found",
14027
+ "operation-error",
14028
+ "unavailable",
14029
+ "voice-native-unavailable"
14030
+ ]);
13863
14031
  function safeOperations(raw) {
13864
14032
  if (!Array.isArray(raw?.events)) return void 0;
13865
14033
  return {
@@ -13877,7 +14045,8 @@ function safeOperations(raw) {
13877
14045
  action: value.action,
13878
14046
  status: value.status,
13879
14047
  source: value.source,
13880
- observedAt: value.observedAt
14048
+ observedAt: value.observedAt,
14049
+ ...value.status === "failed" && RPC_FAILURES.has(value.code) ? { code: value.code } : {}
13881
14050
  }];
13882
14051
  })
13883
14052
  };
@@ -13885,7 +14054,7 @@ function safeOperations(raw) {
13885
14054
  function createDiagnosticOperations({ now = Date.now } = {}) {
13886
14055
  const events = [];
13887
14056
  let sequence = 0, dropped = 0;
13888
- const record = (action, status, source = "rpc") => {
14057
+ const record = (action, status, source = "rpc", code) => {
13889
14058
  if (!Object.hasOwn(actions, action) || ![
13890
14059
  "completed",
13891
14060
  "failed",
@@ -13897,7 +14066,8 @@ function createDiagnosticOperations({ now = Date.now } = {}) {
13897
14066
  action,
13898
14067
  source,
13899
14068
  status,
13900
- observedAt: now()
14069
+ observedAt: now(),
14070
+ ...status === "failed" && RPC_FAILURES.has(code) ? { code } : {}
13901
14071
  });
13902
14072
  if (status === "failed") diagnosticLog.error(actions[action], `${action} failed`);
13903
14073
  else if (status === "completed" && !QUIET.has(action)) diagnosticLog.info(actions[action], `${action} completed`);
@@ -13920,7 +14090,7 @@ function createDiagnosticOperations({ now = Date.now } = {}) {
13920
14090
  }[result.value?.reason];
13921
14091
  diagnosticLog.info("predictions", result.value?.prediction ? "suggestion ready" : `no suggestion${reason ? `: ${reason}` : ""}`);
13922
14092
  }
13923
- record(endpoint, result?.ok === true ? "completed" : "failed");
14093
+ record(endpoint, signal?.aborted ? "cancelled" : result?.ok === true ? "completed" : "failed", "rpc", result?.error?.code);
13924
14094
  return result;
13925
14095
  } catch (error) {
13926
14096
  record(endpoint, signal?.aborted ? "cancelled" : "failed");
@@ -13969,7 +14139,8 @@ const codes = /* @__PURE__ */ new Set([
13969
14139
  ]);
13970
14140
  function safeHistory(raw) {
13971
14141
  if (!raw || !Array.isArray(raw.events)) return void 0;
13972
- const events = raw.events.slice(-32).flatMap((value) => {
14142
+ const maximum = 32 + NETWORK_FAILURE_LIMIT;
14143
+ const events = raw.events.slice(-maximum).flatMap((value) => {
13973
14144
  if (!value || !isNetworkDiagnosticArea(value.area) || !statuses.has(value.status) || !Number.isSafeInteger(value.sequence) || value.sequence < 1 || !Number.isSafeInteger(value.observedAt) || value.observedAt < 0) return [];
13974
14145
  return [{
13975
14146
  area: value.area,
@@ -13985,7 +14156,7 @@ function safeHistory(raw) {
13985
14156
  return {
13986
14157
  scope: "plugin-process",
13987
14158
  capacity: 32,
13988
- dropped: (Number.isSafeInteger(raw.dropped) && raw.dropped >= 0 ? raw.dropped : 0) + Math.max(0, raw.events.length - 32),
14159
+ dropped: (Number.isSafeInteger(raw.dropped) && raw.dropped >= 0 ? raw.dropped : 0) + Math.max(0, raw.events.length - maximum),
13989
14160
  events
13990
14161
  };
13991
14162
  }
@@ -14098,6 +14269,7 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
14098
14269
  "compaction",
14099
14270
  () => compaction ? safeCounters(compaction, [
14100
14271
  "requests",
14272
+ "checkpointsReceived",
14101
14273
  "checkpointsSaved",
14102
14274
  "checkpointsReused"
14103
14275
  ]) : void 0
@@ -14262,6 +14434,9 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
14262
14434
  } } : {},
14263
14435
  configuration: {
14264
14436
  ...typeof preference.autoQuotaRetry === "boolean" ? { autoQuotaRetry: preference.autoQuotaRetry } : {},
14437
+ connectionMode: preference.connectionMode,
14438
+ compactionMode: preference.compactionMode,
14439
+ composerModelPicker: preference.composerModelPicker,
14265
14440
  contextMode: preference.contextMode,
14266
14441
  quickQuotaMode: preference.quickQuotaMode,
14267
14442
  ...typeof preference.outputVerbosity === "string" ? { outputVerbosity: preference.outputVerbosity } : {},
@@ -15499,7 +15674,10 @@ function refineQuotaRate(samples, conservative) {
15499
15674
  //#endregion
15500
15675
  //#region src/quota-forecast.js
15501
15676
  const HOUR_MS = 3600 * 1e3;
15502
- const HISTORY_MS = 24 * HOUR_MS;
15677
+ const HISTORY_MS = 720 * HOUR_MS;
15678
+ const WEEK_MS = 168 * HOUR_MS;
15679
+ const RECENT_MS = 2 * HOUR_MS;
15680
+ const OBSERVATION_GAP_MS = 90 * 6e4;
15503
15681
  const finite = (value) => value !== null && value !== void 0 && Number.isFinite(Number(value));
15504
15682
  const clampPercent = (value) => Math.max(0, Math.min(100, Number(value)));
15505
15683
  const cleanSegment = (value) => String(value ?? "default").slice(0, 96);
@@ -15508,6 +15686,35 @@ const keyFor = (window, context = {}) => JSON.stringify([
15508
15686
  cleanSegment(context.limitId ?? "codex"),
15509
15687
  Number(window.windowSeconds) || "limit"
15510
15688
  ]);
15689
+ function retainSamples(samples, now) {
15690
+ const older = /* @__PURE__ */ new Map(), recent = [];
15691
+ for (const sample of samples) {
15692
+ if (sample.at < now - HISTORY_MS) continue;
15693
+ if (sample.at >= now - RECENT_MS) recent.push(sample);
15694
+ else {
15695
+ const width = sample.at >= now - WEEK_MS ? RECENT_MS : 8 * HOUR_MS;
15696
+ const bucket = `${width}:${Math.floor(sample.at / width)}`;
15697
+ if (!older.has(bucket) || sample.reset === true) older.set(bucket, sample);
15698
+ }
15699
+ }
15700
+ return [...older.values(), ...recent.slice(-104)];
15701
+ }
15702
+ function historicalForecast(samples, window, common) {
15703
+ if (window.windowSeconds < 24 * 3600) return void 0;
15704
+ const spanHours = (samples.at(-1).at - samples[0].at) / HOUR_MS;
15705
+ const consumedPercent = samples[0].remainingPercent - samples.at(-1).remainingPercent;
15706
+ if (spanHours < 6 || consumedPercent < 3 || new Set(samples.map((sample) => sample.remainingPercent)).size < 3) return void 0;
15707
+ const pacePerHour = consumedPercent / spanHours;
15708
+ return {
15709
+ ...common,
15710
+ status: "ready",
15711
+ provisional: true,
15712
+ rateMethod: "historical",
15713
+ pacePerHour,
15714
+ runwaySeconds: clampPercent(window.remainingPercent) / pacePerHour * 3600,
15715
+ survivesReset: false
15716
+ };
15717
+ }
15511
15718
  function observeQuotaForecast(state, windows, now = Date.now(), context = {}) {
15512
15719
  const next = { windows: { ...state?.windows ?? {} } };
15513
15720
  let changed = false;
@@ -15520,24 +15727,20 @@ function observeQuotaForecast(state, windows, now = Date.now(), context = {}) {
15520
15727
  const resetChanged = previous !== void 0 && (previous.resetsAt === null !== (resetsAt === null) || previous.resetsAt !== null && Math.abs(previous.resetsAt - resetsAt) > 300);
15521
15728
  const last = previous?.samples?.at(-1);
15522
15729
  const quotaIncreased = last !== void 0 && remainingPercent > last.remainingPercent + .5;
15523
- const observationGap = last !== void 0 && now - last.at > 90 * 6e4;
15524
- const record = resetChanged || quotaIncreased || observationGap ? {
15525
- resetsAt,
15526
- samples: []
15527
- } : {
15730
+ if (last !== void 0 && now <= last.at) continue;
15731
+ const epochStart = resetChanged || quotaIncreased ? now : previous?.epochStart ?? previous?.samples?.[0]?.at ?? now;
15732
+ const sample = {
15733
+ at: now,
15734
+ remainingPercent,
15735
+ ...resetChanged || quotaIncreased ? { reset: true } : {}
15736
+ };
15737
+ const record = {
15528
15738
  resetsAt,
15529
- samples: [...previous?.samples ?? []]
15739
+ epochStart,
15740
+ samples: retainSamples([...previous?.samples ?? [], sample], now)
15530
15741
  };
15531
- const latest = record.samples.at(-1);
15532
- if (latest === void 0 || now > latest.at) {
15533
- record.samples.push({
15534
- at: now,
15535
- remainingPercent
15536
- });
15537
- record.samples = record.samples.filter((sample) => sample.at >= now - HISTORY_MS).slice(-192);
15538
- changed = true;
15539
- }
15540
15742
  next.windows[key] = record;
15743
+ changed = true;
15541
15744
  }
15542
15745
  return {
15543
15746
  state: next,
@@ -15550,16 +15753,26 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
15550
15753
  if (record === void 0) return { status: "calibrating" };
15551
15754
  const resetsAt = finite(window.resetsAt) ? Number(window.resetsAt) : null;
15552
15755
  if (record.resetsAt === null !== (resetsAt === null) || resetsAt !== null && Math.abs(record.resetsAt - resetsAt) > 300) return { status: "calibrating" };
15553
- const newest = record.samples.filter((sample) => sample.at <= now).at(-1);
15554
- let samples = newest === void 0 ? [] : record.samples.filter((sample) => sample.at >= newest.at - 2 * HOUR_MS && sample.at <= newest.at);
15555
- if (samples.length < 2) return {
15756
+ const history = record.samples.filter((sample) => sample.at >= (record.epochStart ?? 0) && sample.at <= now);
15757
+ const newest = history.at(-1);
15758
+ if (newest === void 0) return {
15556
15759
  status: "calibrating",
15557
- sampleCount: samples.length
15760
+ sampleCount: 0
15558
15761
  };
15559
- if (now - samples.at(-1).at > 20 * 6e4) return {
15762
+ if (now - newest.at > 20 * 6e4 || resetsAt !== null && resetsAt <= now / 1e3) return {
15560
15763
  status: "calibrating",
15561
15764
  reason: "stale"
15562
15765
  };
15766
+ let samples = history.filter((sample) => sample.at >= newest.at - RECENT_MS);
15767
+ const lastGap = samples.findLastIndex((sample, index) => index > 0 && sample.at - samples[index - 1].at > OBSERVATION_GAP_MS);
15768
+ if (lastGap > 0) samples = samples.slice(lastGap);
15769
+ const recentChange = samples.findLastIndex((sample) => sample.remainingPercent !== newest.remainingPercent);
15770
+ const flat = samples.slice(recentChange + 1);
15771
+ if (flat.length >= 3 && newest.at - flat[0].at >= 30 * 6e4) return { status: "idle" };
15772
+ if (samples.length < 2) return historicalForecast(history, window, { sampleCount: history.length }) ?? {
15773
+ status: "calibrating",
15774
+ sampleCount: samples.length
15775
+ };
15563
15776
  const rateBounds = (readings) => refineQuotaRate(readings, quotaRateInterval(readings));
15564
15777
  const contradicted = (range) => !range.feasible || range.steadyHypothesisFailed === true || range.min > 1e-9 && range.max - range.min <= 1e-9;
15565
15778
  let bounds = rateBounds(samples);
@@ -15602,7 +15815,7 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
15602
15815
  survivesReset: false
15603
15816
  };
15604
15817
  }
15605
- if (spanMs < 6e4 || bounds.min <= 1e-9) return {
15818
+ if (spanMs < 6e4 || bounds.min <= 1e-9) return historicalForecast(history, window, common) ?? {
15606
15819
  ...common,
15607
15820
  status: "calibrating",
15608
15821
  reason: "resolution"
@@ -15745,7 +15958,7 @@ function createQuotaForecastReader({ reader, enabled, now = Date.now, scope = ()
15745
15958
  //#region src/quota-forecast-store.js
15746
15959
  const DEFAULT_MAX_BYTES = 256 * 1024;
15747
15960
  const MAX_WINDOWS = 128;
15748
- const MAX_SAMPLES = 192;
15961
+ const MAX_SAMPLES = 280;
15749
15962
  function sanitize(value) {
15750
15963
  if (value === null || typeof value !== "object" || Array.isArray(value) || value.windows === null || typeof value.windows !== "object" || Array.isArray(value.windows)) return void 0;
15751
15964
  const entries = Object.entries(value.windows);
@@ -15762,11 +15975,15 @@ function sanitize(value) {
15762
15975
  if (!Number.isFinite(at) || !Number.isFinite(remainingPercent) || remainingPercent < 0 || remainingPercent > 100) return void 0;
15763
15976
  samples.push({
15764
15977
  at,
15765
- remainingPercent
15978
+ remainingPercent,
15979
+ ...sample.reset === true ? { reset: true } : {}
15766
15980
  });
15767
15981
  }
15982
+ const epochStart = record.epochStart;
15983
+ if (epochStart !== void 0 && !Number.isFinite(epochStart)) return void 0;
15768
15984
  windows[key] = {
15769
15985
  resetsAt,
15986
+ ...epochStart === void 0 ? {} : { epochStart },
15770
15987
  samples
15771
15988
  };
15772
15989
  }