dsh-codex-subscription 3.2.14 → 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
@@ -15,14 +15,15 @@ import * as dshLlm from "@deepseek-ai/dsh-llm";
15
15
  import { LlmError, createUserMessage } from "@deepseek-ai/dsh-llm";
16
16
  import { fileURLToPath, pathToFileURL } from "node:url";
17
17
  import { openaiCodexProvider as createOpenAICodexProvider } from "@earendil-works/pi-ai/providers/openai-codex";
18
+ import { isContextOverflow } from "@earendil-works/pi-ai/utils/overflow";
18
19
  import { createModels } from "@earendil-works/pi-ai";
19
20
  import { clientRequestSchema } from "@deepseek-ai/dsh-client-connection";
20
21
  import { lstat, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
21
22
  import { PassThrough } from "node:stream";
23
+ import { dshHomePath, resolveDshHome } from "@deepseek-ai/dsh-home-paths";
22
24
  import * as dshCredentials from "@deepseek-ai/dsh-credentials";
23
25
  import { homedir, hostname } from "node:os";
24
26
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
25
- import { dshHomePath, resolveDshHome } from "@deepseek-ai/dsh-home-paths";
26
27
  import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
27
28
  import { WebError } from "@deepseek-ai/dsh-web";
28
29
  import { performance as performance$1 } from "node:perf_hooks";
@@ -278,6 +279,14 @@ function createDefaultModelController({ resolveService, resolveEditor, listModel
278
279
  //#endregion
279
280
  //#region src/image-models.js
280
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
+ ]);
281
290
  const IMAGE_MODELS = Object.freeze({
282
291
  "gpt-image-2": Object.freeze([
283
292
  "auto",
@@ -285,22 +294,10 @@ const IMAGE_MODELS = Object.freeze({
285
294
  "medium",
286
295
  "high"
287
296
  ]),
288
- "gpt-image-2.5-flare": Object.freeze([
289
- "auto",
290
- "low",
291
- "medium",
292
- "high",
293
- "xhigh",
294
- "max"
295
- ]),
296
- "gpt-image-2.5-sunburst": Object.freeze([
297
- "auto",
298
- "low",
299
- "medium",
300
- "high",
301
- "xhigh",
302
- "max"
303
- ])
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
304
301
  });
305
302
  function resolveImageModel(model = DEFAULT_IMAGE_MODEL) {
306
303
  if (typeof model !== "string" || !Object.hasOwn(IMAGE_MODELS, model)) throw new Error("Unknown image model");
@@ -1178,6 +1175,7 @@ const phases = /* @__PURE__ */ new Set([
1178
1175
  "payload",
1179
1176
  "stream"
1180
1177
  ]);
1178
+ const fetchPaths = /* @__PURE__ */ new Set(["host-fetch", "dedicated-proxy"]);
1181
1179
  const elapsedBuckets$1 = /* @__PURE__ */ new Set([
1182
1180
  "under-1s",
1183
1181
  "1-5s",
@@ -1200,6 +1198,12 @@ function safeAttempt(value = {}) {
1200
1198
  ...typeof value.attemptId === "string" && /^[a-f0-9-]{36}$/.test(value.attemptId) ? { attemptId: value.attemptId } : {},
1201
1199
  ...choices.has(value.preference) ? { preference: value.preference } : {},
1202
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 } : {},
1203
1207
  ...Array.isArray(value.transports) ? { transports: value.transports.filter((item) => transports.has(item)).slice(0, 8) } : {},
1204
1208
  ...typeof value.headersReceived === "boolean" ? { headersReceived: value.headersReceived } : {},
1205
1209
  ...typeof value.eventDelivered === "boolean" ? { eventDelivered: value.eventDelivered } : {},
@@ -1228,8 +1232,11 @@ function createModelAttempt({ now = Date.now, publish = () => {} } = {}) {
1228
1232
  transport(value) {
1229
1233
  if (!finished && transports.has(value) && data.transports.at(-1) !== value && data.transports.length < 8) data.transports.push(value);
1230
1234
  },
1231
- response() {
1232
- if (!finished) data.headersReceived = true;
1235
+ response(status) {
1236
+ if (!finished) {
1237
+ data.headersReceived = true;
1238
+ if (Number.isInteger(status)) data.httpStatus = status;
1239
+ }
1233
1240
  },
1234
1241
  fetchFailure(error) {
1235
1242
  if (!finished) data.networkFailure = safeFetchFailure(error);
@@ -1278,6 +1285,7 @@ const areas$1 = /* @__PURE__ */ new Set([
1278
1285
  "predictions"
1279
1286
  ]);
1280
1287
  const isNetworkDiagnosticArea = (area) => areas$1.has(area);
1288
+ const NETWORK_FAILURE_LIMIT = areas$1.size;
1281
1289
  const codes$1 = /* @__PURE__ */ new Set([
1282
1290
  "timeout",
1283
1291
  "dns",
@@ -1309,6 +1317,7 @@ const safeNetworkTiming = ({ route, elapsed }) => ({
1309
1317
  /** Process-local bounded evidence. No bodies, URLs, exception strings or identities. */
1310
1318
  function createDiagnosticEvents({ limit = 32, now = Date.now } = {}) {
1311
1319
  const events = [];
1320
+ const lastFailure = /* @__PURE__ */ new Map();
1312
1321
  const capacity = Math.max(1, Math.min(128, Number.isInteger(limit) ? limit : 32));
1313
1322
  let dropped = 0, sequence = 0;
1314
1323
  return {
@@ -1324,17 +1333,26 @@ function createDiagnosticEvents({ limit = 32, now = Date.now } = {}) {
1324
1333
  ...codes$1.has(value.code) ? { code: value.code } : {},
1325
1334
  ...Number.isInteger(value.httpStatus) && value.httpStatus >= 100 && value.httpStatus <= 599 ? { httpStatus: value.httpStatus } : {}
1326
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
+ }
1327
1341
  if (events.length > capacity) {
1328
- events.shift();
1329
- dropped++;
1342
+ const oldest = events.shift();
1343
+ if (lastFailure.get(oldest.area) !== oldest) dropped++;
1330
1344
  }
1331
1345
  },
1332
- snapshot: () => ({
1333
- scope: "plugin-process",
1334
- capacity,
1335
- dropped,
1336
- events: events.map((value) => ({ ...value }))
1337
- })
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
+ }
1338
1356
  };
1339
1357
  }
1340
1358
  //#endregion
@@ -1704,6 +1722,7 @@ async function fetchInCodexScope(scope, fetchBeforeScope, input, init) {
1704
1722
  route = await proxy;
1705
1723
  }
1706
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");
1707
1726
  scopedOptions.onRoute?.(hostModelFetch ? "host" : route.source);
1708
1727
  try {
1709
1728
  scopedOptions.onTransport?.("sse");
@@ -1743,6 +1762,7 @@ async function fetchInCodexScope(scope, fetchBeforeScope, input, init) {
1743
1762
  } catch {}
1744
1763
  throw error;
1745
1764
  }
1765
+ if (hostModelFetch || dedicatedProxy) scopedOptions.onModelHttpStatus?.(response.status);
1746
1766
  return scopedOptions.transformResponse?.(response, target) ?? response;
1747
1767
  }
1748
1768
  async function withCodexNetwork(run, options = {}) {
@@ -2190,6 +2210,7 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
2190
2210
  const scope = new AsyncLocalStorage();
2191
2211
  const stats = {
2192
2212
  requests: 0,
2213
+ checkpointsReceived: 0,
2193
2214
  checkpointsSaved: 0,
2194
2215
  checkpointsReused: 0
2195
2216
  };
@@ -2341,7 +2362,10 @@ function createCompactionBridge({ enabled = () => false, threshold, accountScope
2341
2362
  oversized = true;
2342
2363
  }
2343
2364
  }
2344
- 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
+ }
2345
2369
  };
2346
2370
  const stream = response.body.pipeThrough(new TransformStream({
2347
2371
  transform(bytes, controller) {
@@ -2991,7 +3015,13 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
2991
3015
  const settle = (status, error, healthError = error) => {
2992
3016
  if (attempt.snapshot().status) return;
2993
3017
  health?.finish(status === "ok" ? "completed" : status === "abandoned" ? "cancelled" : status, healthError);
2994
- 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
+ }
2995
3025
  attempt.finish(status, stage);
2996
3026
  };
2997
3027
  const finish = () => {
@@ -3019,7 +3049,8 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3019
3049
  };
3020
3050
  attempt.configure({
3021
3051
  preference: request.diagnostic?.preference ?? request.options?.transport ?? "auto",
3022
- requestedTransport: next.transport ?? "auto"
3052
+ requestedTransport: next.transport ?? "auto",
3053
+ model: source?.model?.id
3023
3054
  });
3024
3055
  effectiveSource = {
3025
3056
  ...source,
@@ -3041,6 +3072,12 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3041
3072
  attempt.route(route);
3042
3073
  scopedNetwork?.onRoute?.(route);
3043
3074
  },
3075
+ onModelFetchPath(fetchPath) {
3076
+ attempt.configure({ fetchPath });
3077
+ },
3078
+ onModelHttpStatus(status) {
3079
+ attempt.response(status);
3080
+ },
3044
3081
  onTransport(transport) {
3045
3082
  attempt.transport(transport);
3046
3083
  scopedNetwork?.onTransport?.(transport);
@@ -3073,7 +3110,7 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3073
3110
  ...fetch === void 0 ? {} : { fetch },
3074
3111
  async onResponse(info, requestModel) {
3075
3112
  health.response(info);
3076
- attempt.response();
3113
+ attempt.response(info?.status);
3077
3114
  retryHint?.onResponse(info);
3078
3115
  return next.onResponse?.(info, requestModel);
3079
3116
  },
@@ -3085,6 +3122,12 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3085
3122
  stage = "payload";
3086
3123
  signal.throwIfAborted();
3087
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
+ });
3088
3131
  signal.throwIfAborted();
3089
3132
  stage = "request";
3090
3133
  return body;
@@ -4784,9 +4827,10 @@ async function readSubscriptionCredentials(getAuth, readCredential, signal) {
4784
4827
  }
4785
4828
  const ORIGINAL_IMAGE_CHUNK_BYTES = 4 * 1024 * 1024;
4786
4829
  const ORIGINAL_IMAGE_ID_PATTERN = /^img_[0-9a-f]{32}$/u;
4830
+ const GENERATED_IMAGE_MEDIA_TYPES = Object.freeze(["image/png", "image/gif"]);
4787
4831
  const positiveInteger$1 = (value) => Number.isSafeInteger(value) && value > 0;
4788
4832
  function decodeOriginalImageRef(value) {
4789
- 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;
4790
4834
  return {
4791
4835
  assetId: value.assetId,
4792
4836
  mediaType: value.mediaType,
@@ -4829,9 +4873,185 @@ function inheritedOriginalImageRef(session, assetId) {
4829
4873
  }
4830
4874
  //#endregion
4831
4875
  //#region src/version.js
4832
- const PACKAGE_VERSION = "3.2.14";
4876
+ const PACKAGE_VERSION = "3.2.15";
4833
4877
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
4834
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
4835
5055
  //#region src/codex-images.js
4836
5056
  const CODEX_IMAGE_TOOL_NAME = "codex_image_generate";
4837
5057
  const CODEX_IMAGE_GENERATION_URL = "https://chatgpt.com/backend-api/codex/images/generations";
@@ -4932,16 +5152,44 @@ async function readJsonWithin(response, maximumBytes) {
4932
5152
  }
4933
5153
  }
4934
5154
  /** Strictly decode one PNG returned by the subscription backend. */
4935
- function decodeCodexPng(value, maximumBytes) {
5155
+ function decodeImageBytes(value, maximumBytes, format) {
4936
5156
  const encoded = nonEmpty$2(value);
4937
5157
  const padding = encoded?.endsWith("==") ? 2 : encoded?.endsWith("=") ? 1 : 0;
4938
- 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}`);
4939
5159
  const decodedBytes = encoded.length / 4 * 3 - padding;
4940
5160
  if (decodedBytes > maximumBytes) throw new Error("Codex image exceeds the image size limit");
4941
5161
  const data = Buffer.from(encoded, "base64");
4942
- 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");
4943
5168
  return new Uint8Array(data);
4944
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
+ }
4945
5193
  function imageReference(value) {
4946
5194
  const originalDimensions = record$8(value.originalDimensions) ? {
4947
5195
  width: value.originalDimensions.width,
@@ -5027,7 +5275,7 @@ function imageContent(value) {
5027
5275
  const label = typeof value.size === "string" && value.size.length > 0 ? `Generated a ${value.size} image.` : "Generated an image.";
5028
5276
  return [{
5029
5277
  type: "text",
5030
- 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.`
5031
5279
  }, {
5032
5280
  type: "image",
5033
5281
  attachment: imageReference(value.image)
@@ -5049,7 +5297,12 @@ function imageOutputSchema() {
5049
5297
  },
5050
5298
  mediaType: {
5051
5299
  type: "string",
5052
- enum: ["image/png"],
5300
+ enum: [
5301
+ "image/png",
5302
+ "image/jpeg",
5303
+ "image/webp",
5304
+ "image/gif"
5305
+ ],
5053
5306
  required: true
5054
5307
  },
5055
5308
  bytes: {
@@ -5092,7 +5345,7 @@ function imageOutputSchema() {
5092
5345
  },
5093
5346
  mediaType: {
5094
5347
  type: "string",
5095
- enum: ["image/png"],
5348
+ enum: GENERATED_IMAGE_MEDIA_TYPES,
5096
5349
  required: true
5097
5350
  },
5098
5351
  bytes: {
@@ -5124,7 +5377,7 @@ function imageOutputSchema() {
5124
5377
  localPath: {
5125
5378
  type: "string",
5126
5379
  required: true,
5127
- description: "Absolute path to the original PNG on the DSH host."
5380
+ description: "Absolute path to the original image on the DSH host."
5128
5381
  },
5129
5382
  quality: { type: "string" },
5130
5383
  size: { type: "string" }
@@ -5204,7 +5457,7 @@ function createCodexImageTool(options) {
5204
5457
  model: {
5205
5458
  type: "string",
5206
5459
  enum: Object.keys(IMAGE_MODELS),
5207
- 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."
5208
5461
  },
5209
5462
  prompt: {
5210
5463
  type: "string",
@@ -5236,6 +5489,21 @@ function createCodexImageTool(options) {
5236
5489
  ],
5237
5490
  description: "Optional background mode. Request transparent only when the user needs transparency."
5238
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
+ },
5239
5507
  referenceImages: {
5240
5508
  type: "array",
5241
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.",
@@ -5313,11 +5581,23 @@ function createCodexImageTool(options) {
5313
5581
  const prompt = nonEmpty$2(args.prompt);
5314
5582
  if (prompt === void 0) throw new Error("prompt must be a non-empty string");
5315
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
+ }
5316
5597
  const { access, accountId } = await readSubscriptionCredentials(options.getAuth, options.readCredential, exec.signal);
5317
5598
  if (typeof access !== "string" || access.length === 0 || typeof accountId !== "string" || accountId.length === 0) throw new Error("ChatGPT subscription is not signed in");
5318
- 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`);
5319
5600
  const maximumBytes = Math.min(attachments.imageLimits.maxImageBytes, attachments.imageLimits.maxMessageImageBytes);
5320
- const editing = args.referenceImages !== void 0;
5321
5601
  const sessionMessages = editing && typeof options.getSessionMessages === "function" ? await options.getSessionMessages(exec.agent?.id) : void 0;
5322
5602
  const images = editing ? await editImages(args.referenceImages, attachments, exec.signal, sessionMessages ?? (options.getSessionMessages ? [] : void 0)) : void 0;
5323
5603
  let response;
@@ -5341,7 +5621,8 @@ function createCodexImageTool(options) {
5341
5621
  background: imageOptions.background,
5342
5622
  model: resolveImageModel(args.model),
5343
5623
  quality: imageOptions.quality,
5344
- size: imageOptions.size
5624
+ size: imageOptions.size,
5625
+ ...imageOptions.animation
5345
5626
  }),
5346
5627
  signal: exec.signal
5347
5628
  });
@@ -5355,19 +5636,24 @@ function createCodexImageTool(options) {
5355
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}`);
5356
5637
  if (authFailure !== void 0) throw new Error(authFailure);
5357
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
+ }
5358
5643
  throw new Error(`Codex image ${editing ? "edit" : "generation"} failed (HTTP ${response.status})${requestId}`);
5359
5644
  }
5360
5645
  const metadata = responseMetadata(await readJsonWithin(response, encodedLimit(maximumBytes) + RESPONSE_ENVELOPE_BYTES));
5361
- const data = decodeCodexPng(metadata.encoded, maximumBytes);
5646
+ const data = animated ? decodeAnimatedGif(metadata.encoded, maximumBytes) : decodeCodexPng(metadata.encoded, maximumBytes);
5362
5647
  const sessionId = exec.agent?.id;
5363
5648
  if (sessionId === void 0) throw new Error("Codex image generation requires a session-owned tool call");
5364
- 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);
5365
5651
  let ref;
5366
5652
  try {
5367
5653
  ref = await attachments.saveImage({
5368
5654
  data,
5369
- mediaType: "image/png",
5370
- name: "codex-generated.png"
5655
+ mediaType,
5656
+ name: `codex-generated.${extension}`
5371
5657
  });
5372
5658
  } catch (error) {
5373
5659
  await options.originalImages.remove(original);
@@ -13522,170 +13808,6 @@ function watchImageTool(settings, register) {
13522
13808
  };
13523
13809
  }
13524
13810
  //#endregion
13525
- //#region src/image-original-store.js
13526
- const ORIGINAL_IMAGE_DIRECTORY = "dsh-codex-subscription/images/v1";
13527
- const METADATA_VERSION = 1;
13528
- const digest = (data) => createHash("sha256").update(data).digest("hex");
13529
- const validSessionId = (value) => typeof value === "string" && value.length > 0 && value.length <= 512;
13530
- function pngDimensions(data) {
13531
- 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");
13532
- const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
13533
- const width = view.getUint32(16, false);
13534
- const height = view.getUint32(20, false);
13535
- if (width === 0 || height === 0) throw new TypeError("invalid PNG dimensions");
13536
- return {
13537
- width,
13538
- height
13539
- };
13540
- }
13541
- async function writeExclusive(filename, data) {
13542
- await mkdir(dirname(filename), {
13543
- recursive: true,
13544
- mode: 448
13545
- });
13546
- const handle = await open(filename, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY, 384);
13547
- try {
13548
- await handle.writeFile(data);
13549
- await handle.sync();
13550
- } finally {
13551
- await handle.close();
13552
- }
13553
- }
13554
- async function assertPrivateFile(filename) {
13555
- const stat = await lstat(filename);
13556
- if (!stat.isFile()) throw new Error("not a regular file");
13557
- if (process.platform !== "win32" && (stat.mode & 63) !== 0) throw new Error("file is not owner-only");
13558
- }
13559
- function parseMetadata(text) {
13560
- let value;
13561
- try {
13562
- value = JSON.parse(text);
13563
- } catch {
13564
- return;
13565
- }
13566
- if (value?.version !== METADATA_VERSION || !validSessionId(value.sessionId)) return void 0;
13567
- const image = decodeOriginalImageRef(value.image);
13568
- return image === void 0 ? void 0 : {
13569
- sessionId: value.sessionId,
13570
- image
13571
- };
13572
- }
13573
- var OriginalImageStore = class {
13574
- constructor(dshHome) {
13575
- this.root = resolve(join(resolveDshHome(dshHome), ORIGINAL_IMAGE_DIRECTORY));
13576
- }
13577
- directory(assetId) {
13578
- if (!ORIGINAL_IMAGE_ID_PATTERN.test(assetId)) throw new TypeError("invalid original image asset id");
13579
- return join(this.root, assetId.slice(4, 6), assetId);
13580
- }
13581
- originalPath(assetId) {
13582
- return join(this.directory(assetId), "original");
13583
- }
13584
- async save(sessionId, data, name = "codex-generated-original.png") {
13585
- if (!validSessionId(sessionId) || !(data instanceof Uint8Array) || data.byteLength === 0 || data.byteLength > 48 * 1024 * 1024) throw new TypeError("invalid original image input");
13586
- const { width, height } = pngDimensions(data);
13587
- const assetId = `img_${randomBytes(16).toString("hex")}`;
13588
- const directory = this.directory(assetId);
13589
- const ref = {
13590
- assetId,
13591
- mediaType: "image/png",
13592
- bytes: data.byteLength,
13593
- width,
13594
- height,
13595
- name,
13596
- sha256: digest(data)
13597
- };
13598
- try {
13599
- await mkdir(dirname(directory), {
13600
- recursive: true,
13601
- mode: 448
13602
- });
13603
- await mkdir(directory, {
13604
- recursive: false,
13605
- mode: 448
13606
- });
13607
- await writeExclusive(join(directory, "original"), data);
13608
- const temporary = join(directory, `metadata.${randomBytes(8).toString("hex")}.tmp`);
13609
- await writeExclusive(temporary, Buffer.from(`${JSON.stringify({
13610
- version: METADATA_VERSION,
13611
- sessionId,
13612
- image: ref
13613
- }, null, 2)}\n`));
13614
- await rename(temporary, join(directory, "metadata.json"));
13615
- return ref;
13616
- } catch (error) {
13617
- await rm(directory, {
13618
- recursive: true,
13619
- force: true
13620
- }).catch(() => void 0);
13621
- throw error;
13622
- }
13623
- }
13624
- async remove(ref) {
13625
- if (ref !== void 0 && ORIGINAL_IMAGE_ID_PATTERN.test(ref.assetId)) await rm(this.directory(ref.assetId), {
13626
- recursive: true,
13627
- force: true
13628
- }).catch(() => void 0);
13629
- }
13630
- async read(sessionId, assetId, inherited) {
13631
- if (!validSessionId(sessionId) || !ORIGINAL_IMAGE_ID_PATTERN.test(assetId)) return void 0;
13632
- try {
13633
- const directory = this.directory(assetId);
13634
- const metadataFile = join(directory, "metadata.json");
13635
- const originalFile = join(directory, "original");
13636
- await Promise.all([assertPrivateFile(metadataFile), assertPrivateFile(originalFile)]);
13637
- const metadata = parseMetadata(await readFile(metadataFile, "utf8"));
13638
- if (metadata === void 0 || metadata.image.assetId !== assetId || metadata.sessionId !== sessionId && !originalImageRefsEqual(metadata.image, inherited)) return void 0;
13639
- const buffer = await readFile(originalFile);
13640
- const data = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
13641
- const dimensions = pngDimensions(data);
13642
- if (data.byteLength !== metadata.image.bytes || digest(data) !== metadata.image.sha256 || dimensions.width !== metadata.image.width || dimensions.height !== metadata.image.height) return void 0;
13643
- return {
13644
- ref: metadata.image,
13645
- data
13646
- };
13647
- } catch {
13648
- return;
13649
- }
13650
- }
13651
- async chunk(sessionId, assetId, offset, inherited) {
13652
- if (!validSessionId(sessionId) || !ORIGINAL_IMAGE_ID_PATTERN.test(assetId) || !Number.isSafeInteger(offset) || offset < 0 || offset % 4194304 !== 0) return void 0;
13653
- let handle;
13654
- try {
13655
- const metadataFile = join(this.directory(assetId), "metadata.json");
13656
- const originalFile = this.originalPath(assetId);
13657
- await Promise.all([assertPrivateFile(metadataFile), assertPrivateFile(originalFile)]);
13658
- const metadata = parseMetadata(await readFile(metadataFile, "utf8"));
13659
- if (!metadata || metadata.image.assetId !== assetId || metadata.sessionId !== sessionId && !originalImageRefsEqual(metadata.image, inherited)) return void 0;
13660
- handle = await open(originalFile, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
13661
- const stat = await handle.stat();
13662
- if (!stat.isFile() || stat.size !== metadata.image.bytes || offset >= stat.size || process.platform !== "win32" && (stat.mode & 63) !== 0) return void 0;
13663
- const header = Buffer.alloc(24);
13664
- if ((await handle.read(header, 0, 24, 0)).bytesRead !== 24) return void 0;
13665
- const dimensions = pngDimensions(header);
13666
- if (dimensions.width !== metadata.image.width || dimensions.height !== metadata.image.height) return void 0;
13667
- const length = Math.min(ORIGINAL_IMAGE_CHUNK_BYTES, stat.size - offset);
13668
- const chunk = Buffer.alloc(length);
13669
- let read = 0;
13670
- while (read < length) {
13671
- const result = await handle.read(chunk, read, length - read, offset + read);
13672
- if (!result.bytesRead) return void 0;
13673
- read += result.bytesRead;
13674
- }
13675
- return {
13676
- ref: metadata.image,
13677
- offset,
13678
- encoded: chunk.toString("base64"),
13679
- done: offset + length === stat.size
13680
- };
13681
- } catch {
13682
- return;
13683
- } finally {
13684
- await handle?.close();
13685
- }
13686
- }
13687
- };
13688
- //#endregion
13689
13811
  //#region src/diagnostic-checks.js
13690
13812
  const states = /* @__PURE__ */ new Set([
13691
13813
  "pass",
@@ -13882,6 +14004,13 @@ const actions = Object.freeze({
13882
14004
  "runtime/install": "subagents",
13883
14005
  "runtime/remove": "subagents",
13884
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",
13885
14014
  codex_image_generate: "images",
13886
14015
  codex_sketch: "sketch"
13887
14016
  });
@@ -13891,6 +14020,14 @@ const QUIET = /* @__PURE__ */ new Set([
13891
14020
  "preferences/models",
13892
14021
  "predictions/generate"
13893
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
+ ]);
13894
14031
  function safeOperations(raw) {
13895
14032
  if (!Array.isArray(raw?.events)) return void 0;
13896
14033
  return {
@@ -13908,7 +14045,8 @@ function safeOperations(raw) {
13908
14045
  action: value.action,
13909
14046
  status: value.status,
13910
14047
  source: value.source,
13911
- observedAt: value.observedAt
14048
+ observedAt: value.observedAt,
14049
+ ...value.status === "failed" && RPC_FAILURES.has(value.code) ? { code: value.code } : {}
13912
14050
  }];
13913
14051
  })
13914
14052
  };
@@ -13916,7 +14054,7 @@ function safeOperations(raw) {
13916
14054
  function createDiagnosticOperations({ now = Date.now } = {}) {
13917
14055
  const events = [];
13918
14056
  let sequence = 0, dropped = 0;
13919
- const record = (action, status, source = "rpc") => {
14057
+ const record = (action, status, source = "rpc", code) => {
13920
14058
  if (!Object.hasOwn(actions, action) || ![
13921
14059
  "completed",
13922
14060
  "failed",
@@ -13928,7 +14066,8 @@ function createDiagnosticOperations({ now = Date.now } = {}) {
13928
14066
  action,
13929
14067
  source,
13930
14068
  status,
13931
- observedAt: now()
14069
+ observedAt: now(),
14070
+ ...status === "failed" && RPC_FAILURES.has(code) ? { code } : {}
13932
14071
  });
13933
14072
  if (status === "failed") diagnosticLog.error(actions[action], `${action} failed`);
13934
14073
  else if (status === "completed" && !QUIET.has(action)) diagnosticLog.info(actions[action], `${action} completed`);
@@ -13951,7 +14090,7 @@ function createDiagnosticOperations({ now = Date.now } = {}) {
13951
14090
  }[result.value?.reason];
13952
14091
  diagnosticLog.info("predictions", result.value?.prediction ? "suggestion ready" : `no suggestion${reason ? `: ${reason}` : ""}`);
13953
14092
  }
13954
- record(endpoint, result?.ok === true ? "completed" : "failed");
14093
+ record(endpoint, signal?.aborted ? "cancelled" : result?.ok === true ? "completed" : "failed", "rpc", result?.error?.code);
13955
14094
  return result;
13956
14095
  } catch (error) {
13957
14096
  record(endpoint, signal?.aborted ? "cancelled" : "failed");
@@ -14000,7 +14139,8 @@ const codes = /* @__PURE__ */ new Set([
14000
14139
  ]);
14001
14140
  function safeHistory(raw) {
14002
14141
  if (!raw || !Array.isArray(raw.events)) return void 0;
14003
- const events = raw.events.slice(-32).flatMap((value) => {
14142
+ const maximum = 32 + NETWORK_FAILURE_LIMIT;
14143
+ const events = raw.events.slice(-maximum).flatMap((value) => {
14004
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 [];
14005
14145
  return [{
14006
14146
  area: value.area,
@@ -14016,7 +14156,7 @@ function safeHistory(raw) {
14016
14156
  return {
14017
14157
  scope: "plugin-process",
14018
14158
  capacity: 32,
14019
- 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),
14020
14160
  events
14021
14161
  };
14022
14162
  }
@@ -14129,6 +14269,7 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
14129
14269
  "compaction",
14130
14270
  () => compaction ? safeCounters(compaction, [
14131
14271
  "requests",
14272
+ "checkpointsReceived",
14132
14273
  "checkpointsSaved",
14133
14274
  "checkpointsReused"
14134
14275
  ]) : void 0
@@ -14293,6 +14434,9 @@ async function createSubscriptionDiagnostics({ auth, preferences, login = { phas
14293
14434
  } } : {},
14294
14435
  configuration: {
14295
14436
  ...typeof preference.autoQuotaRetry === "boolean" ? { autoQuotaRetry: preference.autoQuotaRetry } : {},
14437
+ connectionMode: preference.connectionMode,
14438
+ compactionMode: preference.compactionMode,
14439
+ composerModelPicker: preference.composerModelPicker,
14296
14440
  contextMode: preference.contextMode,
14297
14441
  quickQuotaMode: preference.quickQuotaMode,
14298
14442
  ...typeof preference.outputVerbosity === "string" ? { outputVerbosity: preference.outputVerbosity } : {},
@@ -15530,7 +15674,10 @@ function refineQuotaRate(samples, conservative) {
15530
15674
  //#endregion
15531
15675
  //#region src/quota-forecast.js
15532
15676
  const HOUR_MS = 3600 * 1e3;
15533
- 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;
15534
15681
  const finite = (value) => value !== null && value !== void 0 && Number.isFinite(Number(value));
15535
15682
  const clampPercent = (value) => Math.max(0, Math.min(100, Number(value)));
15536
15683
  const cleanSegment = (value) => String(value ?? "default").slice(0, 96);
@@ -15539,6 +15686,35 @@ const keyFor = (window, context = {}) => JSON.stringify([
15539
15686
  cleanSegment(context.limitId ?? "codex"),
15540
15687
  Number(window.windowSeconds) || "limit"
15541
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
+ }
15542
15718
  function observeQuotaForecast(state, windows, now = Date.now(), context = {}) {
15543
15719
  const next = { windows: { ...state?.windows ?? {} } };
15544
15720
  let changed = false;
@@ -15551,24 +15727,20 @@ function observeQuotaForecast(state, windows, now = Date.now(), context = {}) {
15551
15727
  const resetChanged = previous !== void 0 && (previous.resetsAt === null !== (resetsAt === null) || previous.resetsAt !== null && Math.abs(previous.resetsAt - resetsAt) > 300);
15552
15728
  const last = previous?.samples?.at(-1);
15553
15729
  const quotaIncreased = last !== void 0 && remainingPercent > last.remainingPercent + .5;
15554
- const observationGap = last !== void 0 && now - last.at > 90 * 6e4;
15555
- const record = resetChanged || quotaIncreased || observationGap ? {
15556
- resetsAt,
15557
- samples: []
15558
- } : {
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 = {
15559
15738
  resetsAt,
15560
- samples: [...previous?.samples ?? []]
15739
+ epochStart,
15740
+ samples: retainSamples([...previous?.samples ?? [], sample], now)
15561
15741
  };
15562
- const latest = record.samples.at(-1);
15563
- if (latest === void 0 || now > latest.at) {
15564
- record.samples.push({
15565
- at: now,
15566
- remainingPercent
15567
- });
15568
- record.samples = record.samples.filter((sample) => sample.at >= now - HISTORY_MS).slice(-192);
15569
- changed = true;
15570
- }
15571
15742
  next.windows[key] = record;
15743
+ changed = true;
15572
15744
  }
15573
15745
  return {
15574
15746
  state: next,
@@ -15581,16 +15753,26 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
15581
15753
  if (record === void 0) return { status: "calibrating" };
15582
15754
  const resetsAt = finite(window.resetsAt) ? Number(window.resetsAt) : null;
15583
15755
  if (record.resetsAt === null !== (resetsAt === null) || resetsAt !== null && Math.abs(record.resetsAt - resetsAt) > 300) return { status: "calibrating" };
15584
- const newest = record.samples.filter((sample) => sample.at <= now).at(-1);
15585
- let samples = newest === void 0 ? [] : record.samples.filter((sample) => sample.at >= newest.at - 2 * HOUR_MS && sample.at <= newest.at);
15586
- 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 {
15587
15759
  status: "calibrating",
15588
- sampleCount: samples.length
15760
+ sampleCount: 0
15589
15761
  };
15590
- if (now - samples.at(-1).at > 20 * 6e4) return {
15762
+ if (now - newest.at > 20 * 6e4 || resetsAt !== null && resetsAt <= now / 1e3) return {
15591
15763
  status: "calibrating",
15592
15764
  reason: "stale"
15593
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
+ };
15594
15776
  const rateBounds = (readings) => refineQuotaRate(readings, quotaRateInterval(readings));
15595
15777
  const contradicted = (range) => !range.feasible || range.steadyHypothesisFailed === true || range.min > 1e-9 && range.max - range.min <= 1e-9;
15596
15778
  let bounds = rateBounds(samples);
@@ -15633,7 +15815,7 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
15633
15815
  survivesReset: false
15634
15816
  };
15635
15817
  }
15636
- if (spanMs < 6e4 || bounds.min <= 1e-9) return {
15818
+ if (spanMs < 6e4 || bounds.min <= 1e-9) return historicalForecast(history, window, common) ?? {
15637
15819
  ...common,
15638
15820
  status: "calibrating",
15639
15821
  reason: "resolution"
@@ -15776,7 +15958,7 @@ function createQuotaForecastReader({ reader, enabled, now = Date.now, scope = ()
15776
15958
  //#region src/quota-forecast-store.js
15777
15959
  const DEFAULT_MAX_BYTES = 256 * 1024;
15778
15960
  const MAX_WINDOWS = 128;
15779
- const MAX_SAMPLES = 192;
15961
+ const MAX_SAMPLES = 280;
15780
15962
  function sanitize(value) {
15781
15963
  if (value === null || typeof value !== "object" || Array.isArray(value) || value.windows === null || typeof value.windows !== "object" || Array.isArray(value.windows)) return void 0;
15782
15964
  const entries = Object.entries(value.windows);
@@ -15793,11 +15975,15 @@ function sanitize(value) {
15793
15975
  if (!Number.isFinite(at) || !Number.isFinite(remainingPercent) || remainingPercent < 0 || remainingPercent > 100) return void 0;
15794
15976
  samples.push({
15795
15977
  at,
15796
- remainingPercent
15978
+ remainingPercent,
15979
+ ...sample.reset === true ? { reset: true } : {}
15797
15980
  });
15798
15981
  }
15982
+ const epochStart = record.epochStart;
15983
+ if (epochStart !== void 0 && !Number.isFinite(epochStart)) return void 0;
15799
15984
  windows[key] = {
15800
15985
  resetsAt,
15986
+ ...epochStart === void 0 ? {} : { epochStart },
15801
15987
  samples
15802
15988
  };
15803
15989
  }